From d8fa598081d29556dcaaca00a1a67084d47cdce7 Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Mon, 27 Apr 2015 11:12:06 +0200 Subject: [PATCH 01/16] Remove zone-host connection [Feature] No dbus connection with zone [Cause] N/A [Solution] Remove code responsible for zone connection [Verification] Build with and without DBUS_CONNECTION macro, run tests for each build (NOTE: ClientSuite/NotRunningServer will fail) Change-Id: Ida474fba31111eb431ddc97c4bc3def1eeb932c7 --- client/dbus-connection.cpp | 119 ---- client/dbus-connection.hpp | 135 ---- client/host-dbus-connection.cpp | 191 ------ client/host-dbus-connection.hpp | 84 --- client/host-ipc-connection.cpp | 194 ++++-- client/host-ipc-connection.hpp | 23 +- client/ipc-connection.cpp | 47 -- client/ipc-connection.hpp | 90 --- client/vasum-client-impl.cpp | 137 +--- client/vasum-client-impl.hpp | 11 - client/zone-dbus-connection.cpp | 71 -- client/zone-dbus-connection.hpp | 60 -- ...dbus-definitions.hpp => common-definitions.hpp} | 26 +- server/configs/lxc-templates/template.sh | 1 - server/configs/templates/default.conf | 1 - server/host-dbus-connection.cpp | 141 ++-- server/host-dbus-connection.hpp | 37 + server/host-dbus-definitions.hpp | 48 +- server/host-ipc-connection.cpp | 244 +++---- server/host-ipc-connection.hpp | 102 ++- server/host-ipc-definitions.hpp | 15 +- server/ipc-callback-wrapper.hpp | 107 +++ server/zone-config.hpp | 7 - server/zone-connection-transport.cpp | 125 ---- server/zone-connection-transport.hpp | 63 -- server/zone-connection.cpp | 263 -------- server/zone-connection.hpp | 137 ---- server/zone-dbus-definitions.hpp | 85 --- server/zone.cpp | 195 +----- server/zone.hpp | 82 +-- server/zones-manager.cpp | 179 +++-- server/zones-manager.hpp | 17 +- tests/unit_tests/client/configs/CMakeLists.txt | 2 + .../ut-client/templates/console-dbus.conf.in | 1 - .../ut-client/templates/console-ipc.conf.in | 18 + tests/unit_tests/client/ut-client.cpp | 115 +--- tests/unit_tests/lxc/templates/minimal-dbus.sh | 1 - tests/unit_tests/server/configs/CMakeLists.txt | 7 +- .../configs/ut-server/templates/default.conf | 1 - .../configs/ut-zone-admin/templates/buggy.conf | 1 - .../configs/ut-zone-admin/templates/missing.conf | 1 - .../ut-zone-admin/templates/test-no-shutdown.conf | 1 - .../configs/ut-zone-admin/templates/test.conf | 1 - .../server/configs/ut-zone-connection/ut-dbus.conf | 18 - .../server/configs/ut-zone/templates/buggy.conf | 1 - .../configs/ut-zone/templates/test-dbus.conf.in | 1 - .../server/configs/ut-zone/templates/test.conf | 1 - .../templates/console-dbus.conf.in | 1 - .../ut-zones-manager/templates/console-ipc.conf.in | 18 + .../ut-zones-manager/templates/console.conf | 1 - tests/unit_tests/server/ut-zone-connection.cpp | 234 ------- tests/unit_tests/server/ut-zone.cpp | 3 +- tests/unit_tests/server/ut-zones-manager.cpp | 746 ++++++--------------- 53 files changed, 1021 insertions(+), 3189 deletions(-) delete mode 100644 client/dbus-connection.cpp delete mode 100644 client/dbus-connection.hpp delete mode 100644 client/host-dbus-connection.cpp delete mode 100644 client/host-dbus-connection.hpp delete mode 100644 client/ipc-connection.cpp delete mode 100644 client/ipc-connection.hpp delete mode 100644 client/zone-dbus-connection.cpp delete mode 100644 client/zone-dbus-connection.hpp rename server/{common-dbus-definitions.hpp => common-definitions.hpp} (52%) create mode 100644 server/ipc-callback-wrapper.hpp delete mode 100644 server/zone-connection-transport.cpp delete mode 100644 server/zone-connection-transport.hpp delete mode 100644 server/zone-connection.cpp delete mode 100644 server/zone-connection.hpp delete mode 100644 server/zone-dbus-definitions.hpp create mode 100644 tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in delete mode 100644 tests/unit_tests/server/configs/ut-zone-connection/ut-dbus.conf create mode 100644 tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in delete mode 100644 tests/unit_tests/server/ut-zone-connection.cpp diff --git a/client/dbus-connection.cpp b/client/dbus-connection.cpp deleted file mode 100644 index b52bd71..0000000 --- a/client/dbus-connection.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief SimpleDbus's wrapper - */ - -#include -#include "dbus-connection.hpp" -#include "exception.hpp" -#include -#include - -using namespace vasum::client; - - -DbusConnection::DbusConnection(const std::string& definition, - const std::string& busName, - const std::string& objectPath, - const std::string& interface) - : mDefinition(definition) - , mBusName(busName) - , mObjectPath(objectPath) - , mInterface(interface) -{ -} - -DbusConnection::~DbusConnection() -{ -} - -void DbusConnection::create(const std::shared_ptr& connection) -{ - mConnection = connection; -} - -void DbusConnection::callMethod(const std::string& method, - GVariant* args_in, - const std::string& args_spec_out, - GVariant** args_out) -{ - dbus::GVariantPtr ret = mConnection->callMethod(mBusName, - mObjectPath, - mInterface, - method, - args_in, - args_spec_out); - if (args_out != NULL) { - *args_out = ret.release(); - } -} - -DbusConnection::SubscriptionId DbusConnection::signalSubscribe(const std::string& signal, - const SignalCallback& signalCallback) -{ - auto onSignal = [this, signal, signalCallback](const std::string& /*senderBusName*/, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant * parameters) { - if (objectPath == mObjectPath && - interface == mInterface && - signalName == signal) { - - signalCallback(parameters); - } - }; - return mConnection->signalSubscribe(onSignal, mBusName); -} - -void DbusConnection::signalUnsubscribe(SubscriptionId id) -{ - mConnection->signalUnsubscribe(id); -} - -std::string DbusConnection::getArgsOutSpec(const std::string& methodName) -{ - //TODO: Information about output argumnets of all methods can be computed in constuctor - GError *error = NULL; - GDBusNodeInfo* nodeInfo = g_dbus_node_info_new_for_xml(mDefinition.c_str(), &error); - if (error) { - std::string msg = error->message; - g_error_free (error); - throw ClientException("Invalid xml: " + msg); - } - GDBusInterfaceInfo* interfaceInfo = g_dbus_node_info_lookup_interface(nodeInfo, mInterface.c_str()); - if (interfaceInfo == NULL) { - throw ClientException("Invalid xml: can't find interface: " + mInterface); - } - GDBusMethodInfo* methodInfo = g_dbus_interface_info_lookup_method(interfaceInfo, methodName.c_str()); - if (methodInfo == NULL) { - throw ClientException("Invalid xml: can't find method: " + methodName); - } - - std::string signature; - for (GDBusArgInfo** argInfo = methodInfo->out_args; *argInfo; ++argInfo) { - signature += (*argInfo)->signature; - } - g_dbus_node_info_unref(nodeInfo); - return "(" + signature + ")"; -} diff --git a/client/dbus-connection.hpp b/client/dbus-connection.hpp deleted file mode 100644 index 3cb37ad..0000000 --- a/client/dbus-connection.hpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief SimpleDbus's wrapper - */ - -#ifndef VASUM_CLIENT_DBUS_CONNECTION_HPP -#define VASUM_CLIENT_DBUS_CONNECTION_HPP - -#include -#include -#include -#include -#include -#include - -namespace vasum { -namespace client { - -/** - * SimpleDbus client definition. - * - * DbusConnection uses SimpleDbus API. - */ -class DbusConnection { -public: - typedef unsigned int SubscriptionId; - - DbusConnection(const std::string& definition, - const std::string& busName, - const std::string& objectPath, - const std::string& interface); - virtual ~DbusConnection(); - void create(const std::shared_ptr& connection); - - template - typename std::enable_if::value>::type - call(const std::string& method, const ArgIn& argIn, ArgOut& argOut); - - template - typename std::enable_if::value>::type - call(const std::string& method, const ArgIn& argIn, ArgOut& argOut); - - template - typename std::enable_if::value>::type - call(const std::string& method, ArgOut& argOut) { - vasum::api::Void argIn; - call(method, argIn, argOut); - } - - template - typename std::enable_if::value>::type - call(const std::string& method, ArgIn& argIn) { - vasum::api::Void argOut; - call(method, argIn, argOut); - } - - template - SubscriptionId signalSubscribe(const std::string& signal, - const std::function& signalCallback); - void signalUnsubscribe(SubscriptionId id); - -private: - typedef std::function SignalCallback; - - std::shared_ptr mConnection; - const std::string mDefinition; - const std::string mBusName; - const std::string mObjectPath; - const std::string mInterface; - - void callMethod(const std::string& method, - GVariant* args_in, - const std::string& args_spec_out, - GVariant** args_out); - SubscriptionId signalSubscribe(const std::string& signal, const SignalCallback& signalCallback); - - /** - * Get signature of method output parameters - */ - std::string getArgsOutSpec(const std::string& methodName); -}; - -template -typename std::enable_if::value>::type -DbusConnection::call(const std::string& method, const ArgIn& argIn, ArgOut& argOut) -{ - GVariant* gArgOut = NULL; - callMethod(method, config::saveToGVariant(argIn), getArgsOutSpec(method), &gArgOut); - config::loadFromGVariant(gArgOut, argOut); - g_variant_unref(gArgOut); -} - -template -typename std::enable_if::value>::type -DbusConnection::call(const std::string& method, const ArgIn& argIn, ArgOut& /* argOut */) -{ - callMethod(method, config::saveToGVariant(argIn), "", NULL); -} - -template -DbusConnection::SubscriptionId DbusConnection::signalSubscribe(const std::string& signal, - const std::function& signalCallback) -{ - SignalCallback callback = [signalCallback](GVariant* parameters) { - Arg param; - config::loadFromGVariant(parameters, param); - signalCallback(param); - }; - return signalSubscribe(signal, callback); -} - -} // namespace client -} // namespace vasum - -#endif /* VASUM_CLIENT_DBUS_CONNECTION_HPP */ diff --git a/client/host-dbus-connection.cpp b/client/host-dbus-connection.cpp deleted file mode 100644 index 1f375a0..0000000 --- a/client/host-dbus-connection.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief Host client class - */ - - -#include -#include "host-dbus-connection.hpp" -#include -#include - -namespace vasum { -namespace client { - -HostDbusConnection::HostDbusConnection() - : mConnection(vasum::api::host::DEFINITION, - vasum::api::host::BUS_NAME, - vasum::api::host::OBJECT_PATH, - vasum::api::host::INTERFACE) -{ -} - -void HostDbusConnection::create(const std::shared_ptr& connection) -{ - mConnection.create(connection); -} - -void HostDbusConnection::callGetZoneIds(vasum::api::ZoneIds& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_ZONE_ID_LIST, argOut); -} - -void HostDbusConnection::callGetActiveZoneId(vasum::api::ZoneId& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_ACTIVE_ZONE_ID, argOut); -} - -void HostDbusConnection::callSetActiveZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_SET_ACTIVE_ZONE, argIn); -} - -void HostDbusConnection::callGetZoneInfo(const vasum::api::ZoneId& argIn, vasum::api::ZoneInfoOut& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_ZONE_INFO, argIn, argOut); -} - -void HostDbusConnection::callSetNetdevAttrs(const vasum::api::SetNetDevAttrsIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_SET_NETDEV_ATTRS, argIn); -} - -void HostDbusConnection::callGetNetdevAttrs(const vasum::api::GetNetDevAttrsIn& argIn, vasum::api::GetNetDevAttrs& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_NETDEV_ATTRS, argIn, argOut); -} - -void HostDbusConnection::callGetNetdevList(const vasum::api::ZoneId& argIn, vasum::api::NetDevList& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_NETDEV_LIST, argIn, argOut); -} - -void HostDbusConnection::callCreateNetdevVeth(const vasum::api::CreateNetDevVethIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_VETH, argIn); -} - -void HostDbusConnection::callCreateNetdevMacvlan(const vasum::api::CreateNetDevMacvlanIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_MACVLAN, argIn); -} - -void HostDbusConnection::callCreateNetdevPhys(const vasum::api::CreateNetDevPhysIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_PHYS, argIn); -} - -void HostDbusConnection::callDestroyNetdev(const vasum::api::DestroyNetDevIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_DESTROY_NETDEV, argIn); -} - -void HostDbusConnection::callDeleteNetdevIpAddress(const vasum::api::DeleteNetdevIpAddressIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_DELETE_NETDEV_IP_ADDRESS, argIn); -} - -void HostDbusConnection::callDeclareFile(const vasum::api::DeclareFileIn& argIn, vasum::api::Declaration& argOut) -{ - mConnection.call(vasum::api::host::METHOD_DECLARE_FILE, argIn, argOut); -} - -void HostDbusConnection::callDeclareMount(const vasum::api::DeclareMountIn& argIn, vasum::api::Declaration& argOut) -{ - mConnection.call(vasum::api::host::METHOD_DECLARE_MOUNT, argIn, argOut); -} - -void HostDbusConnection::callDeclareLink(const vasum::api::DeclareLinkIn& argIn, vasum::api::Declaration& argOut) -{ - mConnection.call(vasum::api::host::METHOD_DECLARE_LINK, argIn, argOut); -} - -void HostDbusConnection::callGetDeclarations(const vasum::api::ZoneId& argIn, vasum::api::Declarations& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_DECLARATIONS, argIn, argOut); -} - -void HostDbusConnection::callRemoveDeclaration(const vasum::api::RemoveDeclarationIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_REMOVE_DECLARATION, argIn); -} - -void HostDbusConnection::callCreateZone(const vasum::api::CreateZoneIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_CREATE_ZONE, argIn); -} - -void HostDbusConnection::callDestroyZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_DESTROY_ZONE, argIn); -} - -void HostDbusConnection::callShutdownZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_SHUTDOWN_ZONE, argIn); -} - -void HostDbusConnection::callStartZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_START_ZONE, argIn); -} - -void HostDbusConnection::callLockZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_LOCK_ZONE, argIn); -} - -void HostDbusConnection::callUnlockZone(const vasum::api::ZoneId& argIn) -{ - mConnection.call(vasum::api::host::METHOD_UNLOCK_ZONE, argIn); -} - -void HostDbusConnection::callGrantDevice(const vasum::api::GrantDeviceIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_GRANT_DEVICE, argIn); -} - -void HostDbusConnection::callRevokeDevice(const vasum::api::RevokeDeviceIn& argIn) -{ - mConnection.call(vasum::api::host::METHOD_REVOKE_DEVICE, argIn); -} - -void HostDbusConnection::callGetZoneConnections(vasum::api::Connections& argOut) -{ - mConnection.call(vasum::api::host::METHOD_GET_ZONE_CONNECTIONS, argOut); -} - -HostDbusConnection::SubscriptionId -HostDbusConnection::subscribeZoneConnectionState(const ZoneConnectionStateCallback& callback) -{ - return mConnection.signalSubscribe( - vasum::api::host::SIGNAL_ZONE_CONNECTION_STATE, callback); -} - -void HostDbusConnection::unsubscribe(const SubscriptionId& id) -{ - mConnection.signalUnsubscribe(id); -} - -} // namespace client -} // namespace vasum diff --git a/client/host-dbus-connection.hpp b/client/host-dbus-connection.hpp deleted file mode 100644 index 8785fa0..0000000 --- a/client/host-dbus-connection.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief Host client class - */ - -#ifndef VASUM_CLIENT_HOST_DBUS_CONNECTION_HPP -#define VASUM_CLIENT_HOST_DBUS_CONNECTION_HPP - -#include "dbus-connection.hpp" -#include - -namespace vasum { -namespace client { - -/** - * vasum's client definition. - * - * HostDbusConnection is used for communication with the vasum's server from host through dbus - */ -class HostDbusConnection { -public: - typedef unsigned int SubscriptionId; - typedef std::function ZoneConnectionStateCallback; - - HostDbusConnection(); - - void create(const std::shared_ptr& connection); - - void callGetZoneIds(vasum::api::ZoneIds& argOut); - void callGetActiveZoneId(vasum::api::ZoneId& argOut); - void callSetActiveZone(const vasum::api::ZoneId& argIn); - void callGetZoneInfo(const vasum::api::ZoneId& argIn, vasum::api::ZoneInfoOut& argOut); - void callSetNetdevAttrs(const vasum::api::SetNetDevAttrsIn& argIn); - void callGetNetdevAttrs(const vasum::api::GetNetDevAttrsIn& argIn, vasum::api::GetNetDevAttrs& argOut); - void callGetNetdevList(const vasum::api::ZoneId& argIn, vasum::api::NetDevList& argOut); - void callCreateNetdevVeth(const vasum::api::CreateNetDevVethIn& argIn); - void callCreateNetdevMacvlan(const vasum::api::CreateNetDevMacvlanIn& argIn); - void callCreateNetdevPhys(const vasum::api::CreateNetDevPhysIn& argIn); - void callDestroyNetdev(const vasum::api::DestroyNetDevIn& argIn); - void callDeleteNetdevIpAddress(const vasum::api::DeleteNetdevIpAddressIn& argIn); - void callDeclareFile(const vasum::api::DeclareFileIn& argIn, vasum::api::Declaration& argOut); - void callDeclareMount(const vasum::api::DeclareMountIn& argIn, vasum::api::Declaration& argOut); - void callDeclareLink(const vasum::api::DeclareLinkIn& argIn, vasum::api::Declaration& argOut); - void callGetDeclarations(const vasum::api::ZoneId& argIn, vasum::api::Declarations& argOut); - void callRemoveDeclaration(const vasum::api::RemoveDeclarationIn& argIn); - void callCreateZone(const vasum::api::CreateZoneIn& argIn); - void callDestroyZone(const vasum::api::ZoneId& argIn); - void callShutdownZone(const vasum::api::ZoneId& argIn); - void callStartZone(const vasum::api::ZoneId& argIn); - void callLockZone(const vasum::api::ZoneId& argIn); - void callUnlockZone(const vasum::api::ZoneId& argIn); - void callGrantDevice(const vasum::api::GrantDeviceIn& argIn); - void callRevokeDevice(const vasum::api::RevokeDeviceIn& argIn); - void callGetZoneConnections(vasum::api::Connections& argOut); - SubscriptionId subscribeZoneConnectionState(const ZoneConnectionStateCallback& callback); - void unsubscribe(const SubscriptionId& id); -private: - DbusConnection mConnection; -}; - -} // namespace client -} // namespace vasum - -#endif /* VASUM_CLIENT_HOST_DBUS_CONNECTION_HPP */ diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index adb44eb..121f7ad 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -33,150 +33,228 @@ namespace client { void HostIPCConnection::createSystem() { - mConnection.createSystem(); + mClient.reset(new ipc::Client(mDispatcher.getPoll(), HOST_IPC_SOCKET)); + mClient->start(); } -void HostIPCConnection::callGetZoneIds(vasum::api::ZoneIds& argOut) +void HostIPCConnection::create(const std::string& address) { - mConnection.call(vasum::api::host::METHOD_GET_ZONE_ID_LIST, argOut); + mClient.reset(new ipc::Client(mDispatcher.getPoll(), address)); + mClient->start(); } -void HostIPCConnection::callGetActiveZoneId(vasum::api::ZoneId& argOut) +void HostIPCConnection::callGetZoneIds(api::ZoneIds& argOut) { - mConnection.call(vasum::api::host::METHOD_GET_ACTIVE_ZONE_ID, argOut); + api::Void argVoid; + call(api::METHOD_GET_ZONE_ID_LIST, argVoid, argOut); } -void HostIPCConnection::callSetActiveZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callGetActiveZoneId(api::ZoneId& argOut) { - mConnection.call(vasum::api::host::METHOD_SET_ACTIVE_ZONE, argIn); + api::Void argVoid; + call(api::METHOD_GET_ACTIVE_ZONE_ID, argVoid, argOut); } -void HostIPCConnection::callGetZoneInfo(const vasum::api::ZoneId& argIn, vasum::api::ZoneInfoOut& argOut) +void HostIPCConnection::callSetActiveZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_GET_ZONE_INFO, argIn, argOut); + mClient->callSync( + api::METHOD_SET_ACTIVE_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callSetNetdevAttrs(const vasum::api::SetNetDevAttrsIn& argIn) +void HostIPCConnection::callGetZoneInfo(const api::ZoneId& argIn, api::ZoneInfoOut& argOut) { - mConnection.call(vasum::api::host::METHOD_SET_NETDEV_ATTRS, argIn); + argOut = *mClient->callSync( + api::METHOD_GET_ZONE_INFO, + std::make_shared(argIn)); } -void HostIPCConnection::callGetNetdevAttrs(const vasum::api::GetNetDevAttrsIn& argIn, vasum::api::GetNetDevAttrs& argOut) +void HostIPCConnection::callSetNetdevAttrs(const api::SetNetDevAttrsIn& argIn) { - mConnection.call(vasum::api::host::METHOD_GET_NETDEV_ATTRS, argIn, argOut); + mClient->callSync( + api::METHOD_SET_NETDEV_ATTRS, + std::make_shared(argIn)); + + api::Void argVoid; + call(api::METHOD_SET_NETDEV_ATTRS, argIn, argVoid); +} + +void HostIPCConnection::callGetNetdevAttrs(const api::GetNetDevAttrsIn& argIn, api::GetNetDevAttrs& argOut) +{ + argOut = *mClient->callSync( + api::METHOD_GET_NETDEV_ATTRS, + std::make_shared(argIn)); } -void HostIPCConnection::callGetNetdevList(const vasum::api::ZoneId& argIn, vasum::api::NetDevList& argOut) +void HostIPCConnection::callGetNetdevList(const api::ZoneId& argIn, api::NetDevList& argOut) { - mConnection.call(vasum::api::host::METHOD_GET_NETDEV_LIST, argIn, argOut); + argOut = *mClient->callSync( + api::METHOD_GET_NETDEV_LIST, + std::make_shared(argIn)); } -void HostIPCConnection::callCreateNetdevVeth(const vasum::api::CreateNetDevVethIn& argIn) +void HostIPCConnection::callCreateNetdevVeth(const api::CreateNetDevVethIn& argIn) { - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_VETH, argIn); + mClient->callSync( + api::METHOD_CREATE_NETDEV_VETH, + std::make_shared(argIn)); } -void HostIPCConnection::callCreateNetdevMacvlan(const vasum::api::CreateNetDevMacvlanIn& argIn) +void HostIPCConnection::callCreateNetdevMacvlan(const api::CreateNetDevMacvlanIn& argIn) { - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_MACVLAN, argIn); + mClient->callSync( + api::METHOD_CREATE_NETDEV_MACVLAN, + std::make_shared(argIn)); } -void HostIPCConnection::callCreateNetdevPhys(const vasum::api::CreateNetDevPhysIn& argIn) +void HostIPCConnection::callCreateNetdevPhys(const api::CreateNetDevPhysIn& argIn) { - mConnection.call(vasum::api::host::METHOD_CREATE_NETDEV_PHYS, argIn); + mClient->callSync( + api::METHOD_CREATE_NETDEV_PHYS, + std::make_shared(argIn)); } -void HostIPCConnection::callDestroyNetdev(const vasum::api::DestroyNetDevIn& argIn) +void HostIPCConnection::callDestroyNetdev(const api::DestroyNetDevIn& argIn) { - mConnection.call(vasum::api::host::METHOD_DESTROY_NETDEV, argIn); + mClient->callSync( + api::METHOD_DESTROY_NETDEV, + std::make_shared(argIn)); } -void HostIPCConnection::callDeleteNetdevIpAddress(const vasum::api::DeleteNetdevIpAddressIn& argIn) +void HostIPCConnection::callDeleteNetdevIpAddress(const api::DeleteNetdevIpAddressIn& argIn) { - mConnection.call(vasum::api::host::METHOD_DELETE_NETDEV_IP_ADDRESS, argIn); + mClient->callSync( + api::METHOD_DELETE_NETDEV_IP_ADDRESS, + std::make_shared(argIn)); } -void HostIPCConnection::callDeclareFile(const vasum::api::DeclareFileIn& argIn, vasum::api::Declaration& argOut) +void HostIPCConnection::callDeclareFile(const api::DeclareFileIn& argIn, api::Declaration& argOut) { - mConnection.call(vasum::api::host::METHOD_DECLARE_FILE, argIn, argOut); + argOut = *mClient->callSync( + api::METHOD_DECLARE_FILE, + std::make_shared(argIn)); } -void HostIPCConnection::callDeclareMount(const vasum::api::DeclareMountIn& argIn, vasum::api::Declaration& argOut) +void HostIPCConnection::callDeclareMount(const api::DeclareMountIn& argIn, api::Declaration& argOut) { - mConnection.call(vasum::api::host::METHOD_DECLARE_MOUNT, argIn, argOut); + argOut = *mClient->callSync( + api::METHOD_DECLARE_MOUNT, + std::make_shared(argIn)); } -void HostIPCConnection::callDeclareLink(const vasum::api::DeclareLinkIn& argIn, vasum::api::Declaration& argOut) +void HostIPCConnection::callDeclareLink(const api::DeclareLinkIn& argIn, api::Declaration& argOut) { - mConnection.call(vasum::api::host::METHOD_DECLARE_LINK, argIn, argOut); + argOut = *mClient->callSync( + api::METHOD_DECLARE_LINK, + std::make_shared(argIn)); } -void HostIPCConnection::callGetDeclarations(const vasum::api::ZoneId& argIn, vasum::api::Declarations& argOut) +void HostIPCConnection::callGetDeclarations(const api::ZoneId& argIn, api::Declarations& argOut) { - mConnection.call(vasum::api::host::METHOD_GET_DECLARATIONS, argIn, argOut); + argOut = *mClient->callSync( + api::METHOD_GET_DECLARATIONS, + std::make_shared(argIn)); } -void HostIPCConnection::callRemoveDeclaration(const vasum::api::RemoveDeclarationIn& argIn) +void HostIPCConnection::callRemoveDeclaration(const api::RemoveDeclarationIn& argIn) { - mConnection.call(vasum::api::host::METHOD_REMOVE_DECLARATION, argIn); + mClient->callSync( + api::METHOD_REMOVE_DECLARATION, + std::make_shared(argIn)); } -void HostIPCConnection::callCreateZone(const vasum::api::CreateZoneIn& argIn) +void HostIPCConnection::callCreateZone(const api::CreateZoneIn& argIn) { - mConnection.call(vasum::api::host::METHOD_CREATE_ZONE, argIn); + mClient->callSync( + api::METHOD_CREATE_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callDestroyZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callDestroyZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_DESTROY_ZONE, argIn); + mClient->callSync( + api::METHOD_DESTROY_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callShutdownZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callShutdownZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_SHUTDOWN_ZONE, argIn); + mClient->callSync( + api::METHOD_SHUTDOWN_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callStartZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callStartZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_START_ZONE, argIn); + mClient->callSync( + api::METHOD_START_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callLockZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callLockZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_LOCK_ZONE, argIn); + mClient->callSync( + api::METHOD_LOCK_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callUnlockZone(const vasum::api::ZoneId& argIn) +void HostIPCConnection::callUnlockZone(const api::ZoneId& argIn) { - mConnection.call(vasum::api::host::METHOD_UNLOCK_ZONE, argIn); + mClient->callSync( + api::METHOD_UNLOCK_ZONE, + std::make_shared(argIn)); } -void HostIPCConnection::callGrantDevice(const vasum::api::GrantDeviceIn& argIn) +void HostIPCConnection::callGrantDevice(const api::GrantDeviceIn& argIn) { - mConnection.call(vasum::api::host::METHOD_GRANT_DEVICE, argIn); + mClient->callSync( + api::METHOD_GRANT_DEVICE, + std::make_shared(argIn)); } -void HostIPCConnection::callRevokeDevice(const vasum::api::RevokeDeviceIn& argIn) +void HostIPCConnection::callRevokeDevice(const api::RevokeDeviceIn& argIn) { - mConnection.call(vasum::api::host::METHOD_REVOKE_DEVICE, argIn); + mClient->callSync( + api::METHOD_REVOKE_DEVICE, + std::make_shared(argIn)); } -void HostIPCConnection::callGetZoneConnections(vasum::api::Connections& argOut) +void HostIPCConnection::callNotifyActiveZone(const api::NotifActiveZoneIn& argIn) { - mConnection.call(vasum::api::host::METHOD_GET_ZONE_CONNECTIONS, argOut); + mClient->callSync( + api::METHOD_NOTIFY_ACTIVE_ZONE, + std::make_shared(argIn)); +} + +void HostIPCConnection::callFileMoveRequest(const api::FileMoveRequestIn& argIn, + api::FileMoveRequestStatus& argOut) +{ + argOut = *mClient->callSync( + api::METHOD_FILE_MOVE_REQUEST, + std::make_shared(argIn)); +} + +void HostIPCConnection::signalSwitchToDefault() +{ + + mClient->signal(api::SIGNAL_SWITCH_TO_DEFAULT, + std::make_shared()); } HostIPCConnection::SubscriptionId -HostIPCConnection::subscribeZoneConnectionState(const ZoneConnectionStateCallback& callback) +HostIPCConnection::subscribeNotification(const NotificationCallback& callback) { - mConnection.subscribe( - vasum::api::host::SIGNAL_ZONE_CONNECTION_STATE, callback); - return vasum::api::host::SIGNAL_ZONE_CONNECTION_STATE; + auto callbackWrapper = [callback] (const ipc::PeerID, + std::shared_ptr& data) { + callback(*data); + }; + mClient->setSignalHandler(api::SIGNAL_NOTIFICATION, callbackWrapper); + return api::SIGNAL_NOTIFICATION; } void HostIPCConnection::unsubscribe(const SubscriptionId& id) { - mConnection.unsubscribe(id); + mClient->removeMethod(id); } } // namespace client diff --git a/client/host-ipc-connection.hpp b/client/host-ipc-connection.hpp index 216e976..8fa6e06 100644 --- a/client/host-ipc-connection.hpp +++ b/client/host-ipc-connection.hpp @@ -26,8 +26,11 @@ #ifndef VASUM_CLIENT_HOST_IPC_CONNECTION_HPP #define VASUM_CLIENT_HOST_IPC_CONNECTION_HPP -#include "ipc-connection.hpp" #include +#include +#include + +#include namespace vasum { namespace client { @@ -38,8 +41,9 @@ namespace client { class HostIPCConnection { public: typedef unsigned int SubscriptionId; - typedef std::function ZoneConnectionStateCallback; + typedef std::function NotificationCallback; void createSystem(); + void create(const std::string& address); void callGetZoneIds(vasum::api::ZoneIds& argOut); void callGetActiveZoneId(vasum::api::ZoneId& argOut); @@ -67,11 +71,22 @@ public: void callGrantDevice(const vasum::api::GrantDeviceIn& argIn); void callRevokeDevice(const vasum::api::RevokeDeviceIn& argIn); void callGetZoneConnections(vasum::api::Connections& argOut); - SubscriptionId subscribeZoneConnectionState(const ZoneConnectionStateCallback& callback); + void callNotifyActiveZone(const vasum::api::NotifActiveZoneIn& argIn); + void callFileMoveRequest(const vasum::api::FileMoveRequestIn& argIn, + vasum::api::FileMoveRequestStatus& argOut); + void signalSwitchToDefault(); + SubscriptionId subscribeNotification(const NotificationCallback& callback); void unsubscribe(const SubscriptionId& id); private: - IPCConnection mConnection; + epoll::ThreadDispatcher mDispatcher; + std::unique_ptr mClient; + + template + void call(const ipc::MethodID method, const ArgIn& argIn, ArgOut& argOut, int timeout = 5000) { + auto out = mClient->callSync(method, std::make_shared(argIn), timeout); + argOut = *out; + } }; } // namespace client diff --git a/client/ipc-connection.cpp b/client/ipc-connection.cpp deleted file mode 100644 index 04954bc..0000000 --- a/client/ipc-connection.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief IPCConnection class - */ - -#include -#include "ipc-connection.hpp" - -namespace { - -const std::string SOCKET_PATH = HOST_IPC_SOCKET; - -} // namespace - -vasum::client::IPCConnection::IPCConnection() -{ -} - -vasum::client::IPCConnection::~IPCConnection() -{ -} - -void vasum::client::IPCConnection::createSystem() -{ - mClient.reset(new ipc::Client(mDispatcher.getPoll(), SOCKET_PATH)); - mClient->start(); -} diff --git a/client/ipc-connection.hpp b/client/ipc-connection.hpp deleted file mode 100644 index 1cb4d10..0000000 --- a/client/ipc-connection.hpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief IPCConnection class - */ - -#ifndef VASUM_CLIENT_IPC_CONNECTION_HPP -#define VASUM_CLIENT_IPC_CONNECTION_HPP - -#include -#include -#include -#include -#include -#include - -namespace vasum { -namespace client { - -/** - * IPCConnection class - */ -class IPCConnection { -public: - IPCConnection(); - virtual ~IPCConnection(); - - void createSystem(); - - template - typename std::enable_if::value>::type - call(const ipc::MethodID method, const ArgIn& argIn, ArgOut& argOut, unsigned int timeout = 50000) { - auto out = mClient->callSync(method, std::make_shared(argIn), timeout); - argOut = *out; - } - - template - typename std::enable_if::value>::type - call(const ipc::MethodID method, ArgOut& argOut, unsigned int timeout = 50000) { - vasum::api::Void argIn; - call(method, argIn, argOut, timeout); - } - - template - typename std::enable_if::value>::type - call(const ipc::MethodID method, ArgIn& argIn, unsigned int timeout = 50000) { - vasum::api::Void argOut; - call(method, argIn, argOut, timeout); - } - - template - void subscribe(const ipc::MethodID signal, const Callback& callback) { - auto callbackWrapper = [callback] (const ipc::PeerID, std::shared_ptr& data) { - callback(*data); - }; - mClient->setSignalHandler(signal, callbackWrapper); - } - - void unsubscribe(const ipc::MethodID signal) { - mClient->removeMethod(signal); - } - -private: - epoll::ThreadDispatcher mDispatcher; - std::unique_ptr mClient; -}; - -} // namespace client -} // namespace vasum - -#endif /* VASUM_CLIENT_IPC_CONNECTION_HPP */ diff --git a/client/vasum-client-impl.cpp b/client/vasum-client-impl.cpp index 49b5846..8866e5f 100644 --- a/client/vasum-client-impl.cpp +++ b/client/vasum-client-impl.cpp @@ -27,14 +27,7 @@ #include "vasum-client-impl.hpp" #include "utils.hpp" #include "exception.hpp" -#include "host-dbus-connection.hpp" #include "host-ipc-connection.hpp" -#include "zone-dbus-connection.hpp" -#include - -#include -#include -#include #include #include @@ -52,8 +45,6 @@ using namespace vasum; namespace { -unique_ptr gGlibLoop; - VsmZoneState getZoneState(const char* state) { if (strcmp(state, "STOPPED") == 0) { @@ -90,16 +81,6 @@ void convert(const api::VectorOfStrings& in, VsmArrayString& out) } } -void convert(const api::VectorOfStringPairs& in, VsmArrayString& keys, VsmArrayString& values) -{ - keys = reinterpret_cast(calloc(in.values.size() + 1, sizeof(char*))); - values = reinterpret_cast(calloc(in.values.size() + 1, sizeof(char*))); - for (size_t i = 0; i < in.values.size(); ++i) { - keys[i] = ::strdup(in.values[i].first.c_str()); - values[i] = ::strdup(in.values[i].second.c_str()); - } -} - void convert(const api::ZoneInfoOut& info, VsmZone& zone) { VsmZone vsmZone = reinterpret_cast(malloc(sizeof(*vsmZone))); @@ -145,23 +126,13 @@ bool readFirstLineOfFile(const string& path, string& ret) VsmStatus Client::vsm_start_glib_loop() noexcept { - try { - if (!gGlibLoop) { - gGlibLoop.reset(new utils::ScopedGlibLoop()); - } - } catch (const exception&) { - return VSMCLIENT_OTHER_ERROR; - } + // TPDP: Remove vsm_start_glib_loop from API return VSMCLIENT_SUCCESS; } VsmStatus Client::vsm_stop_glib_loop() noexcept { - try { - gGlibLoop.reset(); - } catch (const exception&) { - return VSMCLIENT_OTHER_ERROR; - } + // TPDP: Remove vsm_stop_glib_loop from API return VSMCLIENT_SUCCESS; } @@ -198,16 +169,10 @@ VsmStatus Client::coverException(const function& worker) noexcept mStatus = Status(VSMCLIENT_OTHER_ERROR, ex.what()); } catch (const vasum::ClientException& ex) { mStatus = Status(VSMCLIENT_CUSTOM_ERROR, ex.what()); - } catch (const dbus::DbusCustomException& ex) { + } catch (const ipc::IPCUserException& ex) { mStatus = Status(VSMCLIENT_CUSTOM_ERROR, ex.what()); - } catch (const dbus::DbusIOException& ex) { + } catch (const ipc::IPCException& ex) { mStatus = Status(VSMCLIENT_IO_ERROR, ex.what()); - } catch (const dbus::DbusOperationException& ex) { - mStatus = Status(VSMCLIENT_OPERATION_FAILED, ex.what()); - } catch (const dbus::DbusInvalidArgumentException& ex) { - mStatus = Status(VSMCLIENT_INVALID_ARGUMENT, ex.what()); - } catch (const dbus::DbusException& ex) { - mStatus = Status(VSMCLIENT_OTHER_ERROR, ex.what()); } catch (const exception& ex) { mStatus = Status(VSMCLIENT_CUSTOM_ERROR, ex.what()); } @@ -217,28 +182,14 @@ VsmStatus Client::coverException(const function& worker) noexcept VsmStatus Client::createSystem() noexcept { return coverException([&] { - shared_ptr connection(dbus::DbusConnection::createSystem().release()); - -#ifdef DBUS_CONNECTION - mHostClient.create(connection); -#else mHostClient.createSystem(); -#endif - mZoneClient.create(connection); }); } VsmStatus Client::create(const string& address) noexcept { return coverException([&] { - shared_ptr connection(dbus::DbusConnection::create(address).release()); - -#ifdef DBUS_CONNECTION - mHostClient.create(connection); -#else - mHostClient.createSystem(); -#endif - mZoneClient.create(connection); + mHostClient.create(address); }); } @@ -252,15 +203,11 @@ VsmStatus Client::vsm_get_status() const noexcept return mStatus.mVsmStatus; } -VsmStatus Client::vsm_get_zone_dbuses(VsmArrayString* keys, VsmArrayString* values) noexcept +VsmStatus Client::vsm_get_zone_dbuses(VsmArrayString* /*keys*/, VsmArrayString* /*values*/) noexcept { - assert(keys); - assert(values); - return coverException([&] { - api::Connections dbuses; - mHostClient.callGetZoneConnections(dbuses); - convert(dbuses, *keys, *values); + //TODO: Remove vsm_get_zone_dbuses from API + throw OperationFailedException("Not implemented"); }); } @@ -322,6 +269,7 @@ VsmStatus Client::vsm_lookup_zone_by_id(const char* id, VsmZone* zone) noexcept VsmStatus Client::vsm_lookup_zone_by_terminal_id(int, VsmString*) noexcept { return coverException([&] { + //TODO: Implement vsm_lookup_zone_by_terminal_id throw OperationFailedException("Not implemented"); }); } @@ -390,25 +338,13 @@ VsmStatus Client::vsm_unlock_zone(const char* id) noexcept }); } -VsmStatus Client::vsm_add_state_callback(VsmZoneDbusStateCallback zoneDbusStateCallback, - void* data, - VsmSubscriptionId* subscriptionId) noexcept +VsmStatus Client::vsm_add_state_callback(VsmZoneDbusStateCallback /* zoneDbusStateCallback */, + void* /* data */, + VsmSubscriptionId* /* subscriptionId */) noexcept { - assert(zoneDbusStateCallback); - return coverException([&] { - auto onSigal = [=](const api::ConnectionState& dbus) - { - zoneDbusStateCallback(dbus.first.c_str(), - dbus.second.c_str(), - data); - }; - - VsmSubscriptionId id; - id = mHostClient.subscribeZoneConnectionState(onSigal); - if (subscriptionId) { - *subscriptionId = id; - } + //TODO: Implement vsm_add_state_callback + throw OperationFailedException("Not implemented"); }); } @@ -758,57 +694,36 @@ VsmStatus Client::vsm_remove_declaration(const char* id, VsmString declaration) }); } -VsmStatus Client::vsm_notify_active_zone(const char* application, const char* message) noexcept +VsmStatus Client::vsm_notify_active_zone(const char* /*application*/, const char* /*message*/) noexcept { - assert(application); - assert(message); - return coverException([&] { - mZoneClient.callNotifyActiveZone({ application, message }); + //TODO: Implement vsm_notify_active_zone + throw OperationFailedException("Not implemented"); }); } -VsmStatus Client::vsm_file_move_request(const char* destZone, const char* path) noexcept +VsmStatus Client::vsm_file_move_request(const char* /*destZone*/, const char* /*path*/) noexcept { - assert(destZone); - assert(path); - return coverException([&] { - api::FileMoveRequestStatus status; - mZoneClient.callFileMoveRequest({ destZone, path }, status); - if (status.value != api::zone::FILE_MOVE_SUCCEEDED) { - throw ClientException(status.value); - } + //TODO: Implement vsm_file_move_request + throw OperationFailedException("Not implemented"); }); } -VsmStatus Client::vsm_add_notification_callback(VsmNotificationCallback notificationCallback, - void* data, - VsmSubscriptionId* subscriptionId) noexcept +VsmStatus Client::vsm_add_notification_callback(VsmNotificationCallback /*notificationCallback*/, + void* /*data*/, + VsmSubscriptionId* /*subscriptionId*/) noexcept { - assert(notificationCallback); - return coverException([&] { - auto onSignal = [=](const api::Notification& notification) - { - notificationCallback(notification.zone.c_str(), - notification.application.c_str(), - notification.message.c_str(), - data); - }; - - VsmSubscriptionId id; - id = mZoneClient.subscribeNotification(onSignal); - if (subscriptionId) { - *subscriptionId = id; - } + //TODO: Implement vsm_add_notification_callback + throw OperationFailedException("Not implemented"); }); } VsmStatus Client::vsm_del_notification_callback(VsmSubscriptionId subscriptionId) noexcept { return coverException([&] { - mZoneClient.unsubscribe(subscriptionId); + mHostClient.unsubscribe(subscriptionId); }); } diff --git a/client/vasum-client-impl.hpp b/client/vasum-client-impl.hpp index 9e8118c..3f3b13a 100644 --- a/client/vasum-client-impl.hpp +++ b/client/vasum-client-impl.hpp @@ -27,12 +27,7 @@ #define VASUM_CLIENT_IMPL_HPP #include "vasum-client.h" -#ifdef DBUS_CONNECTION -#include "host-dbus-connection.hpp" -#else #include "host-ipc-connection.hpp" -#endif -#include "zone-dbus-connection.hpp" #include #include @@ -324,12 +319,7 @@ public: */ static VsmStatus vsm_stop_glib_loop() noexcept; private: -#ifdef DBUS_CONNECTION - typedef vasum::client::HostDbusConnection HostConnection; -#else typedef vasum::client::HostIPCConnection HostConnection; -#endif - typedef vasum::client::ZoneDbusConnection ZoneConnection; struct Status { Status(); Status(VsmStatus status, const std::string& msg = ""); @@ -340,7 +330,6 @@ private: Status mStatus; HostConnection mHostClient; - ZoneConnection mZoneClient; VsmStatus coverException(const std::function& worker) noexcept; VsmStatus vsm_netdev_get_ip_addr(const char* zone, diff --git a/client/zone-dbus-connection.cpp b/client/zone-dbus-connection.cpp deleted file mode 100644 index b7f82a8..0000000 --- a/client/zone-dbus-connection.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief Zone client class - */ - -#include -#include "zone-dbus-connection.hpp" -#include -#include - -namespace vasum { -namespace client { - -ZoneDbusConnection::ZoneDbusConnection() - : mConnection(vasum::api::zone::DEFINITION, - vasum::api::zone::BUS_NAME, - vasum::api::zone::OBJECT_PATH, - vasum::api::zone::INTERFACE) -{ -} - -void ZoneDbusConnection::create(const std::shared_ptr& connection) -{ - mConnection.create(connection); -} - -void ZoneDbusConnection::callNotifyActiveZone(const vasum::api::NotifActiveZoneIn& argIn) -{ - mConnection.call(vasum::api::zone::METHOD_NOTIFY_ACTIVE_ZONE, argIn); -} - -void ZoneDbusConnection::callFileMoveRequest(const vasum::api::FileMoveRequestIn& argIn, - vasum::api::FileMoveRequestStatus& argOut) -{ - mConnection.call(vasum::api::zone::METHOD_FILE_MOVE_REQUEST, argIn, argOut); -} - -ZoneDbusConnection::SubscriptionId -ZoneDbusConnection::subscribeNotification(const NotificationCallback& callback) -{ - return mConnection.signalSubscribe( - vasum::api::zone::SIGNAL_NOTIFICATION, callback); -} - -void ZoneDbusConnection::unsubscribe(const SubscriptionId& id ) -{ - mConnection.signalUnsubscribe(id); -} - -} // namespace client -} // namespace vasum diff --git a/client/zone-dbus-connection.hpp b/client/zone-dbus-connection.hpp deleted file mode 100644 index 576b4cb..0000000 --- a/client/zone-dbus-connection.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Mateusz Malicki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief Zone client class - */ - -#ifndef VASUM_CLIENT_ZONE_DBUS_CONNECTION_HPP -#define VASUM_CLIENT_ZONE_DBUS_CONNECTION_HPP - -#include "dbus-connection.hpp" -#include - -namespace vasum { -namespace client { - -/** - * vasum's client definition. - * - * ZoneDbusConnection is used for communication with the vasum's server from zone through dbus - */ -class ZoneDbusConnection { -public: - typedef unsigned int SubscriptionId; - typedef std::function NotificationCallback; - - ZoneDbusConnection(); - void create(const std::shared_ptr& connection); - - void callNotifyActiveZone(const vasum::api::NotifActiveZoneIn& argIn); - void callFileMoveRequest(const vasum::api::FileMoveRequestIn& argIn, - vasum::api::FileMoveRequestStatus& argOut); - SubscriptionId subscribeNotification(const NotificationCallback& callback); - void unsubscribe(const SubscriptionId& id); -private: - DbusConnection mConnection; -}; - -} // namespace client -} // namespace vasum - -#endif /* VASUM_CLIENT_ZONE_DBUS_CONNECTION_HPP */ diff --git a/server/common-dbus-definitions.hpp b/server/common-definitions.hpp similarity index 52% rename from server/common-dbus-definitions.hpp rename to server/common-definitions.hpp index 178f363..5e85f92 100644 --- a/server/common-dbus-definitions.hpp +++ b/server/common-definitions.hpp @@ -19,27 +19,33 @@ /** * @file * @author Jan Olszak (j.olszak@samsung.com) - * @brief Common dbus api definitions + * @brief Common (dbus, IPC) api definitions */ -#ifndef SERVER_COMMON_DBUS_DEFINITIONS_HPP -#define SERVER_COMMON_DBUS_DEFINITIONS_HPP +#ifndef SERVER_COMMON_DEFINITIONS_HPP +#define SERVER_COMMON_DEFINITIONS_HPP #include namespace vasum { namespace api { -const std::string ERROR_FORBIDDEN = "org.tizen.vasum.Error.Forbidden"; -const std::string ERROR_FORWARDED = "org.tizen.vasum.Error.Forwarded"; -const std::string ERROR_INVALID_ID = "org.tizen.vasum.Error.InvalidId"; -const std::string ERROR_INVALID_STATE = "org.tizen.vasum.Error.InvalidState"; -const std::string ERROR_INTERNAL = "org.tizen.vasum.Error.Internal"; -const std::string METHOD_PROXY_CALL = "ProxyCall"; +/** + * Error codes that can be set in API handlers + */ +//TODO: Errors should use exception handling mechanism +///@{ +const std::string ERROR_FORBIDDEN = "org.tizen.vasum.Error.Forbidden"; +const std::string ERROR_FORWARDED = "org.tizen.vasum.Error.Forwarded"; +const std::string ERROR_INVALID_ID = "org.tizen.vasum.Error.InvalidId"; +const std::string ERROR_INVALID_STATE = "org.tizen.vasum.Error.InvalidState"; +const std::string ERROR_INTERNAL = "org.tizen.vasum.Error.Internal"; +const std::string ERROR_ZONE_NOT_RUNNING = "org.tizen.vasum.Error.ZonesNotRunning"; +///@} } // namespace api } // namespace vasum -#endif // SERVER_COMMON_DBUS_DEFINITIONS_HPP +#endif // SERVER_COMMON_DEFINITIONS_HPP diff --git a/server/configs/lxc-templates/template.sh b/server/configs/lxc-templates/template.sh index e7d5533..82cd0f9 100755 --- a/server/configs/lxc-templates/template.sh +++ b/server/configs/lxc-templates/template.sh @@ -40,7 +40,6 @@ lxc.pts = 256 lxc.tty = 0 lxc.mount.auto = proc sys cgroup -lxc.mount.entry = /var/run/zones/${name}/run var/run none rw,bind 0 0 # create a separate network per zone # - it forbids traffic sniffing (like macvlan in bridge mode) diff --git a/server/configs/templates/default.conf b/server/configs/templates/default.conf index 3a99d20..ce88c6e 100644 --- a/server/configs/templates/default.conf +++ b/server/configs/templates/default.conf @@ -10,7 +10,6 @@ "vt" : 0, "shutdownTimeout" : 10, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "runMountPoint" : "~NAME~/run", "provisions" : [], "permittedToSend" : [ "/tmp/.*" ], diff --git a/server/host-dbus-connection.cpp b/server/host-dbus-connection.cpp index 76f5bb8..b93ad21 100644 --- a/server/host-dbus-connection.cpp +++ b/server/host-dbus-connection.cpp @@ -53,27 +53,31 @@ HostDbusConnection::HostDbusConnection() mDbusConnection = dbus::DbusConnection::createSystem(); LOGT("Setting DBUS name"); - mDbusConnection->setName(api::host::BUS_NAME, + mDbusConnection->setName(api::BUS_NAME, std::bind(&HostDbusConnection::onNameAcquired, this), std::bind(&HostDbusConnection::onNameLost, this)); if (!waitForName(NAME_ACQUIRED_TIMEOUT)) { - LOGE("Could not acquire dbus name: " << api::host::BUS_NAME); - throw HostConnectionException("Could not acquire dbus name: " + api::host::BUS_NAME); + LOGE("Could not acquire dbus name: " << api::BUS_NAME); + throw HostConnectionException("Could not acquire dbus name: " + api::BUS_NAME); } LOGT("Registering DBUS interface"); using namespace std::placeholders; - mDbusConnection->registerObject(api::host::OBJECT_PATH, - api::host::DEFINITION, + mDbusConnection->registerObject(api::OBJECT_PATH, + api::DEFINITION, std::bind(&HostDbusConnection::onMessageCall, - this, _1, _2, _3, _4, _5)); + this, _1, _2, _3, _4, _5)); + mSubscriptionId = mDbusConnection->signalSubscribe(std::bind(&HostDbusConnection::onSignalCall, + this, _1, _2, _3, _4, _5), + std::string()); LOGD("Connected"); } HostDbusConnection::~HostDbusConnection() { + mDbusConnection->signalUnsubscribe(mSubscriptionId); } bool HostDbusConnection::waitForName(const unsigned int timeoutMs) @@ -242,6 +246,20 @@ void HostDbusConnection::setRevokeDeviceCallback(const RevokeDeviceCallback& cal mRevokeDeviceCallback = callback; } +void HostDbusConnection::setNotifyActiveZoneCallback(const NotifyActiveZoneCallback& callback) +{ + mNotifyActiveZoneCallback = callback; +} + +void HostDbusConnection::setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback) +{ + mSwitchToDefaultCallback = callback; +} + +void HostDbusConnection::setFileMoveCallback(const FileMoveCallback& callback) +{ + mFileMoveCallback = callback; +} void HostDbusConnection::onMessageCall(const std::string& objectPath, const std::string& interface, @@ -249,11 +267,11 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, GVariant* parameters, dbus::MethodResultBuilder::Pointer result) { - if (objectPath != api::host::OBJECT_PATH || interface != api::host::INTERFACE) { + if (objectPath != api::OBJECT_PATH || interface != api::INTERFACE) { return; } - if (methodName == api::host::METHOD_SET_ACTIVE_ZONE) { + if (methodName == api::METHOD_SET_ACTIVE_ZONE) { api::ZoneId zoneId; config::loadFromGVariant(parameters, zoneId); @@ -264,14 +282,6 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_ZONE_CONNECTIONS) { - if (mGetZoneConnectionsCallback) { - auto rb = std::make_shared>(result); - mGetZoneConnectionsCallback(rb); - } - return; - } - if (methodName == api::METHOD_PROXY_CALL) { const gchar* target = NULL; const gchar* targetBusName = NULL; @@ -301,7 +311,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_ZONE_ID_LIST) { + if (methodName == api::METHOD_GET_ZONE_ID_LIST) { if (mGetZoneIdsCallback) { auto rb = std::make_shared>(result); mGetZoneIdsCallback(rb); @@ -309,7 +319,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_ACTIVE_ZONE_ID) { + if (methodName == api::METHOD_GET_ACTIVE_ZONE_ID) { if (mGetActiveZoneIdCallback) { auto rb = std::make_shared>(result); mGetActiveZoneIdCallback(rb); @@ -317,7 +327,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_ZONE_INFO) { + if (methodName == api::METHOD_GET_ZONE_INFO) { api::ZoneId zoneId; config::loadFromGVariant(parameters, zoneId); @@ -328,7 +338,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_SET_NETDEV_ATTRS) { + if (methodName == api::METHOD_SET_NETDEV_ATTRS) { api::SetNetDevAttrsIn data; config::loadFromGVariant(parameters, data); @@ -339,7 +349,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_NETDEV_ATTRS) { + if (methodName == api::METHOD_GET_NETDEV_ATTRS) { api::GetNetDevAttrsIn data; config::loadFromGVariant(parameters, data); @@ -350,7 +360,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_NETDEV_LIST) { + if (methodName == api::METHOD_GET_NETDEV_LIST) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -361,7 +371,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_CREATE_NETDEV_VETH) { + if (methodName == api::METHOD_CREATE_NETDEV_VETH) { api::CreateNetDevVethIn data; config::loadFromGVariant(parameters, data); @@ -372,7 +382,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_CREATE_NETDEV_MACVLAN) { + if (methodName == api::METHOD_CREATE_NETDEV_MACVLAN) { api::CreateNetDevMacvlanIn data; config::loadFromGVariant(parameters, data); @@ -382,7 +392,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_CREATE_NETDEV_PHYS) { + if (methodName == api::METHOD_CREATE_NETDEV_PHYS) { api::CreateNetDevPhysIn data; config::loadFromGVariant(parameters, data); @@ -392,7 +402,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_DESTROY_NETDEV) { + if (methodName == api::METHOD_DESTROY_NETDEV) { api::DestroyNetDevIn data; config::loadFromGVariant(parameters, data); @@ -402,7 +412,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_DELETE_NETDEV_IP_ADDRESS) { + if (methodName == api::METHOD_DELETE_NETDEV_IP_ADDRESS) { api::DeleteNetdevIpAddressIn data; config::loadFromGVariant(parameters, data); if (mDeleteNetdevIpAddressCallback) { @@ -411,7 +421,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_DECLARE_FILE) { + if (methodName == api::METHOD_DECLARE_FILE) { api::DeclareFileIn data; config::loadFromGVariant(parameters, data); @@ -422,7 +432,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_DECLARE_MOUNT) { + if (methodName == api::METHOD_DECLARE_MOUNT) { api::DeclareMountIn data; config::loadFromGVariant(parameters, data); @@ -433,7 +443,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_DECLARE_LINK) { + if (methodName == api::METHOD_DECLARE_LINK) { api::DeclareLinkIn data; config::loadFromGVariant(parameters, data); @@ -444,7 +454,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GET_DECLARATIONS) { + if (methodName == api::METHOD_GET_DECLARATIONS) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -455,7 +465,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_REMOVE_DECLARATION) { + if (methodName == api::METHOD_REMOVE_DECLARATION) { api::RemoveDeclarationIn data; config::loadFromGVariant(parameters, data); @@ -466,7 +476,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_CREATE_ZONE) { + if (methodName == api::METHOD_CREATE_ZONE) { api::CreateZoneIn data; config::loadFromGVariant(parameters, data); @@ -477,7 +487,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_DESTROY_ZONE) { + if (methodName == api::METHOD_DESTROY_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -488,7 +498,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_SHUTDOWN_ZONE) { + if (methodName == api::METHOD_SHUTDOWN_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -498,7 +508,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_START_ZONE) { + if (methodName == api::METHOD_START_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -508,7 +518,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::host::METHOD_LOCK_ZONE) { + if (methodName == api::METHOD_LOCK_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -519,7 +529,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_UNLOCK_ZONE) { + if (methodName == api::METHOD_UNLOCK_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -530,7 +540,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_GRANT_DEVICE) { + if (methodName == api::METHOD_GRANT_DEVICE) { api::GrantDeviceIn data; config::loadFromGVariant(parameters, data); @@ -541,7 +551,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::host::METHOD_REVOKE_DEVICE) { + if (methodName == api::METHOD_REVOKE_DEVICE) { api::RevokeDeviceIn data; config::loadFromGVariant(parameters, data); @@ -551,6 +561,43 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } return; } + + if (methodName == api::METHOD_NOTIFY_ACTIVE_ZONE) { + api::NotifActiveZoneIn data; + config::loadFromGVariant(parameters, data); + + if (mNotifyActiveZoneCallback) { + auto rb = std::make_shared>(result); + mNotifyActiveZoneCallback(data, rb); + } + } + + if (methodName == api::METHOD_FILE_MOVE_REQUEST) { + api::FileMoveRequestIn data; + config::loadFromGVariant(parameters, data); + + if (mFileMoveCallback) { + auto rb = std::make_shared>(result); + mFileMoveCallback(data, rb); + } + } +} + +void HostDbusConnection::onSignalCall(const std::string& /* senderBusName */, + const std::string& objectPath, + const std::string& interface, + const std::string& signalName, + GVariant* /* parameters */) +{ + if (objectPath != api::OBJECT_PATH || interface != api::INTERFACE) { + return; + } + + if (signalName == api::SIGNAL_SWITCH_TO_DEFAULT) { + if (mSwitchToDefaultCallback) { + mSwitchToDefaultCallback(); + } + } } void HostDbusConnection::proxyCallAsync(const std::string& busName, @@ -569,14 +616,16 @@ void HostDbusConnection::proxyCallAsync(const std::string& busName, callback); } -void HostDbusConnection::signalZoneConnectionState(const api::ConnectionState& state) +void HostDbusConnection::sendNotification(const api::Notification& notify) { - GVariant* parameters = g_variant_new("(ss)", state.first.c_str(), state.second.c_str()); - mDbusConnection->emitSignal(api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::SIGNAL_ZONE_CONNECTION_STATE, + GVariant* parameters = g_variant_new("(sss)", + notify.zone.c_str(), + notify.application.c_str(), + notify.message.c_str()); + mDbusConnection->emitSignal(api::OBJECT_PATH, + api::INTERFACE, + api::SIGNAL_NOTIFICATION, parameters); } - } // namespace vasum diff --git a/server/host-dbus-connection.hpp b/server/host-dbus-connection.hpp index 455437d..cdd8dda 100644 --- a/server/host-dbus-connection.hpp +++ b/server/host-dbus-connection.hpp @@ -131,6 +131,14 @@ public: typedef std::function RevokeDeviceCallback; + typedef std::function NotifyActiveZoneCallback; + typedef std::function FileMoveCallback; + typedef std::function SwitchToDefaultCallback; + /** * Register proxy call callback @@ -273,6 +281,26 @@ public: void setRevokeDeviceCallback(const RevokeDeviceCallback& callback); /** + * Register notification request callback + */ + void setNotifyActiveZoneCallback(const NotifyActiveZoneCallback& callback); + + /** + * Register switch to default request callback + */ + void setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback); + + /* + * Register file move request callback + */ + void setFileMoveCallback(const FileMoveCallback& callback); + + /** + * Send notification signal to this zone + */ + void sendNotification(const api::Notification& notify); + + /** * Make a proxy call */ void proxyCallAsync(const std::string& busName, @@ -288,6 +316,7 @@ private: std::condition_variable mNameCondition; bool mNameAcquired; bool mNameLost; + dbus::DbusConnection::SubscriptionId mSubscriptionId; ProxyCallCallback mProxyCallCallback; GetZoneConnectionsCallback mGetZoneConnectionsCallback; GetZoneIdsCallback mGetZoneIdsCallback; @@ -315,6 +344,9 @@ private: UnlockZoneCallback mUnlockZoneCallback; GrantDeviceCallback mGrantDeviceCallback; RevokeDeviceCallback mRevokeDeviceCallback; + NotifyActiveZoneCallback mNotifyActiveZoneCallback; + SwitchToDefaultCallback mSwitchToDefaultCallback; + FileMoveCallback mFileMoveCallback; void onNameAcquired(); void onNameLost(); @@ -325,6 +357,11 @@ private: const std::string& methodName, GVariant* parameters, dbus::MethodResultBuilder::Pointer result); + void onSignalCall(const std::string& senderBusName, + const std::string& objectPath, + const std::string& interface, + const std::string& signalName, + GVariant* parameters); }; diff --git a/server/host-dbus-definitions.hpp b/server/host-dbus-definitions.hpp index b814c90..208276e 100644 --- a/server/host-dbus-definitions.hpp +++ b/server/host-dbus-definitions.hpp @@ -25,20 +25,16 @@ #ifndef SERVER_HOST_DBUS_DEFINITIONS_HPP #define SERVER_HOST_DBUS_DEFINITIONS_HPP -#include "common-dbus-definitions.hpp" - +#include namespace vasum { namespace api { -namespace host { const std::string BUS_NAME = "org.tizen.vasum.host"; const std::string OBJECT_PATH = "/org/tizen/vasum/host"; const std::string INTERFACE = "org.tizen.vasum.host.manager"; -const std::string ERROR_ZONE_NOT_RUNNING = "org.tizen.vasum.host.Error.ZonesNotRunning"; -const std::string METHOD_GET_ZONE_CONNECTIONS = "GetZoneConnections"; const std::string METHOD_GET_ZONE_ID_LIST = "GetZoneIds"; const std::string METHOD_GET_ACTIVE_ZONE_ID = "GetActiveZoneId"; const std::string METHOD_GET_ZONE_INFO = "GetZoneInfo"; @@ -64,8 +60,19 @@ const std::string METHOD_LOCK_ZONE = "LockZone"; const std::string METHOD_UNLOCK_ZONE = "UnlockZone"; const std::string METHOD_GRANT_DEVICE = "GrantDevice"; const std::string METHOD_REVOKE_DEVICE = "RevokeDevice"; +const std::string METHOD_PROXY_CALL = "ProxyCall"; + +const std::string METHOD_NOTIFY_ACTIVE_ZONE = "NotifyActiveZone"; +const std::string METHOD_FILE_MOVE_REQUEST = "FileMoveRequest"; +const std::string SIGNAL_NOTIFICATION = "Notification"; +const std::string SIGNAL_SWITCH_TO_DEFAULT = "SwitchToDefault"; -const std::string SIGNAL_ZONE_CONNECTION_STATE = "ZoneConnectionState"; +const std::string FILE_MOVE_DESTINATION_NOT_FOUND = "FILE_MOVE_DESTINATION_NOT_FOUND"; +const std::string FILE_MOVE_WRONG_DESTINATION = "FILE_MOVE_WRONG_DESTINATION"; +const std::string FILE_MOVE_NO_PERMISSIONS_SEND = "FILE_MOVE_NO_PERMISSIONS_SEND"; +const std::string FILE_MOVE_NO_PERMISSIONS_RECEIVE = "FILE_MOVE_NO_PERMISSIONS_RECEIVE"; +const std::string FILE_MOVE_FAILED = "FILE_MOVE_FAILED"; +const std::string FILE_MOVE_SUCCEEDED = "FILE_MOVE_SUCCEEDED"; const std::string DEFINITION = @@ -80,9 +87,6 @@ const std::string DEFINITION = " " " " " " - " " - " " - " " " " " " " " @@ -196,14 +200,34 @@ const std::string DEFINITION = " " " " " " - " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " " " - " " + " " + " " + " " + " " " " " " ""; -} // namespace host } // namespace api } // namespace vasum diff --git a/server/host-ipc-connection.cpp b/server/host-ipc-connection.cpp index 817e62f..1bf2e78c 100644 --- a/server/host-ipc-connection.cpp +++ b/server/host-ipc-connection.cpp @@ -31,17 +31,10 @@ namespace vasum { -namespace { - -const std::string SOCKET_PATH = HOST_IPC_SOCKET; - -} // namespace - - HostIPCConnection::HostIPCConnection() { LOGT("Connecting to host IPC socket"); - mService.reset(new ipc::Service(mDispatcher.getPoll(), SOCKET_PATH)); + mService.reset(new ipc::Service(mDispatcher.getPoll(), HOST_IPC_SOCKET)); LOGT("Starting IPC"); mService->start(); @@ -52,221 +45,238 @@ HostIPCConnection::~HostIPCConnection() { } -void HostIPCConnection::setGetZoneConnectionsCallback(const Callback::type& callback) +void HostIPCConnection::setGetZoneIdsCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_ZONE_CONNECTIONS, - Callback::getCallbackWrapper(callback)); + api::METHOD_GET_ZONE_ID_LIST, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetZoneIdsCallback(const Callback::type& callback) +void HostIPCConnection::setGetActiveZoneIdCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_ZONE_ID_LIST, - Callback::getCallbackWrapper(callback)); + api::METHOD_GET_ACTIVE_ZONE_ID, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetActiveZoneIdCallback(const Callback::type& callback) +void HostIPCConnection::setGetZoneInfoCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_ACTIVE_ZONE_ID, - Callback::getCallbackWrapper(callback)); - + api::METHOD_GET_ZONE_INFO, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetZoneInfoCallback(const Callback::type& callback) +void HostIPCConnection::setSetNetdevAttrsCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_ZONE_INFO, - Callback::getCallbackWrapper(callback)); + api::METHOD_SET_NETDEV_ATTRS, + Callback::getWrapper(callback)); } -void HostIPCConnection::setSetNetdevAttrsCallback(const Callback::type& callback) +void HostIPCConnection::setGetNetdevAttrsCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_SET_NETDEV_ATTRS, - Callback::getCallbackWrapper(callback)); + api::METHOD_GET_NETDEV_ATTRS, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetNetdevAttrsCallback(const Callback::type& callback) +void HostIPCConnection::setGetNetdevListCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_NETDEV_ATTRS, - Callback::getCallbackWrapper(callback)); + api::METHOD_GET_NETDEV_LIST, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetNetdevListCallback(const Callback::type& callback) +void HostIPCConnection::setCreateNetdevVethCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_NETDEV_LIST, - Callback::getCallbackWrapper(callback)); + api::METHOD_CREATE_NETDEV_VETH, + Callback::getWrapper(callback)); } -void HostIPCConnection::setCreateNetdevVethCallback(const Callback::type& callback) +void HostIPCConnection::setCreateNetdevMacvlanCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_CREATE_NETDEV_VETH, - Callback::getCallbackWrapper(callback)); + api::METHOD_CREATE_NETDEV_MACVLAN, + Callback::getWrapper(callback)); } -void HostIPCConnection::setCreateNetdevMacvlanCallback(const Callback::type& callback) +void HostIPCConnection::setCreateNetdevPhysCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_CREATE_NETDEV_MACVLAN, - Callback::getCallbackWrapper(callback)); + api::METHOD_CREATE_NETDEV_PHYS, + Callback::getWrapper(callback)); } -void HostIPCConnection::setCreateNetdevPhysCallback(const Callback::type& callback) +void HostIPCConnection::setDestroyNetdevCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_CREATE_NETDEV_PHYS, - Callback::getCallbackWrapper(callback)); + api::METHOD_DESTROY_NETDEV, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDestroyNetdevCallback(const Callback::type& callback) +void HostIPCConnection::setDeleteNetdevIpAddressCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DESTROY_NETDEV, - Callback::getCallbackWrapper(callback)); + api::METHOD_DELETE_NETDEV_IP_ADDRESS, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDeleteNetdevIpAddressCallback(const Callback::type& callback) +void HostIPCConnection::setDeclareFileCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DELETE_NETDEV_IP_ADDRESS, - Callback::getCallbackWrapper(callback)); + api::METHOD_DECLARE_FILE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDeclareFileCallback(const Callback::type& callback) +void HostIPCConnection::setDeclareMountCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DECLARE_FILE, - Callback::getCallbackWrapper(callback)); + api::METHOD_DECLARE_MOUNT, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDeclareMountCallback(const Callback::type& callback) +void HostIPCConnection::setDeclareLinkCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DECLARE_MOUNT, - Callback::getCallbackWrapper(callback)); + api::METHOD_DECLARE_LINK, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDeclareLinkCallback(const Callback::type& callback) +void HostIPCConnection::setGetDeclarationsCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DECLARE_LINK, - Callback::getCallbackWrapper(callback)); + api::METHOD_GET_DECLARATIONS, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGetDeclarationsCallback(const Callback::type& callback) +void HostIPCConnection::setRemoveDeclarationCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GET_DECLARATIONS, - Callback::getCallbackWrapper(callback)); + api::METHOD_REMOVE_DECLARATION, + Callback::getWrapper(callback)); } -void HostIPCConnection::setRemoveDeclarationCallback(const Callback::type& callback) +void HostIPCConnection::setSetActiveZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_REMOVE_DECLARATION, - Callback::getCallbackWrapper(callback)); + api::METHOD_SET_ACTIVE_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setSetActiveZoneCallback(const Callback::type& callback) +void HostIPCConnection::setCreateZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_SET_ACTIVE_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_CREATE_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setCreateZoneCallback(const Callback::type& callback) +void HostIPCConnection::setDestroyZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_CREATE_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_DESTROY_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setDestroyZoneCallback(const Callback::type& callback) +void HostIPCConnection::setShutdownZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_DESTROY_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_SHUTDOWN_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setShutdownZoneCallback(const Callback::type& callback) +void HostIPCConnection::setStartZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_SHUTDOWN_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_START_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setStartZoneCallback(const Callback::type& callback) +void HostIPCConnection::setLockZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_START_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_LOCK_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setLockZoneCallback(const Callback::type& callback) +void HostIPCConnection::setUnlockZoneCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_LOCK_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_UNLOCK_ZONE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setUnlockZoneCallback(const Callback::type& callback) +void HostIPCConnection::setGrantDeviceCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_UNLOCK_ZONE, - Callback::getCallbackWrapper(callback)); + api::METHOD_GRANT_DEVICE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setGrantDeviceCallback(const Callback::type& callback) +void HostIPCConnection::setRevokeDeviceCallback(const Method::type& callback) { - typedef Callback Callback; + typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::host::METHOD_GRANT_DEVICE, - Callback::getCallbackWrapper(callback)); + api::METHOD_REVOKE_DEVICE, + Callback::getWrapper(callback)); } -void HostIPCConnection::setRevokeDeviceCallback(const Callback::type& callback) +void HostIPCConnection::setNotifyActiveZoneCallback( + const Method::type& callback) { - typedef Callback Callback; - mService->setMethodHandler( - api::host::METHOD_REVOKE_DEVICE, - Callback::getCallbackWrapper(callback)); + typedef IPCMethodWrapper Method; + mService->setMethodHandler( + api::METHOD_NOTIFY_ACTIVE_ZONE, + Method::getWrapper(callback)); +} + +void HostIPCConnection::setSwitchToDefaultCallback(const Signal::type& callback) +{ + typedef IPCSignalWrapper Signal; + mService->setSignalHandler( + api::SIGNAL_SWITCH_TO_DEFAULT, + Signal::getWrapper(callback)); +} + +void HostIPCConnection::setFileMoveCallback(const Method::type& callback) +{ + typedef IPCMethodWrapper Method; + mService->setMethodHandler( + api::METHOD_FILE_MOVE_REQUEST, + Method::getWrapper(callback)); } -void HostIPCConnection::signalZoneConnectionState(const api::ConnectionState& connectionState) +void HostIPCConnection::sendNotification(const api::Notification& notification) { - mService->signal(api::host::SIGNAL_ZONE_CONNECTION_STATE, - std::make_shared(connectionState)); + mService->signal(api::SIGNAL_NOTIFICATION, + std::make_shared(notification)); } } // namespace vasum diff --git a/server/host-ipc-connection.hpp b/server/host-ipc-connection.hpp index 61c8f4a..d5144fd 100644 --- a/server/host-ipc-connection.hpp +++ b/server/host-ipc-connection.hpp @@ -27,87 +27,61 @@ #define SERVER_HOST_IPC_CONNECTION_HPP #include "api/messages.hpp" -#include "api/method-result-builder.hpp" -#include "api/ipc-method-result-builder.hpp" #include "epoll/thread-dispatcher.hpp" #include "ipc/service.hpp" - -#include +#include "ipc-callback-wrapper.hpp" namespace vasum { - class HostIPCConnection { public: - template - class Callback { + template + class Method { public: - typedef typename std::remove_cv::type in; - typedef ArgOut out; - typedef std::function type; - - static typename ipc::MethodHandler::type - getCallbackWrapper(const type& callback) { - return [callback](const ipc::PeerID, - const std::shared_ptr& argIn, - ipc::MethodResult::Pointer&& argOut) - { - auto rb = std::make_shared(argOut); - callback(*argIn, rb); - }; - } + typedef typename IPCMethodWrapper::type type; }; - - template - class Callback::value, api::Void>::type> { + template + class Signal { public: - typedef api::Void in; - typedef ArgOut out; - typedef std::function type; - - static typename ipc::MethodHandler::type - getCallbackWrapper(const type& callback) { - return [callback](const ipc::PeerID, - const std::shared_ptr& /* argIn */, - ipc::MethodResult::Pointer&& argOut) - { - auto rb = std::make_shared(argOut); - callback(rb); - }; - } + typedef typename IPCSignalWrapper::type type; }; HostIPCConnection(); ~HostIPCConnection(); - void setGetZoneConnectionsCallback(const Callback::type& callback); - void setGetZoneIdsCallback(const Callback::type& callback); - void setGetActiveZoneIdCallback(const Callback::type& callback); - void setGetZoneInfoCallback(const Callback::type& callback); - void setSetNetdevAttrsCallback(const Callback::type& callback); - void setGetNetdevAttrsCallback(const Callback::type& callback); - void setGetNetdevListCallback(const Callback::type& callback); - void setCreateNetdevVethCallback(const Callback::type& callback); - void setCreateNetdevMacvlanCallback(const Callback::type& callback); - void setCreateNetdevPhysCallback(const Callback::type& callback); - void setDestroyNetdevCallback(const Callback::type& callback); - void setDeleteNetdevIpAddressCallback(const Callback::type& callback); - void setDeclareFileCallback(const Callback::type& callback); - void setDeclareMountCallback(const Callback::type& callback); - void setDeclareLinkCallback(const Callback::type& callback); - void setGetDeclarationsCallback(const Callback::type& callback); - void setRemoveDeclarationCallback(const Callback::type& callback); - void setSetActiveZoneCallback(const Callback::type& callback); - void setCreateZoneCallback(const Callback::type& callback); - void setDestroyZoneCallback(const Callback::type& callback); - void setShutdownZoneCallback(const Callback::type& callback); - void setStartZoneCallback(const Callback::type& callback); - void setLockZoneCallback(const Callback::type& callback); - void setUnlockZoneCallback(const Callback::type& callback); - void setGrantDeviceCallback(const Callback::type& callback); - void setRevokeDeviceCallback(const Callback::type& callback); + void setGetZoneConnectionsCallback(const Method::type& callback); + void setGetZoneIdsCallback(const Method::type& callback); + void setGetActiveZoneIdCallback(const Method::type& callback); + void setGetZoneInfoCallback(const Method::type& callback); + void setSetNetdevAttrsCallback(const Method::type& callback); + void setGetNetdevAttrsCallback(const Method::type& callback); + void setGetNetdevListCallback(const Method::type& callback); + void setCreateNetdevVethCallback(const Method::type& callback); + void setCreateNetdevMacvlanCallback(const Method::type& callback); + void setCreateNetdevPhysCallback(const Method::type& callback); + void setDestroyNetdevCallback(const Method::type& callback); + void setDeleteNetdevIpAddressCallback(const Method::type& callback); + void setDeclareFileCallback(const Method::type& callback); + void setDeclareMountCallback(const Method::type& callback); + void setDeclareLinkCallback(const Method::type& callback); + void setGetDeclarationsCallback(const Method::type& callback); + void setRemoveDeclarationCallback(const Method::type& callback); + void setSetActiveZoneCallback(const Method::type& callback); + void setCreateZoneCallback(const Method::type& callback); + void setDestroyZoneCallback(const Method::type& callback); + void setShutdownZoneCallback(const Method::type& callback); + void setStartZoneCallback(const Method::type& callback); + void setLockZoneCallback(const Method::type& callback); + void setUnlockZoneCallback(const Method::type& callback); + void setGrantDeviceCallback(const Method::type& callback); + void setRevokeDeviceCallback(const Method::type& callback); + void setNotifyActiveZoneCallback(const Method::type& callback); + void setSwitchToDefaultCallback(const Signal::type& callback); + void setFileMoveCallback(const Method::type& callback); void signalZoneConnectionState(const api::ConnectionState& connectionState); + void sendNotification(const api::Notification& notification); private: epoll::ThreadDispatcher mDispatcher; diff --git a/server/host-ipc-definitions.hpp b/server/host-ipc-definitions.hpp index b1fca09..8c31339 100644 --- a/server/host-ipc-definitions.hpp +++ b/server/host-ipc-definitions.hpp @@ -29,9 +29,7 @@ namespace vasum { namespace api { -namespace host { -const vasum::ipc::MethodID METHOD_GET_ZONE_CONNECTIONS = 1; const vasum::ipc::MethodID METHOD_GET_ZONE_ID_LIST = 2; const vasum::ipc::MethodID METHOD_GET_ACTIVE_ZONE_ID = 3; const vasum::ipc::MethodID METHOD_GET_ZONE_INFO = 4; @@ -58,9 +56,18 @@ const vasum::ipc::MethodID METHOD_UNLOCK_ZONE = 24; const vasum::ipc::MethodID METHOD_GRANT_DEVICE = 25; const vasum::ipc::MethodID METHOD_REVOKE_DEVICE = 26; -const vasum::ipc::MethodID SIGNAL_ZONE_CONNECTION_STATE = 27; +const vasum::ipc::MethodID METHOD_NOTIFY_ACTIVE_ZONE = 100; +const vasum::ipc::MethodID METHOD_FILE_MOVE_REQUEST = 101; +const vasum::ipc::MethodID SIGNAL_NOTIFICATION = 102; +const vasum::ipc::MethodID SIGNAL_SWITCH_TO_DEFAULT = 103; + +const std::string FILE_MOVE_DESTINATION_NOT_FOUND = "FILE_MOVE_DESTINATION_NOT_FOUND"; +const std::string FILE_MOVE_WRONG_DESTINATION = "FILE_MOVE_WRONG_DESTINATION"; +const std::string FILE_MOVE_NO_PERMISSIONS_SEND = "FILE_MOVE_NO_PERMISSIONS_SEND"; +const std::string FILE_MOVE_NO_PERMISSIONS_RECEIVE = "FILE_MOVE_NO_PERMISSIONS_RECEIVE"; +const std::string FILE_MOVE_FAILED = "FILE_MOVE_FAILED"; +const std::string FILE_MOVE_SUCCEEDED = "FILE_MOVE_SUCCEEDED"; -} // namespace host } // namespace api } // namespace vasum diff --git a/server/ipc-callback-wrapper.hpp b/server/ipc-callback-wrapper.hpp new file mode 100644 index 0000000..04c0544 --- /dev/null +++ b/server/ipc-callback-wrapper.hpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Mateusz Malicki + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + +/** + * @file + * @author Mateusz Malicki (m.malicki2@samsung.com) + * @brief IPCSignalWrapper and IPCMethodWrapper classes used to hide IPC specifics + */ + + +#ifndef SERVER_IPC_CALLBACK_WRAPPER_HPP +#define SERVER_IPC_CALLBACK_WRAPPER_HPP + +#include "api/messages.hpp" +#include "api/method-result-builder.hpp" +#include "api/ipc-method-result-builder.hpp" + +#include + +namespace vasum { + +template +class IPCSignalWrapper { +public: + typedef typename std::remove_cv::type in; + typedef std::function type; + + static typename ipc::SignalHandler::type + getWrapper(const type& callback) { + return [callback](const ipc::PeerID, const std::shared_ptr& argIn) + { + callback(*argIn); + }; + } +}; + +template<> +class IPCSignalWrapper { +public: + typedef api::Void in; + typedef std::function type; + + static typename ipc::SignalHandler::type + getWrapper(const type& callback) { + return [callback](const ipc::PeerID, const std::shared_ptr& /* argIn */) + { + callback(); + }; + } +}; + +template +class IPCMethodWrapper { +public: + typedef typename std::remove_cv::type in; + typedef ArgOut out; + typedef std::function type; + + static typename ipc::MethodHandler::type + getWrapper(const type& callback) { + return [callback](const ipc::PeerID, + const std::shared_ptr& argIn, + ipc::MethodResult::Pointer&& argOut) + { + auto rb = std::make_shared(argOut); + callback(*argIn, rb); + }; + } +}; + +template +class IPCMethodWrapper::value, api::Void>::type> { +public: + typedef api::Void in; + typedef ArgOut out; + typedef std::function type; + + static typename ipc::MethodHandler::type + getWrapper(const type& callback) { + return [callback](const ipc::PeerID, + const std::shared_ptr& /* argIn */, + ipc::MethodResult::Pointer&& argOut) + { + auto rb = std::make_shared(argOut); + callback(rb); + }; + } +}; + +} // namespace vasum + +#endif // SERVER_IPC_CALLBACK_WRAPPER_HPP diff --git a/server/zone-config.hpp b/server/zone-config.hpp index 67b5f93..b845ef9 100644 --- a/server/zone-config.hpp +++ b/server/zone-config.hpp @@ -60,12 +60,6 @@ struct ZoneConfig { bool switchToDefaultAfterTimeout; /** - * Specify, if D-Bus communication with the zone will be enabled. - * Setting this value to "false" will make the zone API not work inside the zone. - */ - bool enableZoneConnection; - - /** * Zone's CFS quota in us when it's in the foreground */ std::int64_t cpuQuotaForeground; @@ -106,7 +100,6 @@ struct ZoneConfig { initWithArgs, privilege, // TODO not needed? switchToDefaultAfterTimeout, // TODO move to dynamic and add an API to change - enableZoneConnection, cpuQuotaForeground, cpuQuotaBackground, permittedToSend, // TODO move to dynamic and add an API to change diff --git a/server/zone-connection-transport.cpp b/server/zone-connection-transport.cpp deleted file mode 100644 index 0a8f8a0..0000000 --- a/server/zone-connection-transport.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Implementation of a class for communication transport between zone and server - */ - -#include "config.hpp" - -#include "zone-connection-transport.hpp" -#include "exception.hpp" - -#include "utils/file-wait.hpp" -#include "utils/fs.hpp" -#include "logger/logger.hpp" - -#include -#include - -namespace vasum { - -namespace { - -// Timeout in ms for waiting for dbus transport. -// Should be very long to ensure dbus in zone is ready. -// TODO: this should be in zone's configuration file -const unsigned int TRANSPORT_READY_TIMEOUT = 2 * 60 * 1000; - -} // namespace - - -ZoneConnectionTransport::ZoneConnectionTransport(const std::string& runMountPoint) - : mRunMountPoint(runMountPoint), mDetachOnExit(false) -{ - if (runMountPoint.empty()) { - return; - } - boost::system::error_code errorCode; - boost::filesystem::create_directories(runMountPoint, errorCode); - if (errorCode) { - LOGE("Initialization failed: could not create '" << runMountPoint << "' :" << errorCode); - throw ZoneConnectionException("Could not create: " + runMountPoint + - " :" + errorCode.message()); - } - - bool isMount = false; - if (!utils::isMountPoint(runMountPoint, isMount)) { - LOGE("Failed to check if " << runMountPoint << " is a mount point."); - throw ZoneConnectionException("Could not check if " + runMountPoint + - " is a mount point."); - } - - if (!isMount) { - LOGD(runMountPoint << " not mounted - mounting."); - - if (!utils::mountRun(runMountPoint)) { - LOGE("Initialization failed: could not mount " << runMountPoint); - throw ZoneConnectionException("Could not mount: " + runMountPoint); - } - LOGI("Mounted: " << runMountPoint); - } - - // if there is no systemd in the zone this dir won't be created automatically - // TODO: will require chown with USER namespace enabled - std::string dbusDirectory = runMountPoint + "/dbus"; - boost::filesystem::create_directories(dbusDirectory, errorCode); - if (errorCode) { - LOGE("Initialization failed: could not create '" << dbusDirectory << "' :" << errorCode); - throw ZoneConnectionException("Could not create: " + dbusDirectory + - " :" + errorCode.message()); - } -} - - -ZoneConnectionTransport::~ZoneConnectionTransport() -{ - if (!mDetachOnExit) { - if (!mRunMountPoint.empty()) { - if (!utils::umount(mRunMountPoint)) { - LOGE("Deinitialization failed: could not umount " << mRunMountPoint); - } - LOGI("Unmounted: " << mRunMountPoint); - } - } -} - - -std::string ZoneConnectionTransport::acquireAddress() const -{ - if (mRunMountPoint.empty()) { - return std::string(); - } - - const std::string dbusPath = mRunMountPoint + "/dbus/system_bus_socket"; - - // TODO This should be done asynchronously. - LOGT("Waiting for " << dbusPath); - utils::waitForFile(dbusPath, TRANSPORT_READY_TIMEOUT); - - return "unix:path=" + dbusPath; -} - -void ZoneConnectionTransport::setDetachOnExit() -{ - mDetachOnExit = true; -} - -} // namespace vasum diff --git a/server/zone-connection-transport.hpp b/server/zone-connection-transport.hpp deleted file mode 100644 index d651f3c..0000000 --- a/server/zone-connection-transport.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Declaration of a class for communication transport between zone and server - */ - - -#ifndef SERVER_ZONE_CONNECTION_TRANSPORT_HPP -#define SERVER_ZONE_CONNECTION_TRANSPORT_HPP - -#include "dbus/connection.hpp" - - -namespace vasum { - - -/** - * This class provides a communication transport between zone and server. - * The object lifecycle should cover lifecycle of a zone. - */ -class ZoneConnectionTransport { -public: - ZoneConnectionTransport(const std::string& runMountPoint); - ~ZoneConnectionTransport(); - - /** - * Gets dbus addres. Will block until address is available. - */ - std::string acquireAddress() const; - - /** - * Set whether object should detach from transport filesystem on exit - */ - void setDetachOnExit(); - -private: - std::string mRunMountPoint; - bool mDetachOnExit; -}; - - -} // namespace vasum - - -#endif // SERVER_ZONE_CONNECTION_TRANSPORT_HPP diff --git a/server/zone-connection.cpp b/server/zone-connection.cpp deleted file mode 100644 index 56aa547..0000000 --- a/server/zone-connection.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Implementation of a class for communication between zone and server - */ - -#include "config.hpp" - -#include "zone-connection.hpp" -#include "zone-dbus-definitions.hpp" -#include "exception.hpp" -// TODO: Switch to real power-manager dbus defs when they will be implemented in power-manager -#include "fake-power-manager-dbus-definitions.hpp" - -#include "api/dbus-method-result-builder.hpp" -#include "api/messages.hpp" - -#include "logger/logger.hpp" - - -namespace vasum { - -namespace { - -// Timeout in ms for waiting for dbus name. -// Can happen if glib loop is busy or not present. -// TODO: this should be in zone's configuration file -const unsigned int NAME_ACQUIRED_TIMEOUT = 5 * 1000; - -} // namespace - - -ZoneConnection::ZoneConnection(const std::string& address, const OnNameLostCallback& callback) - : mNameAcquired(false) - , mNameLost(false) -{ - if (address.empty()) { - LOGE("Invalid zone connection address"); - throw ZoneConnectionException("Invalid zone connection address"); - } - - LOGT("Connecting to DBUS on " << address); - mDbusConnection = dbus::DbusConnection::create(address); - - LOGT("Setting DBUS name"); - mDbusConnection->setName(api::zone::BUS_NAME, - std::bind(&ZoneConnection::onNameAcquired, this), - std::bind(&ZoneConnection::onNameLost, this)); - - if (!waitForNameAndSetCallback(NAME_ACQUIRED_TIMEOUT, callback)) { - LOGE("Could not acquire dbus name: " << api::zone::BUS_NAME); - throw ZoneConnectionException("Could not acquire dbus name: " + api::zone::BUS_NAME); - } - - LOGT("Registering DBUS interface"); - using namespace std::placeholders; - mDbusConnection->registerObject(api::zone::OBJECT_PATH, - api::zone::DEFINITION, - std::bind(&ZoneConnection::onMessageCall, - this, - _1, - _2, - _3, - _4, - _5)); - - mDbusConnection->signalSubscribe(std::bind(&ZoneConnection::onSignalReceived, - this, - _1, - _2, - _3, - _4, - _5), - std::string(fake_power_manager_api::BUS_NAME)); - - LOGD("Connected"); -} - -ZoneConnection::~ZoneConnection() -{ -} - -bool ZoneConnection::waitForNameAndSetCallback(const unsigned int timeoutMs, const OnNameLostCallback& callback) -{ - std::unique_lock lock(mNameMutex); - mNameCondition.wait_for(lock, - std::chrono::milliseconds(timeoutMs), - [this] { - return mNameAcquired || mNameLost; - }); - if(mNameAcquired) { - mOnNameLostCallback = callback; - } - - return mNameAcquired; -} - -void ZoneConnection::onNameAcquired() -{ - std::unique_lock lock(mNameMutex); - mNameAcquired = true; - mNameCondition.notify_one(); -} - -void ZoneConnection::onNameLost() -{ - std::unique_lock lock(mNameMutex); - mNameLost = true; - mNameCondition.notify_one(); - - if (mOnNameLostCallback) { - mOnNameLostCallback(); - } -} - -void ZoneConnection::setNotifyActiveZoneCallback( - const NotifyActiveZoneCallback& callback) -{ - mNotifyActiveZoneCallback = callback; -} - -void ZoneConnection::setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback) -{ - mSwitchToDefaultCallback = callback; -} - -void ZoneConnection::setFileMoveCallback( - const FileMoveCallback& callback) -{ - mFileMoveCallback = callback; -} - -void ZoneConnection::setProxyCallCallback(const ProxyCallCallback& callback) -{ - mProxyCallCallback = callback; -} - -void ZoneConnection::onMessageCall(const std::string& objectPath, - const std::string& interface, - const std::string& methodName, - GVariant* parameters, - dbus::MethodResultBuilder::Pointer result) -{ - if (objectPath != api::zone::OBJECT_PATH || interface != api::zone::INTERFACE) { - return; - } - - if (methodName == api::zone::METHOD_NOTIFY_ACTIVE_ZONE) { - const gchar* application = NULL; - const gchar* message = NULL; - g_variant_get(parameters, "(&s&s)", &application, &message); - if (mNotifyActiveZoneCallback) { - auto rb = std::make_shared>(result); - mNotifyActiveZoneCallback(application, message, rb); - } - } - - if (methodName == api::zone::METHOD_FILE_MOVE_REQUEST) { - const gchar* destination = NULL; - const gchar* path = NULL; - g_variant_get(parameters, "(&s&s)", &destination, &path); - if (mFileMoveCallback) { - auto rb = std::make_shared>(result); - mFileMoveCallback(destination, path, rb); - } - } - - if (methodName == api::METHOD_PROXY_CALL) { - const gchar* target = NULL; - const gchar* targetBusName = NULL; - const gchar* targetObjectPath = NULL; - const gchar* targetInterface = NULL; - const gchar* targetMethod = NULL; - GVariant* rawArgs = NULL; - g_variant_get(parameters, - "(&s&s&s&s&sv)", - &target, - &targetBusName, - &targetObjectPath, - &targetInterface, - &targetMethod, - &rawArgs); - dbus::GVariantPtr args(rawArgs, g_variant_unref); - - if (mProxyCallCallback) { - mProxyCallCallback(target, - targetBusName, - targetObjectPath, - targetInterface, - targetMethod, - args.get(), - result); - } - } -} - -void ZoneConnection::onSignalReceived(const std::string& senderBusName, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* /*parameters*/) -{ - LOGD("Received signal: " << senderBusName << "; " << objectPath << "; " << interface << "; " - << signalName); - if (objectPath == fake_power_manager_api::OBJECT_PATH && - interface == fake_power_manager_api::INTERFACE) { - //power-manager sent us a signal, check it - if (signalName == fake_power_manager_api::SIGNAL_DISPLAY_OFF && mSwitchToDefaultCallback) { - mSwitchToDefaultCallback(); - } - } -} - -void ZoneConnection::sendNotification(const std::string& zone, - const std::string& application, - const std::string& message) -{ - GVariant* parameters = g_variant_new("(sss)", - zone.c_str(), - application.c_str(), - message.c_str()); - mDbusConnection->emitSignal(api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::SIGNAL_NOTIFICATION, - parameters); -} - -void ZoneConnection::proxyCallAsync(const std::string& busName, - const std::string& objectPath, - const std::string& interface, - const std::string& method, - GVariant* parameters, - const dbus::DbusConnection::AsyncMethodCallCallback& callback) -{ - mDbusConnection->callMethodAsync(busName, - objectPath, - interface, - method, - parameters, - std::string(), - callback); -} - - -} // namespace vasum diff --git a/server/zone-connection.hpp b/server/zone-connection.hpp deleted file mode 100644 index 441f645..0000000 --- a/server/zone-connection.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Declaration of a class for communication between zone and server - */ - - -#ifndef SERVER_ZONE_CONNECTION_HPP -#define SERVER_ZONE_CONNECTION_HPP - -#include "dbus/connection.hpp" -#include "api/method-result-builder.hpp" - -#include -#include - -namespace vasum { - - -class ZoneConnection { - -public: - typedef std::function OnNameLostCallback; - typedef std::function SwitchToDefaultCallback; - - ZoneConnection(const std::string& address, const OnNameLostCallback& callback); - ~ZoneConnection(); - - // ------------- API -------------- - - typedef std::function NotifyActiveZoneCallback; - - typedef std::function FileMoveCallback; - - typedef std::function ProxyCallCallback; - - /** - * Register notification request callback - */ - void setNotifyActiveZoneCallback(const NotifyActiveZoneCallback& callback); - - /** - * Register switch to default request callback - */ - void setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback); - - /* - * Register file move request callback - */ - void setFileMoveCallback(const FileMoveCallback& callback); - - /** - * Register proxy call callback - */ - void setProxyCallCallback(const ProxyCallCallback& callback); - - /** - * Send notification signal to this zone - */ - void sendNotification(const std::string& zone, - const std::string& application, - const std::string& message); - - /** - * Make a proxy call - */ - void proxyCallAsync(const std::string& busName, - const std::string& objectPath, - const std::string& interface, - const std::string& method, - GVariant* parameters, - const dbus::DbusConnection::AsyncMethodCallCallback& callback); - -private: - dbus::DbusConnection::Pointer mDbusConnection; - std::mutex mNameMutex; - std::condition_variable mNameCondition; - bool mNameAcquired; - bool mNameLost; - OnNameLostCallback mOnNameLostCallback; - NotifyActiveZoneCallback mNotifyActiveZoneCallback; - SwitchToDefaultCallback mSwitchToDefaultCallback; - FileMoveCallback mFileMoveCallback; - ProxyCallCallback mProxyCallCallback; - - void onNameAcquired(); - void onNameLost(); - bool waitForNameAndSetCallback(const unsigned int timeoutMs, const OnNameLostCallback& callback); - - void onMessageCall(const std::string& objectPath, - const std::string& interface, - const std::string& methodName, - GVariant* parameters, - dbus::MethodResultBuilder::Pointer result); - void onSignalReceived(const std::string& senderBusName, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* parameters); -}; - - -} // namespace vasum - - -#endif // SERVER_ZONE_CONNECTION_HPP diff --git a/server/zone-dbus-definitions.hpp b/server/zone-dbus-definitions.hpp deleted file mode 100644 index c46e99a..0000000 --- a/server/zone-dbus-definitions.hpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Zone dbus api definitions - */ - -#ifndef SERVER_ZONE_DBUS_DEFINITIONS_HPP -#define SERVER_ZONE_DBUS_DEFINITIONS_HPP - -#include "common-dbus-definitions.hpp" - - -namespace vasum { -namespace api { -namespace zone { - -const std::string BUS_NAME = "org.tizen.vasum.zone"; -const std::string OBJECT_PATH = "/org/tizen/vasum/zone"; -const std::string INTERFACE = "org.tizen.vasum.zone.manager"; - -const std::string METHOD_NOTIFY_ACTIVE_ZONE = "NotifyActiveZone"; -const std::string METHOD_FILE_MOVE_REQUEST = "FileMoveRequest"; -const std::string SIGNAL_NOTIFICATION = "Notification"; - -const std::string FILE_MOVE_DESTINATION_NOT_FOUND = "FILE_MOVE_DESTINATION_NOT_FOUND"; -const std::string FILE_MOVE_WRONG_DESTINATION = "FILE_MOVE_WRONG_DESTINATION"; -const std::string FILE_MOVE_NO_PERMISSIONS_SEND = "FILE_MOVE_NO_PERMISSIONS_SEND"; -const std::string FILE_MOVE_NO_PERMISSIONS_RECEIVE = "FILE_MOVE_NO_PERMISSIONS_RECEIVE"; -const std::string FILE_MOVE_FAILED = "FILE_MOVE_FAILED"; -const std::string FILE_MOVE_SUCCEEDED = "FILE_MOVE_SUCCEEDED"; - - -const std::string DEFINITION = - "" - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - " " - ""; - -} // namespace zone -} // namespace api -} // namespace vasum - - -#endif // SERVER_ZONE_DBUS_DEFINITIONS_HPP diff --git a/server/zone.cpp b/server/zone.cpp index 2e47f25..8a1aa0b 100644 --- a/server/zone.cpp +++ b/server/zone.cpp @@ -46,25 +46,19 @@ namespace { typedef std::lock_guard Lock; -// TODO: move constants to the config file when default values are implemented there -const int RECONNECT_RETRIES = 15; -const int RECONNECT_DELAY = 1 * 1000; - const std::string STATE_STOPPED = "stopped"; const std::string STATE_RUNNING = "running"; const std::string STATE_PAUSED = "paused"; } // namespace -Zone::Zone(const utils::Worker::Pointer& worker, - const std::string& zoneId, +Zone::Zone(const std::string& zoneId, const std::string& zonesPath, const std::string& zoneTemplatePath, const std::string& dbPath, const std::string& lxcTemplatePrefix, const std::string& baseRunMountPointPath) - : mWorker(worker) - , mDbPath(dbPath) + : mDbPath(dbPath) { const std::string dbPrefix = getZoneDbPrefix(zoneId); config::loadFromKVStoreWithJsonFile(dbPath, zoneTemplatePath, mConfig, dbPrefix); @@ -89,19 +83,6 @@ Zone::Zone(const utils::Worker::Pointer& worker, mProvision.reset(new ZoneProvision(mRootPath, zoneTemplatePath, dbPath, dbPrefix, mConfig.validLinkPrefixes)); } -Zone::~Zone() -{ - // Make sure all OnNameLostCallbacks get finished and no new will - // get called before proceeding further. This guarantees no race - // condition on the reconnect thread. - { - Lock lock(mReconnectMutex); - disconnect(); - } - // wait for all tasks to complete - mWorker.reset(); -} - const std::vector& Zone::getPermittedToSend() const { return mPermittedToSend; @@ -164,16 +145,9 @@ void Zone::start() Lock lock(mReconnectMutex); updateRequestedState(STATE_RUNNING); mProvision->start(); - if (mConfig.enableZoneConnection) { - mConnectionTransport.reset(new ZoneConnectionTransport(mRunMountPoint)); - } - mAdmin->start(); - if (mConfig.enableZoneConnection) { - // Increase cpu quota before connect, otherwise it'd take ages. - goForeground(); - connect(); - } + // Increase cpu quota before connect, otherwise it'd take ages. + goForeground(); // refocus in ZonesManager will adjust cpu quota after all } @@ -187,54 +161,10 @@ void Zone::stop(bool saveState) // boost stopping goForeground(); } - disconnect(); mAdmin->stop(); - mConnectionTransport.reset(); mProvision->stop(); } -void Zone::connect() -{ - // assume called under reconnect lock - mConnectionAddress = mConnectionTransport->acquireAddress(); - mConnection.reset(new ZoneConnection(mConnectionAddress, - std::bind(&Zone::onNameLostCallback, this))); - if (mNotifyCallback) { - mConnection->setNotifyActiveZoneCallback(mNotifyCallback); - } - if (mSwitchToDefaultCallback) { - mConnection->setSwitchToDefaultCallback(mSwitchToDefaultCallback); - } - if (mFileMoveCallback) { - mConnection->setFileMoveCallback(mFileMoveCallback); - } - if (mProxyCallCallback) { - mConnection->setProxyCallCallback(mProxyCallCallback); - } - if (mConnectionStateChangedCallback) { - mConnectionStateChangedCallback(mConnectionAddress); - } -} - -void Zone::disconnect() -{ - // assume called under reconnect lock - if (mConnection) { - mConnection.reset(); - mConnectionAddress.clear(); - if (mConnectionStateChangedCallback) { - // notify about invalid address for this zone - mConnectionStateChangedCallback(std::string()); - } - } -} - -std::string Zone::getConnectionAddress() const -{ - Lock lock(mReconnectMutex); - return mConnectionAddress; -} - int Zone::getVT() const { Lock lock(mReconnectMutex); @@ -300,9 +230,6 @@ void Zone::setDetachOnExit() { Lock lock(mReconnectMutex); mAdmin->setDetachOnExit(); - if (mConnectionTransport) { - mConnectionTransport->setDetachOnExit(); - } } void Zone::setDestroyOnExit() @@ -348,120 +275,6 @@ bool Zone::isSwitchToDefaultAfterTimeoutAllowed() const return mConfig.switchToDefaultAfterTimeout; } -void Zone::onNameLostCallback() -{ - LOGI(getId() << ": A connection to the DBUS server has been lost, reconnecting..."); - - mWorker->addTask(std::bind(&Zone::reconnectHandler, this)); -} - -void Zone::reconnectHandler() -{ - { - Lock lock(mReconnectMutex); - disconnect(); - } - - for (int i = 0; i < RECONNECT_RETRIES; ++i) { - // This sleeps even before the first try to give DBUS some time to come back up - std::this_thread::sleep_for(std::chrono::milliseconds(RECONNECT_DELAY)); - - Lock lock(mReconnectMutex); - if (isStopped()) { - LOGI(getId() << ": Has stopped, nothing to reconnect to, bailing out"); - return; - } - - try { - LOGT(getId() << ": Reconnect try " << i + 1); - connect(); - LOGI(getId() << ": Reconnected"); - return; - } catch (VasumException&) { - LOGT(getId() << ": Reconnect try " << i + 1 << " has been unsuccessful"); - } - } - - LOGE(getId() << ": Reconnecting to the DBUS has failed, stopping the zone"); - stop(false); -} - -void Zone::setNotifyActiveZoneCallback(const NotifyActiveZoneCallback& callback) -{ - Lock lock(mReconnectMutex); - mNotifyCallback = callback; - if (mConnection) { - mConnection->setNotifyActiveZoneCallback(mNotifyCallback); - } -} - -void Zone::sendNotification(const std::string& zone, - const std::string& application, - const std::string& message) -{ - Lock lock(mReconnectMutex); - if (mConnection) { - mConnection->sendNotification(zone, application, message); - } else { - LOGE(getId() << ": Can't send notification, no connection to DBUS"); - } -} - -void Zone::setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback) -{ - Lock lock(mReconnectMutex); - - mSwitchToDefaultCallback = callback; - if (mConnection) { - mConnection->setSwitchToDefaultCallback(callback); - } -} - -void Zone::setFileMoveCallback(const FileMoveCallback& callback) -{ - Lock lock(mReconnectMutex); - - mFileMoveCallback = callback; - if (mConnection) { - mConnection->setFileMoveCallback(callback); - } -} - -void Zone::setProxyCallCallback(const ProxyCallCallback& callback) -{ - Lock lock(mReconnectMutex); - - mProxyCallCallback = callback; - if (mConnection) { - mConnection->setProxyCallCallback(callback); - } -} - -void Zone::setConnectionStateChangedCallback(const ConnectionStateChangedCallback& callback) -{ - mConnectionStateChangedCallback = callback; -} - -void Zone::proxyCallAsync(const std::string& busName, - const std::string& objectPath, - const std::string& interface, - const std::string& method, - GVariant* parameters, - const dbus::DbusConnection::AsyncMethodCallCallback& callback) -{ - Lock lock(mReconnectMutex); - if (mConnection) { - mConnection->proxyCallAsync(busName, - objectPath, - interface, - method, - parameters, - callback); - } else { - LOGE(getId() << ": Can't do a proxy call, no connection to DBUS"); - } -} - std::string Zone::declareFile(const int32_t& type, const std::string& path, const int32_t& flags, diff --git a/server/zone.hpp b/server/zone.hpp index f24a6e6..6d13d85 100644 --- a/server/zone.hpp +++ b/server/zone.hpp @@ -28,11 +28,9 @@ #include "zone-config.hpp" #include "zone-admin.hpp" -#include "zone-connection.hpp" -#include "zone-connection-transport.hpp" #include "zone-provision.hpp" -#include "utils/worker.hpp" +#include #include #include #include @@ -54,8 +52,7 @@ public: * @param lxcTemplatePrefix directory where templates are stored * @param baseRunMountPointPath base directory for run mount point */ - Zone(const utils::Worker::Pointer& worker, - const std::string& zoneId, + Zone(const std::string& zoneId, const std::string& zonesPath, const std::string& zoneTemplatePath, const std::string& dbPath, @@ -63,14 +60,7 @@ public: const std::string& baseRunMountPointPath); Zone(const Zone&) = delete; Zone& operator=(const Zone&) = delete; - ~Zone(); - typedef ZoneConnection::NotifyActiveZoneCallback NotifyActiveZoneCallback; - typedef ZoneConnection::SwitchToDefaultCallback SwitchToDefaultCallback; - typedef ZoneConnection::FileMoveCallback FileMoveCallback; - typedef ZoneConnection::ProxyCallCallback ProxyCallCallback; - - typedef std::function ConnectionStateChangedCallback; typedef std::function StartAsyncResultCallback; /** @@ -135,8 +125,7 @@ public: /** * Set if zone should be detached on exit. * - * This sends detach flag to ZoneAdmin object and disables unmounting tmpfs - * in ZoneConnectionTransport. + * This sends detach flag to ZoneAdmin object. */ void setDetachOnExit(); @@ -174,65 +163,12 @@ public: */ bool isPaused(); - // ZoneConnection API - /** * @return Is switching to default zone after timeout allowed? */ bool isSwitchToDefaultAfterTimeoutAllowed() const; /** - * Register notification request callback - */ - void setNotifyActiveZoneCallback(const NotifyActiveZoneCallback& callback); - - /** - * Register callback used when switching to default zone. - */ - void setSwitchToDefaultCallback(const SwitchToDefaultCallback& callback); - - /** - * Register proxy call callback - */ - void setProxyCallCallback(const ProxyCallCallback& callback); - - /** - * Send notification signal to this zone - * - * @param zone name of zone in which the notification occurred - * @param application name of application that cause notification - * @param message message to be send to zone - */ - void sendNotification(const std::string& zone, - const std::string& application, - const std::string& message); - - /** - * Register file move request callback - */ - void setFileMoveCallback(const FileMoveCallback& callback); - - /** - * Register dbus state changed callback - */ - void setConnectionStateChangedCallback(const ConnectionStateChangedCallback& callback); - - /** - * Make a proxy call - */ - void proxyCallAsync(const std::string& busName, - const std::string& objectPath, - const std::string& interface, - const std::string& method, - GVariant* parameters, - const dbus::DbusConnection::AsyncMethodCallCallback& callback); - - /** - * Get a dbus address - */ - std::string getConnectionAddress() const; - - /** * Get id of VT */ int getVT() const; @@ -317,30 +253,18 @@ public: void deleteNetdevIpAddress(const std::string& netdev, const std::string& ip); private: - utils::Worker::Pointer mWorker; ZoneConfig mConfig; ZoneDynamicConfig mDynamicConfig; std::vector mPermittedToSend; std::vector mPermittedToRecv; - std::unique_ptr mConnectionTransport; std::unique_ptr mAdmin; - std::unique_ptr mConnection; std::unique_ptr mProvision; mutable std::recursive_mutex mReconnectMutex; - NotifyActiveZoneCallback mNotifyCallback; - SwitchToDefaultCallback mSwitchToDefaultCallback; - FileMoveCallback mFileMoveCallback; - ProxyCallCallback mProxyCallCallback; - ConnectionStateChangedCallback mConnectionStateChangedCallback; - std::string mConnectionAddress; std::string mRunMountPoint; std::string mRootPath; std::string mDbPath; void onNameLostCallback(); - void reconnectHandler(); - void connect(); - void disconnect(); void saveDynamicConfig(); void updateRequestedState(const std::string& state); }; diff --git a/server/zones-manager.cpp b/server/zones-manager.cpp index 1b6edf3..e6621d8 100644 --- a/server/zones-manager.cpp +++ b/server/zones-manager.cpp @@ -24,9 +24,12 @@ #include "config.hpp" +#ifdef DBUS_CONNECTION #include "host-dbus-definitions.hpp" -#include "common-dbus-definitions.hpp" -#include "zone-dbus-definitions.hpp" +#else +#include "host-ipc-definitions.hpp" +#endif +#include "common-definitions.hpp" #include "dynamic-config-scheme.hpp" #include "zones-manager.hpp" #include "zone-admin.hpp" @@ -55,6 +58,7 @@ namespace vasum { namespace { +#ifdef ZONE_CONNECTION bool regexMatchVector(const std::string& str, const std::vector& v) { for (const boost::regex& toMatch : v) { @@ -65,6 +69,7 @@ bool regexMatchVector(const std::string& str, const std::vector& v return false; } +#endif const std::string HOST_ID = "host"; const std::string ENABLED_FILE_NAME = "enabled"; @@ -124,17 +129,14 @@ ZonesManager::ZonesManager(const std::string& configPath) mDynamicConfig, getVasumDbPrefix()); - mProxyCallPolicy.reset(new ProxyCallPolicy(mConfig.proxyCallRules)); using namespace std::placeholders; #ifdef DBUS_CONNECTION + mProxyCallPolicy.reset(new ProxyCallPolicy(mConfig.proxyCallRules)); mHostConnection.setProxyCallCallback(bind(&ZonesManager::handleProxyCall, this, HOST_ID, _1, _2, _3, _4, _5, _6, _7)); #endif - mHostConnection.setGetZoneConnectionsCallback(bind(&ZonesManager::handleGetZoneConnectionsCall, - this, _1)); - mHostConnection.setGetZoneIdsCallback(bind(&ZonesManager::handleGetZoneIdsCall, this, _1)); @@ -210,6 +212,15 @@ ZonesManager::ZonesManager(const std::string& configPath) mHostConnection.setRevokeDeviceCallback(bind(&ZonesManager::handleRevokeDeviceCall, this, _1, _2)); + mHostConnection.setNotifyActiveZoneCallback(bind(&ZonesManager::handleNotifyActiveZoneCall, + this, "", _1, _2)); + + mHostConnection.setSwitchToDefaultCallback(bind(&ZonesManager::handleSwitchToDefaultCall, + this, "")); + + mHostConnection.setFileMoveCallback(bind(&ZonesManager::handleFileMoveCall, + this, "", _1, _2)); + for (const auto& zoneId : mDynamicConfig.zoneIds) { insertZone(zoneId, getTemplatePathForExistingZone(zoneId)); } @@ -307,30 +318,13 @@ void ZonesManager::insertZone(const std::string& zoneId, const std::string& zone } LOGT("Creating Zone " << zoneId); - std::unique_ptr zone(new Zone(mWorker->createSubWorker(), - zoneId, + std::unique_ptr zone(new Zone(zoneId, mConfig.zonesPath, zoneTemplatePath, mConfig.dbPath, mConfig.lxcTemplatePrefix, mConfig.runMountPointPrefix)); - using namespace std::placeholders; - zone->setNotifyActiveZoneCallback(bind(&ZonesManager::handleNotifyActiveZoneCall, - this, zoneId, _1, _2, _3)); - - zone->setSwitchToDefaultCallback(bind(&ZonesManager::handleSwitchToDefaultCall, - this, zoneId)); - - zone->setFileMoveCallback(bind(&ZonesManager::handleFileMoveCall, - this, zoneId, _1, _2, _3)); - - zone->setProxyCallCallback(bind(&ZonesManager::handleProxyCall, - this, zoneId, _1, _2, _3, _4, _5, _6, _7)); - - zone->setConnectionStateChangedCallback(bind(&ZonesManager::handleConnectionStateChanged, - this, zoneId, _1)); - mZones.push_back(std::move(zone)); // after zone is created successfully, put a file informing that zones are enabled @@ -556,28 +550,6 @@ void ZonesManager::setZonesDetachOnExit() } } -void ZonesManager::handleNotifyActiveZoneCall(const std::string& caller, - const std::string& application, - const std::string& message, - api::MethodResultBuilder::Pointer result) -{ - LOGI("handleNotifyActiveZoneCall(" << caller << ", " << application << ", " << message - << ") called"); - - Lock lock(mMutex); - - try { - auto iter = getRunningForegroundZoneIterator(); - if (iter != mZones.end() && caller != get(iter).getId()) { - get(iter).sendNotification(caller, application, message); - } - result->setVoid(); - } catch (const VasumException&) { - LOGE("Notification from " << caller << " hasn't been sent"); - result->setError(api::ERROR_INTERNAL, "Notification hasn't been sent"); - } -} - void ZonesManager::handleSwitchToDefaultCall(const std::string& /*caller*/) { // get config of currently set zone and switch if switchToDefaultAfterTimeout is true @@ -596,10 +568,33 @@ void ZonesManager::handleSwitchToDefaultCall(const std::string& /*caller*/) } } +#ifdef ZONE_CONNECTION +void ZonesManager::handleNotifyActiveZoneCall(const std::string& caller, + const api::NotifActiveZoneIn& notif, + api::MethodResultBuilder::Pointer result) +{ + const std::string& application = notif.first; + const std::string& message = notif.second; + LOGI("handleNotifyActiveZoneCall(" << caller << ", " << application << ", " << message + << ") called"); + + Lock lock(mMutex); + + try { + auto iter = getRunningForegroundZoneIterator(); + if (iter != mZones.end() && caller != get(iter).getId()) { + //XXX:get(iter).sendNotification(caller, application, message); + } + result->setVoid(); + } catch (const VasumException&) { + LOGE("Notification from " << caller << " hasn't been sent"); + result->setError(api::ERROR_INTERNAL, "Notification hasn't been sent"); + } +} + void ZonesManager::handleFileMoveCall(const std::string& srcZoneId, - const std::string& dstZoneId, - const std::string& path, - api::MethodResultBuilder::Pointer result) + const api::FileMoveRequestIn& request, + api::MethodResultBuilder::Pointer result) { // TODO: this implementation is only a placeholder. // There are too many unanswered questions and security concerns: @@ -620,6 +615,8 @@ void ZonesManager::handleFileMoveCall(const std::string& srcZoneId, // Now when the main process has obtained FDs (by either of those methods) // it can do the copying by itself. + const std::string& dstZoneId = request.first; + const std::string& path = request.second; LOGI("File move requested\n" << "src: " << srcZoneId << "\n" << "dst: " << dstZoneId << "\n" @@ -639,7 +636,7 @@ void ZonesManager::handleFileMoveCall(const std::string& srcZoneId, auto dstIter = findZone(dstZoneId); if (dstIter == mZones.end()) { LOGE("Destination zone '" << dstZoneId << "' not found"); - status->value = api::zone::FILE_MOVE_DESTINATION_NOT_FOUND; + status->value = api::FILE_MOVE_DESTINATION_NOT_FOUND; result->set(status); return; } @@ -647,21 +644,21 @@ void ZonesManager::handleFileMoveCall(const std::string& srcZoneId, if (srcZoneId == dstZoneId) { LOGE("Cannot send a file to yourself"); - status->value = api::zone::FILE_MOVE_WRONG_DESTINATION; + status->value = api::FILE_MOVE_WRONG_DESTINATION; result->set(status); return; } if (!regexMatchVector(path, srcZone.getPermittedToSend())) { LOGE("Source zone has no permissions to send the file: " << path); - status->value = api::zone::FILE_MOVE_NO_PERMISSIONS_SEND; + status->value = api::FILE_MOVE_NO_PERMISSIONS_SEND; result->set(status); return; } if (!regexMatchVector(path, dstContanier.getPermittedToRecv())) { LOGE("Destination zone has no permissions to receive the file: " << path); - status->value = api::zone::FILE_MOVE_NO_PERMISSIONS_RECEIVE; + status->value = api::FILE_MOVE_NO_PERMISSIONS_RECEIVE; result->set(status); return; } @@ -672,19 +669,36 @@ void ZonesManager::handleFileMoveCall(const std::string& srcZoneId, if (!utils::moveFile(srcPath, dstPath)) { LOGE("Failed to move the file: " << path); - status->value = api::zone::FILE_MOVE_FAILED; + status->value = api::FILE_MOVE_FAILED; result->set(status); } else { - status->value = api::zone::FILE_MOVE_SUCCEEDED; + status->value = api::FILE_MOVE_SUCCEEDED; result->set(status); try { - dstContanier.sendNotification(srcZoneId, path, api::zone::FILE_MOVE_SUCCEEDED); + //XXX: dstContanier.sendNotification(srcZoneId, path, api::FILE_MOVE_SUCCEEDED); } catch (ServerException&) { LOGE("Notification to '" << dstZoneId << "' has not been sent"); } } } +#else +void ZonesManager::handleNotifyActiveZoneCall(const std::string& /* caller */, + const api::NotifActiveZoneIn& /*notif*/, + api::MethodResultBuilder::Pointer result) +{ + result->setError(api::ERROR_INTERNAL, "Not implemented"); +} + +void ZonesManager::handleFileMoveCall(const std::string& /*srcZoneId*/, + const api::FileMoveRequestIn& /*request*/, + api::MethodResultBuilder::Pointer result) +{ + result->setError(api::ERROR_INTERNAL, "Not implemented"); +} +#endif /* ZONE_CONNECTION */ + +#ifdef DBUS_CONNECTION void ZonesManager::handleProxyCall(const std::string& caller, const std::string& target, const std::string& targetBusName, @@ -718,54 +732,19 @@ void ZonesManager::handleProxyCall(const std::string& caller, } }; - if (target == HOST_ID) { -#ifdef DBUS_CONNECTION - mHostConnection.proxyCallAsync(targetBusName, - targetObjectPath, - targetInterface, - targetMethod, - parameters, - asyncResultCallback); -#else - result->setError(api::ERROR_INVALID_ID, "Unsupported proxy call target"); -#endif - return; - } - - Lock lock(mMutex); - - auto targetIter = findZone(target); - if (targetIter == mZones.end()) { - LOGE("Target zone '" << target << "' not found"); + if (target != HOST_ID) { result->setError(api::ERROR_INVALID_ID, "Unknown proxy call target"); return; } - Zone& targetZone = get(targetIter); - targetZone.proxyCallAsync(targetBusName, - targetObjectPath, - targetInterface, - targetMethod, - parameters, - asyncResultCallback); -} - -void ZonesManager::handleGetZoneConnectionsCall(api::MethodResultBuilder::Pointer result) -{ - Lock lock(mMutex); - - auto connections = std::make_shared(); - for (auto& zone : mZones) { - connections->values.push_back({zone->getId(), zone->getConnectionAddress()}); - } - result->set(connections); -} - -void ZonesManager::handleConnectionStateChanged(const std::string& zoneId , - const std::string& address) -{ - mHostConnection.signalZoneConnectionState({zoneId, address}); + mHostConnection.proxyCallAsync(targetBusName, + targetObjectPath, + targetInterface, + targetMethod, + parameters, + asyncResultCallback); } +#endif void ZonesManager::handleGetZoneIdsCall(api::MethodResultBuilder::Pointer result) { @@ -1081,7 +1060,7 @@ void ZonesManager::handleSetActiveZoneCall(const api::ZoneId& zoneId, if (!get(iter).isRunning()) { LOGE("Could not activate stopped or paused zone"); - result->setError(api::host::ERROR_ZONE_NOT_RUNNING, + result->setError(api::ERROR_ZONE_NOT_RUNNING, "Could not activate stopped or paused zone"); return; } diff --git a/server/zones-manager.hpp b/server/zones-manager.hpp index 31c90cd..42477ae 100644 --- a/server/zones-manager.hpp +++ b/server/zones-manager.hpp @@ -30,11 +30,11 @@ #include "zones-manager-config.hpp" #ifdef DBUS_CONNECTION #include "host-dbus-connection.hpp" +#include "proxy-call-policy.hpp" #else #include "host-ipc-connection.hpp" #endif #include "input-monitor.hpp" -#include "proxy-call-policy.hpp" #include "utils/worker.hpp" #include "api/method-result-builder.hpp" @@ -131,7 +131,6 @@ private: HostConnection mHostConnection; // to hold InputMonitor pointer to monitor if zone switching sequence is recognized std::unique_ptr mSwitchingSequenceMonitor; - std::unique_ptr mProxyCallPolicy; // like set but keep insertion order // smart pointer is needed because Zone is not moveable (because of mutex) typedef std::vector> Zones; @@ -157,14 +156,14 @@ private: // Zone's handlers--------------------------------------------------------- void handleNotifyActiveZoneCall(const std::string& caller, - const std::string& appliaction, - const std::string& message, + const api::NotifActiveZoneIn& notif, api::MethodResultBuilder::Pointer result); void handleSwitchToDefaultCall(const std::string& caller); void handleFileMoveCall(const std::string& srcZoneId, - const std::string& dstZoneId, - const std::string& path, + const api::FileMoveRequestIn& request, api::MethodResultBuilder::Pointer result); +#ifdef DBUS_CONNECTION + std::unique_ptr mProxyCallPolicy; void handleProxyCall(const std::string& caller, const std::string& target, const std::string& targetBusName, @@ -173,10 +172,8 @@ private: const std::string& targetMethod, GVariant* parameters, dbus::MethodResultBuilder::Pointer result); - void handleGetZoneConnectionsCall(api::MethodResultBuilder::Pointer result); - void handleConnectionStateChanged(const std::string& zoneId, - const std::string& address); - // Host's handlers -------------------------------------------------------- +#endif + // Handlers -------------------------------------------------------- void handleGetZoneIdsCall(api::MethodResultBuilder::Pointer result); void handleGetActiveZoneIdCall(api::MethodResultBuilder::Pointer result); void handleGetZoneInfoCall(const api::ZoneId& data, diff --git a/tests/unit_tests/client/configs/CMakeLists.txt b/tests/unit_tests/client/configs/CMakeLists.txt index 5587d11..64618ed 100644 --- a/tests/unit_tests/client/configs/CMakeLists.txt +++ b/tests/unit_tests/client/configs/CMakeLists.txt @@ -26,6 +26,8 @@ FILE(GLOB client_manager_CONF_GEN ${CMAKE_BINARY_DIR}/ut-client/*.conf) CONFIGURE_FILE(ut-client/templates/console-dbus.conf.in ${CMAKE_BINARY_DIR}/ut-client/templates/console-dbus.conf @ONLY) +CONFIGURE_FILE(ut-client/templates/console-ipc.conf.in + ${CMAKE_BINARY_DIR}/ut-client/templates/console-ipc.conf @ONLY) FILE(GLOB client_templates_CONF_GEN ${CMAKE_BINARY_DIR}/ut-client/templates/*.conf) ## Install ##################################################################### diff --git a/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in b/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in index 3481c09..2ff5998 100644 --- a/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in +++ b/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in @@ -7,7 +7,6 @@ "privilege" : 20, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : true, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in b/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in new file mode 100644 index 0000000..b7b103a --- /dev/null +++ b/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in @@ -0,0 +1,18 @@ +{ + "lxcTemplate" : "minimal-dbus.sh", + "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], + "requestedState" : "running", + "ipv4Gateway" : "", + "ipv4" : "", + "privilege" : 20, + "vt" : -1, + "switchToDefaultAfterTimeout" : true, + "cpuQuotaForeground" : -1, + "cpuQuotaBackground" : 1000, + "shutdownTimeout" : 10, + "runMountPoint" : "/tmp/ut-run/~NAME~", + "provisions" : [], + "permittedToSend" : [ "/tmp/.*" ], + "permittedToRecv" : [ "/tmp/.*" ], + "validLinkPrefixes" : [] +} diff --git a/tests/unit_tests/client/ut-client.cpp b/tests/unit_tests/client/ut-client.cpp index d53238f..f0e6b2e 100644 --- a/tests/unit_tests/client/ut-client.cpp +++ b/tests/unit_tests/client/ut-client.cpp @@ -23,6 +23,8 @@ * @brief Unit tests of the client C API */ +#ifndef DBUS_CONNECTION + #include #include "ut.hpp" #include @@ -30,7 +32,7 @@ #include "utils/latch.hpp" #include "utils/scoped-dir.hpp" #include "zones-manager.hpp" -#include "zone-dbus-definitions.hpp" +#include "host-ipc-definitions.hpp" #include "logger/logger.hpp" #include @@ -49,35 +51,23 @@ namespace { const std::string TEST_CONFIG_PATH = VSM_TEST_CONFIG_INSTALL_DIR "/client/ut-client/test-daemon.conf"; const std::string ZONES_PATH = "/tmp/ut-zones"; // the same as in daemon.conf -const std::string TEMPLATE_NAME = "console-dbus"; - -struct Loop { - Loop() - { - vsm_start_glib_loop(); - } - ~Loop() - { - vsm_stop_glib_loop(); - } -}; +const std::string TEMPLATE_NAME = "console-ipc"; struct Fixture { - Loop loop; utils::ScopedDir mZonesPathGuard; utils::ScopedDir mRunGuard; - ZonesManager cm; + std::unique_ptr cm; Fixture() : mZonesPathGuard(ZONES_PATH) , mRunGuard("/tmp/ut-run") - , cm(TEST_CONFIG_PATH) + , cm(new ZonesManager(TEST_CONFIG_PATH)) { - cm.createZone("zone1", TEMPLATE_NAME); - cm.createZone("zone2", TEMPLATE_NAME); - cm.createZone("zone3", TEMPLATE_NAME); - cm.restoreAll(); + cm->createZone("zone1", TEMPLATE_NAME); + cm->createZone("zone2", TEMPLATE_NAME); + cm->createZone("zone3", TEMPLATE_NAME); + cm->restoreAll(); LOGI("------- setup complete --------"); } @@ -87,32 +77,7 @@ struct Fixture { } }; -const int EVENT_TIMEOUT = 5000; ///< ms -const std::map EXPECTED_CONNECTIONS = { - { - "zone1", - "unix:path=/tmp/ut-run/zone1/dbus/system_bus_socket" - }, - { - "zone2", - "unix:path=/tmp/ut-run/zone2/dbus/system_bus_socket" - }, - { - "zone3", - "unix:path=/tmp/ut-run/zone3/dbus/system_bus_socket" - } -}; - -void convertDictToMap(VsmArrayString keys, - VsmArrayString values, - std::map& ret) -{ - VsmArrayString iKeys; - VsmArrayString iValues; - for (iKeys = keys, iValues = values; *iKeys && *iValues; iKeys++, iValues++) { - ret.insert(std::make_pair(*iKeys, *iValues)); - } -} +const std::set EXPECTED_ZONES = { "zone1", "zone2", "zone3" }; void convertArrayToSet(VsmArrayString values, std::set& ret) { @@ -153,35 +118,11 @@ BOOST_FIXTURE_TEST_SUITE(ClientSuite, Fixture) BOOST_AUTO_TEST_CASE(NotRunningServer) { - cm.shutdownAll(); - - VsmClient client = vsm_client_create(); - VsmStatus status = vsm_connect_custom(client, - EXPECTED_CONNECTIONS.begin()->second.c_str()); - BOOST_CHECK_EQUAL(VSMCLIENT_IO_ERROR, status); - vsm_client_free(client); -} + cm.reset(); -BOOST_AUTO_TEST_CASE(GetZoneConnections) -{ VsmClient client = vsm_client_create(); VsmStatus status = vsm_connect(client); - BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); - VsmArrayString keys, values; - status = vsm_get_zone_dbuses(client, &keys, &values); - //TODO: Clean up if BOOST_REQUIRE_EQUAL fail (remove client). Same in other client tests. - BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); - - BOOST_CHECK_EQUAL(getArrayStringLength(keys, EXPECTED_CONNECTIONS.size() + 1u), - EXPECTED_CONNECTIONS.size()); - BOOST_CHECK_EQUAL(getArrayStringLength(values, EXPECTED_CONNECTIONS.size() + 1u), - EXPECTED_CONNECTIONS.size()); - - std::map zones; - convertDictToMap(keys, values, zones); - BOOST_CHECK(zones == EXPECTED_CONNECTIONS); - vsm_array_string_free(keys); - vsm_array_string_free(values); + BOOST_CHECK_EQUAL(VSMCLIENT_IO_ERROR, status); vsm_client_free(client); } @@ -193,14 +134,14 @@ BOOST_AUTO_TEST_CASE(GetZoneIds) VsmArrayString values; status = vsm_get_zone_ids(client, &values); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); - BOOST_CHECK_EQUAL(getArrayStringLength(values, EXPECTED_CONNECTIONS.size() + 1u), - EXPECTED_CONNECTIONS.size()); + BOOST_CHECK_EQUAL(getArrayStringLength(values, EXPECTED_ZONES.size() + 1u), + EXPECTED_ZONES.size()); std::set zones; convertArrayToSet(values, zones); for (const auto& zone : zones) { - BOOST_CHECK(EXPECTED_CONNECTIONS.find(zone) != EXPECTED_CONNECTIONS.cend()); + BOOST_CHECK(EXPECTED_ZONES.find(zone) != EXPECTED_ZONES.cend()); } vsm_array_string_free(values); vsm_client_free(client); @@ -215,7 +156,7 @@ BOOST_AUTO_TEST_CASE(GetActiveZoneId) status = vsm_get_active_zone_id(client, &zone); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); - BOOST_CHECK_EQUAL(zone, cm.getRunningForegroundZoneId()); + BOOST_CHECK_EQUAL(zone, cm->getRunningForegroundZoneId()); vsm_string_free(zone); vsm_client_free(client); @@ -245,14 +186,14 @@ BOOST_AUTO_TEST_CASE(SetActiveZone) { const std::string newActiveZoneId = "zone2"; - BOOST_REQUIRE_NE(newActiveZoneId, cm.getRunningForegroundZoneId()); + BOOST_REQUIRE_NE(newActiveZoneId, cm->getRunningForegroundZoneId()); VsmClient client = vsm_client_create(); VsmStatus status = vsm_connect(client); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); status = vsm_set_active_zone(client, newActiveZoneId.c_str()); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); - BOOST_CHECK_EQUAL(newActiveZoneId, cm.getRunningForegroundZoneId()); + BOOST_CHECK_EQUAL(newActiveZoneId, cm->getRunningForegroundZoneId()); vsm_client_free(client); } @@ -296,17 +237,18 @@ BOOST_AUTO_TEST_CASE(LockUnlockZone) vsm_client_free(client); } +#ifdef ZONE_CONNECTION BOOST_AUTO_TEST_CASE(FileMoveRequest) { const std::string path = "/tmp/fake_path"; const std::string secondZone = "fake_zone"; VsmClient client = vsm_client_create(); - VsmStatus status = vsm_connect_custom(client, EXPECTED_CONNECTIONS.begin()->second.c_str()); + VsmStatus status = vsm_connect(client); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); status = vsm_file_move_request(client, secondZone.c_str(), path.c_str()); BOOST_REQUIRE_EQUAL(VSMCLIENT_CUSTOM_ERROR, status); - BOOST_REQUIRE_EQUAL(api::zone::FILE_MOVE_DESTINATION_NOT_FOUND, + BOOST_REQUIRE_EQUAL(api::FILE_MOVE_DESTINATION_NOT_FOUND, vsm_get_status_message(client)); vsm_client_free(client); } @@ -332,9 +274,9 @@ BOOST_AUTO_TEST_CASE(Notification) CallbackData callbackData; std::map clients; - for (const auto& it : EXPECTED_CONNECTIONS) { + for (const auto& it : EXPECTED_ZONES) { VsmClient client = vsm_client_create(); - VsmStatus status = vsm_connect_custom(client, it.second.c_str()); + VsmStatus status = vsm_connect_custom(client, it.c_str()); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, status); clients[it.first] = client; } @@ -365,6 +307,7 @@ BOOST_AUTO_TEST_CASE(Notification) vsm_client_free(client.second); } } +#endif BOOST_AUTO_TEST_CASE(GetZoneIdByPidTestSingle) { @@ -398,8 +341,8 @@ BOOST_AUTO_TEST_CASE(GetZoneIdByPidTestMultiple) BOOST_CHECK(ids.count("host") == 1); - for (const auto& dbus : EXPECTED_CONNECTIONS) { - BOOST_CHECK(ids.count(dbus.first) == 1); + for (const auto& dbus : EXPECTED_ZONES) { + BOOST_CHECK(ids.count(dbus) == 1); } } @@ -429,7 +372,7 @@ BOOST_AUTO_TEST_CASE(Provision) { VsmClient client = vsm_client_create(); BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, vsm_connect(client)); - const std::string zone = cm.getRunningForegroundZoneId(); + const std::string zone = cm->getRunningForegroundZoneId(); VsmArrayString declarations; BOOST_REQUIRE_EQUAL(VSMCLIENT_SUCCESS, vsm_list_declarations(client, zone.c_str(), &declarations)); BOOST_REQUIRE(declarations != NULL && declarations[0] == NULL); @@ -469,3 +412,5 @@ BOOST_AUTO_TEST_CASE(ZoneGetNetdevs) BOOST_AUTO_TEST_SUITE_END() + +#endif /* !DBUS_CONNECTION */ diff --git a/tests/unit_tests/lxc/templates/minimal-dbus.sh b/tests/unit_tests/lxc/templates/minimal-dbus.sh index a8ff5b9..a33ccac 100755 --- a/tests/unit_tests/lxc/templates/minimal-dbus.sh +++ b/tests/unit_tests/lxc/templates/minimal-dbus.sh @@ -68,7 +68,6 @@ lxc.mount.entry = /lib lib none ro,bind 0 0 lxc.mount.entry = /sbin sbin none ro,bind 0 0 lxc.mount.entry = /usr usr none ro,rbind 0 0 lxc.mount.entry = /opt opt none ro,rbind 0 0 -lxc.mount.entry = /tmp/ut-run/${name} var/run none rw,bind 0 0 EOF if [ "$(uname -m)" = "x86_64" ]; then diff --git a/tests/unit_tests/server/configs/CMakeLists.txt b/tests/unit_tests/server/configs/CMakeLists.txt index 6c8a1af..c5880b1 100644 --- a/tests/unit_tests/server/configs/CMakeLists.txt +++ b/tests/unit_tests/server/configs/CMakeLists.txt @@ -32,8 +32,6 @@ FILE(GLOB zone_provision_CONF ut-zone-provision/*.conf) FILE(GLOB admin_templates_CONF ut-zone-admin/templates/*.conf) -FILE(GLOB connection_CONF ut-zone-connection/*.conf) - ## Generate #################################################################### CONFIGURE_FILE(ut-server/test-daemon.conf.in @@ -50,6 +48,8 @@ FILE(GLOB manager_manager_CONF_GEN ${CMAKE_BINARY_DIR}/ut-zones-manager/*.conf) CONFIGURE_FILE(ut-zones-manager/templates/console-dbus.conf.in ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/console-dbus.conf @ONLY) +CONFIGURE_FILE(ut-zones-manager/templates/console-ipc.conf.in + ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/console-ipc.conf @ONLY) FILE(GLOB manager_templates_CONF_GEN ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/*.conf) @@ -83,8 +83,5 @@ INSTALL(FILES ${zone_provision_CONF} INSTALL(FILES ${admin_templates_CONF} DESTINATION ${VSM_TEST_CONFIG_INSTALL_DIR}/server/ut-zone-admin/templates) -INSTALL(FILES ${connection_CONF} - DESTINATION ${VSM_TEST_CONFIG_INSTALL_DIR}/server/ut-zone-connection) - INSTALL(FILES dbus-1/system.d/org.tizen.vasum.tests.conf DESTINATION ${SYSCONF_INSTALL_DIR}/dbus-1/system.d/) diff --git a/tests/unit_tests/server/configs/ut-server/templates/default.conf b/tests/unit_tests/server/configs/ut-server/templates/default.conf index d07ecc6..5261493 100644 --- a/tests/unit_tests/server/configs/ut-server/templates/default.conf +++ b/tests/unit_tests/server/configs/ut-server/templates/default.conf @@ -7,7 +7,6 @@ "privilege" : 20, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf index c3b07fe..99bc05e 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf index 7e20d62..6c7ce34 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf index 4aa7bd2..e4f2bf9 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf index 5083c0e..8af8d42 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone-connection/ut-dbus.conf b/tests/unit_tests/server/configs/ut-zone-connection/ut-dbus.conf deleted file mode 100644 index 66ee3f9..0000000 --- a/tests/unit_tests/server/configs/ut-zone-connection/ut-dbus.conf +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - custom - unix:path=/tmp/ut-zones/mount-point/dbus/system_bus_socket - - - - - - - - - - diff --git a/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf b/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf index 1e71ece..5c98cfd 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf +++ b/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in b/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in index da02e3b..d2fea11 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in +++ b/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : true, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zone/templates/test.conf b/tests/unit_tests/server/configs/ut-zone/templates/test.conf index 7827fe3..38907a0 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/test.conf +++ b/tests/unit_tests/server/configs/ut-zone/templates/test.conf @@ -7,7 +7,6 @@ "privilege" : 10, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in index 3481c09..2ff5998 100644 --- a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in +++ b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in @@ -7,7 +7,6 @@ "privilege" : 20, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : true, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in new file mode 100644 index 0000000..fab7e58 --- /dev/null +++ b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in @@ -0,0 +1,18 @@ +{ + "lxcTemplate" : "minimal.sh", + "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], + "requestedState" : "running", + "ipv4Gateway" : "", + "ipv4" : "", + "privilege" : 20, + "vt" : -1, + "switchToDefaultAfterTimeout" : true, + "cpuQuotaForeground" : -1, + "cpuQuotaBackground" : 1000, + "shutdownTimeout" : 10, + "runMountPoint" : "/tmp/ut-run/~NAME~", + "provisions" : [], + "permittedToSend" : [ "/tmp/.*" ], + "permittedToRecv" : [ "/tmp/.*" ], + "validLinkPrefixes" : [] +} diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf b/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf index d9f69ec..02a7dc6 100644 --- a/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf +++ b/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf @@ -7,7 +7,6 @@ "privilege" : 20, "vt" : -1, "switchToDefaultAfterTimeout" : true, - "enableZoneConnection" : false, "cpuQuotaForeground" : -1, "cpuQuotaBackground" : 1000, "shutdownTimeout" : 10, diff --git a/tests/unit_tests/server/ut-zone-connection.cpp b/tests/unit_tests/server/ut-zone-connection.cpp deleted file mode 100644 index c374c81..0000000 --- a/tests/unit_tests/server/ut-zone-connection.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Piotr Bartosiewicz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ - - -/** - * @file - * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) - * @brief Unit tests of the ZoneConnection class - */ - -#include "config.hpp" -#include "ut.hpp" - -#include "zone-connection.hpp" -#include "zone-connection-transport.hpp" -#include "host-dbus-definitions.hpp" -#include "zone-dbus-definitions.hpp" -// TODO: Switch to real power-manager dbus defs when they will be implemented in power-manager -#include "fake-power-manager-dbus-definitions.hpp" - -#include "dbus/connection.hpp" -#include "dbus/exception.hpp" -#include "utils/scoped-daemon.hpp" -#include "utils/glib-loop.hpp" -#include "utils/latch.hpp" -#include "utils/fs.hpp" -#include "utils/scoped-dir.hpp" - -#include "api/method-result-builder.hpp" - - -using namespace vasum; -using namespace vasum::utils; -using namespace dbus; - -namespace { - -const char* DBUS_DAEMON_PROC = "/usr/bin/dbus-daemon"; -const char* const DBUS_DAEMON_ARGS[] = { - DBUS_DAEMON_PROC, - "--config-file=" VSM_TEST_CONFIG_INSTALL_DIR "/server/ut-zone-connection/ut-dbus.conf", - "--nofork", - NULL -}; - -const std::string ZONES_PATH = "/tmp/ut-zones"; -const std::string TRANSPORT_MOUNT_POINT = ZONES_PATH + "/mount-point"; -const int EVENT_TIMEOUT = 1000; - -class Fixture { -public: - Fixture() - : mZonesPathGuard(ZONES_PATH) - , mTransport(TRANSPORT_MOUNT_POINT) - { - mDaemon.start(DBUS_DAEMON_PROC, DBUS_DAEMON_ARGS); - } - - std::string acquireAddress() - { - return mTransport.acquireAddress(); - } -private: - ScopedGlibLoop mLoop; - ScopedDir mZonesPathGuard; - ZoneConnectionTransport mTransport; - ScopedDaemon mDaemon; -}; - -class DbusNameSetter { -public: - DbusNameSetter() - : mNameAcquired(false), - mPendingDisconnect(false) - { - } - - void setName(const std::unique_ptr& conn, const std::string& name) - { - conn->setName(name, - std::bind(&DbusNameSetter::onNameAcquired, this), - std::bind(&DbusNameSetter::onDisconnect, this)); - - if(!waitForName()) { - throw dbus::DbusOperationException("Could not acquire name."); - } - } - - bool waitForName() - { - std::unique_lock lock(mMutex); - mNameCondition.wait(lock, [this] {return mNameAcquired || mPendingDisconnect;}); - return mNameAcquired; - } - - void onNameAcquired() - { - std::unique_lock lock(mMutex); - mNameAcquired = true; - mNameCondition.notify_one(); - } - - void onDisconnect() - { - std::unique_lock lock(mMutex); - mPendingDisconnect = true; - mNameCondition.notify_one(); - } - -private: - bool mNameAcquired; - bool mPendingDisconnect; - std::mutex mMutex; - std::condition_variable mNameCondition; -}; - -} // namespace - -BOOST_FIXTURE_TEST_SUITE(ZoneConnectionSuite, Fixture) - -BOOST_AUTO_TEST_CASE(ConstructorDestructorConnect) -{ - ZoneConnection(acquireAddress(), nullptr); -} - -BOOST_AUTO_TEST_CASE(NotifyActiveZoneApi) -{ - Latch notifyCalled; - ZoneConnection connection(acquireAddress(), nullptr); - - auto callback = [&](const std::string& application, const std::string& message, api::MethodResultBuilder::Pointer result) { - if (application == "testapp" && message == "testmessage") { - notifyCalled.set(); - } - result->setVoid(); - }; - connection.setNotifyActiveZoneCallback(callback); - - DbusConnection::Pointer client = DbusConnection::create(acquireAddress()); - client->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::METHOD_NOTIFY_ACTIVE_ZONE, - g_variant_new("(ss)", "testapp", "testmessage"), - "()"); - BOOST_CHECK(notifyCalled.wait(EVENT_TIMEOUT)); -} - -BOOST_AUTO_TEST_CASE(SignalNotificationApi) -{ - Latch signalEmitted; - ZoneConnection connection(acquireAddress(), nullptr); - - DbusConnection::Pointer client = DbusConnection::create(acquireAddress()); - - auto handler = [&](const std::string& /*senderBusName*/, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* parameters) { - if (objectPath == api::zone::OBJECT_PATH && - interface == api::zone::INTERFACE && - signalName == api::zone::SIGNAL_NOTIFICATION && - g_variant_is_of_type(parameters, G_VARIANT_TYPE("(sss)"))) { - - const gchar* zone = NULL; - const gchar* application = NULL; - const gchar* message = NULL; - g_variant_get(parameters, "(&s&s&s)", &zone, &application, &message); - if (zone == std::string("testzone") && - application == std::string("testapp") && - message == std::string("testmessage")) { - signalEmitted.set(); - } - } - }; - client->signalSubscribe(handler, api::zone::BUS_NAME); - - connection.sendNotification("testzone", "testapp", "testmessage"); - - BOOST_CHECK(signalEmitted.wait(EVENT_TIMEOUT)); -} - -BOOST_AUTO_TEST_CASE(SignalSwitchToDefaultApi) -{ - Latch switchToDefaultCalled; - ZoneConnection connection(acquireAddress(), nullptr); - - DbusConnection::Pointer client = DbusConnection::create(acquireAddress()); - - auto callback = [&]() { - switchToDefaultCalled.set(); - }; - - connection.setSwitchToDefaultCallback(callback); - - client->emitSignal(fake_power_manager_api::OBJECT_PATH, - fake_power_manager_api::INTERFACE, - fake_power_manager_api::SIGNAL_DISPLAY_OFF, - nullptr); - - // timeout should occur, since no name is set to client - BOOST_CHECK(!switchToDefaultCalled.wait(EVENT_TIMEOUT)); - - DbusNameSetter setter; - - setter.setName(client, fake_power_manager_api::BUS_NAME); - - client->emitSignal(fake_power_manager_api::OBJECT_PATH, - fake_power_manager_api::INTERFACE, - fake_power_manager_api::SIGNAL_DISPLAY_OFF, - nullptr); - - // now signal should be delivered correctly - BOOST_CHECK(switchToDefaultCalled.wait(EVENT_TIMEOUT)); -} - - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit_tests/server/ut-zone.cpp b/tests/unit_tests/server/ut-zone.cpp index dc66753..b4938b4 100644 --- a/tests/unit_tests/server/ut-zone.cpp +++ b/tests/unit_tests/server/ut-zone.cpp @@ -84,8 +84,7 @@ struct Fixture { std::unique_ptr create(const std::string& configPath) { - return std::unique_ptr(new Zone(utils::Worker::create(), - "zoneId", + return std::unique_ptr(new Zone("zoneId", ZONES_PATH, configPath, DB_PATH, diff --git a/tests/unit_tests/server/ut-zones-manager.cpp b/tests/unit_tests/server/ut-zones-manager.cpp index 5a9693f..a2811a9 100644 --- a/tests/unit_tests/server/ut-zones-manager.cpp +++ b/tests/unit_tests/server/ut-zones-manager.cpp @@ -27,22 +27,21 @@ #include "ut.hpp" #include "zones-manager.hpp" -#include "zone-dbus-definitions.hpp" #ifdef DBUS_CONNECTION +// TODO: Switch to real power-manager dbus defs when they will be implemented in power-manager +#include "fake-power-manager-dbus-definitions.hpp" #include "host-dbus-definitions.hpp" +#include "test-dbus-definitions.hpp" +#include "dbus/connection.hpp" +#include "dbus/exception.hpp" #else #include "host-ipc-definitions.hpp" #include #include #include #endif -#include "test-dbus-definitions.hpp" -// TODO: Switch to real power-manager dbus defs when they will be implemented in power-manager -#include "fake-power-manager-dbus-definitions.hpp" #include "exception.hpp" -#include "dbus/connection.hpp" -#include "dbus/exception.hpp" #include "utils/glib-loop.hpp" #include "config/exception.hpp" #include "utils/latch.hpp" @@ -64,7 +63,9 @@ using namespace vasum; using namespace config; using namespace vasum::utils; +#ifdef DBUS_CONNECTION using namespace dbus; +#endif namespace { @@ -73,7 +74,6 @@ const std::string TEST_CONFIG_PATH = CONFIG_DIR + "/test-daemon.conf"; const std::string MISSING_CONFIG_PATH = CONFIG_DIR + "/missing-daemon.conf"; const int EVENT_TIMEOUT = 5000; //const int UNEXPECTED_EVENT_TIMEOUT = EVENT_TIMEOUT / 5; -const int TEST_DBUS_CONNECTION_ZONES_COUNT = 3; const std::string TEST_APP_NAME = "testapp"; const std::string TEST_MESSAGE = "testmessage"; const std::string FILE_CONTENT = "File content\n" @@ -82,7 +82,11 @@ const std::string FILE_CONTENT = "File content\n" const std::string NON_EXISTANT_ZONE_ID = "NON_EXISTANT_ZONE_ID"; const std::string ZONES_PATH = "/tmp/ut-zones"; // the same as in daemon.conf const std::string SIMPLE_TEMPLATE = "console"; +#ifdef DBUS_CONNECTION const std::string ZONE_ACCESS_TEMPLATE = "console-dbus"; +#else +const std::string ZONE_ACCESS_TEMPLATE = "console-ipc"; +#endif #ifdef DBUS_CONNECTION /** @@ -109,8 +113,7 @@ public: MethodResultBuilder::Pointer result )> TestApiMethodCallback; typedef std::function VoidResultCallback; - typedef std::function SignalCallback; + typedef std::function NotificationCallback; typedef std::map Connections; @@ -165,44 +168,48 @@ public: void signalSubscribe(const DbusConnection::SignalCallback& callback) { - mClient->signalSubscribe(callback, isHost() ? api::host::BUS_NAME : api::zone::BUS_NAME); + mClient->signalSubscribe(callback, isHost() ? api::BUS_NAME : api::BUS_NAME); } - void subscribeZoneConnectionState(const SignalCallback& callback) { - assert(isHost()); - auto onSignal = [callback] (const std::string& /*senderBusName*/, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* parameters) { - if (objectPath == api::host::OBJECT_PATH && - interface == api::host::INTERFACE && - signalName == api::host::SIGNAL_ZONE_CONNECTION_STATE) { - - const gchar* zoneId = NULL; - const gchar* address = NULL; - g_variant_get(parameters, "(&s&s)", &zoneId, &address); - callback(zoneId, address); + void subscribeNotification(const NotificationCallback& callback) + { + auto handler = [callback](const std::string& /*senderBusName*/, + const std::string& objectPath, + const std::string& interface, + const std::string& signalName, + GVariant* parameters) + { + if (objectPath == api::OBJECT_PATH && + interface == api::INTERFACE && + signalName == api::SIGNAL_NOTIFICATION && + g_variant_is_of_type(parameters, G_VARIANT_TYPE("(sss)"))) { + + const gchar* zone = NULL; + const gchar* application = NULL; + const gchar* message = NULL; + g_variant_get(parameters, "(&s&s&s)", &zone, &application, &message); + callback({zone, application, message}); } }; - mClient->signalSubscribe(onSignal, api::host::BUS_NAME); + mClient->signalSubscribe(handler, api::BUS_NAME); } - void emitSignal(const std::string& objectPath, - const std::string& interface, - const std::string& name, - GVariant* parameters) + void signalSwitchToDefault() { - mClient->emitSignal(objectPath, interface, name, parameters); + // emit signal from dbus connection + mClient->emitSignal(api::OBJECT_PATH, + api::INTERFACE, + api::SIGNAL_SWITCH_TO_DEFAULT, + nullptr); } void callMethodNotify() { GVariant* parameters = g_variant_new("(ss)", TEST_APP_NAME.c_str(), TEST_MESSAGE.c_str()); - mClient->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::METHOD_NOTIFY_ACTIVE_ZONE, + mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_NOTIFY_ACTIVE_ZONE, parameters, "()"); } @@ -210,10 +217,10 @@ public: std::string callMethodMove(const std::string& dest, const std::string& path) { GVariant* parameters = g_variant_new("(ss)", dest.c_str(), path.c_str()); - GVariantPtr result = mClient->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::METHOD_FILE_MOVE_REQUEST, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_FILE_MOVE_REQUEST, parameters, "(s)"); @@ -271,12 +278,12 @@ public: interface.c_str(), method.c_str(), parameters); - GVariantPtr result = mClient->callMethod(isHost() ? api::host::BUS_NAME : - api::zone::BUS_NAME, - isHost() ? api::host::OBJECT_PATH : - api::zone::OBJECT_PATH, - isHost() ? api::host::INTERFACE : - api::zone::INTERFACE, + GVariantPtr result = mClient->callMethod(isHost() ? api::BUS_NAME : + api::BUS_NAME, + isHost() ? api::OBJECT_PATH : + api::OBJECT_PATH, + isHost() ? api::INTERFACE : + api::INTERFACE, api::METHOD_PROXY_CALL, packedParameters, "(v)"); @@ -285,36 +292,13 @@ public: return GVariantPtr(unpackedResult, g_variant_unref); } - Connections callMethodGetZoneConnections() - { - assert(isHost()); - Connections connections; - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_GET_ZONE_CONNECTIONS, - NULL, - "(a(ss))"); - GVariant* array = NULL; - g_variant_get(result.get(), "(*)", &array); - dbus::GVariantPtr autounref(array, g_variant_unref); - size_t count = g_variant_n_children(array); - for (size_t n = 0; n < count; ++n) { - const char* zoneId = NULL; - const char* address = NULL; - g_variant_get_child(array, n, "(&s&s)", &zoneId, &address); - connections.insert(Connections::value_type(zoneId, address)); - } - return connections; - } - std::vector callMethodGetZoneIds() { assert(isHost()); - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_GET_ZONE_ID_LIST, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_GET_ZONE_ID_LIST, NULL, "(as)"); @@ -336,10 +320,10 @@ public: std::string callMethodGetActiveZoneId() { assert(isHost()); - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_GET_ACTIVE_ZONE_ID, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_GET_ACTIVE_ZONE_ID, NULL, "(s)"); @@ -352,10 +336,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_SET_ACTIVE_ZONE, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_SET_ACTIVE_ZONE, parameters, "()"); @@ -373,10 +357,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(ss)", id.c_str(), templateName.c_str()); - mClient->callMethodAsync(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_CREATE_ZONE, + mClient->callMethodAsync(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_CREATE_ZONE, parameters, "()", dropException(asyncResult)); @@ -393,10 +377,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_DESTROY_ZONE, + mClient->callMethodAsync(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_DESTROY_ZONE, parameters, "()", dropException(asyncResult)); @@ -413,10 +397,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_SHUTDOWN_ZONE, + mClient->callMethodAsync(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_SHUTDOWN_ZONE, parameters, "()", dropException(asyncResult)); @@ -433,10 +417,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_START_ZONE, + mClient->callMethodAsync(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_START_ZONE, parameters, "()", dropException(asyncResult)); @@ -446,10 +430,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_LOCK_ZONE, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_LOCK_ZONE, parameters, "()"); } @@ -458,10 +442,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::host::BUS_NAME, - api::host::OBJECT_PATH, - api::host::INTERFACE, - api::host::METHOD_UNLOCK_ZONE, + GVariantPtr result = mClient->callMethod(api::BUS_NAME, + api::OBJECT_PATH, + api::INTERFACE, + api::METHOD_UNLOCK_ZONE, parameters, "()"); } @@ -490,21 +474,14 @@ private: }; typedef DbusAccessory HostAccessory; -typedef DbusAccessory ZoneAccessory; #else //#ifdef DBUS_CONNECTION class HostIPCAccessory { public: - typedef std::function TestApiMethodCallback; typedef std::function VoidResultCallback; - typedef std::function SignalCallback; - - typedef std::map Connections; + typedef std::function NotificationCallback; HostIPCAccessory() : mClient(mDispatcher.getPoll(), HOST_IPC_SOCKET) @@ -512,43 +489,23 @@ public: mClient.start(); } - void subscribeZoneConnectionState(const SignalCallback& callback) - { - auto callbackWrapper = [callback] (const ipc::PeerID, std::shared_ptr& data) { - callback(data->first, data->second); - }; - mClient.setSignalHandler(api::host::SIGNAL_ZONE_CONNECTION_STATE, - callbackWrapper); - } - - Connections callMethodGetZoneConnections() - { - const auto out = mClient.callSync(api::host::METHOD_GET_ZONE_CONNECTIONS, - std::make_shared()); - Connections connections; - for (const auto& dbus : out->values) { - connections.insert(Connections::value_type(dbus.first, dbus.second)); - } - return connections; - } - std::vector callMethodGetZoneIds() { - const auto out = mClient.callSync(api::host::METHOD_GET_ZONE_ID_LIST, + const auto out = mClient.callSync(api::METHOD_GET_ZONE_ID_LIST, std::make_shared()); return out->values; } std::string callMethodGetActiveZoneId() { - const auto out = mClient.callSync(api::host::METHOD_GET_ACTIVE_ZONE_ID, + const auto out = mClient.callSync(api::METHOD_GET_ACTIVE_ZONE_ID, std::make_shared()); return out->value; } void callMethodSetActiveZone(const std::string& id) { - mClient.callSync(api::host::METHOD_SET_ACTIVE_ZONE, + mClient.callSync(api::METHOD_SET_ACTIVE_ZONE, std::make_shared(api::ZoneId{id})); } @@ -561,7 +518,7 @@ public: result(); } }; - mClient.callAsync(api::host::METHOD_CREATE_ZONE, + mClient.callAsync(api::METHOD_CREATE_ZONE, std::make_shared(api::CreateZoneIn{id, templateName}), asyncResult); } @@ -574,7 +531,7 @@ public: result(); } }; - mClient.callAsync(api::host::METHOD_DESTROY_ZONE, + mClient.callAsync(api::METHOD_DESTROY_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } @@ -587,7 +544,7 @@ public: result(); } }; - mClient.callAsync(api::host::METHOD_SHUTDOWN_ZONE, + mClient.callAsync(api::METHOD_SHUTDOWN_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } @@ -600,195 +557,62 @@ public: result(); } }; - mClient.callAsync(api::host::METHOD_START_ZONE, + mClient.callAsync(api::METHOD_START_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } void callMethodLockZone(const std::string& id) { - mClient.callSync(api::host::METHOD_LOCK_ZONE, + mClient.callSync(api::METHOD_LOCK_ZONE, std::make_shared(api::ZoneId{id}), EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } void callMethodUnlockZone(const std::string& id) { - mClient.callSync(api::host::METHOD_UNLOCK_ZONE, + mClient.callSync(api::METHOD_UNLOCK_ZONE, std::make_shared(api::ZoneId{id}), EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } -private: - epoll::ThreadDispatcher mDispatcher; - ipc::Client mClient; -}; - -class ZoneDbusAccessory { -public: - typedef std::function TestApiMethodCallback; - - typedef std::map Connections; - - ZoneDbusAccessory(int id) - : mId(id), - mClient(DbusConnection::create(acquireAddress())), - mNameAcquired(false), - mPendingDisconnect(false) - { - } - - void setName(const std::string& name) - { - mClient->setName(name, - std::bind(&ZoneDbusAccessory::onNameAcquired, this), - std::bind(&ZoneDbusAccessory::onDisconnect, this)); - - if(!waitForName()) { - mClient.reset(); - throw dbus::DbusOperationException("Could not acquire name."); - } - } - - bool waitForName() - { - std::unique_lock lock(mMutex); - mNameCondition.wait(lock, [this] {return mNameAcquired || mPendingDisconnect;}); - return mNameAcquired; - } - - void onNameAcquired() - { - std::unique_lock lock(mMutex); - mNameAcquired = true; - mNameCondition.notify_one(); - } - - void onDisconnect() - { - std::unique_lock lock(mMutex); - mPendingDisconnect = true; - mNameCondition.notify_one(); - } - - void signalSubscribe(const DbusConnection::SignalCallback& callback) + void subscribeNotification(const NotificationCallback& callback) { - mClient->signalSubscribe(callback, api::zone::BUS_NAME); + auto callbackWrapper = [callback] (const ipc::PeerID, std::shared_ptr& data) { + callback(*data); + }; + mClient.setSignalHandler(api::SIGNAL_NOTIFICATION, + callbackWrapper); } - void emitSignal(const std::string& objectPath, - const std::string& interface, - const std::string& name, - GVariant* parameters) + void signalSwitchToDefault() { - mClient->emitSignal(objectPath, interface, name, parameters); + mClient.signal(api::SIGNAL_SWITCH_TO_DEFAULT, std::make_shared()); } void callMethodNotify() { - GVariant* parameters = g_variant_new("(ss)", TEST_APP_NAME.c_str(), TEST_MESSAGE.c_str()); - mClient->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::METHOD_NOTIFY_ACTIVE_ZONE, - parameters, - "()"); + mClient.callSync( + api::METHOD_NOTIFY_ACTIVE_ZONE, + std::make_shared(api::NotifActiveZoneIn{TEST_APP_NAME, TEST_MESSAGE}), + EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } std::string callMethodMove(const std::string& dest, const std::string& path) { - GVariant* parameters = g_variant_new("(ss)", dest.c_str(), path.c_str()); - GVariantPtr result = mClient->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::zone::METHOD_FILE_MOVE_REQUEST, - parameters, - "(s)"); - - const gchar* retcode = NULL; - g_variant_get(result.get(), "(&s)", &retcode); - return std::string(retcode); - } - - void registerTestApiObject(const TestApiMethodCallback& callback) - { - auto handler = [callback](const std::string& objectPath, - const std::string& interface, - const std::string& methodName, - GVariant* parameters, - MethodResultBuilder::Pointer result) { - if (objectPath == testapi::OBJECT_PATH && - interface == testapi::INTERFACE && - methodName == testapi::METHOD) { - const gchar* argument = NULL; - g_variant_get(parameters, "(&s)", &argument); - if (callback) { - callback(argument, result); - } - } - }; - mClient->registerObject(testapi::OBJECT_PATH, testapi::DEFINITION, handler); - } - - std::string testApiProxyCall(const std::string& target, const std::string& argument) - { - GVariant* parameters = g_variant_new("(s)", argument.c_str()); - GVariantPtr result = proxyCall(target, - testapi::BUS_NAME, - testapi::OBJECT_PATH, - testapi::INTERFACE, - testapi::METHOD, - parameters); - const gchar* ret = NULL; - g_variant_get(result.get(), "(&s)", &ret); - return ret; - } - - - GVariantPtr proxyCall(const std::string& target, - const std::string& busName, - const std::string& objectPath, - const std::string& interface, - const std::string& method, - GVariant* parameters) - { - GVariant* packedParameters = g_variant_new("(sssssv)", - target.c_str(), - busName.c_str(), - objectPath.c_str(), - interface.c_str(), - method.c_str(), - parameters); - GVariantPtr result = mClient->callMethod(api::zone::BUS_NAME, - api::zone::OBJECT_PATH, - api::zone::INTERFACE, - api::METHOD_PROXY_CALL, - packedParameters, - "(v)"); - GVariant* unpackedResult = NULL; - g_variant_get(result.get(), "(v)", &unpackedResult); - return GVariantPtr(unpackedResult, g_variant_unref); + auto result = mClient.callSync( + api::METHOD_FILE_MOVE_REQUEST, + std::make_shared(api::FileMoveRequestIn{dest, path}), + EVENT_TIMEOUT*10); + return result->value; } private: - const int mId; - DbusConnection::Pointer mClient; - bool mNameAcquired; - bool mPendingDisconnect; - std::mutex mMutex; - std::condition_variable mNameCondition; - - std::string acquireAddress() const - { - std::string zoneId = "zone" + std::to_string(mId); - return "unix:path=/tmp/ut-run/" + zoneId + "/dbus/system_bus_socket"; - } + epoll::ThreadDispatcher mDispatcher; + ipc::Client mClient; }; typedef HostIPCAccessory HostAccessory; -typedef ZoneDbusAccessory ZoneAccessory; #endif //DBUS_CONNECTION @@ -889,6 +713,16 @@ BOOST_AUTO_TEST_CASE(Focus) BOOST_CHECK(cm.getRunningForegroundZoneId() == "zone3"); } +BOOST_AUTO_TEST_CASE(StartStopWithZoneAccess) +{ + ZonesManager cm(TEST_CONFIG_PATH); + cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.restoreAll(); +} + +#ifdef ZONE_CONNECTION BOOST_AUTO_TEST_CASE(NotifyActiveZone) { ZonesManager cm(TEST_CONFIG_PATH); @@ -907,37 +741,23 @@ BOOST_AUTO_TEST_CASE(NotifyActiveZone) auto handler = [](Latch& latch, std::vector& receivedSignalSources, - const std::string& /*senderBusName*/, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* parameters) + const api::Notification& notify) { - if (objectPath == api::zone::OBJECT_PATH && - interface == api::zone::INTERFACE && - signalName == api::zone::SIGNAL_NOTIFICATION && - g_variant_is_of_type(parameters, G_VARIANT_TYPE("(sss)"))) { - - const gchar* zone = NULL; - const gchar* application = NULL; - const gchar* message = NULL; - g_variant_get(parameters, "(&s&s&s)", &zone, &application, &message); - receivedSignalSources.push_back(zone); - if (application == TEST_APP_NAME && message == TEST_MESSAGE) { - latch.set(); - } + receivedSignalSources.push_back(notify.zone); + if (notify.application == TEST_APP_NAME && notify.message == TEST_MESSAGE) { + latch.set(); } }; using namespace std::placeholders; for (int i = 1; i <= TEST_DBUS_CONNECTION_ZONES_COUNT; ++i) { - connections[i]->signalSubscribe(std::bind(handler, - std::ref(signalReceivedLatch), - std::ref(signalReceivedSourcesMap[i]), - _1, _2, _3, _4, _5)); + connections[i]->subscribeNotification(std::bind(handler, + std::ref(signalReceivedLatch), + std::ref(signalReceivedSourcesMap[i]), + _1)); } - for (auto& dbus : connections) { - dbus.second->callMethodNotify(); + for (auto& connection : connections) { + connection.second->callMethodNotify(); } BOOST_REQUIRE(signalReceivedLatch.waitForN(connections.size() - 1u, EVENT_TIMEOUT)); @@ -959,43 +779,6 @@ BOOST_AUTO_TEST_CASE(NotifyActiveZone) connections.clear(); } -BOOST_AUTO_TEST_CASE(SwitchToDefault) -{ - ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); - cm.restoreAll(); - - std::vector> clients; - for (int i = 1; i <= TEST_DBUS_CONNECTION_ZONES_COUNT; ++i) { - clients.push_back(std::unique_ptr(new ZoneAccessory(i))); - } - - for (auto& client : clients) { - client->setName(fake_power_manager_api::BUS_NAME); - } - - auto isDefaultFocused = [&cm]() -> bool { - return cm.getRunningForegroundZoneId() == "zone1"; - }; - - for (auto& client : clients) { - // TEST SWITCHING TO DEFAULT ZONE - // focus non-default zone - cm.focus("zone3"); - - // emit signal from dbus connection - client->emitSignal(fake_power_manager_api::OBJECT_PATH, - fake_power_manager_api::INTERFACE, - fake_power_manager_api::SIGNAL_DISPLAY_OFF, - nullptr); - - // check if default zone has focus - BOOST_CHECK(spinWaitFor(EVENT_TIMEOUT, isDefaultFocused)); - } -} - BOOST_AUTO_TEST_CASE(MoveFile) { ZonesManager cm(TEST_CONFIG_PATH); @@ -1014,31 +797,16 @@ BOOST_AUTO_TEST_CASE(MoveFile) connections[i] = std::unique_ptr(new ZoneAccessory(i)); } - auto handler = [&](const std::string& /*senderBusName*/, - const std::string& objectPath, - const std::string& interface, - const std::string& signalName, - GVariant* parameters) + auto handler = [&](const api::Notification& notify) { - if (objectPath == api::zone::OBJECT_PATH && - interface == api::zone::INTERFACE && - signalName == api::zone::SIGNAL_NOTIFICATION && - g_variant_is_of_type(parameters, G_VARIANT_TYPE("(sss)"))) { - - const gchar* source = NULL; - const gchar* path = NULL; - const gchar* retcode = NULL; - g_variant_get(parameters, "(&s&s&s)", &source, &path, &retcode); - - notificationSource = source; - notificationPath = path; - notificationRetcode = retcode; + notificationSource = notify.zone; + notificationPath = notify.application; + notificationRetcode = notify.message; notificationLatch.set(); - } }; // subscribe the second (destination) zone for notifications - connections.at(2)->signalSubscribe(handler); + connections.at(2)->subscribeNotification(handler); const std::string TMP = "/tmp/ut-zones"; const std::string NO_PATH = "path_doesnt_matter_here"; @@ -1051,28 +819,28 @@ BOOST_AUTO_TEST_CASE(MoveFile) // sending to a non existing zone BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(BUGGY_ZONE, NO_PATH), - api::zone::FILE_MOVE_DESTINATION_NOT_FOUND); + api::FILE_MOVE_DESTINATION_NOT_FOUND); BOOST_CHECK(notificationLatch.empty()); // sending to self BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(ZONE1, NO_PATH), - api::zone::FILE_MOVE_WRONG_DESTINATION); + api::FILE_MOVE_WRONG_DESTINATION); BOOST_CHECK(notificationLatch.empty()); // no permission to send BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(ZONE2, "/etc/secret1"), - api::zone::FILE_MOVE_NO_PERMISSIONS_SEND); + api::FILE_MOVE_NO_PERMISSIONS_SEND); BOOST_CHECK(notificationLatch.empty()); // no permission to receive // TODO uncomment this after adding an api to change 'permittedTo*' config //BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(ZONE2, "/etc/secret2"), - // api::zone::FILE_MOVE_NO_PERMISSIONS_RECEIVE); + // api::FILE_MOVE_NO_PERMISSIONS_RECEIVE); //BOOST_CHECK(notificationLatch.empty()); // non existing file BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(ZONE2, BUGGY_PATH), - api::zone::FILE_MOVE_FAILED); + api::FILE_MOVE_FAILED); BOOST_CHECK(notificationLatch.empty()); // a working scenario @@ -1085,20 +853,21 @@ BOOST_AUTO_TEST_CASE(MoveFile) BOOST_REQUIRE(utils::saveFileContent(ZONE1PATH + "/file", FILE_CONTENT)); BOOST_CHECK_EQUAL(connections.at(1)->callMethodMove(ZONE2, TMP + "/file"), - api::zone::FILE_MOVE_SUCCEEDED); + api::FILE_MOVE_SUCCEEDED); BOOST_REQUIRE(notificationLatch.wait(EVENT_TIMEOUT)); BOOST_REQUIRE(notificationLatch.empty()); BOOST_CHECK_EQUAL(notificationSource, ZONE1); BOOST_CHECK_EQUAL(notificationPath, TMP + "/file"); - BOOST_CHECK_EQUAL(notificationRetcode, api::zone::FILE_MOVE_SUCCEEDED); + BOOST_CHECK_EQUAL(notificationRetcode, api::FILE_MOVE_SUCCEEDED); BOOST_CHECK(!fs::exists(ZONE1PATH + "/file")); BOOST_CHECK_EQUAL(utils::readFileContent(ZONE2PATH + "/file"), FILE_CONTENT); fs::remove_all(ZONE1PATH, ec); fs::remove_all(ZONE2PATH, ec); } +#endif -BOOST_AUTO_TEST_CASE(AllowSwitchToDefault) +BOOST_AUTO_TEST_CASE(SwitchToDefault) { ZonesManager cm(TEST_CONFIG_PATH); cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); @@ -1106,49 +875,21 @@ BOOST_AUTO_TEST_CASE(AllowSwitchToDefault) cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); cm.restoreAll(); - std::vector> clients; - for (int i = 1; i <= TEST_DBUS_CONNECTION_ZONES_COUNT; ++i) { - clients.push_back(std::unique_ptr(new ZoneAccessory(i))); - } - - for (auto& client : clients) { - client->setName(fake_power_manager_api::BUS_NAME); - } + HostAccessory host; auto isDefaultFocused = [&cm]() -> bool { return cm.getRunningForegroundZoneId() == "zone1"; }; - for (auto& client : clients) { - // focus non-default zone with allowed switching - cm.focus("zone3"); - - // emit signal from dbus connection - client->emitSignal(fake_power_manager_api::OBJECT_PATH, - fake_power_manager_api::INTERFACE, - fake_power_manager_api::SIGNAL_DISPLAY_OFF, - nullptr); - - // check if default zone has focus - BOOST_CHECK(spinWaitFor(EVENT_TIMEOUT, isDefaultFocused)); + cm.focus("zone3"); - // focus non-default zone with disabled switching - cm.focus("zone2"); + host.signalSwitchToDefault(); - // emit signal from dbus connection - client->emitSignal(fake_power_manager_api::OBJECT_PATH, - fake_power_manager_api::INTERFACE, - fake_power_manager_api::SIGNAL_DISPLAY_OFF, - nullptr); - - // now default zone should not be focused - // TODO uncomment this after adding an api to change 'switchToDefaultAfterTimeout' - //BOOST_CHECK(!spinWaitFor(UNEXPECTED_EVENT_TIMEOUT, isDefaultFocused)); - } + // check if default zone has focus + BOOST_CHECK(spinWaitFor(EVENT_TIMEOUT, isDefaultFocused)); } -#ifdef DBUS_CONNECTION -BOOST_AUTO_TEST_CASE(ProxyCall) +BOOST_AUTO_TEST_CASE(AllowSwitchToDefault) { ZonesManager cm(TEST_CONFIG_PATH); cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); @@ -1156,152 +897,83 @@ BOOST_AUTO_TEST_CASE(ProxyCall) cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); cm.restoreAll(); - std::map> connections; - connections[0] = std::unique_ptr(new HostAccessory()); - for (int i = 1; i <= TEST_DBUS_CONNECTION_ZONES_COUNT; ++i) { - connections[i] = std::unique_ptr(new ZoneAccessory(i)); - } + HostAccessory host; - for (auto& dbus : connections) { - dbus.second->setName(testapi::BUS_NAME); + auto isDefaultFocused = [&cm]() -> bool { + return cm.getRunningForegroundZoneId() == "zone1"; + }; - const int id = dbus.first; - auto handler = [id](const std::string& argument, MethodResultBuilder::Pointer result) { - if (argument.empty()) { - result->setError("org.tizen.vasum.Error.Test", "Test error"); - } else { - std::string ret = "reply from " + std::to_string(id) + ": " + argument; - result->set(g_variant_new("(s)", ret.c_str())); - } - }; - dbus.second->registerTestApiObject(handler); - } + // focus non-default zone with allowed switching + cm.focus("zone3"); - // host -> zone2 - BOOST_CHECK_EQUAL("reply from 2: param1", - connections.at(0)->testApiProxyCall("zone2", - "param1")); + host.signalSwitchToDefault(); - // host -> host - BOOST_CHECK_EQUAL("reply from 0: param2", - connections.at(0)->testApiProxyCall("host", - "param2")); + // check if default zone has focus + BOOST_CHECK(spinWaitFor(EVENT_TIMEOUT, isDefaultFocused)); + + // focus non-default zone with disabled switching + cm.focus("zone2"); + + host.signalSwitchToDefault(); - // zone1 -> host - BOOST_CHECK_EQUAL("reply from 0: param3", - connections.at(1)->testApiProxyCall("host", - "param3")); + // now default zone should not be focused + // TODO uncomment this after adding an api to change 'switchToDefaultAfterTimeout' + //BOOST_CHECK(!spinWaitFor(UNEXPECTED_EVENT_TIMEOUT, isDefaultFocused)); +} - // zone1 -> zone2 - BOOST_CHECK_EQUAL("reply from 2: param4", - connections.at(1)->testApiProxyCall("zone2", - "param4")); +#ifdef DBUS_CONNECTION +BOOST_AUTO_TEST_CASE(ProxyCall) +{ + ZonesManager cm(TEST_CONFIG_PATH); + cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.restoreAll(); + + HostAccessory host; + host.setName(testapi::BUS_NAME); + + auto handler = [](const std::string& argument, MethodResultBuilder::Pointer result) { + if (argument.empty()) { + result->setError("org.tizen.vasum.Error.Test", "Test error"); + } else { + std::string ret = "reply from host: " + argument; + result->set(g_variant_new("(s)", ret.c_str())); + } + }; + host.registerTestApiObject(handler); - // zone2 -> zone2 - BOOST_CHECK_EQUAL("reply from 2: param5", - connections.at(2)->testApiProxyCall("zone2", - "param5")); + // host -> host + BOOST_CHECK_EQUAL("reply from host: param2", + host.testApiProxyCall("host", "param2")); // host -> unknown - BOOST_CHECK_EXCEPTION(connections.at(0)->testApiProxyCall("unknown", "param"), + BOOST_CHECK_EXCEPTION(host.testApiProxyCall("unknown", "param"), DbusCustomException, WhatEquals("Unknown proxy call target")); // forwarding error - BOOST_CHECK_EXCEPTION(connections.at(0)->testApiProxyCall("host", ""), + BOOST_CHECK_EXCEPTION(host.testApiProxyCall("host", ""), DbusCustomException, WhatEquals("Test error")); // forbidden call - BOOST_CHECK_EXCEPTION(connections.at(0)->proxyCall("host", - "org.fake", - "/a/b", - "c.d", - "foo", - g_variant_new("(s)", "arg")), + BOOST_CHECK_EXCEPTION(host.proxyCall("host", + "org.fake", + "/a/b", + "c.d", + "foo", + g_variant_new("(s)", "arg")), DbusCustomException, WhatEquals("Proxy call forbidden")); } #endif // DBUS_CONNECTION namespace { - const HostAccessory::Connections EXPECTED_CONNECTIONS_NONE = { - {"zone1", ""}, - {"zone2", ""}, - {"zone3", ""}}; - - const HostAccessory::Connections EXPECTED_CONNECTIONS_ALL = { - {"zone1", - "unix:path=/tmp/ut-run/zone1/dbus/system_bus_socket"}, - {"zone2", - "unix:path=/tmp/ut-run/zone2/dbus/system_bus_socket"}, - {"zone3", - "unix:path=/tmp/ut-run/zone3/dbus/system_bus_socket"}}; -} // namespace - -BOOST_AUTO_TEST_CASE(GetZoneConnections) -{ - ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); - - BOOST_CHECK(EXPECTED_CONNECTIONS_NONE == host.callMethodGetZoneConnections()); - cm.restoreAll(); - BOOST_CHECK(EXPECTED_CONNECTIONS_ALL == host.callMethodGetZoneConnections()); - cm.shutdownAll(); - BOOST_CHECK(EXPECTED_CONNECTIONS_NONE == host.callMethodGetZoneConnections()); -} - -BOOST_AUTO_TEST_CASE(GetZoneConnectionsNoDbus) -{ - ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; - cm.createZone("zone1", SIMPLE_TEMPLATE); - cm.createZone("zone2", SIMPLE_TEMPLATE); - cm.createZone("zone3", SIMPLE_TEMPLATE); - - BOOST_CHECK(EXPECTED_CONNECTIONS_NONE == host.callMethodGetZoneConnections()); - cm.restoreAll(); - BOOST_CHECK(EXPECTED_CONNECTIONS_NONE == host.callMethodGetZoneConnections()); - cm.shutdownAll(); - BOOST_CHECK(EXPECTED_CONNECTIONS_NONE == host.callMethodGetZoneConnections()); -} -BOOST_AUTO_TEST_CASE(ZoneConnectionsSignals) -{ - Latch signalLatch; - HostAccessory::Connections collectedConnections; - std::mutex collectedConnectionsMutex; - - auto onSignal = [&] (const std::string& zoneId, const std::string& address) { - std::unique_lock lock(collectedConnectionsMutex); - collectedConnections.insert(HostAccessory::Connections::value_type(zoneId, address)); - signalLatch.set(); - }; - - { - ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; - host.subscribeZoneConnectionState(onSignal); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); - - BOOST_CHECK(signalLatch.empty()); - BOOST_CHECK(collectedConnections.empty()); - - cm.restoreAll(); - - BOOST_REQUIRE(signalLatch.waitForN(TEST_DBUS_CONNECTION_ZONES_COUNT, EVENT_TIMEOUT)); - BOOST_CHECK(signalLatch.empty()); - std::unique_lock lock(collectedConnectionsMutex); - BOOST_CHECK(EXPECTED_CONNECTIONS_ALL == collectedConnections); - collectedConnections.clear(); - } -} +const std::set EXPECTED_CONNECTIONS_NONE = { "zone1", "zone2", "zone3" }; +} // namespace BOOST_AUTO_TEST_CASE(GetZoneIds) { -- 2.7.4 From 762ce7ad4b9d8f640d360f1e3502da590166af22 Mon Sep 17 00:00:00 2001 From: Dariusz Michaluk Date: Mon, 20 Apr 2015 15:21:39 +0200 Subject: [PATCH 02/16] Create libLogger, libSimpleDbus, libConfig packages. [Bug/Feature] Create libLogger, libSimpleDbus, libConfig packages. [Cause] N/A [Solution] N/A [Verification] Build, install, run tests, run server. Change-Id: Iab8c507315f6534ffd11e9f664e017ab45d7e94e Signed-off-by: Dariusz Michaluk --- CMakeLists.txt | 7 ++ client/CMakeLists.txt | 13 +-- libs/config/CMakeLists.txt | 60 ++++++++++++ libs/config/config.hpp | 78 ++++++++++++++++ {common => libs}/config/exception.hpp | 0 {common => libs}/config/fdstore.cpp | 2 +- {common => libs}/config/fdstore.hpp | 0 {common => libs}/config/fields-union.hpp | 0 {common => libs}/config/fields.hpp | 0 {common => libs}/config/from-fdstore-visitor.hpp | 0 {common => libs}/config/from-gvariant-visitor.hpp | 0 {common => libs}/config/from-json-visitor.hpp | 0 {common => libs}/config/from-kvjson-visitor.hpp | 0 {common => libs}/config/from-kvstore-visitor.hpp | 0 {common => libs}/config/fs-utils.cpp | 0 {common => libs}/config/fs-utils.hpp | 0 {common => libs}/config/is-union.hpp | 0 {common => libs}/config/is-visitable.hpp | 0 {common => libs}/config/kvstore.cpp | 2 +- {common => libs}/config/kvstore.hpp | 0 libs/config/libConfig.pc.in | 12 +++ {common => libs}/config/manager.hpp | 0 {common => libs}/config/sqlite3/connection.cpp | 0 {common => libs}/config/sqlite3/connection.hpp | 0 {common => libs}/config/sqlite3/statement.cpp | 0 {common => libs}/config/sqlite3/statement.hpp | 0 {common => libs}/config/to-fdstore-visitor.hpp | 0 {common => libs}/config/to-gvariant-visitor.hpp | 0 {common => libs}/config/to-json-visitor.hpp | 0 {common => libs}/config/to-kvstore-visitor.hpp | 0 libs/dbus/CMakeLists.txt | 68 ++++++++++++++ libs/dbus/config.hpp | 78 ++++++++++++++++ {common => libs}/dbus/connection.cpp | 2 +- {common => libs}/dbus/connection.hpp | 0 {common => libs}/dbus/exception.hpp | 0 libs/dbus/libSimpleDbus.pc.in | 12 +++ libs/logger/CMakeLists.txt | 56 +++++++++++ {common => libs}/logger/backend-journal.cpp | 2 +- {common => libs}/logger/backend-journal.hpp | 0 {common => libs}/logger/backend-null.hpp | 0 {common => libs}/logger/backend-stderr.cpp | 2 +- {common => libs}/logger/backend-stderr.hpp | 0 {common => libs}/logger/backend.hpp | 0 {common => libs}/logger/ccolor.cpp | 2 +- {common => libs}/logger/ccolor.hpp | 0 libs/logger/config.hpp | 78 ++++++++++++++++ {common => libs}/logger/formatter.cpp | 2 +- {common => libs}/logger/formatter.hpp | 0 {common => libs}/logger/level.cpp | 2 +- {common => libs}/logger/level.hpp | 0 libs/logger/libLogger.pc.in | 12 +++ {common => libs}/logger/logger-scope.cpp | 0 {common => libs}/logger/logger-scope.hpp | 0 {common => libs}/logger/logger.cpp | 2 +- {common => libs}/logger/logger.hpp | 0 packaging/vasum.spec | 109 +++++++++++++++++++++- server/CMakeLists.txt | 7 +- tests/unit_tests/CMakeLists.txt | 10 +- zone-daemon/CMakeLists.txt | 8 +- 59 files changed, 595 insertions(+), 31 deletions(-) create mode 100644 libs/config/CMakeLists.txt create mode 100644 libs/config/config.hpp rename {common => libs}/config/exception.hpp (100%) rename {common => libs}/config/fdstore.cpp (99%) rename {common => libs}/config/fdstore.hpp (100%) rename {common => libs}/config/fields-union.hpp (100%) rename {common => libs}/config/fields.hpp (100%) rename {common => libs}/config/from-fdstore-visitor.hpp (100%) rename {common => libs}/config/from-gvariant-visitor.hpp (100%) rename {common => libs}/config/from-json-visitor.hpp (100%) rename {common => libs}/config/from-kvjson-visitor.hpp (100%) rename {common => libs}/config/from-kvstore-visitor.hpp (100%) rename {common => libs}/config/fs-utils.cpp (100%) rename {common => libs}/config/fs-utils.hpp (100%) rename {common => libs}/config/is-union.hpp (100%) rename {common => libs}/config/is-visitable.hpp (100%) rename {common => libs}/config/kvstore.cpp (99%) rename {common => libs}/config/kvstore.hpp (100%) create mode 100644 libs/config/libConfig.pc.in rename {common => libs}/config/manager.hpp (100%) rename {common => libs}/config/sqlite3/connection.cpp (100%) rename {common => libs}/config/sqlite3/connection.hpp (100%) rename {common => libs}/config/sqlite3/statement.cpp (100%) rename {common => libs}/config/sqlite3/statement.hpp (100%) rename {common => libs}/config/to-fdstore-visitor.hpp (100%) rename {common => libs}/config/to-gvariant-visitor.hpp (100%) rename {common => libs}/config/to-json-visitor.hpp (100%) rename {common => libs}/config/to-kvstore-visitor.hpp (100%) create mode 100644 libs/dbus/CMakeLists.txt create mode 100644 libs/dbus/config.hpp rename {common => libs}/dbus/connection.cpp (99%) rename {common => libs}/dbus/connection.hpp (100%) rename {common => libs}/dbus/exception.hpp (100%) create mode 100644 libs/dbus/libSimpleDbus.pc.in create mode 100644 libs/logger/CMakeLists.txt rename {common => libs}/logger/backend-journal.cpp (98%) rename {common => libs}/logger/backend-journal.hpp (100%) rename {common => libs}/logger/backend-null.hpp (100%) rename {common => libs}/logger/backend-stderr.cpp (98%) rename {common => libs}/logger/backend-stderr.hpp (100%) rename {common => libs}/logger/backend.hpp (100%) rename {common => libs}/logger/ccolor.cpp (97%) rename {common => libs}/logger/ccolor.hpp (100%) create mode 100644 libs/logger/config.hpp rename {common => libs}/logger/formatter.cpp (99%) rename {common => libs}/logger/formatter.hpp (100%) rename {common => libs}/logger/level.cpp (98%) rename {common => libs}/logger/level.hpp (100%) create mode 100644 libs/logger/libLogger.pc.in rename {common => libs}/logger/logger-scope.cpp (100%) rename {common => libs}/logger/logger-scope.hpp (100%) rename {common => libs}/logger/logger.cpp (98%) rename {common => libs}/logger/logger.hpp (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 308fb45..9b61793 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -133,6 +133,10 @@ ENDIF(NOT DEFINED PYTHON_SITELIB) ## Subdirectories ############################################################## SET(COMMON_FOLDER ${PROJECT_SOURCE_DIR}/common) +SET(LIBS_FOLDER ${PROJECT_SOURCE_DIR}/libs) +SET(LOGGER_FOLDER ${PROJECT_SOURCE_DIR}/libs/logger) +SET(DBUS_FOLDER ${PROJECT_SOURCE_DIR}/libs/dbus) +SET(CONFIG_FOLDER ${PROJECT_SOURCE_DIR}/libs/config) SET(CLIENT_FOLDER ${PROJECT_SOURCE_DIR}/client) SET(SERVER_FOLDER ${PROJECT_SOURCE_DIR}/server) SET(ZONE_SUPPORT_FOLDER ${PROJECT_SOURCE_DIR}/zone-support) @@ -172,6 +176,9 @@ SET(VSM_CONFIG_INSTALL_DIR ${SYSCONF_INSTALL_DIR}/vasum) SET(VSM_SERVER_IPC_SOCKET_PATH /var/run/vasum-ipc.socket) SET(VSM_UNIT_TESTS_IPC_SOCKET_PATH /var/run/vasum-ipc-unit-tests.socket) +ADD_SUBDIRECTORY(${LOGGER_FOLDER}) +ADD_SUBDIRECTORY(${DBUS_FOLDER}) +ADD_SUBDIRECTORY(${CONFIG_FOLDER}) ADD_SUBDIRECTORY(${CLIENT_FOLDER}) ADD_SUBDIRECTORY(${SERVER_FOLDER}) ADD_SUBDIRECTORY(${ZONE_SUPPORT_FOLDER}) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index afe609f..753b7c4 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -20,13 +20,9 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") FILE(GLOB project_SRCS *.cpp *.hpp *.h) -FILE(GLOB common_SRCS ${COMMON_FOLDER}/config/*.hpp ${COMMON_FOLDER}/config/*.cpp - ${COMMON_FOLDER}/config/sqlite3/*.hpp ${COMMON_FOLDER}/config/sqlite3/*.cpp - ${COMMON_FOLDER}/dbus/*.hpp ${COMMON_FOLDER}/dbus/*.cpp - ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp +FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp ${COMMON_FOLDER}/ipc/*.hpp ${COMMON_FOLDER}/ipc/*.cpp ${COMMON_FOLDER}/ipc/internals/*.hpp ${COMMON_FOLDER}/ipc/internals/*.cpp - ${COMMON_FOLDER}/logger/*.hpp ${COMMON_FOLDER}/logger/*.cpp ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/utils/*.cpp ${COMMON_FOLDER}/*.hpp ${COMMON_FOLDER}/*.cpp) @@ -47,14 +43,15 @@ SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${_LIB_VERSION_} COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") - ## Link libraries ############################################################## FIND_PACKAGE(Boost COMPONENTS system filesystem) -PKG_CHECK_MODULES(LIB_DEPS REQUIRED gio-2.0 libsystemd-daemon libsystemd-journal libcap-ng sqlite3) +PKG_CHECK_MODULES(LIB_DEPS REQUIRED gio-2.0 libsystemd-daemon libcap-ng) INCLUDE_DIRECTORIES(SYSTEM ${LIB_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) INCLUDE_DIRECTORIES(${SERVER_FOLDER}) -TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Config SimpleDbus) ## Generate the pc file ######################################################## CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_BINARY_DIR}/${PC_FILE} @ONLY) diff --git a/libs/config/CMakeLists.txt b/libs/config/CMakeLists.txt new file mode 100644 index 0000000..377b734 --- /dev/null +++ b/libs/config/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Dariusz Michaluk (d.michaluk@samsung.com) +# + +PROJECT(Config) + +MESSAGE(STATUS "") +MESSAGE(STATUS "Generating makefile for the libConfig...") +FILE(GLOB HEADERS *.hpp) +FILE(GLOB HEADERS_SQLITE3 ${CMAKE_CURRENT_BINARY_DIR}/sqlite3/*.hpp) +FILE(GLOB_RECURSE SRCS *.cpp *.hpp) + +SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_SOVERSION_ "0") +SET(PC_FILE "lib${PROJECT_NAME}.pc") + +## Setup target ################################################################ +ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRCS}) +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + SOVERSION ${_LIB_SOVERSION_} + VERSION ${_LIB_VERSION_} +) + +## Link libraries ############################################################## +PKG_CHECK_MODULES(CONFIG_DEPS REQUIRED sqlite3 glib-2.0) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) +INCLUDE_DIRECTORIES(SYSTEM ${CONFIG_DEPS_INCLUDE_DIRS}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${pkgs_LDFLAGS} ${CONFIG_DEPS_LIBRARIES}) + +## Generate the pc file ######################################################## +CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} @ONLY) + +## Install ##################################################################### +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} + DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) + +INSTALL(TARGETS ${PROJECT_NAME} + DESTINATION ${LIB_INSTALL_DIR} + COMPONENT RuntimeLibraries) + +INSTALL(FILES ${HEADERS} + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum-tools/config) + +INSTALL(FILES ${HEADERS_SQLITE3} + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum-tools/config/sqlite3) diff --git a/libs/config/config.hpp b/libs/config/config.hpp new file mode 100644 index 0000000..753430e --- /dev/null +++ b/libs/config/config.hpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + +/** + * @file + * @author Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * @brief Configuration file for the code + */ + + +#ifndef COMMON_CONFIG_HPP +#define COMMON_CONFIG_HPP + + +#ifdef __clang__ +#define CLANG_VERSION (__clang__major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) +#endif // __clang__ + +#if defined __GNUC__ && !defined __clang__ // clang also defines GCC versions +#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + + +#ifdef GCC_VERSION + +#if GCC_VERSION < 40800 +// GCC 4.8 is the first where those defines are not required for +// std::this_thread::sleep_for() and ::yield(). They might exist though +// in previous versions depending on the build configuration of the GCC. +#ifndef _GLIBCXX_USE_NANOSLEEP +#define _GLIBCXX_USE_NANOSLEEP +#endif // _GLIBCXX_USE_NANOSLEEP +#ifndef _GLIBCXX_USE_SCHED_YIELD +#define _GLIBCXX_USE_SCHED_YIELD +#endif // _GLIBCXX_USE_SCHED_YIELD +#endif // GCC_VERSION < 40800 + +#if GCC_VERSION < 40700 +// Those appeared in 4.7 with full c++11 support +#define final +#define override +#define thread_local __thread // use GCC extension instead of C++11 +#define steady_clock monotonic_clock +#endif // GCC_VERSION < 40700 + +#endif // GCC_VERSION + +// Variadic macros support for boost preprocessor should be enabled +// manually for clang since they are marked as untested feature +// (boost trunk if fixed but the latest 1.55 version is not, +// see boost/preprocessor/config/config.hpp) +#ifdef __clang__ +#define BOOST_PP_VARIADICS 1 +#endif + +// This has to be defined always when the boost has not been compiled +// using C++11. Headers detect that you are compiling using C++11 and +// blindly and wrongly assume that boost has been as well. +#ifndef BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_CXX11_SCOPED_ENUMS 1 +#endif + +#endif // COMMON_CONFIG_HPP diff --git a/common/config/exception.hpp b/libs/config/exception.hpp similarity index 100% rename from common/config/exception.hpp rename to libs/config/exception.hpp diff --git a/common/config/fdstore.cpp b/libs/config/fdstore.cpp similarity index 99% rename from common/config/fdstore.cpp rename to libs/config/fdstore.cpp index c1cedfe..2b761eb 100644 --- a/common/config/fdstore.cpp +++ b/libs/config/fdstore.cpp @@ -22,7 +22,7 @@ * @brief Definition of a class for writing and reading data from a file descriptor */ -#include "config.hpp" +#include "config/config.hpp" #include "config/fdstore.hpp" #include "config/exception.hpp" diff --git a/common/config/fdstore.hpp b/libs/config/fdstore.hpp similarity index 100% rename from common/config/fdstore.hpp rename to libs/config/fdstore.hpp diff --git a/common/config/fields-union.hpp b/libs/config/fields-union.hpp similarity index 100% rename from common/config/fields-union.hpp rename to libs/config/fields-union.hpp diff --git a/common/config/fields.hpp b/libs/config/fields.hpp similarity index 100% rename from common/config/fields.hpp rename to libs/config/fields.hpp diff --git a/common/config/from-fdstore-visitor.hpp b/libs/config/from-fdstore-visitor.hpp similarity index 100% rename from common/config/from-fdstore-visitor.hpp rename to libs/config/from-fdstore-visitor.hpp diff --git a/common/config/from-gvariant-visitor.hpp b/libs/config/from-gvariant-visitor.hpp similarity index 100% rename from common/config/from-gvariant-visitor.hpp rename to libs/config/from-gvariant-visitor.hpp diff --git a/common/config/from-json-visitor.hpp b/libs/config/from-json-visitor.hpp similarity index 100% rename from common/config/from-json-visitor.hpp rename to libs/config/from-json-visitor.hpp diff --git a/common/config/from-kvjson-visitor.hpp b/libs/config/from-kvjson-visitor.hpp similarity index 100% rename from common/config/from-kvjson-visitor.hpp rename to libs/config/from-kvjson-visitor.hpp diff --git a/common/config/from-kvstore-visitor.hpp b/libs/config/from-kvstore-visitor.hpp similarity index 100% rename from common/config/from-kvstore-visitor.hpp rename to libs/config/from-kvstore-visitor.hpp diff --git a/common/config/fs-utils.cpp b/libs/config/fs-utils.cpp similarity index 100% rename from common/config/fs-utils.cpp rename to libs/config/fs-utils.cpp diff --git a/common/config/fs-utils.hpp b/libs/config/fs-utils.hpp similarity index 100% rename from common/config/fs-utils.hpp rename to libs/config/fs-utils.hpp diff --git a/common/config/is-union.hpp b/libs/config/is-union.hpp similarity index 100% rename from common/config/is-union.hpp rename to libs/config/is-union.hpp diff --git a/common/config/is-visitable.hpp b/libs/config/is-visitable.hpp similarity index 100% rename from common/config/is-visitable.hpp rename to libs/config/is-visitable.hpp diff --git a/common/config/kvstore.cpp b/libs/config/kvstore.cpp similarity index 99% rename from common/config/kvstore.cpp rename to libs/config/kvstore.cpp index 49656ae..b6d922e 100644 --- a/common/config/kvstore.cpp +++ b/libs/config/kvstore.cpp @@ -22,7 +22,7 @@ * @brief Definition of a class for key-value storage in a sqlite3 database */ -#include "config.hpp" +#include "config/config.hpp" #include "config/kvstore.hpp" #include "config/exception.hpp" diff --git a/common/config/kvstore.hpp b/libs/config/kvstore.hpp similarity index 100% rename from common/config/kvstore.hpp rename to libs/config/kvstore.hpp diff --git a/libs/config/libConfig.pc.in b/libs/config/libConfig.pc.in new file mode 100644 index 0000000..82f4559 --- /dev/null +++ b/libs/config/libConfig.pc.in @@ -0,0 +1,12 @@ +# Package Information for pkg-config + +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@LIB_INSTALL_DIR@ +includedir=@INCLUDE_INSTALL_DIR@ + +Name: libConfig +Description: Config library +Version: @_LIB_VERSION_@ +Libs: -L${libdir} -lConfig +Cflags: -I${includedir}/vasum-tools diff --git a/common/config/manager.hpp b/libs/config/manager.hpp similarity index 100% rename from common/config/manager.hpp rename to libs/config/manager.hpp diff --git a/common/config/sqlite3/connection.cpp b/libs/config/sqlite3/connection.cpp similarity index 100% rename from common/config/sqlite3/connection.cpp rename to libs/config/sqlite3/connection.cpp diff --git a/common/config/sqlite3/connection.hpp b/libs/config/sqlite3/connection.hpp similarity index 100% rename from common/config/sqlite3/connection.hpp rename to libs/config/sqlite3/connection.hpp diff --git a/common/config/sqlite3/statement.cpp b/libs/config/sqlite3/statement.cpp similarity index 100% rename from common/config/sqlite3/statement.cpp rename to libs/config/sqlite3/statement.cpp diff --git a/common/config/sqlite3/statement.hpp b/libs/config/sqlite3/statement.hpp similarity index 100% rename from common/config/sqlite3/statement.hpp rename to libs/config/sqlite3/statement.hpp diff --git a/common/config/to-fdstore-visitor.hpp b/libs/config/to-fdstore-visitor.hpp similarity index 100% rename from common/config/to-fdstore-visitor.hpp rename to libs/config/to-fdstore-visitor.hpp diff --git a/common/config/to-gvariant-visitor.hpp b/libs/config/to-gvariant-visitor.hpp similarity index 100% rename from common/config/to-gvariant-visitor.hpp rename to libs/config/to-gvariant-visitor.hpp diff --git a/common/config/to-json-visitor.hpp b/libs/config/to-json-visitor.hpp similarity index 100% rename from common/config/to-json-visitor.hpp rename to libs/config/to-json-visitor.hpp diff --git a/common/config/to-kvstore-visitor.hpp b/libs/config/to-kvstore-visitor.hpp similarity index 100% rename from common/config/to-kvstore-visitor.hpp rename to libs/config/to-kvstore-visitor.hpp diff --git a/libs/dbus/CMakeLists.txt b/libs/dbus/CMakeLists.txt new file mode 100644 index 0000000..cd2c06c --- /dev/null +++ b/libs/dbus/CMakeLists.txt @@ -0,0 +1,68 @@ +# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Dariusz Michaluk (d.michaluk@samsung.com) +# + +PROJECT(SimpleDbus) + +MESSAGE(STATUS "") +MESSAGE(STATUS "Generating makefile for the libSimpleDbus...") +FILE(GLOB HEADERS *.hpp) +FILE(GLOB HEADERS_UTILS ${COMMON_FOLDER}/utils/callback-guard.hpp + ${COMMON_FOLDER}/utils/scoped-gerror.hpp + ${COMMON_FOLDER}/utils/glib-utils.hpp + ${COMMON_FOLDER}/utils/callback-wrapper.hpp) +FILE(GLOB SRCS_UTILS ${COMMON_FOLDER}/utils/callback-guard.cpp + ${COMMON_FOLDER}/utils/scoped-gerror.cpp + ${COMMON_FOLDER}/utils/glib-utils.cpp + ${COMMON_FOLDER}/utils/callback-wrapper.cpp) +FILE(GLOB SRCS *.cpp *.hpp) + +SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_SOVERSION_ "0") +SET(PC_FILE "lib${PROJECT_NAME}.pc") + +## Setup target ################################################################ +ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRCS} ${SRCS_UTILS}) +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + SOVERSION ${_LIB_SOVERSION_} + VERSION ${_LIB_VERSION_} +) + +## Link libraries ############################################################## +PKG_CHECK_MODULES(DBUS_DEPS REQUIRED glib-2.0 gio-2.0) +INCLUDE_DIRECTORIES(${COMMON_FOLDER}) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) +INCLUDE_DIRECTORIES(SYSTEM ${DBUS_DEPS_INCLUDE_DIRS}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${pkgs_LDFLAGS} ${DBUS_DEPS_LIBRARIES} Logger) + +## Generate the pc file ######################################################## +CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} @ONLY) + +## Install ##################################################################### +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} + DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) + +INSTALL(TARGETS ${PROJECT_NAME} + DESTINATION ${LIB_INSTALL_DIR} + COMPONENT RuntimeLibraries) + +INSTALL(FILES ${HEADERS} + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum-tools/dbus) + +INSTALL(FILES ${HEADERS_UTILS} + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum-tools/dbus/utils) diff --git a/libs/dbus/config.hpp b/libs/dbus/config.hpp new file mode 100644 index 0000000..753430e --- /dev/null +++ b/libs/dbus/config.hpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + +/** + * @file + * @author Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * @brief Configuration file for the code + */ + + +#ifndef COMMON_CONFIG_HPP +#define COMMON_CONFIG_HPP + + +#ifdef __clang__ +#define CLANG_VERSION (__clang__major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) +#endif // __clang__ + +#if defined __GNUC__ && !defined __clang__ // clang also defines GCC versions +#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + + +#ifdef GCC_VERSION + +#if GCC_VERSION < 40800 +// GCC 4.8 is the first where those defines are not required for +// std::this_thread::sleep_for() and ::yield(). They might exist though +// in previous versions depending on the build configuration of the GCC. +#ifndef _GLIBCXX_USE_NANOSLEEP +#define _GLIBCXX_USE_NANOSLEEP +#endif // _GLIBCXX_USE_NANOSLEEP +#ifndef _GLIBCXX_USE_SCHED_YIELD +#define _GLIBCXX_USE_SCHED_YIELD +#endif // _GLIBCXX_USE_SCHED_YIELD +#endif // GCC_VERSION < 40800 + +#if GCC_VERSION < 40700 +// Those appeared in 4.7 with full c++11 support +#define final +#define override +#define thread_local __thread // use GCC extension instead of C++11 +#define steady_clock monotonic_clock +#endif // GCC_VERSION < 40700 + +#endif // GCC_VERSION + +// Variadic macros support for boost preprocessor should be enabled +// manually for clang since they are marked as untested feature +// (boost trunk if fixed but the latest 1.55 version is not, +// see boost/preprocessor/config/config.hpp) +#ifdef __clang__ +#define BOOST_PP_VARIADICS 1 +#endif + +// This has to be defined always when the boost has not been compiled +// using C++11. Headers detect that you are compiling using C++11 and +// blindly and wrongly assume that boost has been as well. +#ifndef BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_CXX11_SCOPED_ENUMS 1 +#endif + +#endif // COMMON_CONFIG_HPP diff --git a/common/dbus/connection.cpp b/libs/dbus/connection.cpp similarity index 99% rename from common/dbus/connection.cpp rename to libs/dbus/connection.cpp index 12544be..441174b 100644 --- a/common/dbus/connection.cpp +++ b/libs/dbus/connection.cpp @@ -22,7 +22,7 @@ * @brief Dbus connection class */ -#include "config.hpp" +#include "dbus/config.hpp" #include "dbus/connection.hpp" #include "dbus/exception.hpp" #include "utils/callback-wrapper.hpp" diff --git a/common/dbus/connection.hpp b/libs/dbus/connection.hpp similarity index 100% rename from common/dbus/connection.hpp rename to libs/dbus/connection.hpp diff --git a/common/dbus/exception.hpp b/libs/dbus/exception.hpp similarity index 100% rename from common/dbus/exception.hpp rename to libs/dbus/exception.hpp diff --git a/libs/dbus/libSimpleDbus.pc.in b/libs/dbus/libSimpleDbus.pc.in new file mode 100644 index 0000000..b3adec3 --- /dev/null +++ b/libs/dbus/libSimpleDbus.pc.in @@ -0,0 +1,12 @@ +# Package Information for pkg-config + +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@LIB_INSTALL_DIR@ +includedir=@INCLUDE_INSTALL_DIR@ + +Name: libSimpleDbus +Description: Simple Dbus library +Version: @_LIB_VERSION_@ +Libs: -L${libdir} -lSimpleDbus +Cflags: -I${includedir}/vasum-tools diff --git a/libs/logger/CMakeLists.txt b/libs/logger/CMakeLists.txt new file mode 100644 index 0000000..786f8bc --- /dev/null +++ b/libs/logger/CMakeLists.txt @@ -0,0 +1,56 @@ +# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Dariusz Michaluk (d.michaluk@samsung.com) +# + +PROJECT(Logger) + +MESSAGE(STATUS "") +MESSAGE(STATUS "Generating makefile for the libLogger...") +FILE(GLOB HEADERS *.hpp) +FILE(GLOB SRCS *.cpp *.hpp) + +SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_SOVERSION_ "0") +SET(PC_FILE "lib${PROJECT_NAME}.pc") + +## Setup target ################################################################ +ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRCS}) +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + SOVERSION ${_LIB_SOVERSION_} + VERSION ${_LIB_VERSION_} +) + +## Link libraries ############################################################## +PKG_CHECK_MODULES(LOGGER_DEPS REQUIRED libsystemd-journal) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) +INCLUDE_DIRECTORIES(SYSTEM ${LOGGER_DEPS_INCLUDE_DIRS}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${pkgs_LDFLAGS} ${LOGGER_DEPS_LIBRARIES}) + +## Generate the pc file ######################################################## +CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} @ONLY) + +## Install ##################################################################### +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PC_FILE} + DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) + +INSTALL(TARGETS ${PROJECT_NAME} + DESTINATION ${LIB_INSTALL_DIR} + COMPONENT RuntimeLibraries) + +INSTALL(FILES ${HEADERS} + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum-tools/logger) diff --git a/common/logger/backend-journal.cpp b/libs/logger/backend-journal.cpp similarity index 98% rename from common/logger/backend-journal.cpp rename to libs/logger/backend-journal.cpp index 12c4eff..74fc581 100644 --- a/common/logger/backend-journal.cpp +++ b/libs/logger/backend-journal.cpp @@ -22,7 +22,7 @@ * @brief Systemd journal backend for logger */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/backend-journal.hpp" #define SD_JOURNAL_SUPPRESS_LOCATION diff --git a/common/logger/backend-journal.hpp b/libs/logger/backend-journal.hpp similarity index 100% rename from common/logger/backend-journal.hpp rename to libs/logger/backend-journal.hpp diff --git a/common/logger/backend-null.hpp b/libs/logger/backend-null.hpp similarity index 100% rename from common/logger/backend-null.hpp rename to libs/logger/backend-null.hpp diff --git a/common/logger/backend-stderr.cpp b/libs/logger/backend-stderr.cpp similarity index 98% rename from common/logger/backend-stderr.cpp rename to libs/logger/backend-stderr.cpp index d4e36b1..c0d3a3c 100644 --- a/common/logger/backend-stderr.cpp +++ b/libs/logger/backend-stderr.cpp @@ -22,7 +22,7 @@ * @brief Stderr backend for logger */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/backend-stderr.hpp" #include "logger/formatter.hpp" diff --git a/common/logger/backend-stderr.hpp b/libs/logger/backend-stderr.hpp similarity index 100% rename from common/logger/backend-stderr.hpp rename to libs/logger/backend-stderr.hpp diff --git a/common/logger/backend.hpp b/libs/logger/backend.hpp similarity index 100% rename from common/logger/backend.hpp rename to libs/logger/backend.hpp diff --git a/common/logger/ccolor.cpp b/libs/logger/ccolor.cpp similarity index 97% rename from common/logger/ccolor.cpp rename to libs/logger/ccolor.cpp index e5e71b0..7424044 100644 --- a/common/logger/ccolor.cpp +++ b/libs/logger/ccolor.cpp @@ -22,7 +22,7 @@ * @brief Console color for StderrBackend logger */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/ccolor.hpp" #include diff --git a/common/logger/ccolor.hpp b/libs/logger/ccolor.hpp similarity index 100% rename from common/logger/ccolor.hpp rename to libs/logger/ccolor.hpp diff --git a/libs/logger/config.hpp b/libs/logger/config.hpp new file mode 100644 index 0000000..753430e --- /dev/null +++ b/libs/logger/config.hpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + +/** + * @file + * @author Lukasz Pawelczyk (l.pawelczyk@partner.samsung.com) + * @brief Configuration file for the code + */ + + +#ifndef COMMON_CONFIG_HPP +#define COMMON_CONFIG_HPP + + +#ifdef __clang__ +#define CLANG_VERSION (__clang__major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) +#endif // __clang__ + +#if defined __GNUC__ && !defined __clang__ // clang also defines GCC versions +#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + + +#ifdef GCC_VERSION + +#if GCC_VERSION < 40800 +// GCC 4.8 is the first where those defines are not required for +// std::this_thread::sleep_for() and ::yield(). They might exist though +// in previous versions depending on the build configuration of the GCC. +#ifndef _GLIBCXX_USE_NANOSLEEP +#define _GLIBCXX_USE_NANOSLEEP +#endif // _GLIBCXX_USE_NANOSLEEP +#ifndef _GLIBCXX_USE_SCHED_YIELD +#define _GLIBCXX_USE_SCHED_YIELD +#endif // _GLIBCXX_USE_SCHED_YIELD +#endif // GCC_VERSION < 40800 + +#if GCC_VERSION < 40700 +// Those appeared in 4.7 with full c++11 support +#define final +#define override +#define thread_local __thread // use GCC extension instead of C++11 +#define steady_clock monotonic_clock +#endif // GCC_VERSION < 40700 + +#endif // GCC_VERSION + +// Variadic macros support for boost preprocessor should be enabled +// manually for clang since they are marked as untested feature +// (boost trunk if fixed but the latest 1.55 version is not, +// see boost/preprocessor/config/config.hpp) +#ifdef __clang__ +#define BOOST_PP_VARIADICS 1 +#endif + +// This has to be defined always when the boost has not been compiled +// using C++11. Headers detect that you are compiling using C++11 and +// blindly and wrongly assume that boost has been as well. +#ifndef BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_CXX11_SCOPED_ENUMS 1 +#endif + +#endif // COMMON_CONFIG_HPP diff --git a/common/logger/formatter.cpp b/libs/logger/formatter.cpp similarity index 99% rename from common/logger/formatter.cpp rename to libs/logger/formatter.cpp index 529cd14..815a111 100644 --- a/common/logger/formatter.cpp +++ b/libs/logger/formatter.cpp @@ -22,7 +22,7 @@ * @brief Helper formatter for logger */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/formatter.hpp" #include "logger/ccolor.hpp" diff --git a/common/logger/formatter.hpp b/libs/logger/formatter.hpp similarity index 100% rename from common/logger/formatter.hpp rename to libs/logger/formatter.hpp diff --git a/common/logger/level.cpp b/libs/logger/level.cpp similarity index 98% rename from common/logger/level.cpp rename to libs/logger/level.cpp index bf46561..3b74205 100644 --- a/common/logger/level.cpp +++ b/libs/logger/level.cpp @@ -22,7 +22,7 @@ * @brief Functions to handle LogLevel */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/level.hpp" #include diff --git a/common/logger/level.hpp b/libs/logger/level.hpp similarity index 100% rename from common/logger/level.hpp rename to libs/logger/level.hpp diff --git a/libs/logger/libLogger.pc.in b/libs/logger/libLogger.pc.in new file mode 100644 index 0000000..f4acc69 --- /dev/null +++ b/libs/logger/libLogger.pc.in @@ -0,0 +1,12 @@ +# Package Information for pkg-config + +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@LIB_INSTALL_DIR@ +includedir=@INCLUDE_INSTALL_DIR@ + +Name: libLogger +Description: Logger library +Version: @_LIB_VERSION_@ +Libs: -L${libdir} -lLogger +Cflags: -I${includedir}/vasum-tools diff --git a/common/logger/logger-scope.cpp b/libs/logger/logger-scope.cpp similarity index 100% rename from common/logger/logger-scope.cpp rename to libs/logger/logger-scope.cpp diff --git a/common/logger/logger-scope.hpp b/libs/logger/logger-scope.hpp similarity index 100% rename from common/logger/logger-scope.hpp rename to libs/logger/logger-scope.hpp diff --git a/common/logger/logger.cpp b/libs/logger/logger.cpp similarity index 98% rename from common/logger/logger.cpp rename to libs/logger/logger.cpp index aa2dccd..ec0855b 100644 --- a/common/logger/logger.cpp +++ b/libs/logger/logger.cpp @@ -22,7 +22,7 @@ * @brief Logger */ -#include "config.hpp" +#include "logger/config.hpp" #include "logger/logger.hpp" #include "logger/formatter.hpp" #include "logger/backend-null.hpp" diff --git a/common/logger/logger.hpp b/libs/logger/logger.hpp similarity index 100% rename from common/logger/logger.hpp rename to libs/logger/logger.hpp diff --git a/packaging/vasum.spec b/packaging/vasum.spec index bd31d68..55567c7 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -147,11 +147,10 @@ Development package including the header files for the client library %defattr(644,root,root,755) %{_libdir}/libvasum.so %{_includedir}/vasum -%{_libdir}/pkgconfig/*.pc +%{_libdir}/pkgconfig/vasum.pc ## Zone Support Package ################################################### -# TODO move to a separate repository %package zone-support Summary: Vasum Support Group: Security/Other @@ -166,7 +165,6 @@ Zones support installed inside every zone. ## Zone Daemon Package #################################################### -# TODO move to a separate repository %package zone-daemon Summary: Vasum Zones Daemon Group: Security/Other @@ -247,3 +245,108 @@ systemctl daemon-reload %config /etc/dbus-1/system.d/org.tizen.vasum.tests.conf %{_unitdir}/vasum-socket-test.socket %{_unitdir}/vasum-socket-test.service + +## libLogger Package ########################################################### +%package -n libLogger +Summary: Logger library +Group: Security/Other +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig + +%description -n libLogger +The package provides libLogger library. + +%post -n libLogger -p /sbin/ldconfig + +%postun -n libLogger -p /sbin/ldconfig + +%files -n libLogger +%defattr(644,root,root,755) +%{_libdir}/libLogger.so.0 +%attr(755,root,root) %{_libdir}/libLogger.so.0.0.1 + +%package -n libLogger-devel +Summary: Development logger library +Group: Development/Libraries +Requires: libLogger = %{version}-%{release} + +%description -n libLogger-devel +The package provides libLogger development tools and libs. + +%files -n libLogger-devel +%defattr(644,root,root,755) +%{_libdir}/libLogger.so +%{_includedir}/vasum-tools/logger +%{_libdir}/pkgconfig/libLogger.pc + +## libSimpleDbus Package ####################################################### +%package -n libSimpleDbus +Summary: Simple dbus library +Group: Security/Other +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig + +%description -n libSimpleDbus +The package provides libSimpleDbus library. + +%post -n libSimpleDbus -p /sbin/ldconfig + +%postun -n libSimpleDbus -p /sbin/ldconfig + +%files -n libSimpleDbus +%defattr(644,root,root,755) +%{_libdir}/libSimpleDbus.so.0 +%attr(755,root,root) %{_libdir}/libSimpleDbus.so.0.0.1 + +%package -n libSimpleDbus-devel +Summary: Development Simple dbus library +Group: Development/Libraries +Requires: libSimpleDbus = %{version}-%{release} +Requires: pkgconfig(libLogger) + +%description -n libSimpleDbus-devel +The package provides libSimpleDbus development tools and libs. + +%files -n libSimpleDbus-devel +%defattr(644,root,root,755) +%{_libdir}/libSimpleDbus.so +%{_includedir}/vasum-tools/dbus +%{_libdir}/pkgconfig/libSimpleDbus.pc + +## libConfig Package ########################################################## +%package -n libConfig +Summary: Config library +Group: Security/Other +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig + +%description -n libConfig +The package provides libConfig library. + +%post -n libConfig -p /sbin/ldconfig + +%postun -n libConfig -p /sbin/ldconfig + +%files -n libConfig +%defattr(644,root,root,755) +%{_libdir}/libConfig.so.0 +%attr(755,root,root) %{_libdir}/libConfig.so.0.0.1 + +%package -n libConfig-devel +Summary: Development Config library +Group: Development/Libraries +Requires: libConfig = %{version}-%{release} +Requires: boost-devel +Requires: pkgconfig(libLogger) +Requires: libjson-devel + +%description -n libConfig-devel +The package provides libConfig development tools and libs. + +%files -n libConfig-devel +%defattr(644,root,root,755) +%{_libdir}/libConfig.so +%{_includedir}/vasum-tools/config +%{_libdir}/pkgconfig/libConfig.pc + + diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 2dbc322..c4e0d8f 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -30,10 +30,10 @@ ADD_EXECUTABLE(${SERVER_CODENAME} ${project_SRCS} ${common_SRCS}) ## Link libraries ############################################################## FIND_PACKAGE(Boost COMPONENTS program_options system filesystem regex) -PKG_CHECK_MODULES(SERVER_DEPS REQUIRED lxc json gio-2.0 libsystemd-journal libsystemd-daemon - libcap-ng sqlite3) +PKG_CHECK_MODULES(SERVER_DEPS REQUIRED lxc json gio-2.0 libsystemd-journal libsystemd-daemon libcap-ng) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) INCLUDE_DIRECTORIES(${CLIENT_FOLDER}) INCLUDE_DIRECTORIES(SYSTEM ${SERVER_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) @@ -43,7 +43,8 @@ SET_TARGET_PROPERTIES(${SERVER_CODENAME} PROPERTIES LINK_FLAGS "-pthread" ) -TARGET_LINK_LIBRARIES(${SERVER_CODENAME} ${SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES}) +TARGET_LINK_LIBRARIES(${SERVER_CODENAME} ${SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Logger Config SimpleDbus) ## Subdirectories ############################################################## ADD_SUBDIRECTORY(configs) diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index bed7d37..20ae2f9 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -48,9 +48,9 @@ ADD_EXECUTABLE(${SOCKET_TEST_CODENAME} ${socket_test_SRCS} ${common_SRCS}) FIND_PACKAGE (Boost COMPONENTS unit_test_framework system filesystem regex) PKG_CHECK_MODULES(UT_SERVER_DEPS REQUIRED lxc json gio-2.0 libsystemd-daemon - libsystemd-journal libcap-ng sqlite3) + libsystemd-journal libcap-ng) INCLUDE_DIRECTORIES(${COMMON_FOLDER} ${SERVER_FOLDER} ${UNIT_TESTS_FOLDER} ${CLIENT_FOLDER} - ${SOCKET_TEST_FOLDER}) + ${LIBS_FOLDER} ${SOCKET_TEST_FOLDER}) INCLUDE_DIRECTORIES(SYSTEM ${UT_SERVER_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) SET_TARGET_PROPERTIES(${UT_SERVER_CODENAME} PROPERTIES @@ -65,8 +65,10 @@ SET_TARGET_PROPERTIES(${SOCKET_TEST_CODENAME} PROPERTIES LINK_FLAGS "-pthread" ) -TARGET_LINK_LIBRARIES(${UT_SERVER_CODENAME} ${UT_SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES}) -TARGET_LINK_LIBRARIES(${SOCKET_TEST_CODENAME} ${UT_SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES}) +TARGET_LINK_LIBRARIES(${UT_SERVER_CODENAME} ${UT_SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Logger Config SimpleDbus) +TARGET_LINK_LIBRARIES(${SOCKET_TEST_CODENAME} ${UT_SERVER_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Logger Config SimpleDbus) ## Subdirectories ############################################################## SET(VSM_TEST_CONFIG_INSTALL_DIR ${VSM_CONFIG_INSTALL_DIR}/tests) diff --git a/zone-daemon/CMakeLists.txt b/zone-daemon/CMakeLists.txt index 7e7bfba..e721dbf 100644 --- a/zone-daemon/CMakeLists.txt +++ b/zone-daemon/CMakeLists.txt @@ -20,9 +20,7 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Zone Daemon...") FILE(GLOB project_SRCS *.cpp *.hpp) -FILE(GLOB common_SRCS ${COMMON_FOLDER}/dbus/*.cpp ${COMMON_FOLDER}/dbus/*.hpp - ${COMMON_FOLDER}/logger/*.cpp ${COMMON_FOLDER}/logger/*.hpp - ${COMMON_FOLDER}/utils/*.cpp ${COMMON_FOLDER}/utils/*.hpp +FILE(GLOB common_SRCS ${COMMON_FOLDER}/utils/*.cpp ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/*.cpp) ## Setup target ################################################################ @@ -36,6 +34,7 @@ FIND_PACKAGE (Boost COMPONENTS program_options system filesystem) PKG_CHECK_MODULES(ZONE_DAEMON_DEPS REQUIRED gio-2.0 libsystemd-journal libcap-ng) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) INCLUDE_DIRECTORIES(SYSTEM ${ZONE_DAEMON_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) SET_TARGET_PROPERTIES(${ZONE_DAEMON_CODENAME} PROPERTIES @@ -43,7 +42,8 @@ SET_TARGET_PROPERTIES(${ZONE_DAEMON_CODENAME} PROPERTIES LINK_FLAGS "-pthread" ) -TARGET_LINK_LIBRARIES(${ZONE_DAEMON_CODENAME} ${ZONE_DAEMON_DEPS_LIBRARIES} ${Boost_LIBRARIES}) +TARGET_LINK_LIBRARIES(${ZONE_DAEMON_CODENAME} ${ZONE_DAEMON_DEPS_LIBRARIES} + ${Boost_LIBRARIES} Logger SimpleDbus) ## Install ##################################################################### -- 2.7.4 From aed669399e583ce0f978cfaf542236520d50461d Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Tue, 5 May 2015 17:44:08 +0200 Subject: [PATCH 03/16] Listen on dbus and ipc socket at the same time [Feature] Possibility to handle ipc and dbus requests without recompiling the code. To build without dbus add --define 'without_dbus ON' to gbs arguments [Cause] N/A [Solution] N/A [Verification] Build with --define 'without_dbus ON' and without it, run tests for each build, check if server starts Change-Id: Ibd00485c4b3a6451a1cb7046f3488ff77150b3ea --- CMakeLists.txt | 4 +- client/host-ipc-connection.cpp | 62 ++--- common/api/dbus-method-result-builder.hpp | 6 +- packaging/vasum.spec | 3 +- server/host-dbus-connection.cpp | 78 +++--- server/host-dbus-definitions.hpp | 2 + server/host-ipc-connection.cpp | 58 ++-- server/host-ipc-definitions.hpp | 2 + server/zones-manager.cpp | 161 +++++------ server/zones-manager.hpp | 25 +- tests/unit_tests/client/ut-client.cpp | 11 +- tests/unit_tests/server/configs/CMakeLists.txt | 4 - .../templates/console-dbus.conf.in | 18 -- .../ut-zones-manager/templates/console-ipc.conf.in | 18 -- tests/unit_tests/server/ut-zones-manager.cpp | 294 ++++++++++----------- 15 files changed, 356 insertions(+), 390 deletions(-) delete mode 100644 tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in delete mode 100644 tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in diff --git a/CMakeLists.txt b/CMakeLists.txt index 9b61793..2e960c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -122,7 +122,9 @@ ADD_DEFINITIONS(-DVASUM_USER="${VASUM_USER}") ADD_DEFINITIONS(-DINPUT_EVENT_GROUP="${INPUT_EVENT_GROUP}") ADD_DEFINITIONS(-DDISK_GROUP="${DISK_GROUP}") ADD_DEFINITIONS(-DTTY_GROUP="${TTY_GROUP}") -#ADD_DEFINITIONS(-DDBUS_CONNECTION) +IF(NOT WITHOUT_DBUS) + ADD_DEFINITIONS(-DDBUS_CONNECTION) +ENDIF(NOT WITHOUT_DBUS) ## Python packages directory ################################################### IF(NOT DEFINED PYTHON_SITELIB) diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index 121f7ad..6541881 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -46,183 +46,183 @@ void HostIPCConnection::create(const std::string& address) void HostIPCConnection::callGetZoneIds(api::ZoneIds& argOut) { api::Void argVoid; - call(api::METHOD_GET_ZONE_ID_LIST, argVoid, argOut); + call(api::ipc::METHOD_GET_ZONE_ID_LIST, argVoid, argOut); } void HostIPCConnection::callGetActiveZoneId(api::ZoneId& argOut) { api::Void argVoid; - call(api::METHOD_GET_ACTIVE_ZONE_ID, argVoid, argOut); + call(api::ipc::METHOD_GET_ACTIVE_ZONE_ID, argVoid, argOut); } void HostIPCConnection::callSetActiveZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_SET_ACTIVE_ZONE, + api::ipc::METHOD_SET_ACTIVE_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callGetZoneInfo(const api::ZoneId& argIn, api::ZoneInfoOut& argOut) { argOut = *mClient->callSync( - api::METHOD_GET_ZONE_INFO, + api::ipc::METHOD_GET_ZONE_INFO, std::make_shared(argIn)); } void HostIPCConnection::callSetNetdevAttrs(const api::SetNetDevAttrsIn& argIn) { mClient->callSync( - api::METHOD_SET_NETDEV_ATTRS, + api::ipc::METHOD_SET_NETDEV_ATTRS, std::make_shared(argIn)); api::Void argVoid; - call(api::METHOD_SET_NETDEV_ATTRS, argIn, argVoid); + call(api::ipc::METHOD_SET_NETDEV_ATTRS, argIn, argVoid); } void HostIPCConnection::callGetNetdevAttrs(const api::GetNetDevAttrsIn& argIn, api::GetNetDevAttrs& argOut) { argOut = *mClient->callSync( - api::METHOD_GET_NETDEV_ATTRS, + api::ipc::METHOD_GET_NETDEV_ATTRS, std::make_shared(argIn)); } void HostIPCConnection::callGetNetdevList(const api::ZoneId& argIn, api::NetDevList& argOut) { argOut = *mClient->callSync( - api::METHOD_GET_NETDEV_LIST, + api::ipc::METHOD_GET_NETDEV_LIST, std::make_shared(argIn)); } void HostIPCConnection::callCreateNetdevVeth(const api::CreateNetDevVethIn& argIn) { mClient->callSync( - api::METHOD_CREATE_NETDEV_VETH, + api::ipc::METHOD_CREATE_NETDEV_VETH, std::make_shared(argIn)); } void HostIPCConnection::callCreateNetdevMacvlan(const api::CreateNetDevMacvlanIn& argIn) { mClient->callSync( - api::METHOD_CREATE_NETDEV_MACVLAN, + api::ipc::METHOD_CREATE_NETDEV_MACVLAN, std::make_shared(argIn)); } void HostIPCConnection::callCreateNetdevPhys(const api::CreateNetDevPhysIn& argIn) { mClient->callSync( - api::METHOD_CREATE_NETDEV_PHYS, + api::ipc::METHOD_CREATE_NETDEV_PHYS, std::make_shared(argIn)); } void HostIPCConnection::callDestroyNetdev(const api::DestroyNetDevIn& argIn) { mClient->callSync( - api::METHOD_DESTROY_NETDEV, + api::ipc::METHOD_DESTROY_NETDEV, std::make_shared(argIn)); } void HostIPCConnection::callDeleteNetdevIpAddress(const api::DeleteNetdevIpAddressIn& argIn) { mClient->callSync( - api::METHOD_DELETE_NETDEV_IP_ADDRESS, + api::ipc::METHOD_DELETE_NETDEV_IP_ADDRESS, std::make_shared(argIn)); } void HostIPCConnection::callDeclareFile(const api::DeclareFileIn& argIn, api::Declaration& argOut) { argOut = *mClient->callSync( - api::METHOD_DECLARE_FILE, + api::ipc::METHOD_DECLARE_FILE, std::make_shared(argIn)); } void HostIPCConnection::callDeclareMount(const api::DeclareMountIn& argIn, api::Declaration& argOut) { argOut = *mClient->callSync( - api::METHOD_DECLARE_MOUNT, + api::ipc::METHOD_DECLARE_MOUNT, std::make_shared(argIn)); } void HostIPCConnection::callDeclareLink(const api::DeclareLinkIn& argIn, api::Declaration& argOut) { argOut = *mClient->callSync( - api::METHOD_DECLARE_LINK, + api::ipc::METHOD_DECLARE_LINK, std::make_shared(argIn)); } void HostIPCConnection::callGetDeclarations(const api::ZoneId& argIn, api::Declarations& argOut) { argOut = *mClient->callSync( - api::METHOD_GET_DECLARATIONS, + api::ipc::METHOD_GET_DECLARATIONS, std::make_shared(argIn)); } void HostIPCConnection::callRemoveDeclaration(const api::RemoveDeclarationIn& argIn) { mClient->callSync( - api::METHOD_REMOVE_DECLARATION, + api::ipc::METHOD_REMOVE_DECLARATION, std::make_shared(argIn)); } void HostIPCConnection::callCreateZone(const api::CreateZoneIn& argIn) { mClient->callSync( - api::METHOD_CREATE_ZONE, + api::ipc::METHOD_CREATE_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callDestroyZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_DESTROY_ZONE, + api::ipc::METHOD_DESTROY_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callShutdownZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_SHUTDOWN_ZONE, + api::ipc::METHOD_SHUTDOWN_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callStartZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_START_ZONE, + api::ipc::METHOD_START_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callLockZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_LOCK_ZONE, + api::ipc::METHOD_LOCK_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callUnlockZone(const api::ZoneId& argIn) { mClient->callSync( - api::METHOD_UNLOCK_ZONE, + api::ipc::METHOD_UNLOCK_ZONE, std::make_shared(argIn)); } void HostIPCConnection::callGrantDevice(const api::GrantDeviceIn& argIn) { mClient->callSync( - api::METHOD_GRANT_DEVICE, + api::ipc::METHOD_GRANT_DEVICE, std::make_shared(argIn)); } void HostIPCConnection::callRevokeDevice(const api::RevokeDeviceIn& argIn) { mClient->callSync( - api::METHOD_REVOKE_DEVICE, + api::ipc::METHOD_REVOKE_DEVICE, std::make_shared(argIn)); } void HostIPCConnection::callNotifyActiveZone(const api::NotifActiveZoneIn& argIn) { mClient->callSync( - api::METHOD_NOTIFY_ACTIVE_ZONE, + api::ipc::METHOD_NOTIFY_ACTIVE_ZONE, std::make_shared(argIn)); } @@ -230,14 +230,14 @@ void HostIPCConnection::callFileMoveRequest(const api::FileMoveRequestIn& argIn, api::FileMoveRequestStatus& argOut) { argOut = *mClient->callSync( - api::METHOD_FILE_MOVE_REQUEST, + api::ipc::METHOD_FILE_MOVE_REQUEST, std::make_shared(argIn)); } void HostIPCConnection::signalSwitchToDefault() { - mClient->signal(api::SIGNAL_SWITCH_TO_DEFAULT, + mClient->signal(api::ipc::SIGNAL_SWITCH_TO_DEFAULT, std::make_shared()); } @@ -248,8 +248,8 @@ HostIPCConnection::subscribeNotification(const NotificationCallback& callback) std::shared_ptr& data) { callback(*data); }; - mClient->setSignalHandler(api::SIGNAL_NOTIFICATION, callbackWrapper); - return api::SIGNAL_NOTIFICATION; + mClient->setSignalHandler(api::ipc::SIGNAL_NOTIFICATION, callbackWrapper); + return api::ipc::SIGNAL_NOTIFICATION; } void HostIPCConnection::unsubscribe(const SubscriptionId& id) diff --git a/common/api/dbus-method-result-builder.hpp b/common/api/dbus-method-result-builder.hpp index 99f3bc0..c6422dc 100644 --- a/common/api/dbus-method-result-builder.hpp +++ b/common/api/dbus-method-result-builder.hpp @@ -42,7 +42,7 @@ namespace api { template class DbusMethodResultBuilder: public MethodResultBuilder { public: - DbusMethodResultBuilder(const dbus::MethodResultBuilder::Pointer& methodResultBuilderPtr); + DbusMethodResultBuilder(const ::dbus::MethodResultBuilder::Pointer& methodResultBuilderPtr); ~DbusMethodResultBuilder() {} private: @@ -50,12 +50,12 @@ private: void setVoid() override; void setError(const std::string& name, const std::string& message) override; - dbus::MethodResultBuilder::Pointer mMethodResultBuilderPtr; + ::dbus::MethodResultBuilder::Pointer mMethodResultBuilderPtr; std::function)> mSerialize; }; template -DbusMethodResultBuilder::DbusMethodResultBuilder(const dbus::MethodResultBuilder::Pointer& methodResultBuilderPtr) +DbusMethodResultBuilder::DbusMethodResultBuilder(const ::dbus::MethodResultBuilder::Pointer& methodResultBuilderPtr) : mMethodResultBuilderPtr(methodResultBuilderPtr) { mSerialize = [](const std::shared_ptr data)->GVariant* { diff --git a/packaging/vasum.spec b/packaging/vasum.spec index 55567c7..64c3662 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -70,7 +70,8 @@ between them. A process from inside a zone can request a switch of context -DVASUM_USER=%{vsm_user} \ -DINPUT_EVENT_GROUP=%{input_event_group} \ -DDISK_GROUP=%{disk_group} \ - -DTTY_GROUP=%{tty_group} + -DTTY_GROUP=%{tty_group} \ + -DWITHOUT_DBUS=%{?without_dbus} make -k %{?jobs:-j%jobs} %install diff --git a/server/host-dbus-connection.cpp b/server/host-dbus-connection.cpp index b93ad21..98325ac 100644 --- a/server/host-dbus-connection.cpp +++ b/server/host-dbus-connection.cpp @@ -53,19 +53,19 @@ HostDbusConnection::HostDbusConnection() mDbusConnection = dbus::DbusConnection::createSystem(); LOGT("Setting DBUS name"); - mDbusConnection->setName(api::BUS_NAME, + mDbusConnection->setName(api::dbus::BUS_NAME, std::bind(&HostDbusConnection::onNameAcquired, this), std::bind(&HostDbusConnection::onNameLost, this)); if (!waitForName(NAME_ACQUIRED_TIMEOUT)) { - LOGE("Could not acquire dbus name: " << api::BUS_NAME); - throw HostConnectionException("Could not acquire dbus name: " + api::BUS_NAME); + LOGE("Could not acquire dbus name: " << api::dbus::BUS_NAME); + throw HostConnectionException("Could not acquire dbus name: " + api::dbus::BUS_NAME); } LOGT("Registering DBUS interface"); using namespace std::placeholders; - mDbusConnection->registerObject(api::OBJECT_PATH, - api::DEFINITION, + mDbusConnection->registerObject(api::dbus::OBJECT_PATH, + api::dbus::DEFINITION, std::bind(&HostDbusConnection::onMessageCall, this, _1, _2, _3, _4, _5)); @@ -267,11 +267,11 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, GVariant* parameters, dbus::MethodResultBuilder::Pointer result) { - if (objectPath != api::OBJECT_PATH || interface != api::INTERFACE) { + if (objectPath != api::dbus::OBJECT_PATH || interface != api::dbus::INTERFACE) { return; } - if (methodName == api::METHOD_SET_ACTIVE_ZONE) { + if (methodName == api::dbus::METHOD_SET_ACTIVE_ZONE) { api::ZoneId zoneId; config::loadFromGVariant(parameters, zoneId); @@ -282,7 +282,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_PROXY_CALL) { + if (methodName == api::dbus::METHOD_PROXY_CALL) { const gchar* target = NULL; const gchar* targetBusName = NULL; const gchar* targetObjectPath = NULL; @@ -311,7 +311,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_ZONE_ID_LIST) { + if (methodName == api::dbus::METHOD_GET_ZONE_ID_LIST) { if (mGetZoneIdsCallback) { auto rb = std::make_shared>(result); mGetZoneIdsCallback(rb); @@ -319,7 +319,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_ACTIVE_ZONE_ID) { + if (methodName == api::dbus::METHOD_GET_ACTIVE_ZONE_ID) { if (mGetActiveZoneIdCallback) { auto rb = std::make_shared>(result); mGetActiveZoneIdCallback(rb); @@ -327,7 +327,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_ZONE_INFO) { + if (methodName == api::dbus::METHOD_GET_ZONE_INFO) { api::ZoneId zoneId; config::loadFromGVariant(parameters, zoneId); @@ -338,7 +338,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_SET_NETDEV_ATTRS) { + if (methodName == api::dbus::METHOD_SET_NETDEV_ATTRS) { api::SetNetDevAttrsIn data; config::loadFromGVariant(parameters, data); @@ -349,7 +349,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_NETDEV_ATTRS) { + if (methodName == api::dbus::METHOD_GET_NETDEV_ATTRS) { api::GetNetDevAttrsIn data; config::loadFromGVariant(parameters, data); @@ -360,7 +360,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_NETDEV_LIST) { + if (methodName == api::dbus::METHOD_GET_NETDEV_LIST) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -371,7 +371,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_CREATE_NETDEV_VETH) { + if (methodName == api::dbus::METHOD_CREATE_NETDEV_VETH) { api::CreateNetDevVethIn data; config::loadFromGVariant(parameters, data); @@ -382,7 +382,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_CREATE_NETDEV_MACVLAN) { + if (methodName == api::dbus::METHOD_CREATE_NETDEV_MACVLAN) { api::CreateNetDevMacvlanIn data; config::loadFromGVariant(parameters, data); @@ -392,7 +392,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_CREATE_NETDEV_PHYS) { + if (methodName == api::dbus::METHOD_CREATE_NETDEV_PHYS) { api::CreateNetDevPhysIn data; config::loadFromGVariant(parameters, data); @@ -402,7 +402,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_DESTROY_NETDEV) { + if (methodName == api::dbus::METHOD_DESTROY_NETDEV) { api::DestroyNetDevIn data; config::loadFromGVariant(parameters, data); @@ -412,7 +412,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_DELETE_NETDEV_IP_ADDRESS) { + if (methodName == api::dbus::METHOD_DELETE_NETDEV_IP_ADDRESS) { api::DeleteNetdevIpAddressIn data; config::loadFromGVariant(parameters, data); if (mDeleteNetdevIpAddressCallback) { @@ -421,7 +421,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_DECLARE_FILE) { + if (methodName == api::dbus::METHOD_DECLARE_FILE) { api::DeclareFileIn data; config::loadFromGVariant(parameters, data); @@ -432,7 +432,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_DECLARE_MOUNT) { + if (methodName == api::dbus::METHOD_DECLARE_MOUNT) { api::DeclareMountIn data; config::loadFromGVariant(parameters, data); @@ -443,7 +443,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_DECLARE_LINK) { + if (methodName == api::dbus::METHOD_DECLARE_LINK) { api::DeclareLinkIn data; config::loadFromGVariant(parameters, data); @@ -454,7 +454,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GET_DECLARATIONS) { + if (methodName == api::dbus::METHOD_GET_DECLARATIONS) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -465,7 +465,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_REMOVE_DECLARATION) { + if (methodName == api::dbus::METHOD_REMOVE_DECLARATION) { api::RemoveDeclarationIn data; config::loadFromGVariant(parameters, data); @@ -476,7 +476,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_CREATE_ZONE) { + if (methodName == api::dbus::METHOD_CREATE_ZONE) { api::CreateZoneIn data; config::loadFromGVariant(parameters, data); @@ -487,7 +487,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_DESTROY_ZONE) { + if (methodName == api::dbus::METHOD_DESTROY_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -498,7 +498,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_SHUTDOWN_ZONE) { + if (methodName == api::dbus::METHOD_SHUTDOWN_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -508,7 +508,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_START_ZONE) { + if (methodName == api::dbus::METHOD_START_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -518,7 +518,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_LOCK_ZONE) { + if (methodName == api::dbus::METHOD_LOCK_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -529,7 +529,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_UNLOCK_ZONE) { + if (methodName == api::dbus::METHOD_UNLOCK_ZONE) { api::ZoneId data; config::loadFromGVariant(parameters, data); @@ -540,7 +540,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_GRANT_DEVICE) { + if (methodName == api::dbus::METHOD_GRANT_DEVICE) { api::GrantDeviceIn data; config::loadFromGVariant(parameters, data); @@ -551,7 +551,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_REVOKE_DEVICE) { + if (methodName == api::dbus::METHOD_REVOKE_DEVICE) { api::RevokeDeviceIn data; config::loadFromGVariant(parameters, data); @@ -562,7 +562,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, return; } - if (methodName == api::METHOD_NOTIFY_ACTIVE_ZONE) { + if (methodName == api::dbus::METHOD_NOTIFY_ACTIVE_ZONE) { api::NotifActiveZoneIn data; config::loadFromGVariant(parameters, data); @@ -572,7 +572,7 @@ void HostDbusConnection::onMessageCall(const std::string& objectPath, } } - if (methodName == api::METHOD_FILE_MOVE_REQUEST) { + if (methodName == api::dbus::METHOD_FILE_MOVE_REQUEST) { api::FileMoveRequestIn data; config::loadFromGVariant(parameters, data); @@ -589,11 +589,11 @@ void HostDbusConnection::onSignalCall(const std::string& /* senderBusName */, const std::string& signalName, GVariant* /* parameters */) { - if (objectPath != api::OBJECT_PATH || interface != api::INTERFACE) { + if (objectPath != api::dbus::OBJECT_PATH || interface != api::dbus::INTERFACE) { return; } - if (signalName == api::SIGNAL_SWITCH_TO_DEFAULT) { + if (signalName == api::dbus::SIGNAL_SWITCH_TO_DEFAULT) { if (mSwitchToDefaultCallback) { mSwitchToDefaultCallback(); } @@ -622,9 +622,9 @@ void HostDbusConnection::sendNotification(const api::Notification& notify) notify.zone.c_str(), notify.application.c_str(), notify.message.c_str()); - mDbusConnection->emitSignal(api::OBJECT_PATH, - api::INTERFACE, - api::SIGNAL_NOTIFICATION, + mDbusConnection->emitSignal(api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::SIGNAL_NOTIFICATION, parameters); } diff --git a/server/host-dbus-definitions.hpp b/server/host-dbus-definitions.hpp index 208276e..2d013c9 100644 --- a/server/host-dbus-definitions.hpp +++ b/server/host-dbus-definitions.hpp @@ -29,6 +29,7 @@ namespace vasum { namespace api { +namespace dbus { const std::string BUS_NAME = "org.tizen.vasum.host"; const std::string OBJECT_PATH = "/org/tizen/vasum/host"; @@ -228,6 +229,7 @@ const std::string DEFINITION = " " ""; +} // namespace dbus } // namespace api } // namespace vasum diff --git a/server/host-ipc-connection.cpp b/server/host-ipc-connection.cpp index 1bf2e78c..d6519e9 100644 --- a/server/host-ipc-connection.cpp +++ b/server/host-ipc-connection.cpp @@ -49,7 +49,7 @@ void HostIPCConnection::setGetZoneIdsCallback(const Method::type& { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_GET_ZONE_ID_LIST, + api::ipc::METHOD_GET_ZONE_ID_LIST, Callback::getWrapper(callback)); } @@ -58,7 +58,7 @@ void HostIPCConnection::setGetActiveZoneIdCallback(const Method::ty { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_GET_ACTIVE_ZONE_ID, + api::ipc::METHOD_GET_ACTIVE_ZONE_ID, Callback::getWrapper(callback)); } @@ -67,7 +67,7 @@ void HostIPCConnection::setGetZoneInfoCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_GET_ZONE_INFO, + api::ipc::METHOD_GET_ZONE_INFO, Callback::getWrapper(callback)); } @@ -75,7 +75,7 @@ void HostIPCConnection::setSetNetdevAttrsCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_SET_NETDEV_ATTRS, + api::ipc::METHOD_SET_NETDEV_ATTRS, Callback::getWrapper(callback)); } @@ -83,7 +83,7 @@ void HostIPCConnection::setGetNetdevAttrsCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_GET_NETDEV_ATTRS, + api::ipc::METHOD_GET_NETDEV_ATTRS, Callback::getWrapper(callback)); } @@ -91,7 +91,7 @@ void HostIPCConnection::setGetNetdevListCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_GET_NETDEV_LIST, + api::ipc::METHOD_GET_NETDEV_LIST, Callback::getWrapper(callback)); } @@ -99,7 +99,7 @@ void HostIPCConnection::setCreateNetdevVethCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_CREATE_NETDEV_VETH, + api::ipc::METHOD_CREATE_NETDEV_VETH, Callback::getWrapper(callback)); } @@ -107,7 +107,7 @@ void HostIPCConnection::setCreateNetdevMacvlanCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_CREATE_NETDEV_MACVLAN, + api::ipc::METHOD_CREATE_NETDEV_MACVLAN, Callback::getWrapper(callback)); } @@ -115,7 +115,7 @@ void HostIPCConnection::setCreateNetdevPhysCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_CREATE_NETDEV_PHYS, + api::ipc::METHOD_CREATE_NETDEV_PHYS, Callback::getWrapper(callback)); } @@ -123,7 +123,7 @@ void HostIPCConnection::setDestroyNetdevCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_DESTROY_NETDEV, + api::ipc::METHOD_DESTROY_NETDEV, Callback::getWrapper(callback)); } @@ -131,7 +131,7 @@ void HostIPCConnection::setDeleteNetdevIpAddressCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_DELETE_NETDEV_IP_ADDRESS, + api::ipc::METHOD_DELETE_NETDEV_IP_ADDRESS, Callback::getWrapper(callback)); } @@ -139,7 +139,7 @@ void HostIPCConnection::setDeclareFileCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_DECLARE_FILE, + api::ipc::METHOD_DECLARE_FILE, Callback::getWrapper(callback)); } @@ -147,7 +147,7 @@ void HostIPCConnection::setDeclareMountCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_DECLARE_MOUNT, + api::ipc::METHOD_DECLARE_MOUNT, Callback::getWrapper(callback)); } @@ -155,7 +155,7 @@ void HostIPCConnection::setDeclareLinkCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_DECLARE_LINK, + api::ipc::METHOD_DECLARE_LINK, Callback::getWrapper(callback)); } @@ -163,7 +163,7 @@ void HostIPCConnection::setGetDeclarationsCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_GET_DECLARATIONS, + api::ipc::METHOD_GET_DECLARATIONS, Callback::getWrapper(callback)); } @@ -171,7 +171,7 @@ void HostIPCConnection::setRemoveDeclarationCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_REMOVE_DECLARATION, + api::ipc::METHOD_REMOVE_DECLARATION, Callback::getWrapper(callback)); } @@ -179,7 +179,7 @@ void HostIPCConnection::setSetActiveZoneCallback(const Method { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_SET_ACTIVE_ZONE, + api::ipc::METHOD_SET_ACTIVE_ZONE, Callback::getWrapper(callback)); } @@ -187,7 +187,7 @@ void HostIPCConnection::setCreateZoneCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_CREATE_ZONE, + api::ipc::METHOD_CREATE_ZONE, Callback::getWrapper(callback)); } @@ -195,7 +195,7 @@ void HostIPCConnection::setDestroyZoneCallback(const Method:: { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_DESTROY_ZONE, + api::ipc::METHOD_DESTROY_ZONE, Callback::getWrapper(callback)); } @@ -203,7 +203,7 @@ void HostIPCConnection::setShutdownZoneCallback(const Method: { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_SHUTDOWN_ZONE, + api::ipc::METHOD_SHUTDOWN_ZONE, Callback::getWrapper(callback)); } @@ -211,7 +211,7 @@ void HostIPCConnection::setStartZoneCallback(const Method::ty { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_START_ZONE, + api::ipc::METHOD_START_ZONE, Callback::getWrapper(callback)); } @@ -219,7 +219,7 @@ void HostIPCConnection::setLockZoneCallback(const Method::typ { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_LOCK_ZONE, + api::ipc::METHOD_LOCK_ZONE, Callback::getWrapper(callback)); } @@ -227,7 +227,7 @@ void HostIPCConnection::setUnlockZoneCallback(const Method::t { typedef IPCMethodWrapper Callback; mService->setMethodHandler( - api::METHOD_UNLOCK_ZONE, + api::ipc::METHOD_UNLOCK_ZONE, Callback::getWrapper(callback)); } @@ -235,7 +235,7 @@ void HostIPCConnection::setGrantDeviceCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_GRANT_DEVICE, + api::ipc::METHOD_GRANT_DEVICE, Callback::getWrapper(callback)); } @@ -243,7 +243,7 @@ void HostIPCConnection::setRevokeDeviceCallback(const Method Callback; mService->setMethodHandler( - api::METHOD_REVOKE_DEVICE, + api::ipc::METHOD_REVOKE_DEVICE, Callback::getWrapper(callback)); } @@ -252,7 +252,7 @@ void HostIPCConnection::setNotifyActiveZoneCallback( { typedef IPCMethodWrapper Method; mService->setMethodHandler( - api::METHOD_NOTIFY_ACTIVE_ZONE, + api::ipc::METHOD_NOTIFY_ACTIVE_ZONE, Method::getWrapper(callback)); } @@ -260,7 +260,7 @@ void HostIPCConnection::setSwitchToDefaultCallback(const Signal { typedef IPCSignalWrapper Signal; mService->setSignalHandler( - api::SIGNAL_SWITCH_TO_DEFAULT, + api::ipc::SIGNAL_SWITCH_TO_DEFAULT, Signal::getWrapper(callback)); } @@ -269,13 +269,13 @@ void HostIPCConnection::setFileMoveCallback(const Method Method; mService->setMethodHandler( - api::METHOD_FILE_MOVE_REQUEST, + api::ipc::METHOD_FILE_MOVE_REQUEST, Method::getWrapper(callback)); } void HostIPCConnection::sendNotification(const api::Notification& notification) { - mService->signal(api::SIGNAL_NOTIFICATION, + mService->signal(api::ipc::SIGNAL_NOTIFICATION, std::make_shared(notification)); } diff --git a/server/host-ipc-definitions.hpp b/server/host-ipc-definitions.hpp index 8c31339..a54b679 100644 --- a/server/host-ipc-definitions.hpp +++ b/server/host-ipc-definitions.hpp @@ -29,6 +29,7 @@ namespace vasum { namespace api { +namespace ipc { const vasum::ipc::MethodID METHOD_GET_ZONE_ID_LIST = 2; const vasum::ipc::MethodID METHOD_GET_ACTIVE_ZONE_ID = 3; @@ -68,6 +69,7 @@ const std::string FILE_MOVE_NO_PERMISSIONS_RECEIVE = "FILE_MOVE_NO_PERMISSIONS_ const std::string FILE_MOVE_FAILED = "FILE_MOVE_FAILED"; const std::string FILE_MOVE_SUCCEEDED = "FILE_MOVE_SUCCEEDED"; +} // namespace ipc } // namespace api } // namespace vasum diff --git a/server/zones-manager.cpp b/server/zones-manager.cpp index e6621d8..953fad0 100644 --- a/server/zones-manager.cpp +++ b/server/zones-manager.cpp @@ -24,11 +24,6 @@ #include "config.hpp" -#ifdef DBUS_CONNECTION -#include "host-dbus-definitions.hpp" -#else -#include "host-ipc-definitions.hpp" -#endif #include "common-definitions.hpp" #include "dynamic-config-scheme.hpp" #include "zones-manager.hpp" @@ -117,109 +112,115 @@ bool zoneIsRunning(const std::unique_ptr& zone) { } // namespace -ZonesManager::ZonesManager(const std::string& configPath) - : mWorker(utils::Worker::create()) - , mDetachOnExit(false) +template +void ZonesManager::setHandlers(Connection& connection) { - LOGD("Instantiating ZonesManager object..."); + using namespace std::placeholders; + connection.setGetZoneIdsCallback(bind(&ZonesManager::handleGetZoneIdsCall, + this, _1)); - config::loadFromJsonFile(configPath, mConfig); - config::loadFromKVStoreWithJsonFile(mConfig.dbPath, - configPath, - mDynamicConfig, - getVasumDbPrefix()); + connection.setGetActiveZoneIdCallback(bind(&ZonesManager::handleGetActiveZoneIdCall, + this, _1)); + connection.setGetZoneInfoCallback(bind(&ZonesManager::handleGetZoneInfoCall, + this, _1, _2)); - using namespace std::placeholders; -#ifdef DBUS_CONNECTION - mProxyCallPolicy.reset(new ProxyCallPolicy(mConfig.proxyCallRules)); - mHostConnection.setProxyCallCallback(bind(&ZonesManager::handleProxyCall, - this, HOST_ID, _1, _2, _3, _4, _5, _6, _7)); -#endif + connection.setSetNetdevAttrsCallback(bind(&ZonesManager::handleSetNetdevAttrsCall, + this, _1, _2)); - mHostConnection.setGetZoneIdsCallback(bind(&ZonesManager::handleGetZoneIdsCall, - this, _1)); + connection.setGetNetdevAttrsCallback(bind(&ZonesManager::handleGetNetdevAttrsCall, + this, _1, _2)); - mHostConnection.setGetActiveZoneIdCallback(bind(&ZonesManager::handleGetActiveZoneIdCall, - this, _1)); + connection.setGetNetdevListCallback(bind(&ZonesManager::handleGetNetdevListCall, + this, _1, _2)); - mHostConnection.setGetZoneInfoCallback(bind(&ZonesManager::handleGetZoneInfoCall, + connection.setCreateNetdevVethCallback(bind(&ZonesManager::handleCreateNetdevVethCall, this, _1, _2)); - mHostConnection.setSetNetdevAttrsCallback(bind(&ZonesManager::handleSetNetdevAttrsCall, + connection.setCreateNetdevMacvlanCallback(bind(&ZonesManager::handleCreateNetdevMacvlanCall, this, _1, _2)); - mHostConnection.setGetNetdevAttrsCallback(bind(&ZonesManager::handleGetNetdevAttrsCall, - this, _1, _2)); + connection.setCreateNetdevPhysCallback(bind(&ZonesManager::handleCreateNetdevPhysCall, + this, _1, _2)); - mHostConnection.setGetNetdevListCallback(bind(&ZonesManager::handleGetNetdevListCall, - this, _1, _2)); + connection.setDestroyNetdevCallback(bind(&ZonesManager::handleDestroyNetdevCall, + this, _1, _2)); - mHostConnection.setCreateNetdevVethCallback(bind(&ZonesManager::handleCreateNetdevVethCall, + connection.setDeleteNetdevIpAddressCallback(bind(&ZonesManager::handleDeleteNetdevIpAddressCall, this, _1, _2)); - mHostConnection.setCreateNetdevMacvlanCallback(bind(&ZonesManager::handleCreateNetdevMacvlanCall, - this, _1, _2)); + connection.setDeclareFileCallback(bind(&ZonesManager::handleDeclareFileCall, + this, _1, _2)); - mHostConnection.setCreateNetdevPhysCallback(bind(&ZonesManager::handleCreateNetdevPhysCall, - this, _1, _2)); - - mHostConnection.setDestroyNetdevCallback(bind(&ZonesManager::handleDestroyNetdevCall, - this, _1, _2)); + connection.setDeclareMountCallback(bind(&ZonesManager::handleDeclareMountCall, + this, _1, _2)); - mHostConnection.setDeleteNetdevIpAddressCallback(bind(&ZonesManager::handleDeleteNetdevIpAddressCall, - this, _1, _2)); + connection.setDeclareLinkCallback(bind(&ZonesManager::handleDeclareLinkCall, + this, _1, _2)); - mHostConnection.setDeclareFileCallback(bind(&ZonesManager::handleDeclareFileCall, - this, _1, _2)); + connection.setGetDeclarationsCallback(bind(&ZonesManager::handleGetDeclarationsCall, + this, _1, _2)); - mHostConnection.setDeclareMountCallback(bind(&ZonesManager::handleDeclareMountCall, + connection.setRemoveDeclarationCallback(bind(&ZonesManager::handleRemoveDeclarationCall, this, _1, _2)); - mHostConnection.setDeclareLinkCallback(bind(&ZonesManager::handleDeclareLinkCall, - this, _1, _2)); + connection.setSetActiveZoneCallback(bind(&ZonesManager::handleSetActiveZoneCall, + this, _1, _2)); - mHostConnection.setGetDeclarationsCallback(bind(&ZonesManager::handleGetDeclarationsCall, - this, _1, _2)); + connection.setCreateZoneCallback(bind(&ZonesManager::handleCreateZoneCall, + this, _1, _2)); - mHostConnection.setRemoveDeclarationCallback(bind(&ZonesManager::handleRemoveDeclarationCall, - this, _1, _2)); + connection.setDestroyZoneCallback(bind(&ZonesManager::handleDestroyZoneCall, + this, _1, _2)); - mHostConnection.setSetActiveZoneCallback(bind(&ZonesManager::handleSetActiveZoneCall, - this, _1, _2)); + connection.setShutdownZoneCallback(bind(&ZonesManager::handleShutdownZoneCall, + this, _1, _2)); - mHostConnection.setCreateZoneCallback(bind(&ZonesManager::handleCreateZoneCall, - this, _1, _2)); + connection.setStartZoneCallback(bind(&ZonesManager::handleStartZoneCall, + this, _1, _2)); - mHostConnection.setDestroyZoneCallback(bind(&ZonesManager::handleDestroyZoneCall, - this, _1, _2)); + connection.setLockZoneCallback(bind(&ZonesManager::handleLockZoneCall, + this, _1, _2)); - mHostConnection.setShutdownZoneCallback(bind(&ZonesManager::handleShutdownZoneCall, - this, _1, _2)); + connection.setUnlockZoneCallback(bind(&ZonesManager::handleUnlockZoneCall, + this, _1, _2)); - mHostConnection.setStartZoneCallback(bind(&ZonesManager::handleStartZoneCall, - this, _1, _2)); + connection.setGrantDeviceCallback(bind(&ZonesManager::handleGrantDeviceCall, + this, _1, _2)); - mHostConnection.setLockZoneCallback(bind(&ZonesManager::handleLockZoneCall, - this, _1, _2)); + connection.setRevokeDeviceCallback(bind(&ZonesManager::handleRevokeDeviceCall, + this, _1, _2)); - mHostConnection.setUnlockZoneCallback(bind(&ZonesManager::handleUnlockZoneCall, - this, _1, _2)); + connection.setNotifyActiveZoneCallback(bind(&ZonesManager::handleNotifyActiveZoneCall, + this, "", _1, _2)); - mHostConnection.setGrantDeviceCallback(bind(&ZonesManager::handleGrantDeviceCall, - this, _1, _2)); + connection.setSwitchToDefaultCallback(bind(&ZonesManager::handleSwitchToDefaultCall, + this, "")); - mHostConnection.setRevokeDeviceCallback(bind(&ZonesManager::handleRevokeDeviceCall, - this, _1, _2)); + connection.setFileMoveCallback(bind(&ZonesManager::handleFileMoveCall, + this, "", _1, _2)); +} - mHostConnection.setNotifyActiveZoneCallback(bind(&ZonesManager::handleNotifyActiveZoneCall, - this, "", _1, _2)); +ZonesManager::ZonesManager(const std::string& configPath) + : mWorker(utils::Worker::create()) + , mDetachOnExit(false) +{ + LOGD("Instantiating ZonesManager object..."); - mHostConnection.setSwitchToDefaultCallback(bind(&ZonesManager::handleSwitchToDefaultCall, - this, "")); + config::loadFromJsonFile(configPath, mConfig); + config::loadFromKVStoreWithJsonFile(mConfig.dbPath, + configPath, + mDynamicConfig, + getVasumDbPrefix()); - mHostConnection.setFileMoveCallback(bind(&ZonesManager::handleFileMoveCall, - this, "", _1, _2)); + setHandlers(mHostIPCConnection); +#ifdef DBUS_CONNECTION + using namespace std::placeholders; + mProxyCallPolicy.reset(new ProxyCallPolicy(mConfig.proxyCallRules)); + mHostDbusConnection.setProxyCallCallback(bind(&ZonesManager::handleProxyCall, + this, HOST_ID, _1, _2, _3, _4, _5, _6, _7)); + setHandlers(mHostDbusConnection); +#endif //DBUS_CONNECTION for (const auto& zoneId : mDynamicConfig.zoneIds) { insertZone(zoneId, getTemplatePathForExistingZone(zoneId)); @@ -737,14 +738,14 @@ void ZonesManager::handleProxyCall(const std::string& caller, return; } - mHostConnection.proxyCallAsync(targetBusName, - targetObjectPath, - targetInterface, - targetMethod, - parameters, - asyncResultCallback); + mHostDbusConnection.proxyCallAsync(targetBusName, + targetObjectPath, + targetInterface, + targetMethod, + parameters, + asyncResultCallback); } -#endif +#endif //DBUS_CONNECTION void ZonesManager::handleGetZoneIdsCall(api::MethodResultBuilder::Pointer result) { diff --git a/server/zones-manager.hpp b/server/zones-manager.hpp index 42477ae..2a2f6d7 100644 --- a/server/zones-manager.hpp +++ b/server/zones-manager.hpp @@ -28,16 +28,16 @@ #include "zone.hpp" #include "zones-manager-config.hpp" -#ifdef DBUS_CONNECTION -#include "host-dbus-connection.hpp" -#include "proxy-call-policy.hpp" -#else #include "host-ipc-connection.hpp" -#endif #include "input-monitor.hpp" #include "utils/worker.hpp" #include "api/method-result-builder.hpp" +#ifdef DBUS_CONNECTION +#include "host-dbus-connection.hpp" +#include "proxy-call-policy.hpp" +#endif //DBUS_CONNECTION + #include #include @@ -118,17 +118,15 @@ public: private: typedef std::recursive_mutex Mutex; typedef std::unique_lock Lock; -#ifdef DBUS_CONNECTION - typedef HostDbusConnection HostConnection; -#else - typedef HostIPCConnection HostConnection; -#endif utils::Worker::Pointer mWorker; Mutex mMutex; // used to protect mZones ZonesManagerConfig mConfig; //TODO make it const ZonesManagerDynamicConfig mDynamicConfig; - HostConnection mHostConnection; +#ifdef DBUS_CONNECTION + HostDbusConnection mHostDbusConnection; +#endif //DBUS_CONNECTION + HostIPCConnection mHostIPCConnection; // to hold InputMonitor pointer to monitor if zone switching sequence is recognized std::unique_ptr mSwitchingSequenceMonitor; // like set but keep insertion order @@ -172,7 +170,7 @@ private: const std::string& targetMethod, GVariant* parameters, dbus::MethodResultBuilder::Pointer result); -#endif +#endif //DBUS_CONNECTION // Handlers -------------------------------------------------------- void handleGetZoneIdsCall(api::MethodResultBuilder::Pointer result); void handleGetActiveZoneIdCall(api::MethodResultBuilder::Pointer result); @@ -222,6 +220,9 @@ private: api::MethodResultBuilder::Pointer result); void handleRevokeDeviceCall(const api::RevokeDeviceIn& data, api::MethodResultBuilder::Pointer result); + + template + void setHandlers(Connection& connnection); }; diff --git a/tests/unit_tests/client/ut-client.cpp b/tests/unit_tests/client/ut-client.cpp index f0e6b2e..adc325e 100644 --- a/tests/unit_tests/client/ut-client.cpp +++ b/tests/unit_tests/client/ut-client.cpp @@ -23,8 +23,6 @@ * @brief Unit tests of the client C API */ -#ifndef DBUS_CONNECTION - #include #include "ut.hpp" #include @@ -35,6 +33,10 @@ #include "host-ipc-definitions.hpp" #include "logger/logger.hpp" +#ifdef DBUS_CONNECTION +#include "utils/glib-loop.hpp" +#endif //DBUS_CONNECTION + #include #include #include @@ -56,6 +58,9 @@ const std::string TEMPLATE_NAME = "console-ipc"; struct Fixture { utils::ScopedDir mZonesPathGuard; utils::ScopedDir mRunGuard; +#ifdef DBUS_CONNECTION + utils::ScopedGlibLoop mLoop; +#endif //DBUS_CONNECTION std::unique_ptr cm; @@ -412,5 +417,3 @@ BOOST_AUTO_TEST_CASE(ZoneGetNetdevs) BOOST_AUTO_TEST_SUITE_END() - -#endif /* !DBUS_CONNECTION */ diff --git a/tests/unit_tests/server/configs/CMakeLists.txt b/tests/unit_tests/server/configs/CMakeLists.txt index c5880b1..a91d5d8 100644 --- a/tests/unit_tests/server/configs/CMakeLists.txt +++ b/tests/unit_tests/server/configs/CMakeLists.txt @@ -46,10 +46,6 @@ CONFIGURE_FILE(ut-zones-manager/test-daemon.conf.in ${CMAKE_BINARY_DIR}/ut-zones-manager/test-daemon.conf @ONLY) FILE(GLOB manager_manager_CONF_GEN ${CMAKE_BINARY_DIR}/ut-zones-manager/*.conf) -CONFIGURE_FILE(ut-zones-manager/templates/console-dbus.conf.in - ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/console-dbus.conf @ONLY) -CONFIGURE_FILE(ut-zones-manager/templates/console-ipc.conf.in - ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/console-ipc.conf @ONLY) FILE(GLOB manager_templates_CONF_GEN ${CMAKE_BINARY_DIR}/ut-zones-manager/templates/*.conf) diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in deleted file mode 100644 index 2ff5998..0000000 --- a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-dbus.conf.in +++ /dev/null @@ -1,18 +0,0 @@ -{ - "lxcTemplate" : "minimal-dbus.sh", - "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; /usr/bin/dbus-daemon --config-file=@VSM_TEST_CONFIG_INSTALL_DIR@/server/ut-zones-manager/ut-dbus.conf --fork; read"], - "requestedState" : "running", - "ipv4Gateway" : "", - "ipv4" : "", - "privilege" : 20, - "vt" : -1, - "switchToDefaultAfterTimeout" : true, - "cpuQuotaForeground" : -1, - "cpuQuotaBackground" : 1000, - "shutdownTimeout" : 10, - "runMountPoint" : "/tmp/ut-run/~NAME~", - "provisions" : [], - "permittedToSend" : [ "/tmp/.*" ], - "permittedToRecv" : [ "/tmp/.*" ], - "validLinkPrefixes" : [] -} diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in b/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in deleted file mode 100644 index fab7e58..0000000 --- a/tests/unit_tests/server/configs/ut-zones-manager/templates/console-ipc.conf.in +++ /dev/null @@ -1,18 +0,0 @@ -{ - "lxcTemplate" : "minimal.sh", - "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], - "requestedState" : "running", - "ipv4Gateway" : "", - "ipv4" : "", - "privilege" : 20, - "vt" : -1, - "switchToDefaultAfterTimeout" : true, - "cpuQuotaForeground" : -1, - "cpuQuotaBackground" : 1000, - "shutdownTimeout" : 10, - "runMountPoint" : "/tmp/ut-run/~NAME~", - "provisions" : [], - "permittedToSend" : [ "/tmp/.*" ], - "permittedToRecv" : [ "/tmp/.*" ], - "validLinkPrefixes" : [] -} diff --git a/tests/unit_tests/server/ut-zones-manager.cpp b/tests/unit_tests/server/ut-zones-manager.cpp index a2811a9..e052117 100644 --- a/tests/unit_tests/server/ut-zones-manager.cpp +++ b/tests/unit_tests/server/ut-zones-manager.cpp @@ -34,12 +34,11 @@ #include "test-dbus-definitions.hpp" #include "dbus/connection.hpp" #include "dbus/exception.hpp" -#else +#endif //DBUS_CONNECTION #include "host-ipc-definitions.hpp" #include #include #include -#endif #include "exception.hpp" #include "utils/glib-loop.hpp" @@ -65,7 +64,8 @@ using namespace config; using namespace vasum::utils; #ifdef DBUS_CONNECTION using namespace dbus; -#endif +#endif //DBUS_CONNECTION + namespace { @@ -82,11 +82,6 @@ const std::string FILE_CONTENT = "File content\n" const std::string NON_EXISTANT_ZONE_ID = "NON_EXISTANT_ZONE_ID"; const std::string ZONES_PATH = "/tmp/ut-zones"; // the same as in daemon.conf const std::string SIMPLE_TEMPLATE = "console"; -#ifdef DBUS_CONNECTION -const std::string ZONE_ACCESS_TEMPLATE = "console-dbus"; -#else -const std::string ZONE_ACCESS_TEMPLATE = "console-ipc"; -#endif #ifdef DBUS_CONNECTION /** @@ -105,7 +100,7 @@ dropException(const DbusConnection::AsyncMethodCallCallback& fun) }; } -class DbusAccessory { +class HostDbusAccessory { public: static const int HOST_ID = 0; @@ -114,10 +109,9 @@ public: )> TestApiMethodCallback; typedef std::function VoidResultCallback; typedef std::function NotificationCallback; - typedef std::map Connections; - DbusAccessory() + HostDbusAccessory() : mId(0), mClient(DbusConnection::create(acquireAddress())), mNameAcquired(false), @@ -125,7 +119,7 @@ public: { } - DbusAccessory(int id) + HostDbusAccessory(int id) : mId(id), mClient(DbusConnection::create(acquireAddress())), mNameAcquired(false), @@ -136,8 +130,8 @@ public: void setName(const std::string& name) { mClient->setName(name, - std::bind(&DbusAccessory::onNameAcquired, this), - std::bind(&DbusAccessory::onDisconnect, this)); + std::bind(&HostDbusAccessory::onNameAcquired, this), + std::bind(&HostDbusAccessory::onDisconnect, this)); if(!waitForName()) { mClient.reset(); @@ -168,7 +162,7 @@ public: void signalSubscribe(const DbusConnection::SignalCallback& callback) { - mClient->signalSubscribe(callback, isHost() ? api::BUS_NAME : api::BUS_NAME); + mClient->signalSubscribe(callback, isHost() ? api::dbus::BUS_NAME : api::dbus::BUS_NAME); } void subscribeNotification(const NotificationCallback& callback) @@ -179,9 +173,9 @@ public: const std::string& signalName, GVariant* parameters) { - if (objectPath == api::OBJECT_PATH && - interface == api::INTERFACE && - signalName == api::SIGNAL_NOTIFICATION && + if (objectPath == api::dbus::OBJECT_PATH && + interface == api::dbus::INTERFACE && + signalName == api::dbus::SIGNAL_NOTIFICATION && g_variant_is_of_type(parameters, G_VARIANT_TYPE("(sss)"))) { const gchar* zone = NULL; @@ -191,25 +185,25 @@ public: callback({zone, application, message}); } }; - mClient->signalSubscribe(handler, api::BUS_NAME); + mClient->signalSubscribe(handler, api::dbus::BUS_NAME); } void signalSwitchToDefault() { // emit signal from dbus connection - mClient->emitSignal(api::OBJECT_PATH, - api::INTERFACE, - api::SIGNAL_SWITCH_TO_DEFAULT, + mClient->emitSignal(api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::SIGNAL_SWITCH_TO_DEFAULT, nullptr); } void callMethodNotify() { GVariant* parameters = g_variant_new("(ss)", TEST_APP_NAME.c_str(), TEST_MESSAGE.c_str()); - mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_NOTIFY_ACTIVE_ZONE, + mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_NOTIFY_ACTIVE_ZONE, parameters, "()"); } @@ -217,10 +211,10 @@ public: std::string callMethodMove(const std::string& dest, const std::string& path) { GVariant* parameters = g_variant_new("(ss)", dest.c_str(), path.c_str()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_FILE_MOVE_REQUEST, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_FILE_MOVE_REQUEST, parameters, "(s)"); @@ -278,13 +272,13 @@ public: interface.c_str(), method.c_str(), parameters); - GVariantPtr result = mClient->callMethod(isHost() ? api::BUS_NAME : - api::BUS_NAME, - isHost() ? api::OBJECT_PATH : - api::OBJECT_PATH, - isHost() ? api::INTERFACE : - api::INTERFACE, - api::METHOD_PROXY_CALL, + GVariantPtr result = mClient->callMethod(isHost() ? api::dbus::BUS_NAME : + api::dbus::BUS_NAME, + isHost() ? api::dbus::OBJECT_PATH : + api::dbus::OBJECT_PATH, + isHost() ? api::dbus::INTERFACE : + api::dbus::INTERFACE, + api::dbus::METHOD_PROXY_CALL, packedParameters, "(v)"); GVariant* unpackedResult = NULL; @@ -295,10 +289,10 @@ public: std::vector callMethodGetZoneIds() { assert(isHost()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_GET_ZONE_ID_LIST, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_GET_ZONE_ID_LIST, NULL, "(as)"); @@ -320,10 +314,10 @@ public: std::string callMethodGetActiveZoneId() { assert(isHost()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_GET_ACTIVE_ZONE_ID, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_GET_ACTIVE_ZONE_ID, NULL, "(s)"); @@ -336,10 +330,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_SET_ACTIVE_ZONE, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_SET_ACTIVE_ZONE, parameters, "()"); @@ -357,10 +351,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(ss)", id.c_str(), templateName.c_str()); - mClient->callMethodAsync(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_CREATE_ZONE, + mClient->callMethodAsync(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_CREATE_ZONE, parameters, "()", dropException(asyncResult)); @@ -377,10 +371,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_DESTROY_ZONE, + mClient->callMethodAsync(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_DESTROY_ZONE, parameters, "()", dropException(asyncResult)); @@ -397,10 +391,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_SHUTDOWN_ZONE, + mClient->callMethodAsync(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_SHUTDOWN_ZONE, parameters, "()", dropException(asyncResult)); @@ -417,10 +411,10 @@ public: assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - mClient->callMethodAsync(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_START_ZONE, + mClient->callMethodAsync(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_START_ZONE, parameters, "()", dropException(asyncResult)); @@ -430,10 +424,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_LOCK_ZONE, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_LOCK_ZONE, parameters, "()"); } @@ -442,10 +436,10 @@ public: { assert(isHost()); GVariant* parameters = g_variant_new("(s)", id.c_str()); - GVariantPtr result = mClient->callMethod(api::BUS_NAME, - api::OBJECT_PATH, - api::INTERFACE, - api::METHOD_UNLOCK_ZONE, + GVariantPtr result = mClient->callMethod(api::dbus::BUS_NAME, + api::dbus::OBJECT_PATH, + api::dbus::INTERFACE, + api::dbus::METHOD_UNLOCK_ZONE, parameters, "()"); } @@ -473,10 +467,7 @@ private: } }; -typedef DbusAccessory HostAccessory; - -#else -//#ifdef DBUS_CONNECTION +#endif //DBUS_CONNECTION class HostIPCAccessory { public: @@ -491,21 +482,21 @@ public: std::vector callMethodGetZoneIds() { - const auto out = mClient.callSync(api::METHOD_GET_ZONE_ID_LIST, + const auto out = mClient.callSync(api::ipc::METHOD_GET_ZONE_ID_LIST, std::make_shared()); return out->values; } std::string callMethodGetActiveZoneId() { - const auto out = mClient.callSync(api::METHOD_GET_ACTIVE_ZONE_ID, + const auto out = mClient.callSync(api::ipc::METHOD_GET_ACTIVE_ZONE_ID, std::make_shared()); return out->value; } void callMethodSetActiveZone(const std::string& id) { - mClient.callSync(api::METHOD_SET_ACTIVE_ZONE, + mClient.callSync(api::ipc::METHOD_SET_ACTIVE_ZONE, std::make_shared(api::ZoneId{id})); } @@ -518,7 +509,7 @@ public: result(); } }; - mClient.callAsync(api::METHOD_CREATE_ZONE, + mClient.callAsync(api::ipc::METHOD_CREATE_ZONE, std::make_shared(api::CreateZoneIn{id, templateName}), asyncResult); } @@ -531,7 +522,7 @@ public: result(); } }; - mClient.callAsync(api::METHOD_DESTROY_ZONE, + mClient.callAsync(api::ipc::METHOD_DESTROY_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } @@ -544,7 +535,7 @@ public: result(); } }; - mClient.callAsync(api::METHOD_SHUTDOWN_ZONE, + mClient.callAsync(api::ipc::METHOD_SHUTDOWN_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } @@ -557,21 +548,21 @@ public: result(); } }; - mClient.callAsync(api::METHOD_START_ZONE, + mClient.callAsync(api::ipc::METHOD_START_ZONE, std::make_shared(api::ZoneId{id}), asyncResult); } void callMethodLockZone(const std::string& id) { - mClient.callSync(api::METHOD_LOCK_ZONE, + mClient.callSync(api::ipc::METHOD_LOCK_ZONE, std::make_shared(api::ZoneId{id}), EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } void callMethodUnlockZone(const std::string& id) { - mClient.callSync(api::METHOD_UNLOCK_ZONE, + mClient.callSync(api::ipc::METHOD_UNLOCK_ZONE, std::make_shared(api::ZoneId{id}), EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } @@ -581,19 +572,19 @@ public: auto callbackWrapper = [callback] (const ipc::PeerID, std::shared_ptr& data) { callback(*data); }; - mClient.setSignalHandler(api::SIGNAL_NOTIFICATION, + mClient.setSignalHandler(api::ipc::SIGNAL_NOTIFICATION, callbackWrapper); } void signalSwitchToDefault() { - mClient.signal(api::SIGNAL_SWITCH_TO_DEFAULT, std::make_shared()); + mClient.signal(api::ipc::SIGNAL_SWITCH_TO_DEFAULT, std::make_shared()); } void callMethodNotify() { mClient.callSync( - api::METHOD_NOTIFY_ACTIVE_ZONE, + api::ipc::METHOD_NOTIFY_ACTIVE_ZONE, std::make_shared(api::NotifActiveZoneIn{TEST_APP_NAME, TEST_MESSAGE}), EVENT_TIMEOUT*10); //Prevent from IPCTimeoutException see LockUnlockZone } @@ -601,7 +592,7 @@ public: std::string callMethodMove(const std::string& dest, const std::string& path) { auto result = mClient.callSync( - api::METHOD_FILE_MOVE_REQUEST, + api::ipc::METHOD_FILE_MOVE_REQUEST, std::make_shared(api::FileMoveRequestIn{dest, path}), EVENT_TIMEOUT*10); return result->value; @@ -612,10 +603,6 @@ private: ipc::Client mClient; }; -typedef HostIPCAccessory HostAccessory; - -#endif //DBUS_CONNECTION - template bool spinWaitFor(int timeoutMs, Predicate pred) { @@ -629,6 +616,8 @@ bool spinWaitFor(int timeoutMs, Predicate pred) return true; } +} // namespace + struct Fixture { vasum::utils::ScopedGlibLoop mLoop; @@ -641,7 +630,21 @@ struct Fixture { {} }; -} // namespace +struct IPCFixture : Fixture { + typedef HostIPCAccessory HostAccessory; +}; + +#ifdef DBUS_CONNECTION +struct DbusFixture : Fixture { + typedef HostDbusAccessory HostAccessory; +}; +#endif //DBUS_CONNECTION + +#ifdef DBUS_CONNECTION +#define ACCESSORS IPCFixture, DbusFixture +#else //DBUS_CONNECTION +#define ACCESSORS IPCFixture +#endif //DBUS_CONNECTION BOOST_FIXTURE_TEST_SUITE(ZonesManagerSuite, Fixture) @@ -713,22 +716,13 @@ BOOST_AUTO_TEST_CASE(Focus) BOOST_CHECK(cm.getRunningForegroundZoneId() == "zone3"); } -BOOST_AUTO_TEST_CASE(StartStopWithZoneAccess) -{ - ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); - cm.restoreAll(); -} - #ifdef ZONE_CONNECTION BOOST_AUTO_TEST_CASE(NotifyActiveZone) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); Latch signalReceivedLatch; @@ -782,9 +776,9 @@ BOOST_AUTO_TEST_CASE(NotifyActiveZone) BOOST_AUTO_TEST_CASE(MoveFile) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); Latch notificationLatch; @@ -867,15 +861,15 @@ BOOST_AUTO_TEST_CASE(MoveFile) } #endif -BOOST_AUTO_TEST_CASE(SwitchToDefault) +MULTI_FIXTURE_TEST_CASE(SwitchToDefault, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; auto isDefaultFocused = [&cm]() -> bool { return cm.getRunningForegroundZoneId() == "zone1"; @@ -889,15 +883,15 @@ BOOST_AUTO_TEST_CASE(SwitchToDefault) BOOST_CHECK(spinWaitFor(EVENT_TIMEOUT, isDefaultFocused)); } -BOOST_AUTO_TEST_CASE(AllowSwitchToDefault) +MULTI_FIXTURE_TEST_CASE(AllowSwitchToDefault, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; auto isDefaultFocused = [&cm]() -> bool { return cm.getRunningForegroundZoneId() == "zone1"; @@ -922,15 +916,15 @@ BOOST_AUTO_TEST_CASE(AllowSwitchToDefault) } #ifdef DBUS_CONNECTION -BOOST_AUTO_TEST_CASE(ProxyCall) +MULTI_FIXTURE_TEST_CASE(ProxyCall, F, DbusFixture) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; host.setName(testapi::BUS_NAME); auto handler = [](const std::string& argument, MethodResultBuilder::Pointer result) { @@ -967,7 +961,7 @@ BOOST_AUTO_TEST_CASE(ProxyCall) DbusCustomException, WhatEquals("Proxy call forbidden")); } -#endif // DBUS_CONNECTION +#endif //DBUS_CONNECTION namespace { @@ -975,14 +969,14 @@ const std::set EXPECTED_CONNECTIONS_NONE = { "zone1", "zone2", "zon } // namespace -BOOST_AUTO_TEST_CASE(GetZoneIds) +MULTI_FIXTURE_TEST_CASE(GetZoneIds, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); cm.createZone("zone1", SIMPLE_TEMPLATE); cm.createZone("zone2", SIMPLE_TEMPLATE); cm.createZone("zone3", SIMPLE_TEMPLATE); - HostAccessory host; + typename F::HostAccessory host; std::vector zoneIds = {"zone1", "zone2", @@ -992,7 +986,7 @@ BOOST_AUTO_TEST_CASE(GetZoneIds) BOOST_CHECK(returnedIds == zoneIds);// order should be preserved } -BOOST_AUTO_TEST_CASE(GetActiveZoneId) +MULTI_FIXTURE_TEST_CASE(GetActiveZoneId, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); cm.createZone("zone1", SIMPLE_TEMPLATE); @@ -1000,7 +994,7 @@ BOOST_AUTO_TEST_CASE(GetActiveZoneId) cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; std::vector zoneIds = {"zone1", "zone2", @@ -1015,7 +1009,7 @@ BOOST_AUTO_TEST_CASE(GetActiveZoneId) BOOST_CHECK(host.callMethodGetActiveZoneId() == ""); } -BOOST_AUTO_TEST_CASE(SetActiveZone) +MULTI_FIXTURE_TEST_CASE(SetActiveZone, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); cm.createZone("zone1", SIMPLE_TEMPLATE); @@ -1023,7 +1017,7 @@ BOOST_AUTO_TEST_CASE(SetActiveZone) cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; std::vector zoneIds = {"zone1", "zone2", @@ -1044,7 +1038,7 @@ BOOST_AUTO_TEST_CASE(SetActiveZone) WhatEquals("Could not activate stopped or paused zone")); } -BOOST_AUTO_TEST_CASE(CreateDestroyZone) +MULTI_FIXTURE_TEST_CASE(CreateDestroyZone, F, ACCESSORS) { const std::string zone1 = "test1"; const std::string zone2 = "test2"; @@ -1060,7 +1054,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZone) callDone.set(); }; - HostAccessory host; + typename F::HostAccessory host; // create zone1 host.callAsyncMethodCreateZone(zone1, SIMPLE_TEMPLATE, resultCallback); @@ -1096,7 +1090,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZone) BOOST_CHECK_EQUAL(cm.getRunningForegroundZoneId(), ""); } -BOOST_AUTO_TEST_CASE(CreateDestroyZonePersistence) +MULTI_FIXTURE_TEST_CASE(CreateDestroyZonePersistence, F, ACCESSORS) { const std::string zone = "test1"; @@ -1109,7 +1103,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZonePersistence) ZonesManager cm(TEST_CONFIG_PATH); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; return host.callMethodGetZoneIds(); }; @@ -1118,7 +1112,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZonePersistence) // create zone { ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; + typename F::HostAccessory host; host.callAsyncMethodCreateZone(zone, SIMPLE_TEMPLATE, resultCallback); BOOST_REQUIRE(callDone.wait(EVENT_TIMEOUT)); } @@ -1132,7 +1126,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZonePersistence) // destroy zone { ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; + typename F::HostAccessory host; host.callAsyncMethodDestroyZone(zone, resultCallback); BOOST_REQUIRE(callDone.wait(EVENT_TIMEOUT)); } @@ -1140,7 +1134,7 @@ BOOST_AUTO_TEST_CASE(CreateDestroyZonePersistence) BOOST_CHECK(getZoneIds().empty()); } -BOOST_AUTO_TEST_CASE(ZoneStatePersistence) +MULTI_FIXTURE_TEST_CASE(ZoneStatePersistence, F, ACCESSORS) { const std::string zone1 = "zone1"; const std::string zone2 = "zone2"; @@ -1156,7 +1150,7 @@ BOOST_AUTO_TEST_CASE(ZoneStatePersistence) // firts run { ZonesManager cm(TEST_CONFIG_PATH); - HostAccessory host; + typename F::HostAccessory host; // zone1 - created host.callAsyncMethodCreateZone(zone1, SIMPLE_TEMPLATE, resultCallback); @@ -1211,21 +1205,21 @@ BOOST_AUTO_TEST_CASE(ZoneStatePersistence) } } -BOOST_AUTO_TEST_CASE(StartShutdownZone) +MULTI_FIXTURE_TEST_CASE(StartShutdownZone, F, ACCESSORS) { const std::string zone1 = "zone1"; const std::string zone2 = "zone2"; ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone(zone1, ZONE_ACCESS_TEMPLATE); - cm.createZone(zone2, ZONE_ACCESS_TEMPLATE); + cm.createZone(zone1, SIMPLE_TEMPLATE); + cm.createZone(zone2, SIMPLE_TEMPLATE); Latch callDone; auto resultCallback = [&]() { callDone.set(); }; - HostAccessory host; + typename F::HostAccessory host; // start zone1 host.callAsyncMethodStartZone(zone1, resultCallback); @@ -1251,15 +1245,15 @@ BOOST_AUTO_TEST_CASE(StartShutdownZone) BOOST_CHECK_EQUAL(cm.getRunningForegroundZoneId(), ""); } -BOOST_AUTO_TEST_CASE(LockUnlockZone) +MULTI_FIXTURE_TEST_CASE(LockUnlockZone, F, ACCESSORS) { ZonesManager cm(TEST_CONFIG_PATH); - cm.createZone("zone1", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone2", ZONE_ACCESS_TEMPLATE); - cm.createZone("zone3", ZONE_ACCESS_TEMPLATE); + cm.createZone("zone1", SIMPLE_TEMPLATE); + cm.createZone("zone2", SIMPLE_TEMPLATE); + cm.createZone("zone3", SIMPLE_TEMPLATE); cm.restoreAll(); - HostAccessory host; + typename F::HostAccessory host; std::vector zoneIds = {"zone1", "zone2", @@ -1272,7 +1266,7 @@ BOOST_AUTO_TEST_CASE(LockUnlockZone) //This try catch clause is for prevent from test crashing //and should be removed after resolve following errors //TODO: Abort when zone is locked on destroying ZonesManager - HostAccessory host2; //TODO: After IPCTimeoutException host is useless -- fix it + typename F::HostAccessory host2; //TODO: After IPCTimeoutException host is useless -- fix it try { host2.callMethodUnlockZone(zoneId); } catch (...) {}; throw; } -- 2.7.4 From 49bcbe69cf98fcad1abe8416cd41698478d583ae Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Wed, 29 Apr 2015 12:49:46 +0200 Subject: [PATCH 04/16] Remove strerror usage [Bug] strerror isn't thread-safe [Cause] Thread usage [Solution] Replaces all strerror with strerror_r [Verification] Build, run test Change-Id: I9fc5e84da011d80af7fb7a7877fe868e8e300ea9 --- common/ipc/internals/socket.cpp | 34 ++++++++++++++++++++-------------- common/utils/environment.cpp | 2 +- common/utils/eventfd.cpp | 5 +++-- common/utils/fd-utils.cpp | 25 +++++++++++++++---------- common/utils/fs.cpp | 17 +++++++++-------- common/utils/img.cpp | 13 +++++++------ common/utils/signal.cpp | 10 ++++++---- common/utils/vt.cpp | 9 +++++---- libs/config/fdstore.cpp | 15 ++++++++++++--- server/server.cpp | 3 +-- 10 files changed, 79 insertions(+), 54 deletions(-) diff --git a/common/ipc/internals/socket.cpp b/common/ipc/internals/socket.cpp index 3cdbf7c..26e1c27 100644 --- a/common/ipc/internals/socket.cpp +++ b/common/ipc/internals/socket.cpp @@ -49,8 +49,9 @@ void setFdOptions(int fd) { // Prevent from inheriting fd by zones if (-1 == ::fcntl(fd, F_SETFD, FD_CLOEXEC)) { - LOGE("Error in fcntl: " + std::string(strerror(errno))); - throw IPCException("Error in fcntl: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in fcntl: " + msg); + throw IPCException("Error in fcntl: " + msg); } } @@ -90,8 +91,9 @@ std::shared_ptr Socket::accept() { int sockfd = ::accept(mFD, nullptr, nullptr); if (sockfd == -1) { - LOGE("Error in accept: " << std::string(strerror(errno))); - throw IPCException("Error in accept: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in accept: " << msg); + throw IPCException("Error in accept: " + msg); } setFdOptions(sockfd); return std::make_shared(sockfd); @@ -139,8 +141,9 @@ int Socket::createZoneSocket(const std::string& path) int sockfd = ::socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd == -1) { - LOGE("Error in socket: " + std::string(strerror(errno))); - throw IPCException("Error in socket: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in socket: " + msg); + throw IPCException("Error in socket: " + msg); } setFdOptions(sockfd); @@ -154,7 +157,7 @@ int Socket::createZoneSocket(const std::string& path) if (-1 == ::bind(sockfd, reinterpret_cast(&serverAddress), sizeof(struct sockaddr_un))) { - std::string message = strerror(errno); + std::string message = getSystemErrorMessage(); utils::close(sockfd); LOGE("Error in bind: " << message); throw IPCException("Error in bind: " + message); @@ -162,7 +165,7 @@ int Socket::createZoneSocket(const std::string& path) if (-1 == ::listen(sockfd, MAX_QUEUE_LENGTH)) { - std::string message = strerror(errno); + std::string message = getSystemErrorMessage(); utils::close(sockfd); LOGE("Error in listen: " << message); throw IPCException("Error in listen: " + message); @@ -190,8 +193,9 @@ Socket Socket::connectSocket(const std::string& path) int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { - LOGE("Error in socket: " + std::string(strerror(errno))); - throw IPCException("Error in socket: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in socket: " + msg); + throw IPCException("Error in socket: " + msg); } setFdOptions(fd); @@ -202,17 +206,19 @@ Socket Socket::connectSocket(const std::string& path) if (-1 == connect(fd, reinterpret_cast(&serverAddress), sizeof(struct sockaddr_un))) { + const std::string msg = getSystemErrorMessage(); utils::close(fd); - LOGE("Error in connect: " + std::string(strerror(errno))); - throw IPCException("Error in connect: " + std::string(strerror(errno))); + LOGE("Error in connect: " + msg); + throw IPCException("Error in connect: " + msg); } // Nonblock socket int flags = fcntl(fd, F_GETFL, 0); if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK)) { + const std::string msg = getSystemErrorMessage(); utils::close(fd); - LOGE("Error in fcntl: " + std::string(strerror(errno))); - throw IPCException("Error in fcntl: " + std::string(strerror(errno))); + LOGE("Error in fcntl: " + msg); + throw IPCException("Error in fcntl: " + msg); } return Socket(fd); diff --git a/common/utils/environment.cpp b/common/utils/environment.cpp index 511fcda..209f9ba 100644 --- a/common/utils/environment.cpp +++ b/common/utils/environment.cpp @@ -147,7 +147,7 @@ bool setSuppGroups(const std::vector& groups) } if (::setgroups(gids.size(), gids.data()) != 0) { - LOGE("setgroups() failed: " << strerror(errno)); + LOGE("setgroups() failed: " << getSystemErrorMessage()); return false; } diff --git a/common/utils/eventfd.cpp b/common/utils/eventfd.cpp index 2fd8d62..d69d572 100644 --- a/common/utils/eventfd.cpp +++ b/common/utils/eventfd.cpp @@ -41,8 +41,9 @@ EventFD::EventFD() { mFD = ::eventfd(0, EFD_SEMAPHORE | EFD_CLOEXEC); if (mFD == -1) { - LOGE("Error in eventfd: " << getSystemErrorMessage()); - throw UtilsException("Error in eventfd: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in eventfd: " << msg); + throw UtilsException("Error in eventfd: " + msg); } } diff --git a/common/utils/fd-utils.cpp b/common/utils/fd-utils.cpp index 59bad36..17448b5 100644 --- a/common/utils/fd-utils.cpp +++ b/common/utils/fd-utils.cpp @@ -67,8 +67,9 @@ void waitForEvent(int fd, if (errno == EINTR) { continue; } - LOGE("Error in poll: " + getSystemErrorMessage()); - throw UtilsException("Error in poll: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in poll: " + msg); + throw UtilsException("Error in poll: " + msg); } if (ret == 0) { @@ -128,8 +129,9 @@ void write(int fd, const void* bufferPtr, const size_t size, int timeoutMS) // Neglected errors LOGD("Retrying write"); } else { - LOGE("Error during writing: " + getSystemErrorMessage()); - throw UtilsException("Error during writing: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error during writing: " + msg); + throw UtilsException("Error during writing: " + msg); } waitForEvent(fd, POLLOUT, deadline); @@ -160,8 +162,9 @@ void read(int fd, void* bufferPtr, const size_t size, int timeoutMS) // Neglected errors LOGD("Retrying read"); } else { - LOGE("Error during reading: " + getSystemErrorMessage()); - throw UtilsException("Error during reading: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error during reading: " + msg); + throw UtilsException("Error during reading: " + msg); } waitForEvent(fd, POLLIN, deadline); @@ -172,8 +175,9 @@ unsigned int getMaxFDNumber() { struct rlimit rlim; if (-1 == getrlimit(RLIMIT_NOFILE, &rlim)) { - LOGE("Error during getrlimit: " + getSystemErrorMessage()); - throw UtilsException("Error during getrlimit: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error during getrlimit: " + msg); + throw UtilsException("Error during getrlimit: " + msg); } return rlim.rlim_cur; } @@ -184,8 +188,9 @@ void setMaxFDNumber(unsigned int limit) rlim.rlim_cur = limit; rlim.rlim_max = limit; if (-1 == setrlimit(RLIMIT_NOFILE, &rlim)) { - LOGE("Error during setrlimit: " + getSystemErrorMessage()); - throw UtilsException("Error during setrlimit: " + getSystemErrorMessage()); + const std::string msg = getSystemErrorMessage(); + LOGE("Error during setrlimit: " + msg); + throw UtilsException("Error during setrlimit: " + msg); } } diff --git a/common/utils/fs.cpp b/common/utils/fs.cpp index e3a59b3..e4dcd7f 100644 --- a/common/utils/fs.cpp +++ b/common/utils/fs.cpp @@ -122,7 +122,7 @@ bool removeFile(const std::string& path) LOGD(path << ": exists, removing."); if (::remove(path.c_str())) { if (errno != ENOENT) { - LOGE(path << ": failed to delete: " << ::strerror(errno)); + LOGE(path << ": failed to delete: " << getSystemErrorMessage()); return false; } } @@ -145,7 +145,7 @@ const unsigned long RUN_MOUNT_POINT_FLAGS = MS_NOSUID | MS_NODEV | MS_STRICTATIM bool mountTmpfs(const std::string& path, unsigned long flags, const std::string& options) { if (::mount("tmpfs", path.c_str(), "tmpfs", flags, options.c_str()) != 0) { - LOGD("Mount failed for '" << path << "', options=" << options << ": " << strerror(errno)); + LOGD("Mount failed for '" << path << "', options=" << options << ": " << getSystemErrorMessage()); return false; } return true; @@ -192,7 +192,7 @@ bool mount(const std::string& source, bool umount(const std::string& path) { if (::umount(path.c_str()) != 0) { - LOGD("Umount failed for '" << path << "': " << strerror(errno)); + LOGD("Umount failed for '" << path << "': " << getSystemErrorMessage()); return false; } return true; @@ -213,12 +213,12 @@ bool hasSameMountPoint(const std::string& path1, const std::string& path2, bool& struct stat s1, s2; if (::stat(path1.c_str(), &s1)) { - LOGD("Failed to get stat of " << path1 << ": " << strerror(errno)); + LOGD("Failed to get stat of " << path1 << ": " << getSystemErrorMessage()); return false; } if (::stat(path2.c_str(), &s2)) { - LOGD("Failed to get stat of " << path2 << ": " << strerror(errno)); + LOGD("Failed to get stat of " << path2 << ": " << getSystemErrorMessage()); return false; } @@ -305,11 +305,11 @@ bool copyDirContentsRec(const boost::filesystem::path& src, const boost::filesys ::stat(current.string().c_str(), &info); if (fs::is_symlink(destination)) { if (::lchown(destination.string().c_str(), info.st_uid, info.st_gid) < 0) { - LOGW("Failed to change owner of symlink " << destination.string() << ": " << strerror(errno)); + LOGW("Failed to change owner of symlink " << destination.string() << ": " << getSystemErrorMessage()); } } else { if (::chown(destination.string().c_str(), info.st_uid, info.st_gid) < 0) { - LOGW("Failed to change owner of file " << destination.string() << ": " << strerror(errno)); + LOGW("Failed to change owner of file " << destination.string() << ": " << getSystemErrorMessage()); } } } @@ -366,11 +366,12 @@ bool createDir(const std::string& path, uid_t uid, uid_t gid, boost::filesystem: // set owner if (::chown(path.c_str(), uid, gid) != 0) { + int err = errno; // remove the directory only if it hadn't existed before if (runDirCreated) { fs::remove(dirPath); } - LOGE("chown() failed for path '" << path << "': " << strerror(errno)); + LOGE("chown() failed for path '" << path << "': " << getSystemErrorMessage(err)); return false; } diff --git a/common/utils/img.cpp b/common/utils/img.cpp index a33b5fd..785291c 100644 --- a/common/utils/img.cpp +++ b/common/utils/img.cpp @@ -27,6 +27,7 @@ #include "utils/img.hpp" #include "utils/fs.hpp" #include "utils/paths.hpp" +#include "base-exception.hpp" #include #include @@ -52,7 +53,7 @@ bool isLoopDevFree(const std::string& loopdev, bool& ret) // open loop device FD int loopFD = ::open(loopdev.c_str(), O_RDWR); if (loopFD < 0) { - LOGD("Failed to open loop device descriptor: " << ::strerror(errno)); + LOGD("Failed to open loop device descriptor: " << getSystemErrorMessage()); return false; } @@ -77,21 +78,21 @@ bool mountLoop(const std::string& img, // get image file FD int fileFD = ::open(img.c_str(), O_RDWR); if (fileFD < 0) { - LOGD("Failed to open image file descriptor: " << ::strerror(errno)); + LOGD("Failed to open image file descriptor: " << getSystemErrorMessage()); return false; } // get loop device FD int loopFD = ::open(loopdev.c_str(), O_RDWR); if (loopFD < 0) { - LOGD("Failed to open loop device descriptor: " << ::strerror(errno)); + LOGD("Failed to open loop device descriptor: " << getSystemErrorMessage()); ::close(fileFD); return false; } // set loop device if (::ioctl(loopFD, LOOP_SET_FD, fileFD)) { - LOGD("Failed to assign loop device to image: " << ::strerror(errno)); + LOGD("Failed to assign loop device to image: " << getSystemErrorMessage()); ::close(fileFD); ::close(loopFD); return false; @@ -99,7 +100,7 @@ bool mountLoop(const std::string& img, // mount loop device to path if (::mount(loopdev.c_str(), path.c_str(), type.c_str(), flags, options.c_str()) != 0) { - LOGD("Mount failed for '" << path << "', options=" << options << ": " << strerror(errno)); + LOGD("Mount failed for '" << path << "', options=" << options << ": " << getSystemErrorMessage()); ::ioctl(loopFD, LOOP_CLR_FD, 0); ::close(fileFD); ::close(loopFD); @@ -150,7 +151,7 @@ bool mountImage(const std::string& image, const std::string& path, const std::st bool umountImage(const std::string& path, const std::string& loopdev) { if (::umount(path.c_str()) != 0) { - LOGD("Umount failed for '" << path << "': " << strerror(errno)); + LOGD("Umount failed for '" << path << "': " << getSystemErrorMessage()); return false; } diff --git a/common/utils/signal.cpp b/common/utils/signal.cpp index fdb571c..11ea8f2 100644 --- a/common/utils/signal.cpp +++ b/common/utils/signal.cpp @@ -38,13 +38,15 @@ void signalBlock(const int signalToBlock) { ::sigset_t set; if (-1 == ::sigemptyset(&set)) { - LOGE("Error in sigemptyset: " << std::string(strerror(errno))); - throw UtilsException("Error in sigemptyset: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in sigemptyset: " << msg); + throw UtilsException("Error in sigemptyset: " + msg); } if (-1 ==::sigaddset(&set, signalToBlock)) { - LOGE("Error in sigaddset: " << std::string(strerror(errno))); - throw UtilsException("Error in sigaddset: " + std::string(strerror(errno))); + const std::string msg = getSystemErrorMessage(); + LOGE("Error in sigaddset: " << msg); + throw UtilsException("Error in sigaddset: " + msg); } int ret = ::pthread_sigmask(SIG_BLOCK, &set, nullptr /*&oldSet*/); diff --git a/common/utils/vt.cpp b/common/utils/vt.cpp index df8a923..44461e4 100644 --- a/common/utils/vt.cpp +++ b/common/utils/vt.cpp @@ -25,6 +25,7 @@ #include "config.hpp" #include "utils/vt.hpp" #include "logger/logger.hpp" +#include "base-exception.hpp" #include #include @@ -46,14 +47,14 @@ bool activateVT(const int& vt) { int consoleFD = ::open(TTY_DEV.c_str(), O_WRONLY); if (consoleFD < 0) { - LOGE("console open failed: " << errno << " (" << strerror(errno) << ")"); + LOGE("console open failed: " << errno << " (" << getSystemErrorMessage() << ")"); return false; } struct vt_stat vtstat; vtstat.v_active = 0; if (::ioctl(consoleFD, VT_GETSTATE, &vtstat)) { - LOGE("Failed to get vt state: " << errno << " (" << strerror(errno) << ")"); + LOGE("Failed to get vt state: " << errno << " (" << getSystemErrorMessage() << ")"); ::close(consoleFD); return false; } @@ -66,14 +67,14 @@ bool activateVT(const int& vt) // activate vt if (::ioctl(consoleFD, VT_ACTIVATE, vt)) { - LOGE("Failed to activate vt" << vt << ": " << errno << " (" << strerror(errno) << ")"); + LOGE("Failed to activate vt" << vt << ": " << errno << " (" << getSystemErrorMessage() << ")"); ::close(consoleFD); return false; } // wait until activation is finished if (::ioctl(consoleFD, VT_WAITACTIVE, vt)) { - LOGE("Failed to wait for vt" << vt << " activation: " << errno << " (" << strerror(errno) << ")"); + LOGE("Failed to wait for vt" << vt << " activation: " << errno << " (" << getSystemErrorMessage() << ")"); ::close(consoleFD); return false; } diff --git a/libs/config/fdstore.cpp b/libs/config/fdstore.cpp index 2b761eb..c0b7d08 100644 --- a/libs/config/fdstore.cpp +++ b/libs/config/fdstore.cpp @@ -37,6 +37,15 @@ namespace config { namespace { +const int ERROR_MESSAGE_BUFFER_CAPACITY = 256; + +std::string getSystemErrorMessage() +{ + char buf[ERROR_MESSAGE_BUFFER_CAPACITY]; + return strerror_r(errno, buf, sizeof(buf)); +} + + void waitForEvent(int fd, short event, const std::chrono::high_resolution_clock::time_point deadline) @@ -59,7 +68,7 @@ void waitForEvent(int fd, if (errno == EINTR) { continue; } - throw ConfigException("Error in poll: " + std::string(strerror(errno))); + throw ConfigException("Error in poll: " + getSystemErrorMessage()); } if (ret == 0) { @@ -110,7 +119,7 @@ void FDStore::write(const void* bufferPtr, const size_t size, const unsigned int } else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { // Neglected errors } else { - throw ConfigException("Error during writing: " + std::string(strerror(errno))); + throw ConfigException("Error during writing: " + getSystemErrorMessage()); } waitForEvent(mFD, POLLOUT, deadline); @@ -139,7 +148,7 @@ void FDStore::read(void* bufferPtr, const size_t size, const unsigned int timeou } else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { // Neglected errors } else { - throw ConfigException("Error during reading: " + std::string(strerror(errno))); + throw ConfigException("Error during reading: " + getSystemErrorMessage()); } waitForEvent(mFD, POLLIN, deadline); diff --git a/server/server.cpp b/server/server.cpp index f64ea03..ab8cba3 100644 --- a/server/server.cpp +++ b/server/server.cpp @@ -130,8 +130,7 @@ void Server::reloadIfRequired(char* argv[]) { if (gUpdateTriggered) { execve(argv[0], argv, environ); - - LOGE("Failed to reload " << argv[0] << ": " << strerror(errno)); + LOGE("Failed to reload " << argv[0] << ": " << getSystemErrorMessage()); } } -- 2.7.4 From 0ff9530e23f7f3fac687425461406d86083a994f Mon Sep 17 00:00:00 2001 From: Krzysztof Dynowski Date: Tue, 21 Apr 2015 16:54:03 +0200 Subject: [PATCH 05/16] Vasum Wrapper: wrap old api client library #2 [Bug/Feature] Old API wrapper [Cause] wrap to vasum lib [Solution] #2 binary compatible wrapper [Verification] Build, install on target, check journal Change-Id: Ifadee97d41189937aacc1723f2890bb5904c6851 --- cli/CMakeLists.txt | 2 +- client/CMakeLists.txt | 26 +- client/host-ipc-connection.cpp | 4 + client/host-ipc-connection.hpp | 1 + client/vasum-client-impl.cpp | 13 +- client/vasum-client-impl.hpp | 26 +- client/vasum-client.h | 3 + client/vasum-wrapper.cpp | 632 ++++++++++++ client/vasum.h | 1984 ++++++++++++------------------------- client/{sc_adt.h => vasum_list.h} | 17 +- client/wrapper-compat.cpp | 1580 +++++++++++++++++++++++++++++ client/wrapper-compat.h | 191 ++++ common/epoll/event-poll.cpp | 1 - packaging/vasum.spec | 10 +- tests/unit_tests/CMakeLists.txt | 4 +- 15 files changed, 3138 insertions(+), 1356 deletions(-) create mode 100644 client/vasum-wrapper.cpp rename client/{sc_adt.h => vasum_list.h} (81%) create mode 100644 client/wrapper-compat.cpp create mode 100644 client/wrapper-compat.h diff --git a/cli/CMakeLists.txt b/cli/CMakeLists.txt index 2ffdcc4..957faff 100644 --- a/cli/CMakeLists.txt +++ b/cli/CMakeLists.txt @@ -31,7 +31,7 @@ PKG_CHECK_MODULES(LIB_DEPS REQUIRED vasum) INCLUDE_DIRECTORIES(${CLIENT_FOLDER}) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) -TARGET_LINK_LIBRARIES(${CLI_CODENAME} ${LIB_DEPS_LIBRARIES} ${PROJECT_NAME}) +TARGET_LINK_LIBRARIES(${CLI_CODENAME} ${PROJECT_NAME}-client ${LIB_DEPS_LIBRARIES}) CONFIGURE_FILE(support/vasum-cli-completion.sh.in ${CMAKE_BINARY_DIR}/vasum-cli-completion.sh diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 753b7c4..e366e3c 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -19,14 +19,24 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") +## set client library sources (without vasum-wrapper.cpp) FILE(GLOB project_SRCS *.cpp *.hpp *.h) +FILE(GLOB project_SRCS_rm vasum-wrapper.cpp) +LIST(REMOVE_ITEM project_SRCS ${project_SRCS_rm}) + +## set wrapper library sources (without vasum-client.cpp) +FILE(GLOB wrapper_SRCS *.cpp *.hpp *.h) +FILE(GLOB wrapper_SRCS_rm vasum-client.cpp) +LIST(REMOVE_ITEM wrapper_SRCS ${wrapper_SRCS_rm}) + FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp ${COMMON_FOLDER}/ipc/*.hpp ${COMMON_FOLDER}/ipc/*.cpp ${COMMON_FOLDER}/ipc/internals/*.hpp ${COMMON_FOLDER}/ipc/internals/*.cpp ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/utils/*.cpp ${COMMON_FOLDER}/*.hpp ${COMMON_FOLDER}/*.cpp) -SET(_LIB_VERSION_ "0.0.1") +## set version highier then vasum.so.0.1.0 +SET(_LIB_VERSION_ "0.1.1") SET(_LIB_SOVERSION_ "0") SET(PC_FILE "${PROJECT_NAME}.pc") @@ -37,7 +47,13 @@ SET(PC_FILE "${PROJECT_NAME}.pc") ADD_DEFINITIONS(-fvisibility=hidden) ## Setup target ################################################################ -ADD_LIBRARY(${PROJECT_NAME} SHARED ${project_SRCS} ${common_SRCS}) +ADD_LIBRARY(${PROJECT_NAME}-client SHARED ${project_SRCS} ${common_SRCS}) +SET_TARGET_PROPERTIES(${PROJECT_NAME}-client PROPERTIES + SOVERSION ${_LIB_SOVERSION_} + VERSION ${_LIB_VERSION_} + COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") + +ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS} ${common_SRCS}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${_LIB_SOVERSION_} VERSION ${_LIB_VERSION_} @@ -50,6 +66,8 @@ INCLUDE_DIRECTORIES(SYSTEM ${LIB_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) INCLUDE_DIRECTORIES(${LIBS_FOLDER}) INCLUDE_DIRECTORIES(${SERVER_FOLDER}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME}-client ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Config SimpleDbus) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} Config SimpleDbus) @@ -61,9 +79,9 @@ CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_BINARY_DIR}/${PC_FILE} @ONLY) INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE} DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) -INSTALL(TARGETS ${PROJECT_NAME} +INSTALL(TARGETS ${PROJECT_NAME}-client ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT RuntimeLibraries) -INSTALL(FILES vasum-client.h +INSTALL(FILES vasum-client.h vasum.h vasum_list.h DESTINATION ${INCLUDE_INSTALL_DIR}/${PROJECT_NAME}) diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index 6541881..11741f6 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -36,6 +36,10 @@ void HostIPCConnection::createSystem() mClient.reset(new ipc::Client(mDispatcher.getPoll(), HOST_IPC_SOCKET)); mClient->start(); } +epoll::ThreadDispatcher& HostIPCConnection::getDispatcher() +{ + return mDispatcher; +} void HostIPCConnection::create(const std::string& address) { diff --git a/client/host-ipc-connection.hpp b/client/host-ipc-connection.hpp index 8fa6e06..39015f4 100644 --- a/client/host-ipc-connection.hpp +++ b/client/host-ipc-connection.hpp @@ -44,6 +44,7 @@ public: typedef std::function NotificationCallback; void createSystem(); void create(const std::string& address); + epoll::ThreadDispatcher& getDispatcher(); void callGetZoneIds(vasum::api::ZoneIds& argOut); void callGetActiveZoneId(vasum::api::ZoneId& argOut); diff --git a/client/vasum-client-impl.cpp b/client/vasum-client-impl.cpp index 8866e5f..9694dd3 100644 --- a/client/vasum-client-impl.cpp +++ b/client/vasum-client-impl.cpp @@ -28,6 +28,7 @@ #include "utils.hpp" #include "exception.hpp" #include "host-ipc-connection.hpp" +#include "logger/logger.hpp" #include #include @@ -176,6 +177,9 @@ VsmStatus Client::coverException(const function& worker) noexcept } catch (const exception& ex) { mStatus = Status(VSMCLIENT_CUSTOM_ERROR, ex.what()); } + if (mStatus.mVsmStatus!=VSMCLIENT_SUCCESS) { + LOGE("Exception: " << mStatus.mMsg); + } return mStatus.mVsmStatus; } @@ -193,6 +197,11 @@ VsmStatus Client::create(const string& address) noexcept }); } +epoll::EventPoll& Client::getEventPoll() noexcept +{ + return mHostClient.getDispatcher().getPoll(); +} + const char* Client::vsm_get_status_message() const noexcept { return mStatus.mMsg.c_str(); @@ -338,7 +347,7 @@ VsmStatus Client::vsm_unlock_zone(const char* id) noexcept }); } -VsmStatus Client::vsm_add_state_callback(VsmZoneDbusStateCallback /* zoneDbusStateCallback */, +VsmStatus Client::vsm_add_state_callback(VsmZoneDbusStateFunction /* zoneDbusStateCallback */, void* /* data */, VsmSubscriptionId* /* subscriptionId */) noexcept { @@ -710,7 +719,7 @@ VsmStatus Client::vsm_file_move_request(const char* /*destZone*/, const char* /* }); } -VsmStatus Client::vsm_add_notification_callback(VsmNotificationCallback /*notificationCallback*/, +VsmStatus Client::vsm_add_notification_callback(VsmNotificationFunction /*notificationCallback*/, void* /*data*/, VsmSubscriptionId* /*subscriptionId*/) noexcept { diff --git a/client/vasum-client-impl.hpp b/client/vasum-client-impl.hpp index 3f3b13a..da6dc8f 100644 --- a/client/vasum-client-impl.hpp +++ b/client/vasum-client-impl.hpp @@ -33,6 +33,26 @@ #include /** + * Zone's D-Bus state change callback function signature. + * + * @param[in] zoneId affected zone id + * @param[in] dbusAddress new D-Bus address + * @param data custom user's data pointer passed to vsm_add_state_callback() function + */ +typedef std::function VsmZoneDbusStateFunction; + +/** + * Notification callback function signature. + * + * @param[in] zone source zone + * @param[in] application sending application name + * @param[in] message notification message + * @param data custom user's data pointer passed to vsm_add_notification_callback() + */ +typedef std::function + VsmNotificationFunction; + +/** * vasum's client definition. * * Client uses dbus API. @@ -49,6 +69,8 @@ public: */ VsmStatus createSystem() noexcept; + vasum::epoll::EventPoll& getEventPoll() noexcept; + /** * Create client. * @@ -135,7 +157,7 @@ public: /** * @see ::vsm_add_state_callback */ - VsmStatus vsm_add_state_callback(VsmZoneDbusStateCallback zoneDbusStateCallback, + VsmStatus vsm_add_state_callback(VsmZoneDbusStateFunction zoneDbusStateCallback, void* data, VsmSubscriptionId* subscriptionId) noexcept; @@ -300,7 +322,7 @@ public: /** * @see ::vsm_add_notification_callback */ - VsmStatus vsm_add_notification_callback(VsmNotificationCallback notificationCallback, + VsmStatus vsm_add_notification_callback(VsmNotificationFunction notificationCallback, void* data, VsmSubscriptionId* subscriptionId) noexcept; diff --git a/client/vasum-client.h b/client/vasum-client.h index 50ed162..1d43094 100644 --- a/client/vasum-client.h +++ b/client/vasum-client.h @@ -187,6 +187,7 @@ typedef enum { VSMFILE_REGULAR } VsmFileType; +#ifndef __VASUM_WRAPPER_SOURCE__ /** * Start glib loop. * @@ -831,6 +832,8 @@ VsmStatus vsm_add_notification_callback(VsmClient client, */ VsmStatus vsm_del_notification_callback(VsmClient client, VsmSubscriptionId subscriptionId); +#endif /* __VASUM_WRAPPER_SOURCE__ */ + /** @} Zone API */ #ifdef __cplusplus diff --git a/client/vasum-wrapper.cpp b/client/vasum-wrapper.cpp new file mode 100644 index 0000000..2cbe806 --- /dev/null +++ b/client/vasum-wrapper.cpp @@ -0,0 +1,632 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Krzysztof Dynowski + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + + +/** + * @file + * @author Krzysztof Dynowski (k.dynowski@samsung.com) + * @brief Vasum old API wrapper to slp client lib + */ + +#define __VASUM_WRAPPER_SOURCE__ +#include +#include +#include + +#include "config.hpp" +#include "logger/logger.hpp" +#include "logger/backend-journal.hpp" + +#include "wrapper-compat.h" +#include "vasum-client-impl.hpp" + +#define MAX_EPOLL_EVENTS 16 + +struct WrappedZone +{ + Client *client; + VsmZone zone; + struct vsm_zone vz; + std::vector netdevs; +}; + +struct WrappedContext +{ + Client *client; + vsm_context hq_ctx; + struct vsm_zone hq_root; + std::vector zones; +}; + +static struct +{ + int done; + int glib_stop; +}wrap; + +#ifndef offsetof +#define offsetof(type, memb) ((size_t)&((type *)0)->memb) +#endif +#ifdef container_of +#undef container_of +#endif +#ifndef container_of +#define container_of(ptr, type, memb) (\ + (type *)((char *)(ptr) - offsetof(type, memb))) +#endif + +#define UNUSED(x) ((void)(x)) + +#define vsm_error_t vsm_error_s +#define vsm_attach_command_t vsm_attach_command_s +#define vsm_attach_options_t vsm_attach_options_s +#define vsm_zone_state_cb vsm_zone_state_changed_cb + +void __attribute__ ((constructor)) wrapper_load(void); +void __attribute__ ((destructor)) wrapper_unload(void); +static void init_wrapper(); +extern struct vasum_ops dummy_ops; + +using namespace logger; +void wrapper_load(void) +{ + Logger::setLogLevel(LogLevel::TRACE); + Logger::setLogBackend(new SystemdJournalBackend()); + init_wrapper(); +} + +void wrapper_unload(void) +{ + if (wrap.glib_stop) Client::vsm_stop_glib_loop(); + wrap.glib_stop = 0; +} + +static void callcheck() +{ + init_wrapper(); +} + +void init_wrapper() +{ + if (wrap.done) return ; + memset(&wrap,0,sizeof(wrap)); + wrap.done = 1; + LOGS(""); +} + +static struct vsm_zone* wrap_vsm_zone(WrappedContext *w, VsmZone zone, bool create = false) +{ + if (zone == NULL) { + return NULL; + } + for (auto& zw : w->zones) { + if (zw.zone == zone) { + return &zw.vz; + } + } + if (create) { + w->zones.push_back(WrappedZone()); + WrappedZone& zw = w->zones.back(); + zw.client = w->client; + zw.zone = zone; + zw.vz.name = zone->id; + zw.vz.type = NULL; + zw.vz.user_data = NULL; + zw.vz.rootfs_path = zone->rootfs_path; + zw.vz.parent = &zw.vz; + LOGI("return (create) zone " << zone->id); + return &w->zones.back().vz; + } + LOGE("return zone NULL"); + return NULL; +} + +static int wrap_error(VsmStatus st, const Client *c) +{ + if (st == VSMCLIENT_SUCCESS) LOGI("return success " << st); + else LOGE("return error " << st << "m=" << (c ? c->vsm_get_status_message() : "n/a")); + switch (st) { + case VSMCLIENT_SUCCESS: return VSM_ERROR_NONE; + case VSMCLIENT_CUSTOM_ERROR: return -VSM_ERROR_GENERIC; + case VSMCLIENT_IO_ERROR: return -VSM_ERROR_IO; + case VSMCLIENT_OPERATION_FAILED: return -VSM_ERROR_NOT_PERMITTED; + case VSMCLIENT_INVALID_ARGUMENT: return -VSM_ERROR_INVALID; + case VSMCLIENT_OTHER_ERROR: return -VSM_ERROR_GENERIC; + } + return -VSM_ERROR_GENERIC; +} + +static void init_context_wrap(WrappedContext *w) +{ + Client::vsm_start_glib_loop(); + wrap.glib_stop = 1; + w->client = new Client(); + VsmStatus st = w->client->createSystem(); + wrap_error(st, w->client); + + memset(&w->hq_ctx, 0, sizeof(w->hq_ctx)); + memset(&w->hq_root, 0, sizeof(w->hq_root)); + + vsm_context *ctx = &w->hq_ctx; + adt_init_list(&ctx->listeners); + //init root_zone + ctx->root_zone = &w->hq_root; + ctx->root_zone->name = (char*)""; + ctx->root_zone->id=0; + ctx->root_zone->rootfs_path = (char*)"/"; + + ctx->root_zone->terminal = -1; + ctx->root_zone->state = VSM_ZONE_STATE_RUNNING; + ctx->root_zone->user_data = ctx->root_zone; + + ctx->root_zone->parent = ctx->root_zone; + ctx->root_zone->ctx = ctx; + + pthread_rwlock_init(&ctx->root_zone->lock, NULL); + adt_init_list(&ctx->root_zone->netdevs); + adt_init_list(&ctx->root_zone->devices); + adt_init_list(&ctx->root_zone->children); + + pthread_rwlock_init(&ctx->lock, NULL); + adt_init_list(&ctx->listeners); + adt_init_list(&ctx->sc_listeners); + adt_init_list(&ctx->ev_listeners); + + //struct mainloop *mainloop = mainloop_create(); + //struct mxe_engine *engine = mxe_prepare_engine(mainloop, ctx); + //struct mxe_endpoint *ep = mxe_create_client(engine, SERVICEPATH); + + ctx->foreground_zone = ctx->root_zone; + ctx->vsm_ops = &dummy_ops; + ctx->error = VSM_ERROR_NONE; + //ctx->data = ep; +} + +API struct vsm_context *vsm_create_context(void) +{ + LOGS(""); callcheck(); + WrappedContext *w = new WrappedContext(); + init_context_wrap(w); + + vsm_context *ctx = &w->hq_ctx; + return ctx; +} + +API int vsm_cleanup_context(struct vsm_context *ctx) +{ + LOGS(""); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + if (w->client != NULL) { + delete w->client; + w->client = NULL; + } + for (auto& zw : w->zones) { + zw.netdevs.clear(); + } + w->zones.clear(); + delete w; + return VSM_ERROR_NONE; +} + +static const char *const vsm_error_strtab[] = { + "No error", + "Undefined error", + "Invalid", + "Operation cancelled", + "Operation aborted", + "Connection refused", + "Object exists", + "Resource busy", + "Input/Output error", + "Timeout", + "Overflow", + "Out of memory", + "Out of range", + "Operation not permitted", + "Function not implemented", + "Operation not supported", + "Access denied", + "No object found", + "Bad state" +}; + +API vsm_error_e vsm_last_error(struct vsm_context *ctx) +{ + if (ctx) + return ctx->error; + return static_cast(-1); +} + +API const char *vsm_error_string(vsm_error_e error) +{ + LOGS(""); callcheck(); + if (error < 0 || error > VSM_MAX_ERROR) { + return NULL; + } + return vsm_error_strtab[error]; +} + +API int vsm_get_poll_fd(struct vsm_context *ctx) +{ + LOGS(""); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(w); + //FIXME Client should create Dispatcher and pass to IPCConnection + // now: IPCConnection has field ThreadWrapper + //return w->client->getEventPoll().getPollFD(); + return -1; +} +API int vsm_enter_eventloop(struct vsm_context *ctx, int flags, int timeout) +{ + LOGS(""); callcheck(); + UNUSED(flags); + UNUSED(timeout); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(w); + //FIXME Client should create Dispatcher and pass to IPCConnection + // now: IPCConnection has field ThreadWrapper + //TODO Use EventPoll from Dispatcher + return 0; +} + +API int vsm_create_zone(struct vsm_context *ctx, const char *zone_name, const char *template_name, int flag) +{ + LOGS("create_zone " << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(flag); + //template_name = NULL; //template name not supported by libvasum-client + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_create_zone(zone_name, template_name); + if (st != VSMCLIENT_SUCCESS) { + LOGE("vsm_create_zone(" << zone_name << ") = " << st); + } + return wrap_error(st, w->client); +} + +API int vsm_destroy_zone(struct vsm_context *ctx, const char *zone_name, int force) +{ + LOGS("zone=" << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(force); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_destroy_zone(zone_name); + if (st == VSMCLIENT_SUCCESS) { + auto zonebyname = [zone_name](const WrappedZone& v) {return v.zone->id == zone_name;}; + auto zonelist = std::remove_if(w->zones.begin(), w->zones.end(), zonebyname); + w->zones.erase(zonelist); + } + return wrap_error(st, w->client); +} + +API int vsm_start_zone(struct vsm_context *ctx, const char *zone_name) +{ + LOGS("zone=" << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_start_zone(zone_name); + return wrap_error(st, w->client); +} + +API int vsm_shutdown_zone(struct vsm_context *ctx, const char *zone_name, int force) +{ + LOGS("zone=" << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(force); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_shutdown_zone(zone_name); + return wrap_error(st, w->client); +} + +API int vsm_lock_zone(struct vsm_context *ctx, const char *zone_name, int shutdown) +{ + LOGS("zone=" << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + UNUSED(shutdown); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_lock_zone(zone_name); + return wrap_error(st, w->client); +} + +API int vsm_unlock_zone(struct vsm_context *ctx, const char *zone_name) +{ + LOGS("zone=" << zone_name); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_lock_zone(zone_name); + return wrap_error(st, w->client); +} + +API int vsm_set_foreground(struct vsm_zone *zone) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(zone, WrappedZone, vz); + if (!w->client) return VSM_ERROR_GENERIC; + VsmStatus st = w->client->vsm_set_active_zone(zone->name); + return wrap_error(st, w->client); +} + +//execute command in specified zone +API int vsm_attach_zone(struct vsm_context *ctx, + const char *zone_name, + vsm_attach_command_t *command, + vsm_attach_options_t *opts, + pid_t *attached_process) +{ + return ctx->vsm_ops->attach_zone(ctx, zone_name, command, opts, + attached_process); +} + +//execute command in specified zone and wait +API int vsm_attach_zone_wait(struct vsm_context *ctx, + const char *zone_name, + vsm_attach_command_t *command, + vsm_attach_options_t *opts) +{ + return ctx->vsm_ops->attach_zone_wait(ctx, zone_name, command, opts); +} + +API int vsm_iterate_zone(struct vsm_context *ctx, void (*callback)(struct vsm_zone *zone, void *user_data), void *user_data) +{ + LOGS(""); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + if (!w->client) return -VSM_ERROR_GENERIC; + callback(ctx->root_zone, user_data); + for (auto& z : w->zones) { + callback(&z.vz, user_data); + } + return 0; +} + +API struct vsm_zone *vsm_lookup_zone_by_name(struct vsm_context *ctx, const char *path) +{ + LOGS("name=" << path); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + VsmZone zone; + if (!w->client) return NULL; + //CHECK if path is same as zone_name + if (w->client->vsm_lookup_zone_by_id(path, &zone) != VSMCLIENT_SUCCESS) + return NULL; + return wrap_vsm_zone(w, zone, true); +} + +API struct vsm_zone *vsm_lookup_zone_by_pid(struct vsm_context *ctx, pid_t pid) +{ + LOGS("pid=" << pid); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + VsmZone zone; + VsmString id; + if (!w->client) return NULL; + if (w->client->vsm_lookup_zone_by_pid(pid, &id) != VSMCLIENT_SUCCESS) { + LOGE("vsm_lookup_zone_by_pid(" << pid << ") error"); + return NULL; + } + if (::strcmp(id, "host") == 0) { + return w->hq_ctx.root_zone; + } + w->client->vsm_lookup_zone_by_id(id, &zone); //zone is malloced + return wrap_vsm_zone(w, zone); +} + +API struct vsm_zone *vsm_lookup_zone_by_terminal_id(struct vsm_context *ctx, int terminal) +{ + LOGS("terminal=" << terminal); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + VsmZone zone; + VsmString id; + if (!w->client) return NULL; + if (w->client->vsm_lookup_zone_by_terminal_id(terminal, &id) != VSMCLIENT_SUCCESS) + return NULL; + w->client->vsm_lookup_zone_by_id(id, &zone); + return wrap_vsm_zone(w, zone); +} +#if 0 +API int vsm_add_state_changed_callback(struct vsm_context *ctx, vsm_zone_state_cb callback, void *user_data) +{ + LOGS(""); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + VsmSubscriptionId subscriptionId; + + auto dbus_cb = [=](const char* id, const char* dbusAddress, void* data) -> + void { + VsmZone zone; + //TODO what are valid state, event + UNUSED(dbusAddress); + w->client->vsm_lookup_zone_by_id(id, &zone); + callback(wrap_vsm_zone(w, zone), data); + }; + w->client->vsm_add_state_callback(dbus_cb, user_data, &subscriptionId); + return (int)subscriptionId; +} + +API int vsm_del_state_changed_callback(struct vsm_context *ctx, int handle) +{ + LOGS(""); callcheck(); + WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); + VsmSubscriptionId subscriptionId = (VsmSubscriptionId)handle; + VsmStatus st = w->client->vsm_del_state_callback(subscriptionId); + return wrap_error(st, w->client); +} +#endif +API int vsm_grant_device(struct vsm_zone *dom, const char *name, uint32_t flags) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(dom, WrappedZone, vz); + const char *id = dom->name; + VsmZone zone; + w->client->vsm_lookup_zone_by_id(id, &zone); + VsmStatus st = w->client->vsm_grant_device(id, name, flags); + return wrap_error(st, w->client); +} + +API int vsm_revoke_device(struct vsm_zone *dom, const char *name) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(dom, WrappedZone, vz); + const char *id = dom->name; + VsmStatus st = w->client->vsm_revoke_device(id, name); + return wrap_error(st, w->client); +} + +API struct vsm_netdev *vsm_create_netdev(struct vsm_zone *zone, vsm_netdev_type_t type, const char *target, const char *netdev) +{ + LOGS(""); callcheck(); + UNUSED(zone); + UNUSED(type); + UNUSED(target); + UNUSED(netdev); + + WrappedZone *w = container_of(zone, WrappedZone, vz); + const char *id = zone->name; + VsmStatus st; + if (type == VSM_NETDEV_VETH) + st = w->client->vsm_create_netdev_veth(id, target, netdev); + else if (type == VSM_NETDEV_PHYS) + st = w->client->vsm_create_netdev_phys(id, netdev); + else if (type == VSM_NETDEV_MACVLAN) // macvlan_mode from if_link.h + st = w->client->vsm_create_netdev_macvlan(id, target, netdev, MACVLAN_MODE_BRIDGE); + else { + LOGE("Invalid arguments"); + //ctx->error = VSM_ERROR_INVALID; + return NULL; + } + + if (st != VSMCLIENT_SUCCESS) { + LOGE("vsm_create_netdev(" << netdev << ") = " << st); + return NULL; + } + + vsm_netdev vnd; + vnd.zone = zone; + vnd.name = (char*)netdev; //FIXME? copy content of string + vnd.type = type; + w->netdevs.push_back(vnd); //copy pushed to vector + return &w->netdevs.back(); //pointer to struct on vector +} + +API int vsm_destroy_netdev(struct vsm_zone *zone, struct vsm_netdev *netdev) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(zone, WrappedZone, vz); + + VsmStatus st = w->client->vsm_destroy_netdev(zone->name, netdev->name); + if (st == VSMCLIENT_SUCCESS) { + auto devbyname = [netdev](const vsm_netdev& v) {return ::strcmp(v.name, netdev->name) == 0;}; + auto devlist = std::find_if(w->netdevs.begin(), w->netdevs.end(), devbyname); + if (devlist != w->netdevs.end()) { + w->netdevs.erase(devlist); + } + } + return wrap_error(st, w->client); +} + +API int vsm_iterate_netdev(struct vsm_zone *zone, void (*callback)(struct vsm_netdev *, void *user_data), void *user_data) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(zone, WrappedZone, vz); + for (auto nd : w->netdevs) { + callback(&nd, user_data); + } + return 0; +} + +API struct vsm_netdev *vsm_lookup_netdev_by_name(struct vsm_zone *zone, const char *name) +{ + LOGS(""); callcheck(); + WrappedZone *w = container_of(zone, WrappedZone, vz); + VsmNetdev nd; + VsmStatus st = w->client->vsm_lookup_netdev_by_name(zone->name, name, &nd); + if (st == VSMCLIENT_SUCCESS) { + auto devbyname = [name](const vsm_netdev& v) {return ::strcmp(v.name, name) == 0;}; + auto devlist = std::find_if(w->netdevs.begin(), w->netdevs.end(), devbyname); + if (devlist != w->netdevs.end()) { + return &devlist[0]; + } + } + return NULL; +} + +API int vsm_declare_file(struct vsm_context *ctx, vsm_fso_type_t ftype, const char *path, int flags, vsm_mode_t mode) +{ + LOGS(""); callcheck(); + UNUSED(ctx); + UNUSED(ftype); + UNUSED(path); + UNUSED(flags); + UNUSED(mode); + //TODO apply declare link for existing zones (and those created in the future, so must store paits source, target) + return VSM_ERROR_NONE; +} + +API int vsm_declare_mount(struct vsm_context *ctx, + const char *source, + const char *target, + const char *fstype, + unsigned long flags, + const void *data) +{ + LOGS(""); callcheck(); + UNUSED(ctx); + UNUSED(source); + UNUSED(target); + UNUSED(fstype); + UNUSED(flags); + UNUSED(data); + //TODO apply declare link for existing zones (and those created in the future, so must store paits source, target) + return VSM_ERROR_NONE; +} + +API int vsm_declare_link(struct vsm_context *ctx, const char *source, const char *target) +{ + LOGS("src=" << source << "dst=" << target); callcheck(); + UNUSED(ctx); + UNUSED(source); + UNUSED(target); + //TODO apply declare link for existing zones (and those created in the future, so must store paits source, target) + return VSM_ERROR_NONE; +} + +API int vsm_add_state_changed_callback(vsm_context_h /*ctx*/, vsm_zone_state_changed_cb /*callback*/, void * /*user_data*/) +{ + return VSM_ERROR_NONE; +} +API int vsm_del_state_changed_callback(vsm_context_h /*ctx*/, int /*id*/) +{ + return VSM_ERROR_NONE; +} +API const char * vsm_get_zone_rootpath(vsm_zone_h /*zone*/) +{ + return NULL; +} +API const char * vsm_get_zone_name(vsm_zone_h /*zone*/) +{ + return NULL; +} +API int vsm_is_host_zone(vsm_zone_h /*zone*/) +{ + return VSM_ERROR_NONE; +} +API vsm_zone_h vsm_join_zone(vsm_zone_h /*zone*/) +{ + return NULL; +} +API int vsm_canonicalize_path(const char * /*input_path*/, char ** /*output_path*/) +{ + return VSM_ERROR_NONE; +} + + diff --git a/client/vasum.h b/client/vasum.h index f7393ff..ae4f37d 100644 --- a/client/vasum.h +++ b/client/vasum.h @@ -1,9 +1,9 @@ /* - * Container Control Framework + * Vasum : Tizen Zone Control Framework * * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved * - * Contact: Krzysztof Dynowski + * Contact: Keunhwan Kwak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ #include #include -#include "sc_adt.h" +#include "vasum_list.h" #ifndef API #define API __attribute__((visibility("default"))) @@ -36,1199 +36,662 @@ #ifdef __cplusplus extern "C" { #endif - /* * @file vasum.h - * @version 0.2 - * @brief This file contains APIs of the Container control Framework + * @version 0.3 + * @brief This file contains APIs of the Zone control Framework */ /* * - * * Revision History: - * + * 2014-09-01 sungbae you First created + * 2014-10-07 sungbae you First doxygen commented + * 2015-03-19 kuenhwan Kwak doxygen revise * */ /** - * @addtogroup ZONE_CONTROL Zone Control + * @addtogroup CONTEXT vasum context * @{ */ -typedef enum { - VSM_ERROR_NONE, /* The operation was successful */ - VSM_ERROR_GENERIC, /* Non-specific cause */ - VSM_ERROR_INVALID, /* Invalid argument */ - VSM_ERROR_CANCELED, /* The requested operation was cancelled */ - VSM_ERROR_ABORTED, /* Operation aborted */ - VSM_ERROR_REFUSED, /* Connection refused */ - VSM_ERROR_EXIST, /* Target exists */ - VSM_ERROR_BUSY, /* Resource is busy */ - VSM_ERROR_IO, /* I/O error*/ - VSM_ERROR_TIMEOUT, /* Timer expired */ - VSM_ERROR_OVERFLOW, /* Value too large to be stored in data type */ - VSM_ERROR_OUT_OF_MEMORY, /* No memory space */ - VSM_ERROR_OUT_OF_RANGE, /* Input is out of range */ - VSM_ERROR_NOT_PERMITTED, /* Operation not permitted */ - VSM_ERROR_NOT_IMPLEMENTED, /* Function is not implemented yet */ - VSM_ERROR_NOT_SUPPORTED, /* Operation is not supported */ - VSM_ERROR_ACCESS_DENIED, /* Access privilege is not sufficient */ - VSM_ERROR_NO_OBJECT, /* Object not found */ - VSM_ERROR_BAD_STATE, /* Bad state */ - VSM_MAX_ERROR = VSM_ERROR_BAD_STATE -}vsm_error_t; - /** - *@brief struct vsm_context keeps track of an execution state of the container control framework. + *@brief vasum handle for interact with vasum server process. This is opaque data type. */ -struct vsm_context { - /// — Used for internal — - void *data; - /// Error code - vsm_error_t error; - /// RWLock for list members - pthread_rwlock_t lock; - /// List of callback function for changing state - struct adt_list listeners; - /// Root(host) of zones (except for stopped zones) - struct vsm_zone *root_zone; - /// Foreground zone - struct vsm_zone *foreground_zone; -}; - -/** - * @brief Get last error string. - * - * \par Synopsis: - * \code - * #include - * - * const char *vsm_error_string(struct vsm_context *ctx); - * \endcode - * - * \par Description: - * vsm_error_string return last error string for debug or logging. - * - * \param[in] ctx vsm context - * - * \return string for last error in context. - * - * \par Known issues/bugs: - * None - * - * \pre None - * - * \post None - * - * \see struct vsm_context - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * struct vsm_zone * zone; - * - * ctx = vsm_create_context(); - * zone = vsm_lookup_zone_by_pid(ctx, pid); - * if(zone == NULL) - * { - * fprintf(stderr, "API Failed : %s", vsm_error_string(ctx)); - * } - * ... - * \endcode - * -*/ - -API const char *vsm_error_string(struct vsm_context *ctx); +typedef struct vsm_context* vsm_context_h; /** * @brief Create vsm context - * - * \par Synopsis: - * \code - * #include - * - * struct vsm_context *vsm_create_context(void *) - * \endcode - * * \par Description: * The vsm context is an abstraction of the logical connection between the zone controller and it's clients. - * The vsm context must be initialized before attempting to use almost any of the APIs, - * and it should be finalized when interaction with the zone controller is no longer required.\n - * \n - * A call to vsm_create_context() makes a connection to zone controller(vsm-zone-svc), - * and creates a new instance of struct vsm_context called vsm context.\n - * - * \param None - * - * \return An instance of vsm context on success, or NULL on error (in which case, errno is set appropriately) - * + * and vsm_context_h object should be finalized when interaction with the vasum server is no longer required.\n + * \return An instance of vsm context on success, or NULL + * \retval vsm_context_h successful + * \retval NULL get vasum context failed. * \par Known issues/bugs: - * None - * - * \pre vsm-zone-svc must be started - * - * \post None - * + * Only a host process has permission for vsm_create_context(); + * \pre vsm-zone-svc must be started * \see vsm_cleanup_context() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * - * ctx = vsm_create_context(); - * if(ctx == NULL) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * */ -API struct vsm_context *vsm_create_context(void); +API vsm_context_h vsm_create_context(void); /** * @brief Cleanup zone control context - * - * \par Synopsis: - * \code - * #include - * - * int vsm_cleanup_context(struct vsm_context *ctx) - *\endcode - * * \par Description: * vsm_cleanup_context() finalizes vsm context and release all resources allocated to the vsm context.\n - * \n * This function should be called if interaction with the zone controller is no longer required. - * * \param[in] ctx vsm context - * - * \return 0 on success, or -1 on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post vsm context will not be valid after calling this API - * + * \return #VSM_ERROR_NONE on success. + * \pre vsm_context_h must be initialized by vsm_create_context() + * \post vsm context_h will not be valid after calling this API * \see vsm_create_context() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * retval = vsm_cleanup_context(ctx); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * */ -API int vsm_cleanup_context(struct vsm_context *ctx); +API int vsm_cleanup_context(vsm_context_h ctx); /** * @brief Get file descriptor associated with event dispatcher of zone control context - * - * \par Synopsis: - * \code - * #include - * - * int vsm_get_poll_fd(struct vsm_context *ctx) - * \endcode - * * \par Description: * The function vsm_get_poll_fd() returns the file descriptor associated with the event dispatcher of vsm context.\n * The file descriptor can be bound to another I/O multiplexing facilities like epoll, select, and poll. - * * \param[in] ctx vsm context - * - * \return On success, a nonnegative file descriptor is returned. On error -1 is returned. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_enter_eventloop() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int fd; - * struct vsm_context *ctx; - * ... - * fd = vsm_get_poll_fd(ctx); - * while (1) { - * ... - * epoll_wait(fd, events, MAX_EPOLL_EVENTS, -1); - * ... - * if (vsm_enter_eventloop(ctx, 0, 0) < 0) - * break; - * ... - * } - * ... - * \endcode - * + * \return On success, a nonnegative file descriptor is returned. On negative error code is returned. + * \retval fd nonnegative integer fd value for getting vasum event and refresh vsm_context_h. + * \retval #VSM_ERROR_INVALID invalid vsm_context_h + * \pre vsm_context_h must be initialized by vsm_create_context() + * \see vsm_create_context() */ -API int vsm_get_poll_fd(struct vsm_context *ctx); +API int vsm_get_poll_fd(vsm_context_h ctx); + /** * @brief Wait for an I/O event on a VSM context - * - * \par Synopsis: - * \code - * #incldue - * - * int vsm_enter_eventloop(struct vsm_context *ctx, int flags, int timeout) - * \endcode - * * \par Description: * vsm_enter_eventloop() waits for event on the vsm context.\n *\n * The call waits for a maximum time of timout milliseconds. Specifying a timeout of -1 makes vsm_enter_eventloop() wait indefinitely, * while specifying a timeout equal to zero makes vsm_enter_eventloop() to return immediately even if no events are available. - * * \param[in] ctx vsm context * \param[in] flags Reserved * \param[in] timeout Timeout time (milisecond), -1 is infinite - * - * \return 0 on success, or -1 on error. - * - * \par Known issues/bugs: - * None - * + * \return 0 on success, or negative error code. * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * * \see vsm_create_context(), vsm_get_poll_fd() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * ... - * while (vsm_enter_eventloop(ctx, 0, -1)) { - * ... - * } - * ... - * \endcode - * */ -API int vsm_enter_eventloop(struct vsm_context *ctx, int flags, int timeout); +API int vsm_enter_eventloop(vsm_context_h ctx, int flags, int timeout); /** - * @brief Definition for default zone name. - * Default zone is started at boot sequence by systemd. + * @brief Enumeration for vasum error. + */ +typedef enum { + VSM_ERROR_NONE, /**< The operation was successful */ + VSM_ERROR_GENERIC, /**< Non-specific cause */ + VSM_ERROR_INVALID, /**< Invalid argument */ + VSM_ERROR_CANCELED, /**< The requested operation was cancelled */ + VSM_ERROR_ABORTED, /**< Operation aborted */ + VSM_ERROR_REFUSED, /**< Connection refused */ + VSM_ERROR_EXIST, /**< Target exists */ + VSM_ERROR_BUSY, /**< Resource is busy */ + VSM_ERROR_IO, /**< I/O error*/ + VSM_ERROR_TIMEOUT, /**< Timer expired */ + VSM_ERROR_OVERFLOW, /**< Value too large to be stored in data type */ + VSM_ERROR_OUT_OF_MEMORY, /**< No memory space */ + VSM_ERROR_OUT_OF_RANGE, /**< Input is out of range */ + VSM_ERROR_NOT_PERMITTED, /**< Operation not permitted */ + VSM_ERROR_NOT_IMPLEMENTED, /**< Function is not implemented yet */ + VSM_ERROR_NOT_SUPPORTED, /**< Operation is not supported */ + VSM_ERROR_ACCESS_DENIED, /**< Access privilege is not sufficient */ + VSM_ERROR_NO_OBJECT, /**< Object not found */ + VSM_ERROR_BAD_STATE, /**< Bad state */ + VSM_MAX_ERROR = VSM_ERROR_BAD_STATE +}vsm_error_e; + +/** + * @brief Get last vasum error code from vsm_context. + * \param[in] ctx vsm context + * \return vasum error enum value. + * \par Known issues/bugs: + * thread non-safe + * \see vsm_error_string() */ -#define VSM_DEFAULT_ZONE "personal" +API vsm_error_e vsm_last_error(vsm_context_h ctx); /** - * @brief Definition for zone states. - * This definition shows the available states. - * Zone is started from VSM_ZONE_STATE_STOPPED state. During start up, zone controller instantiates zone and - * starts the first process in the zone. - * Once the first process has started, the state of the zone will not be changed unless - * the process is killed. + * @brief Get vasum error string. + * \par Description: + * return string pointer for vasum error string. + * \param[in] vsm_error_e error. + * \return string pointer value represent to error code. + * \warning Do not free returned pointer. */ +API const char *vsm_error_string(vsm_error_e error); -typedef enum { - VSM_ZONE_STATE_STOPPED, - VSM_ZONE_STATE_STARTING, - VSM_ZONE_STATE_RUNNING, - VSM_ZONE_STATE_STOPPING, - VSM_ZONE_STATE_ABORTING, - VSM_ZONE_STATE_FREEZING, - VSM_ZONE_STATE_FROZEN, - VSM_ZONE_STATE_THAWED, - VSM_ZONE_MAX_STATE = VSM_ZONE_STATE_THAWED -} vsm_zone_state_t; +/// @} -typedef enum { - VSM_ZONE_EVENT_NONE, - VSM_ZONE_EVENT_CREATED, - VSM_ZONE_EVENT_DESTROYED, - VSM_ZONE_EVENT_SWITCHED, - VSM_ZONE_MAX_EVENT = VSM_ZONE_EVENT_SWITCHED -} vsm_zone_event_t; +/** + * @addtogroup LIFECYCLE Vasum Lifecycle + * @{ + */ /** - * @brief Zone structure which is used to represent an instance of container. + * @brief vsm_zone_h opaque datatype which is used to represent an instance of zone. */ -struct vsm_zone { - /// Parent - struct vsm_zone *parent; - /// Name (null-terminated string) - char *name; - /// Zone type (null-terminated string) - char *type; - /// Domain's Virtual Terminal number - int terminal; - /// State - vsm_zone_state_t state; - /// Container's rootfs path - char *rootfs_path; - /// RWLock for list members - pthread_rwlock_t lock; - /// List of child zones - struct adt_list children; - /// List of devices in zone - struct adt_list devices; - /// List of network devices in zone - struct adt_list netdevs; - /// Pointer of user-defined data for clients. - void *user_data; - ///List head - struct adt_list list; -}; + +typedef struct vsm_zone* vsm_zone_h; + +/** + * @brief Definition for default zone name. + * Default zone is started at boot sequence by systemd. +*/ +#define VSM_DEFAULT_ZONE "personal" + /** * @brief Create a new persistent zone - * - * \par Synopsis - * \code - * #include - * - * int vsm_create_zone(struct vsm_context *ctx, const char *name, const char *template_name, int flag) - * \endcode - * * \par Description: - * vsm_create_zone() triggers zone controller to create new persistent zone.\n - * \n + * vsm_create_zone() triggers zone controller to create new persistent zone.\n\n * The zone controller distinguishes two types of zones: peristent and transient. * Persistent zones exist indefinitely in storage. - * While, transient zones are created and started on-the-fly.\n - * \n - * Creating zone requires template. - * In general, creating a zone involves constructing root file filesystem and + * While, transient zones are created and started on-the-fly.\n\n + * Creating zone requires template.\n + * In general, creating a zone involves constructing root file filesystem and * generating configuration files which is used to feature the zone. * Moreover, it often requires downloading tools and applications pages, * which are not available in device. - * In that reason, this Domain Separation Framework delegates this work to templates. - * + * In that reason, Vasum Framework delegates this work to templates. * \param[in] ctx vsm context * \param[in] zone_name zone name * \param[in] template_name template name to be used for constructing the zone * \param[in] flag Reserved - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_start_zone(), vsm_shutdown_zone(), vsm_destroy_zone() - * - * \remarks By default, a zone is in an inactive state even if it has succefully created. - * Thus, the zone should be unlocked explicitly to start its execution.\n - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * retval = vsm_create_zone(ctx, "personal", "tizen", 0); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_EXIST The same name zone is existed. + * \retval #VSM_ERROR_GENERIC Lxc failed to create zone. + * \retval #VSM_ERROR_IO Database access failed */ -API int vsm_create_zone(struct vsm_context *ctx, const char *zone_name, const char *template_name, int flag); +API int vsm_create_zone(vsm_context_h ctx, const char *zone_name, const char *template_name, int flag); + /** * @brief Destroy persistent zone - * - * \par Synopsis: - * \code - * #include - * - * int vsm_destroy_zone(struct vsm_context *ctx, const char *name, int force) - * \endcode - * * \par Description: * The function vsm_destroy_zone() triggers zone controller to destroy persistent zone corresponding to the given name.\n * All data stored in the repository of the zone are also deleted if force argument is set. * Once the zone repository is deleted, it cannot be recovered. - * * \param[in] ctx vsm context - * \param[in] zone_name Domain name - * \param[in] force - * - 0 is Remaining the zone when the zone is running - * - non-zero is Destroy the zone even though the zone is running - * - * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * Parameter "force" is not implemented yet, now it works as non-zero. - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_create_zone(), vsm_shutdown_zone(), vsm_destroy_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * retval = vsm_destroy_zone(ctx, "personal", 1); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \param[in] zone_name zone name + * \param[in] force forced flags + * - 0 : do not destory running zone. + * - non-zero : if zone is running, shutdown forcefully, and destroy. + * \return 0 on success, or negative integer error code on error.i + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_BUSY Target zone is running + * \retval #VSM_ERROR_NO_OBJECT Target zone does not exist + * \retval #VSM_ERROR_GENERIC Lxc failed to destroy zone + * \retval #VSM_ERROR_IO Database access failed */ -API int vsm_destroy_zone(struct vsm_context *ctx, const char *zone_name, int force); +API int vsm_destroy_zone(vsm_context_h ctx, const char *zone_name, int force); + /** * @brief Start an execution of a persistent zone - * - * \par Synopsis: - * \code - * #include - * - * int vsm_start_zone(struct vsm_context *ctx, const char *name) - * \endcode - * * \par Description: * The function vsm_start_zone() triggers zone controller to start zone corresponding to the given name.\n * Caller can speficy the type of zones: transient and peristent. * Persistent zones need to be defined before being start up(see vsm_create_zone()) * While, transient zones are created and started on-the-fly. - * * \param[in] ctx vsm context * \param[in] zone_name zone name - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_shutdown_zone(), vsm_create_zone(), vsm_destroy_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * retval = vsm_start_zone(ctx, "personal"); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid argument. + * \retval #VSM_ERROR_BUSY Target zone is already running state. + * \retval #VSM_ERROR_NO_OBJECT Target zone does not exist + * \retval #VSM_ERROR_GENERIC Lxc failed to start zone */ -API int vsm_start_zone(struct vsm_context *ctx, const char *zone_name); +API int vsm_start_zone(vsm_context_h ctx, const char *zone_name); + /** * @brief Stop an execution of running zone - * - * \par Synopsys - * \code - * #include - * - * int vsm_shutdown_zone(struct vsm_context * ctx, struct zone * zone, int force) - * \endcode - * * \par Description: - * vsm_shutdown_zone() triggers zone controller to stop execution of the zone corresponsing to the given zone.\n - * - * \par Important notes: - * None - * + * Send request to stop running zone.\n * \param[in] ctx vsm context * \param[in] zone_name zone name * \param[in] force option to shutdown. - * Without if 0 send SIGPWR signal to init process in zone, - otherwise, terminate all processes in zone forcefully. - * + * - 0 : send SIGPWR signal to init process of target zone. + * - non-zero : terminate all processes in target zone. * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_create_zone(), vsm_destroy_zone(), vsm_start_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * retval = vsm_shutdown_zone(ctx, "zone", 1); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid argument. + * \retval #VSM_ERROR_BAD_STATE Failed to lookup running zone. + * \retval #VSM_ERROR_NO_OBJECT Target zone does not exist + * \retval #VSM_ERROR_GENERIC Lxc failed to destroy zone */ -API int vsm_shutdown_zone(struct vsm_context *ctx, const char *zone_name, int force); +API int vsm_shutdown_zone(vsm_context_h ctx, const char *zone_name, int force); /** - * @brief Prevent starting zone - * - * \par Synopsys - * \code - * #include - * - * int vsm_lock_zone(struct vsm_context *ctx, const char *name, int shutdown); - * \endcode - * + * @brief Shutdown zone and prevent starting zone * \par Description: - * Prevent starting a zone - * + * Prevent starting target zone. + * If target zone is running, shutdown the zone first. * \param[in] ctx vsm context * \param[in] zone_name zone name - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_create_zone(), vsm_start_zone(), vsm_unlock_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * ... - * ret = vsm_lock_zone(ctx, "zone"); - * if(ret < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_NO_OBJECT Target zone does not exist + * \retval #VSM_ERROR_GENERIC Locking failed. */ -API int vsm_lock_zone(struct vsm_context *ctx, const char *zone_name, int shutdown); +API int vsm_lock_zone(vsm_context_h ctx, const char *zone_name, int shutdown); /** * @brief Allow a zone to be launched - * - * \par Synopsys - * \code - * #include - * - * int vsm_unlock_zone(struct vsm_context *ctx, const char *name) - * \endcode - * * \par Description: * Remove lock applied to the zone corresponding to the given name. - * * \param[in] ctx vsm context * \param[in] zone_name zone name - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_lock_zone(), vsm_create_zone(), vsm_start_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * ... - * if (vsm_unlock_zone(ctx, "zone") < 0) { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_GENERIC Unlocking failed. */ -API int vsm_unlock_zone(struct vsm_context *ctx, const char *zone_name); - - -API int vsm_set_foreground(struct vsm_zone * zone); - - -typedef struct vsm_attach_command_t { - /** @brief excutable file path */ - char * exec; - /** @brief arguments including the executable binary itself in argv[0] */ - char ** argv; -} vsm_attach_command_t; +API int vsm_unlock_zone(vsm_context_h ctx, const char *zone_name); /** - * @brief Domain attach option + * @brief Switch target zone to foreground + * \par Description: + * Switch target zone to foreground on device. + * \param[in] zone vsm_zone_h + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID vsm_zone_h is invalid */ -typedef struct vsm_attach_options_t { - /** @brief user id */ - uid_t uid; - /** @brief group id */ - gid_t gid; - /** @brief number of environment variables */ - int env_num; - /** @brief environment variables */ - char **extra_env; -} vsm_attach_options_t; - -#define VSM_ATTACH_OPT_DEFAULT \ -{ \ - /*.uid =*/ (uid_t)0, \ - /*.gid =*/ (gid_t)0, \ - /*.env_num=*/ 0, \ - /*.extra_env = */ NULL \ -} +API int vsm_set_foreground(vsm_zone_h zone); /** - * @brief Launch a process in a running zone. - * - * \par Synopsys - * \code - * #include - * - * int vsm_attach_zone(struct vsm_context *ctx, const char * name, vsm_attach_command_t * command, vsm_attach_options_t * opt) - * \endcode - * + * @brief Get current foreground zone on device * \par Description: - * Execute specific command inside the container with given arguments and environment - * - * \param[in] ctx vsm context - * \param[in] zone_name zone name - * \param[in] command vsm attach command - * \param[in] opt vsm attach options (can be NULL) - * - * \return On sucess, exit code of attached process. - * otherwise, a negative value. - * - * \par Known issues/bugs: - * - * \pre None - * - * \post None - * - * \see vsm_start_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * struct vsm_zone *zone; - * vsm_attach_command_t comm; - * vsm_attach_options_t opts = VSM_ATTACH_OPT_DEFAULT; - * char * attach_argv[] = {"-al", "/proc/"}; - * - * comm.exec = "ls"; - * comm.argc = 2; - * comm.argv = attach_argv; - * - * opts.uid = 5000; - * opts.gid = 5000; - * opts.env_num = 0; - * - * ... - * res = vsm_attach_zone(ctx, zone, &comm, &opts); - * ... - * \endcode - * + * Get foreground zone handle. + * \param[in] ctx vsm_context_h + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID vsm_context_h is invalid */ +API vsm_zone_h vsm_get_foreground(vsm_context_h ctx); -API int vsm_attach_zone(struct vsm_context *ctx, struct vsm_zone *zone, vsm_attach_command_t * command, vsm_attach_options_t * opt, pid_t *attached_process); +/// @} +/** + * @addtogroup ACCESS Vasum Access + * @{ +*/ +/** + * @brief Definition for zone states. + * This definition shows the available states. +*/ +typedef enum { + VSM_ZONE_STATE_STOPPED, /**< Zone stopped */ + VSM_ZONE_STATE_STARTING, /**< Zone is prepare for running */ + VSM_ZONE_STATE_RUNNING, /**< Zone is running on device */ + VSM_ZONE_STATE_STOPPING, /**< Zone is stopping by request */ + VSM_ZONE_STATE_ABORTING, /**< Zone is failed to start */ + VSM_ZONE_STATE_FREEZING, /**< Reserved State */ + VSM_ZONE_STATE_FROZEN, /**< Reserved State */ + VSM_ZONE_STATE_THAWED, /**< Reserved State */ + VSM_ZONE_MAX_STATE = VSM_ZONE_STATE_THAWED +} vsm_zone_state_t; -API int vsm_attach_zone_wait(struct vsm_context *ctx, struct vsm_zone *zone, vsm_attach_command_t * command, vsm_attach_options_t * opt); /** - * @brief Interate all zone instances which are in running state - * - * \par Synopsys - * \code - * #include - * - * int vsm_iterate_zone(struct vsm_context *ctx, void (*callback)(struct vsm_zone *zone, void *user_data), void *user_data) - * \endcode - * - * \par Description: - * The function vsm_iterate_zone() traverses all zones which are in running state, and callback function will be called on every entry. - * - * \param[in] ctx vsm context - * \param[in] callback Function to be executed in iteration, which can be NULL - * \param[in] user_data Parameter to be passed to callback function - * - * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_lock_zone(), vsm_unlock_zone(), vsm_start_zone(), vsm_shutdown_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_context *ctx; - * ... - * void callback(struct vsm_zone *zone, void *user_data) - * { - * printf("Zone : %s\n", zone->name); - * } - * ... - * zone = vsm_iterate_zone(ctx, callback, NULL); - * if(netdev == NULL) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * @brief Definition for zone events */ -API int vsm_iterate_zone(struct vsm_context *ctx, void (*callback)(struct vsm_zone *zone, void *user_data), void *user_data); +typedef enum { + VSM_ZONE_EVENT_NONE, /**< Zone has no event */ + VSM_ZONE_EVENT_CREATED, /**< Zone is created */ + VSM_ZONE_EVENT_DESTROYED, /**< Zone is destroted */ + VSM_ZONE_EVENT_SWITCHED, /**< Foreground is switched */ + VSM_ZONE_MAX_EVENT = VSM_ZONE_EVENT_SWITCHED +} vsm_zone_event_t; + /** - * @brif Find zone corresponding to the name - * - * \par Synopsys - * \code - * #include - * - * struct zone *vsm_lookup_zone_by_name(struct vsm_context *ctx, const char *path) - * \endcode - * + * @brief Definition for zone iteration callback function. + */ +typedef void (*vsm_zone_iter_cb)(vsm_zone_h zone, void *user_data); +/** + * @brief Definition for zone state changed callback function. + */ +typedef int (*vsm_zone_state_changed_cb)(vsm_zone_h zone, vsm_zone_state_t state, void *user_data); +/** + * @brief Definition for zone event callback function. + */ +typedef int (*vsm_zone_event_cb)(vsm_zone_h zone, vsm_zone_event_t event, void *user_data); + +/** + * @brief Interate all zone instances which are in running state * \par Description: + * This API traverses all zones which are in running state, and callback function will be called on every entry. + * \param[in] ctx vsm context + * \param[in] zone_name zone name string + * \param[in] callback Function to be executed in iteration, which can be NULL + * \param[in] user_data Parameter to be passed to callback function + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_OUT_OF_MEMORY Zone handle allocation failed + * \retval #VSM_ERROR_GENERIC Zone initialize failed + * \remark In case of callback and is NULL, + * This API refresh vsm_context which means reloading current running zone to vsm_context again. +*/ +API int vsm_iterate_zone(vsm_context_h ctx, vsm_zone_iter_cb callback, void *user_data); + +/** + * @brief Find zone corresponding to the name * The function vsm_lookup_zone_by_name() looks for the zone instance corresponding to the given name. - * * \param[in] ctx vsm context * \param[in] path zone path to search - * * \return Zone instance on success, or NULL on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_lookup_zone_by_pid(), vsm_lookup_zone_by_terminal(), vsm_iterate_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_zone *zone; - * struct vsm_context *ctx; - * ... - * zone = vsm_lookup_zone_by_name(ctx, "personal"); - * if(zone == NULL) - * { - * printf("Knox isn't exist or isn't running\n"); - * } else { - * printf("%s is found", zone->name); - * } - * ... - * \endcode - * + * \retval vsm_zone_h Successful + * \retval NULL Failed to lookup + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. + * \see vsm_create_context(), vsm_enter_eventloop() */ -API struct vsm_zone *vsm_lookup_zone_by_name(struct vsm_context *ctx, const char *path); +API vsm_zone_h vsm_lookup_zone_by_name(vsm_context_h ctx, const char *name); /** * @brief Find zone instance associated with the process id - * - * \par Synopsis: - * \code - * #include - * - * struct zone * vsm_lookup_zone_by_pid(struct vsm_context *ctx, pid_t pid) - * \endcode - * * \par Description: * The function vsm_lookup_zone_by_pid() looks for the zone instance associated with the given pid. - * * \param[in] ctx vsm context * \param[in] pid Process id - * * \return Zone instance on success, or NULL on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_lookup_zone_by_name(), vsm_lookup_zone_by_terminal(), vsm_iterate_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_zone *zone; - * struct vsm_context *ctx; - * ... - * zone = vsm_lookup_zone_by_pid(ctx, 1208); - * if(zone == NULL) - * { - * printf("Not found\n"); - * } else { - * printf("%s is found", zone->name); - * } - * ... - * \endcode - * + * \retval vsm_zone_h Successful + * \retval NULL Failed to lookup + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. + * \see vsm_create_context(), vsm_enter_eventloop() */ -API struct vsm_zone *vsm_lookup_zone_by_pid(struct vsm_context *ctx, pid_t pid); +API vsm_zone_h vsm_lookup_zone_by_pid(vsm_context_h ctx, pid_t pid); /** - * @brief Find zone instance associated with the given terminal - * - * \par Synopsis: - * \code - * #include - * - * struct zone *vsm_lookup_zone_by_terminal_id(struct vsm_context *ctx, int terminal) - * \endcode - * - * \par Purpose: - * The function vsm_lookup_zone_by_terminal_id() search zone instance which is associated with the given terminal. - * In general, the terminal id would be tty number. - * + * @brief Register zone status changed callback + * \par Description: + * Register a callback function for zone status change. * \param[in] ctx vsm context - * \param[in] terminal Terminal id to search - * - * \return Zone instance on success, or NULL on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_start_context(), vsm_shutdown_context(), vsm_lookup_zone_by_name(), vsm_lookup_zone_by_pid(), vsm_iterate_zone() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_zone *zone; - * struct vsm_context *ctx; - * ... - * zone = vsm_lookup_zone_by_terminal_id(ctx, 2); - * if(zone == NULL) - * { - * printf("Not found\n"); - * } else { - * printf("%s is found", zone->name); - * } - * ... - * \endcode - * + * \param[in] callback Callback function to invoke when zone satte event occurs + * \return Callback handle on success, or negative error code on error. + * \retval handle nonnegative handle id for callback. + * \retval #VSM_ERROR_OUT_OF_MEMORY Callback hanlder allocation failed. + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or callback function does not called. + * \see vsm_create_context(), vsm_enter_eventloop(), vsm_del_state_changed_callback() */ -API struct vsm_zone *vsm_lookup_zone_by_terminal_id(struct vsm_context *ctx, int terminal); +API int vsm_add_state_changed_callback(vsm_context_h ctx, vsm_zone_state_changed_cb callback, void *user_data); /** - * @brief Definition for zone event callback function. - */ -typedef int (*vsm_zone_state_cb)(struct vsm_zone *zone, vsm_zone_state_t state, vsm_zone_event_t event, void *user_data); + * @brief Deregister zone status changed callback handler + * \par Description: + * Remove an event callback from the zone control context. + * \param[in] ctx vsm context + * \param[in] handle Callback Id to remove + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_NO_OBJECT Failed to lookup callback handler +*/ +API int vsm_del_state_changed_callback(vsm_context_h ctx, int handle); /** - * @brief Register a callback to be notified when zone state has changed - * - * \par Synopsis: - * \code - * #include - * - * int vsm_add_state_callback(struct vsm_context *ctx, zone_state_cb callback, void *user_data) - * \endcode - * + * @brief Register zone event callback * \par Description: - * Register a callback to be notified when zone state event occurs. - * + * Register a callback function for zone event. * \param[in] ctx vsm context - * \param[in] callback Callback function to invoke when zone satte event occurs - * - * \return Callback ID on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_del_state_callback(), vsm_enter_eventloop(), vsm_get_poll_fd() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_context *ctx; - * ... - * void callback(struct zone *zone, vsm_zone_state_t state, vsm_zone_event_t event, void *user_data) - * { - * if (state == VSM_ZONE_STATE_RUNNING) - * printf("Domain(%s) is running\n", zone->name); - * } - * ... - * retval = vsm_add_state_callback(ctx, callback, NULL); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * \param[in] callback callback function to invoke when zone event occurs + * \return positive callback handle on success, or negative error code on error. + * \retval handle nonnegative handle id for callback. + * \retval #VSM_ERROR_OUT_OF_MEMORY Callback hanlder allocation failed. + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or callback function does not called. + * \see vsm_create_context(), vsm_enter_eventloop(), vsm_del_state_changed_callback() */ -API int vsm_add_state_callback(struct vsm_context *ctx, vsm_zone_state_cb callback, void *user_data); +API int vsm_add_event_callback(vsm_context_h ctx, vsm_zone_event_cb callback, void *user_data); + /** - * @brief Remove zone event callback - * - * \par Synopsis - * \code - * #include - * - * \endcode - * + * @brief Deregister zone event callback handler * \par Description: * Remove an event callback from the zone control context. - * - * \par Important notes: - * None - * * \param[in] ctx vsm context - * \param[in] handle Callback Id to remove - * + * \param[in] handle callback handle to remove * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_create_context(), vsm_cleanup_context(), vsm_add_state_callback() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int id; - * struct vsm_context *ctx; - * ... - * void callback(struct zone *zone, vsm_zone_state_t state, vsm_zone_event_t event, void *user_data) - * { - * if (state == VSM_ZONE_STATE_RUNNING) - * printf("Domain(%s) is running\n", zone->name); - * } - * ... - * id = vsm_add_state_callback(ctx, callback, NULL); - * ... - * vsm_del_state_callback(ctx, id); - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_NO_OBJECT Failed to lookup callback handler */ -API int vsm_del_state_callback(struct vsm_context *ctx, int handle); +API int vsm_del_event_callback(vsm_context_h ctx, int handle); -/// @} +/** + * @brief Zone attach parameters + * Arguments are same as linux system-call execv() + */ +typedef struct vsm_attach_command_s { + char * exec; /**< Program binary path */ + char ** argv; /**< An array of argument pointers to null-terminated strings include program path */ +} vsm_attach_command_s; /** - * @addtogroup DEVICE_CONTROL - * @{ + * @brief Zone attach option + */ +typedef struct vsm_attach_options_s { + uid_t uid; /**< requested uid*/ + gid_t gid; /**< requested gid*/ + int env_num; /**< requested environ count */ + char **extra_env; /**< requested environ string pointer array. */ +} vsm_attach_options_s; + +/** + * @brief default attach options + * \n + * uid = root\n + * gid = root\n + * env = no extra env\n + */ + +#define VSM_ATTACH_OPT_DEFAULT { (uid_t)0, (gid_t)0, 0, NULL } + +/** + * @brief Launch a process in a running zone. + * \par Description: + * Execute specific command inside the zone with given arguments and environment + * \param[in] zone vsm_zone_h + * \param[in] command vsm attach command + * \param[in] opt vsm attach options (can be NULL), using VSM_ATTACH_OPT_DEFAULT + * \param[out] attached process pid + * \return On sucess 0, otherwise, a negative integer error code on error + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_NO_OBJECT Target zone is not running state + * \retval #VSM_ERROR_GENERIC IPC failed + */ +API int vsm_attach_zone(vsm_context_h ctx, const char * zone_name, vsm_attach_command_s * command, vsm_attach_options_s * opt, pid_t *attached_process); + +/** + * @brief Launch a process in a running zone and wait till child process exited. + * \par Description: + * Execute specific command inside the zone with given arguments and environment + * \param[in] zone vsm_zone_h + * \param[in] command vsm attach command + * \param[in] opt vsm attach options (can be NULL), using VSM_ATTACH_OPT_DEFAULT + * \return On sucess waitpid exit code or attached process, or a negative error code + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_NO_OBJECT Target zone is not running state + * \retval #VSM_ERROR_GENERIC IPC failed or waitpid error + */ +API int vsm_attach_zone_wait(vsm_context_h ctx, const char * zone_name, vsm_attach_command_s * command, vsm_attach_options_s * opt); + +/** + * @brief Get name string of zone. + * \par Description: + * Get name string of zone. + * \param[in] zone vsm zone handle + * \return a pointer of zone name string on sucess or NULL on fail. + * \retval name string value of zone. + * \retval NULL vsm_zone_h is invalid. + * \warning Do not modify or free returned pointer memroy. + * This memory will be cleanup by vsm_cleanup context() */ +API const char * vsm_get_zone_name(vsm_zone_h zone); /** - * @brief Grant device to zone - * - * \par Synopsys: - * \code - * #include - * - * int vsm_grant_device(struct vsm_zone *zone, const char *name, uint32_t flags) - * \endcode - * + * @brief Get zone root ablsolute path on host side. * \par Description: - * The function vsm_grant_device() permits the zone using the device corresponding to the given name. - * - * \param[in] zone Zone - * \param[in] name Path of device to grant - * \param[in] flags O_RDWR, O_WRONLY, O_RDONLY - * - * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre None - * - * \post None - * - * \see vsm_revoke_device() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_zone *zone; - * ... - * retval = vsm_grant_device(zone, "/dev/dri/card0", O_RDWR); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * Get rootpath string of zone. + * \param[in] zone vsm zone handle + * \return a pointer of zone rootpath string on sucess or NULL on fail. + * \retval rootpath string value of zone. + * \retval NULL vsm_zone_h is invalid. + * \warning Do not modify or free returned memroy. + * This memory will be cleanup by vsm_cleanup context() */ -API int vsm_grant_device(struct vsm_zone *dom, const char *name, uint32_t flags); +API const char * vsm_get_zone_rootpath(vsm_zone_h zone); + /** - * @brief Revoke device from the zone - * - * \par Synopsis: - * \code - * #include - * - * int vsm_revoke_device(struct vsm_zone *zone, const char *name) - * \endcode - * + * @brief Get type of running zone. * \par Description: - * - * \param[in] zone Zone - * \param[in] name Host-side path of device to revoke - * - * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_grant_device() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_zone *zone; - * ... - * retval = vsm_revoke_device(dom, "/dev/samsung_sdb"); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * + * Get type string of zone. This value is defined in template file when using vsm_create_zone() + * \param[in] zone vsm zone handle + * \return a pointer of zone path string on sucess or NULL on fail. + * \retval rootpath string value of zone. + * \retval NULL vsm_zone_h is invalid. + * \see vsm_create_zone() + * \warning Do not modify or free returned memroy. + * This memory will be cleanup by vsm_cleanup context() +*/ +API const char * vsm_get_zone_type(vsm_zone_h zone); + +/** + * @brief Check zone handle, a host or a normal zone by zone handle. + * \param[in] zone vsm zone handle + * \return positive integer on host case, or 0 on normal zone. + * \retval positive target zone is host zone. + * \retval NULL target zone is NOT host. +*/ +API int vsm_is_host_zone(vsm_zone_h zone); + +/** + * @brief get zone state. + * \par Description: + * Get zone state value by zone handle. + * \param[in] zone vsm zone handle + * \return vsm_zone_state_t value, or negative value. + * \retval state vsm_zone_state_t value of zone + * \retval #VSM_ERROR_INVALID vsm_zone_h is invalid +*/ + +API vsm_zone_state_t vsm_get_zone_state(vsm_zone_h zone); + +/** + * @brief get zone id by handle. + * \par Description: + * Get zone id value by zone handle. + * \param[in] zone vsm zone handle + * \return interger id value of zone or negative error. + * \retval id nonnegative interger value. + * \retval #VSM_ERROR_INVALID vsm_zone_h is invalid + * \remarks id '0' is reserved for host. +*/ +API int vsm_get_zone_id(vsm_zone_h zone); + + +/** + * @brief Set userdata pointer value in vsm_zone_h. + * \par Description: + * Get zone id value by zone handle. + * \param[in] zone vsm zone handle + * \return On success 0, or negative error. + * \retval #VSM_ERROR_NONE Successful. + * \retval #VSM_ERROR_INVALID vsm_zone_h is invalid + * \warning This userdata have to be free before vsm_cleanup_context() or VSM_ZONE_STATE_STOPPED callback handler +*/ +API int vsm_set_userdata(vsm_zone_h zone, void * userdata); + +/** + * @brief Set userdata pointer value in vsm_zone_h. + * \par Description: + * Get zone id value by zone handle. + * \param[in] zone vsm zone handle + * \return On success pointer of userdata, or NULL pointer + * \retval userdata pointer of userdata. + * \retval NULL invalid vsm_zone_h. + * \remark initial value is pointer of self vsm_zone_h */ -API int vsm_revoke_device(struct vsm_zone *dom, const char *name); +API void * vsm_get_userdata(vsm_zone_h zone); + +/** + * @brief join current process into zone. + * \par Synopsys: + * Change self peer credential to target zone + * \param[in] vsm_zone_h zone + * \return before vsm_zone on success, or NULL on error. + * \retval vsm_zone_h before zone handle, If caller process running in host, then host handle returned. + * \retval NULL invalid zone handle. + * \pre parameter vsm zone must be lookup by vsm lookup APIs + * \post After finish target zone procedure, must join again before zone by same API. + * \warning This function is not thread-safe. \n + * All requests of threads in same process are considered target zone request to other host processes. + */ +API vsm_zone_h vsm_join_zone(vsm_zone_h zone); + +/** + * @brief get canonical file path based on current zone. + * \par Description: + * get canonical file path based on current zone. + * \param[in] input_path requested zone path + * \param[out] output_path string pointer for canonicalized output path + * \return int positive string length of output_path, or negative error code on error. + * \retval #VSM_ERROR_INVALID Invalid arguments. + * \retval #VSM_ERROR_GENERIC gethostname() is failed. + * \post Out buffer(*output_path) have to be freed by caller after use. + * \remarks This API can call inside zone without vsm_context_h + * It means this API can call library side for apps. + */ +API int vsm_canonicalize_path(const char *input_path, char **output_path); + +/** + * @brief Check current environment, a host or virtualized zone. + * \par Description: + * Check current caller process environment. + * \return positive integer on running in zone, or 0 on running in host. + * \retval NULL Current process running in host. + * \remarks This API can call inside zone without vsm_context_h + * It means this API can call library side for apps. + */ +API int vsm_is_virtualized(void); + +/** + * @brief Check equivalence between caller and target pid. + * \par Description: + * Check API caller process and target pid running in same zone. + * \retval NULL target process is running in another zone. + * \retval 1 target process is running in same zone. + * \retval -1 failed to check target process. + * \remarks This API can check real zone of target pid. + Real zone is not changed by even join API. + */ +API int vsm_is_equivalent_zone(vsm_context_h ctx, pid_t pid); + +/** + * @brief Translate zone pid to host pid. + * \par Description: + * This API would translate zone namespace pid to host namespace pid. + * \param[in] zone the zone of target process + * \param[in] pid target process id of zone namespace + * \return positive pid or negative error code. + * \retval pid translated host pid of zone process. + * \retval #VSM_ERROR_NO_OBJECT No such process in a target zone. + * \retval #VSM_ERROR_NOT_PERMITTED Permission denied to get target pid info. + * \retval #VSM_ERROR_NOT_SUPPORTED Kernel config is not enabled about pid namespace. + * \retval #VSM_ERROR_INVALID Arguments is invalid. + * \retval #VSM_ERROR_IO Failed to get process info. + * \retval #VSM_ERROR_GENERIC Failed to matching zone pid to host pid. + */ +API int vsm_get_host_pid(vsm_zone_h zone, pid_t pid); + /// @} /** - * @addtogroup NETWORK_CONTROL + * @addtogroup NETWORK Vasum Network * @{ */ @@ -1236,410 +699,251 @@ API int vsm_revoke_device(struct vsm_zone *dom, const char *name); * @brief Types of virtual network interfaces */ typedef enum { - ///Virtual Ethernet(veth), this type device will be attached to host-side network bridge - VSM_NETDEV_VETH, - ///Physical device - VSM_NETDEV_PHYS, - ///Mac VLAN, this type isn't implemented yet - VSM_NETDEV_MACVLAN + VSM_NETDEV_VETH, /**< Virtual Ethernet(veth), this type device will be attached to host-side network bridge */ + VSM_NETDEV_PHYS, /**< Physical device */ + VSM_NETDEV_MACVLAN /**< Mac VLAN, this type isn't implemented yet */ } vsm_netdev_type_t; +typedef enum { + VSM_NETDEV_ADDR_IPV4, /**< IPV4 Address family */ + VSM_NETDEV_ADDR_IPV6 /**< IPV6 Address family */ +} vsm_netdev_addr_t; + /** * @brief Network device information */ -struct vsm_netdev { - /// Domain - struct vsm_zone *zone; - /// Device name - char *name; - /// Type - vsm_netdev_type_t type; +typedef struct vsm_netdev *vsm_netdev_h; - ///List head - struct adt_list list; -}; +/** + * @brief Definition for zone network devince iteration callback function. + */ +typedef void (*vsm_zone_netdev_iter)(struct vsm_netdev *, void *user_data); /** * @brief Create a new network device and assisgn it to zone - * - * \par Synopsis: - * \code - * #include - * - * struct vsm_netdev *vsm_create_netdev(struct vsm_zone *zone, vsm_netdev_type_t type, const char *target, const char *netdev) - * \endcode - * * \par Description: * This function creates net netdev instance and assign it to the given zone. - * * \param[in] zone Zone * \param[in] type Type of network device to be create * \param[in] target * - If type is veth, this will be bridge name to attach. * - If type is phys, this will be ignored. * \param[in] netdev Name of network device to be create - * * \return Network devce on success, or NULL on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * + * \retval vsm_netdev_h New net device handle + * \retval NULL Failed to create netdev * \see vsm_create_netdev() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int retval; - * struct vsm_netdev *netdev; - * ... - * netdev = vsm_create_netdev(zone, VSM_NETDEV_VETH, "virbr0", "vethKnox"); - * if(retval < 0) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * - * Macvlan isn't implemented yet. -*/ -API struct vsm_netdev *vsm_create_netdev(struct vsm_zone *zone, vsm_netdev_type_t type, const char *target, const char *netdev); + * \par Known Issues: + * Macvlan is not implemented yet. + */ +API vsm_netdev_h vsm_create_netdev(vsm_zone_h zone, vsm_netdev_type_t type, const char *target, const char *netdev); + /** - * @brief Removes a network device from zone control context - * - * \par Synopsis: - * \code - * #include - * - * int vsm_destroy_netdev(struct vsm_zone *zone, struct vsm_netdev *netdev) - * \endcode - * + * @brief Removes a network device from zone * \par Description: * This function remove the given netdev instance from the zone control context. - * - * \param[in] zone zone * \param[in] netdev network device to be removed - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server * \see vsm_destroy_netdev() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_zone *zone; - * struct vsm_netdev *netdev; - * ... - * netdev = vsm_create_netdev(zone, VSM_NETDEV_VETH, "virbr0", "vethKnox"); - * if(netdev == NULL) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * vsm_destroy_netdev(zone, netdev); - * ... - * \endcode - * -*/ -API int vsm_destroy_netdev(struct vsm_zone *zone, struct vsm_netdev *netdev); + */ +API int vsm_destroy_netdev(vsm_netdev_h netdev); /** * @brief Iterates network devices found in the zone vsm context and executes callback() on each interface. - * - * \par Synopsis: - * \code - * #include - * - * int vsm_iterate_netdev(struct vsm_zone *zone, void (*callback)(struct vsm_netdev *, void *user_data), void *user_data) - * \endcode - * * \par Description: * vsm_destroy_netdev() scans all network interfaces which are registered in the vsm context, and calls callback() on each entry. - * * \param[in] zone Zone * \param[in] callback Function to be executed in iteration, which can be NULL * \param[in] user_data Parameter to be delivered to callback function - * * \return 0 on success, or negative integer error code on error. - * - * \par Known issues/bugs: - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server * \see vsm_create_netdev(), vsm_destroy_netdev() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct zone *zone; - * ... - * void callback(struct vsm_neatdev *netdev, void *user_data) - * { - * printf("Network device : %s\n", netdev->name); - * } - * ... - * netdev = vsm_iterate_netdev(zone, callback, NULL); - * if(netdev == NULL) - * { - * printf("Error has occurred\n"); - * exit(0); - * } - * ... - * \endcode - * -*/ -API int vsm_iterate_netdev(struct vsm_zone *zone, void (*callback)(struct vsm_netdev *, void *user_data), void *user_data); + */ +API int vsm_iterate_netdev(vsm_zone_h zone, vsm_zone_netdev_iter callback, void *user_data); /** * @brief Find a network device corresponding to the name - * - * \par Synopsis: - * \code - * #include - * - * struct zone_netdev *vsm_lookup_netdev_by_name(struct vsm_zone *zone, const char *name) - * \endcode - * * \par Description: - * The function vsm_lookup_netdev_by_name() looks for a network interface corresponding to the given name. - * - * \param[in] zone Zone + * The function vsm_lookup_netdev_by_name() looks for a network interface. * \param[in] name Network device name to search - * * \return Network device on success, or NULL on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_iterate_netdev() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * struct vsm_zone *zone; - * struct vsm_netdev *netdev; - * ... - * netdev = vsm_lookup_netdev(zone, "vethKnox"); - * if(netdev == NULL) - * { - * printf("Network device isn't exist\n"); - * } else { - * printf("There is %s in %s", netdev->name); - * } - * ... - * \endcode - * + * \retval vsm_netdev_h Target net device handle + * \retval NULL Failed to lookup netdev + */ + +API vsm_netdev_h vsm_lookup_netdev_by_name(vsm_zone_h zone, const char *name); + +/** + * @brief Turn up a network device in the zone + * \par Description: + * This function turns up the given netdev instance in the zone. + * \param[in] netdev network device to be removed + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_down_netdev() + */ +API int vsm_up_netdev(vsm_netdev_h netdev); + +/** + * @brief Turn down a network device in the zone + * \par Description: + * This function turns down the given netdev instance in the zone. + * \param[in] netdev network device to be removed + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_down_netdev() + */ +API int vsm_down_netdev(vsm_netdev_h netdev); + +/** + * @brief Get ip address from a network device + * \par Description: + * The function vsm_get_ip_addr_netdev() get ip address from a network interface + * \param[in] netdev Network device to get address + * \param[in] family Address family + * \param[out] addr Buffer to get address from a network device + * \param[out] size Size of buffer + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_OVERFLOW Parameter overflow + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_set_ip_addr_netdev() + */ +API int vsm_get_ip_addr_netdev(vsm_netdev_h netdev, vsm_netdev_addr_t addr_family, char *addr, int size); + +/** + * @brief Set ip address to a network device + * \par Description: + * The function vsm_set_ip_addr_netdev() set ipv4 address to a network interface + * \param[in] netdev Network device to set address + * \param[in] family Address family + * \param[in] addr IP address string to be set + * \param[in] prefix prefix ( ex> 192.168.122.1/24, 24 is prefix ) + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_OVERFLOW Parameter overflow + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_get_ip_addr_netdev() + */ +API int vsm_set_ip_addr_netdev(vsm_netdev_h netdev, vsm_netdev_addr_t addr_family, const char *addr, int prefix); + + + +/// @} + +/** + * @addtogroup DEVICE Vasum Device + * @{ */ -API struct vsm_netdev *vsm_lookup_netdev_by_name(struct vsm_zone *zone, const char *name); +/** + * @brief Grant device to zone + * \par Description: + * Request permission device file node to target zone. + * \param[in] zone vsm_zone_h + * \param[in] name device node path + * \param[in] flags requested permission O_RDWR, O_WRONLY, O_RDONLY + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_NOT_PERMITTED Change cgroup is not permitted + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_revoke_device() + */ +API int vsm_grant_device(vsm_zone_h zone, const char *path, uint32_t flags); + +/** + * @brief Revoke device from the zone + * \par Description: + * Revoke device node permissions from target zone. + * \param[in] zone vsm_zone_h + * \param[in] name device node path + * \return 0 on success, or negative integer error code on error. + * \retval #VSM_ERROR_NONE Successful + * \retval #VSM_ERROR_INVALID Invalid arguments + * \retval #VSM_ERROR_NOT_PERMITTED Change cgroup is not permitted + * \retval #VSM_ERROR_GENERIC Failed to interact with vasum server + * \see vsm_grant_device() + */ +API int vsm_revoke_device(vsm_zone_h zone, const char *path); /// @} + /** - * @addtogroup RESOURCE_PROVISIONING + * @addtogroup RESOURCE Vasum Resource * @{ */ +/** + * @brief Definition for declare file type. +*/ typedef enum { - VSM_FSO_TYPE_DIR, - VSM_FSO_TYPE_REG, - VSM_FSO_TYPE_FIFO, - VSM_FSO_TYPE_SOCK, - VSM_FSO_TYPE_DEV, + VSM_FSO_TYPE_DIR, /**< Directoy type */ + VSM_FSO_TYPE_REG, /**< Regular file type */ + VSM_FSO_TYPE_FIFO, /**< Fifo file type */ + VSM_FSO_TYPE_SOCK, /**< Socket file type */ + VSM_FSO_TYPE_DEV, /**< Device node type */ VSM_FSO_MAX_TYPE = VSM_FSO_TYPE_DEV } vsm_fso_type_t; +/** + * @brief Declare file mode. +*/ + typedef mode_t vsm_mode_t; /** - * @brief Register file system object to vsm context. - * - * \par Synopsis: - * \code - * #include - * - * int vsm_declare_file(struct vsm_context *ctx, vsm_fso_type_t ftype, const char *path, int flags, vsm_mode_t mode) - * \endcode - * + * @brief Declare specific file object to every zone. * \par Description: - * Register file system object to vsm context. Once the object is registered to the context, it will be populated when - * any zone is started.\n - * + * Declare host file system to every running zone. + * In case of host target file exist, create new file in running zone. or create a new file in running zone. + * And add hook info in vsm-resource-provier for automatically link host target file to starting zone. + * Smack labels are also copied as same as host labels. * \param[in] ctx vsm context * \param[in] type Type of file system object * \param[in] path Path for the file system object * \param[in] flags Flasg * \param[in] mode mode - * - * \return zero on success, or negative value on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_declare_mount(), vsm_declare_link() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int ret; - * struct vsm_zone *zone; - * ... - * ret = vsm_declare_file(zone, VSM_FSO_TYPE_DIR, "/vethKnox", 0666); - * if(ret < 0) - * { - * printf("Failed to declare file system object\n"); - * } - * - * ... - * \endcode - * -*/ - -API int vsm_declare_file(struct vsm_context *ctx, vsm_fso_type_t ftype, const char *path, int flags, vsm_mode_t mode); - -/** - * @brief Register file system object to vsm context. - * - * \par Synopsis: - * \code - * #include - * - * int vsm_declare_mount(struct vsm_context *ctx, const char *source, const char *target, const char *fstype, unsigned long flags, const void *data) - * \endcode - * - * \par Description: - * Register mount to vsm context. Once the mount is registered to the context, it will be populated when - * any zone is started.\n - * - * \param[in] ctx vsm context - * \param[in] source filesystem source - * \param[in] target mount point - * \param[in] fstype filesystem type - * \param[in] flags mount options - * \param[in] data filesystem specific data - * * \return zero on success, or negative value on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_decalre_file(), vsm_declare_link() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int ret; - * struct vsm_zone *zone; - * ... - * ret = vsm_declare_file(zone, "/dev/block0", "/mnt/target", "ext4", 0, NULL); - * if(ret < 0) - * { - * printf("Failed to declare file system object\n"); - * } - * - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE successful. + * \retval #VSM_ERROR_INVALID Invalid file type or path. + * \retval #VSM_ERROR_GENERIC Error in vasum server side. + * \retval #VSM_ERROR_NO_OBJECT Source file is not exist in host filesystem */ - -API int vsm_declare_mount(struct vsm_context *ctx, const char *source, const char *target, const char *fstype, unsigned long flags, const void *data); +API int vsm_declare_file(vsm_context_h ctx, vsm_fso_type_t ftype, const char *path, int flags, vsm_mode_t mode); /** - * @brief Declare hardlink to vsm context. - * - * \par Synopsis: - * \code - * #include - * - * int vsm_declare_link(struct vsm_context *ctx, const char *source, const char *target) - * \endcode - * + * @brief Declare hardlink to every zone. * \par Description: - * Declare hardlink to the vsm context.\n - * In general, this function is used to create shared socket. - * + * Declare hardlink to host file to every running zone. + * And add hook info in vsm-resource-provier for automatically link host target file to starting zone. + * In general, this function is used to share file host and all running zones. + * Smack labels are also copied as same as host labels. * \param[in] ctx vsm context * \param[in] source source * \param[in] target target - * * \return zero on success, or negative value on error. - * - * \par Known issues/bugs: - * None - * - * \pre vsm context must be initialized by vsm_create_context() - * - * \post None - * - * \see vsm_declare_file(), vsm_declare_mount() - * - * \remarks None - * - * \par Sample code: - * \code - * #include - * ... - * int ret; - * struct vsm_zone *zone; - * ... - * ret = vsm_declare_link(zone, "/tmp/sock", "/tmp/sock"); - * if(ret < 0) - * { - * printf("Failed to declare file system object\n"); - * } - * - * ... - * \endcode - * + * \retval #VSM_ERROR_NONE successful + * \retval #VSM_ERROR_INVALID Invalid provision type to db. + * \retval #VSM_ERROR_GENERIC Error in vasum server side. + * \retval #VSM_ERROR_NO_OBJECT Source file is not exist in host filesystem */ - -API int vsm_declare_link(struct vsm_context *ctx, const char *source, const char *target); +API int vsm_declare_link(vsm_context_h ctx , const char *source, const char *target); /// @} + #ifdef __cplusplus } #endif diff --git a/client/sc_adt.h b/client/vasum_list.h similarity index 81% rename from client/sc_adt.h rename to client/vasum_list.h index ec4c498..185287b 100644 --- a/client/sc_adt.h +++ b/client/vasum_list.h @@ -1,11 +1,22 @@ -#ifndef __SCX_ADT_LIST_H__ -#define __SCX_ADT_LIST_H__ +#ifndef __VASUM_ADT_LIST_H__ +#define __VASUM_ADT_LIST_H__ struct adt_list { struct adt_list* next; struct adt_list* prev; }; +#undef offsetof +#ifdef __compiler_offsetof +#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) +#else +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +#endif + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + #define adt_iterate_list(__iterator, __list) \ for (__iterator = (__list)->next; \ __iterator != __list; \ @@ -88,4 +99,4 @@ static inline struct adt_list *adt_find_list(struct adt_list* head, return NULL; } -#endif /*!__ADT_LIST_H__*/ +#endif /*!__VASUM_ADT_LIST_H__*/ diff --git a/client/wrapper-compat.cpp b/client/wrapper-compat.cpp new file mode 100644 index 0000000..dcd9e38 --- /dev/null +++ b/client/wrapper-compat.cpp @@ -0,0 +1,1580 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Krzysztof Dynowski + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + + +/** + * @file + * @author Krzysztof Dynowski (k.dynowski@samsung.com) + * @brief Vasum old API compatibility functions + */ + +#include "wrapper-compat.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { + +// find_container_by_pid +char *find_container_by_pid(pid_t /*pid*/) { + return NULL; +} +// get_domain_pid +pid_t get_domain_pid(const char * /*name*/, const char * /*target*/) { + return -1; +} + +// mainloop_add_watch +int mainloop_add_watch(struct mainloop * /*mainloop*/, int /*fd*/, mainloop_event /*event*/, mainloop_callback /*callback*/, void * /*data*/) { + return 0; +} +// mainloop_cleanup +int mainloop_cleanup(struct mainloop * /*mainloop*/) { + return 0; +} +// mainloop_create +struct mainloop *mainloop_create(void) { + struct mainloop *mainloop = (struct mainloop *)malloc(sizeof(struct mainloop)); + mainloop->epfd = -1; // epoll_create(2); + pthread_mutex_init(&mainloop->ml_mutex, NULL); + pthread_rwlock_init(&mainloop->lock, NULL); + adt_init_list(&mainloop->watches); + return mainloop; +} +// mainloop_dispatch +int mainloop_dispatch(struct mainloop * /*mainloop*/, int /*timeout*/) { + return 0; +} +// mainloop_remove_watch +int mainloop_remove_watch(struct mainloop * /*mainloop*/, int /*fd*/) { + return 0; +} +// mainloop_run +int mainloop_run(struct mainloop * /*mainloop*/, int /*timeout*/) { + return 0; +} +// mxe_alloc_endpoint +struct mxe_endpoint *mxe_alloc_endpoint(struct mxe_engine * /*engine*/, int /*fd*/, mainloop_callback /*callback*/, int /*type*/) { + return NULL; +} +// mxe_broadcast +int mxe_broadcast(struct mxe_engine * /*engine*/, struct mxe_emple * /*emple*/, ...) { + return 0; +} +// mxe_create_client +struct mxe_endpoint *mxe_create_client(struct mxe_engine *engine, const char * /*addr*/) { + struct mxe_endpoint *ep = (struct mxe_endpoint *)malloc(sizeof(struct mxe_endpoint)); + ep->type = 1; //MXE_EPT_SLAVE + ep->fd = -1; //sock_connect(addr); + ep->engine = engine; + pthread_rwlock_init(&ep->queue_lock, NULL); + pthread_mutex_init(&ep->rd_mutex, NULL); + pthread_mutex_init(&ep->wr_mutex, NULL); + adt_init_list(&ep->queue); + adt_init_list(&ep->list); + return ep; +} +// mxe_create_server +struct mxe_endpoint *mxe_create_server(struct mxe_engine * /*engine*/, const char * /*addr*/) { + return NULL; +} +// mxe_emple_factory +struct mxe_emple *mxe_emple_factory(struct mxe_proxy * /*proxy*/) { + return NULL; +} +// mxe_finalize_engine +int mxe_finalize_engine(struct mxe_engine * /*engine*/) { + return 0; +} +// mxe_free_endpoint +int mxe_free_endpoint(struct mxe_endpoint * /*ep*/) { + return 0; +} +// mxe_invoke +int mxe_invoke(struct mxe_endpoint * /*ep*/, struct mxe_emple * /*emple*/, ...) { + return 0; +} +// mxe_lookup_emple +struct mxe_emple *mxe_lookup_emple(struct mxe_endpoint * /*ep*/, int /*signature*/) { + return NULL; +} +// mxe_lookup_proxy +struct mxe_proxy *mxe_lookup_proxy(struct mxe_engine * /*engine*/, int /*id*/) { + return NULL; +} +// mxe_pop_integer +int mxe_pop_integer(struct mxe_message * /*msg*/) { + return 0; +} +// mxe_pop_string +char *mxe_pop_string(struct mxe_message * /*msg*/) { + return NULL; +} +// mxe_prepare_engine +struct mxe_engine *mxe_prepare_engine(struct mainloop *mainloop, void *data) { + struct mxe_engine *engine = (struct mxe_engine *)malloc(sizeof(struct mxe_engine)); + engine->data = data; + engine->mainloop = mainloop; + pthread_rwlock_init(&engine->endpoint_lock, NULL); + adt_init_list(&engine->endpoints); + + return engine; +} +// mxe_push_integer +int mxe_push_integer(struct mxe_message * /*msg*/, int /*value*/) { + return 0; +} +// mxe_push_string +int mxe_push_string(struct mxe_message * /*msg*/, const char * /*str*/) { + return 0; +} +// mxe_register_proxy +int mxe_register_proxy(struct mxe_engine * /*engine*/, struct mxe_proxy * /*proxy*/) { + return 0; +} +// mxe_reply_message (intenal) +int mxe_reply_message(struct mxe_endpoint * /*ep*/, struct mxe_message * /*origin*/, ...) { + return 0; +} +// mxe_reset_payload +void mxe_reset_payload(struct mxe_message * /*msg*/) { +} +// mxe_wait_for_event +int mxe_wait_for_event(struct mxe_endpoint * /*ep*/, struct mxe_emple * /*emple*/) { + return 0; +} +// sock_close_socket (intern) +int sock_close_socket(int /*fd*/) { + return 0; +} +// sock_connect +int sock_connect(const char * /*path*/) { + return 0; +} +// sock_create_socket +int sock_create_socket(const char * /*path*/, int /*type*/, int /*flags*/) { + return 0; +} +// sock_monitor_address +int sock_monitor_address(char * /*buffer*/, int /*len*/, const char * /*lxcpath*/) { + return 0; +} +// sock_recv_fd (intern) +int sock_recv_fd(int /*fd*/, int * /*recvfd*/, void * /*data*/, size_t /*size*/) { + return 0; +} +// sock_send_fd +int sock_send_fd(int /*fd*/, int /*sendfd*/, void * /*data*/, size_t /*size*/) { + return 0; +} +// vasum_log +void vasum_log(int /*type*/, const char * /*tag*/, const char * /*fmt*/ , ...) { +} + +#define MAX_ERROR_MSG 0x1000 +#define BUF_SIZE 4096 + +#define SMACK_LABEL_LEN 8 +#define ERROR(...) do{}while(0) +#define WARN(...) do{}while(0) +#define DEBUG(...) do{}while(0) +#define INFO(...) do{}while(0) + +// lib/utils.c +const char *const fso_type_strtab[] = { + "Directory", + "Regular file", + "FIFO", + "Socket", + "Device node" +}; + +const char *fso_type_to_string(vsm_fso_type_t fso) +{ + if (fso < 0 || fso > VSM_FSO_MAX_TYPE) { + return NULL; + } + + return fso_type_strtab[fso]; +} + +int wait_for_pid_status(pid_t pid) +{ + int status, ret; + + again: + ret = waitpid(pid, &status, 0); + if (ret == -1) { + if (errno == EINTR) { + goto again; + } else { + ERROR("waitpid- pid : %d error : %s", pid, + strerror(errno)); + return -1; + } + } + if (ret != pid) + goto again; + return status; +} + +vsm_fso_type_t fso_string_to_type(char *str) +{ + int len; + int i; + for (i = 0; i <= VSM_FSO_MAX_TYPE; i++) { + len = strlen(fso_type_strtab[i]); + if (strncmp(str, fso_type_strtab[i], len) == 0) + return static_cast(i); + } + + return static_cast(-1); +} + +int mkdir_p(const char *dir, mode_t mode) +{ + const char *tmp = dir; + const char *orig = dir; + char *makeme; + + do { + dir = tmp + strspn(tmp, "/"); + tmp = dir + strcspn(dir, "/"); + makeme = strndup(orig, dir - orig); + if (*makeme) { + if (mkdir(makeme, mode) && errno != EEXIST) { + free(makeme); + return -1; + } + } + free(makeme); + } while (tmp != dir); + + return 0; +} + +int lock_fd(int fd, int wait) +{ + int ret; + struct flock f; + + while (1) { + f.l_type = F_WRLCK; + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; + + if (wait) + ret = fcntl(fd, F_SETLKW, &f); + else + ret = fcntl(fd, F_SETLK, &f); + if (ret != -1) + return 0; + if (errno == EINTR) + continue; + return -1; + } +} + +int unlock_fd(int fd) +{ + struct flock f; + f.l_type = F_UNLCK; + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; + return fcntl(fd, F_SETLKW, &f); +} + +int copy_smacklabel(const char * /*source*/, const char * /*dest*/) +{ + return 0; +} + +int remove_file(char *path) +{ + struct stat path_stat; + DIR *dp; + struct dirent *d; + int status = 0; + + if (lstat(path, &path_stat) < 0) { + if (errno != ENOENT) { + ERROR("Unable to stat : %s"); + return -1; + } + } + + if (S_ISDIR(path_stat.st_mode)) { + if ((dp = opendir(path)) == NULL) { + ERROR("Unable to opendir %s", path); + return -1; + } + + while ((d = readdir(dp)) != NULL) { + char new_path[PATH_MAX]; + if (strcmp(d->d_name, ".") == 0 || + strcmp(d->d_name, "..") == 0) + continue; + + snprintf(new_path, PATH_MAX, "%s/%s", path, d->d_name); + if (remove_file(new_path) < 0) + status = -1; + } + + if (closedir(dp) < 0) { + ERROR("Unable to close dp : %s", path); + return -1; + } + + if (rmdir(path) < 0) { + ERROR("Failed to remove dir : %s, cause: %s", path, + strerror(errno)); + return -1; + } + + } else { + if (unlink(path) < 0) { + ERROR("Unable to remove %s", path); + return -1; + } + } + + return status; +} + +int copy_file(const char *source, const char *dest, int /*flags*/) +{ + int ret; + FILE *sfp, *dfp; + size_t nread, nwritten, size = BUF_SIZE; + char buffer[BUF_SIZE]; + + if ((sfp = fopen(source, "r")) == NULL) { + ERROR("Unable to open source : %s", source); + return -1; + } + + if ((dfp = fopen(dest, "w+")) == NULL) { + ERROR("Unable to open destination : %s", dest); + fclose(sfp); + return -1; + } + + while (1) { + nread = fread(buffer, 1, size, sfp); + + if (nread != size && ferror(sfp)) { + ERROR("Read failed"); + return -1; + } else if (nread == 0) { + break; + } + + nwritten = fwrite(buffer, 1, nread, dfp); + + if (nwritten != nread) { + if (ferror(dfp)) + ERROR("write fail"); + else + ERROR("Unable to write all data"); + return -1; + } + } + + fclose(sfp); + fclose(dfp); + + ret = copy_smacklabel(source, dest); + if (ret != 0) { + ERROR("Unable to setting smack lable"); + return -1; + } + return 0; +} + +int regex_compile(regex_t * r, const char *regex_text) +{ + int status = regcomp(r, regex_text, REG_EXTENDED | REG_NEWLINE); + + if (status != 0) { + char error_message[MAX_ERROR_MSG]; + + regerror(status, r, error_message, MAX_ERROR_MSG); + DEBUG("Regex error compiling '%s': %s\n", + regex_text, error_message); + return 1; + } + + return 0; +} + +int regex_match(regex_t * r, const char *to_match) +{ + const char *p = to_match; + const int n_matches = 10; + regmatch_t m[n_matches]; + + while (1) { + int i = 0; + int nomatch = regexec(r, p, n_matches, m, 0); + + if (nomatch) { + DEBUG("No more matches.\n"); + return nomatch; + } + + for (i = 0; i < n_matches; i++) { + int start; + int finish; + (void)start; + (void)finish; + + if (m[i].rm_so == -1) { + break; + } + + start = m[i].rm_so + (p - to_match); + finish = m[i].rm_eo + (p - to_match); + if (i == 0) { + INFO("$& is "); + } else { + INFO("$%d is ", i); + } + + INFO("'%.*s' (bytes %d:%d)\n", (finish - start), + to_match + start, start, finish); + } + + p += m[0].rm_eo; + } + + return 0; +} + +int get_peer_pid(int fd) +{ + struct ucred cred; + socklen_t cr_len = sizeof(cred); + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cr_len) < 0) { + return -1; + } + return cred.pid; +} + +pid_t gettid(void) +{ + return syscall(__NR_gettid); +} + +int set_smacklabel_fd(int fd, const char *xattr_name, const char *label) +{ + size_t len; + int ret; + + if(fd < 0) + return -1; + + len = strnlen(label, SMACK_LABEL_LEN + 1); + if (len > SMACK_LABEL_LEN) + return -1; + + ret = fsetxattr(fd, xattr_name, label, len+1, 0); + if(ret != 0) { + ERROR("Set Smack lable error : %s", strerror(errno)); + } + return ret; +} + +int set_smacklabel(const char *path, const char *xattr_name, const char *label) +{ + size_t len; + int ret; + + if(path == NULL) + return -1; + + len = strnlen(label, SMACK_LABEL_LEN + 1); + if (len > SMACK_LABEL_LEN) + return -1; + + ret = lsetxattr(path, xattr_name, label, len+1, 0); + if(ret != 0) { + ERROR("Set Smack lable error : %s", strerror(errno)); + } + return ret; +} +char *get_self_smacklabel(void) +{ + int ret; + int fd; + const char *attr_path = "/proc/self/attr/current"; + char buffer[SMACK_LABEL_LEN+1]; + + bzero(buffer, SMACK_LABEL_LEN+1); + + fd = open(attr_path, O_RDONLY); + if( fd < 0) { + return NULL; + } + + ret = read(fd, buffer, SMACK_LABEL_LEN+1); + close(fd); + if (ret < 0) { + return NULL; + } + + if( ret > SMACK_LABEL_LEN) { + //return NULL; + } + buffer[SMACK_LABEL_LEN]=0; + + return strdup(buffer); +} + +int get_self_cpuset(char *name, int buf_sz) +{ + int fd; + int lxc_len, ret; + char cpuset_path[] = "/proc/self/cpuset"; + char current_name[NAME_MAX]; + + fd = open(cpuset_path, O_RDONLY); + if (fd < 0) { + return 0; + } + + ret = read(fd, current_name, NAME_MAX - 1); + if (ret < 0) { + close(fd); + return -1; + } + + current_name[ret - 1] = '\0'; + close(fd); + + lxc_len = sizeof("/lxc"); + if( ret < lxc_len) { + name[0] = '/'; + name[1] = 0; + return 1; + } else { + char *p; + p = current_name + lxc_len; + + while(*p != '\0') { + if(*p == '/') { + *p = '\0'; + break; + } + p++; + } + snprintf(name, buf_sz, "%s", current_name+lxc_len); + } + + return ret - lxc_len; +} + + +char * get_pid_cpuset(int pid) +{ + int fd; + int ret; + char cpuset_path[PATH_MAX]; + char current_name[NAME_MAX]; + + snprintf(cpuset_path, PATH_MAX, "/proc/%d/cpuset", pid); + + ret = access(cpuset_path, F_OK | R_OK); + if( ret != 0 ) + return NULL; + + fd = open(cpuset_path, O_RDONLY); + if (fd < 0) { + return NULL; + } + + ret = read(fd, current_name, NAME_MAX - 1); + if (ret < 0) { + close(fd); + return NULL; + } + + current_name[ret - 1] = 0; + close(fd); + + INFO("cpuset path : %s, value : %s", cpuset_path, current_name); + + return strdup(current_name); +} + +char * read_namespace_link(const char *ns, int pid) +{ + char ns_path[PATH_MAX]; + char buf[NAME_MAX]; + int ret; + + snprintf(ns_path, PATH_MAX, "/proc/%d/ns/%s", pid, ns); + + ret = access(ns_path, F_OK); + if(ret != 0) + return NULL; + + ret = readlink(ns_path, buf, NAME_MAX); + if( ret == -1 ) { + ERROR("Failed to readlink ns file - [%s]", ns_path); + return NULL; + } + + buf[ret] = 0; + + INFO("Read ns link data -pid : %d data : %s", pid, buf); + + return strdup(buf); +} + +// libs/device.c +#define DEV_ITERATE_CONTINUE 0 +int dev_enumerate_nodes(const char *cname, dev_enumerator enumerator, + void *data) +{ + int ret; + FILE *fp;; + char path[PATH_MAX], entry[64]; + + ret = snprintf(path, sizeof(path), + "/sys/fs/cgroup/devices/lxc/%s/devices.list", cname); + + if (ret < 0) { + ERROR("Failed to make pathname"); + return -1; + } + + fp = fopen(path, "r"); + if (fp == NULL) { + ERROR("File open failed: %s(%s)", path, strerror(errno)); + return -1; + } + + while (fgets(entry, sizeof(entry), fp) != NULL) { + int major, minor; + char *next, *ptr = &entry[2]; + + major = strtol(ptr, &next, 10); + minor = strtol(++next, (char **)NULL, 10); + + ret = enumerator(entry[0], major, minor, data); + if (ret != DEV_ITERATE_CONTINUE) + break; + } + + fclose(fp); + + return ret; +} + +int dev_terminal_enumerator(int type, int major, int minor, void *data) +{ + int *dev = (int*)data; + + *dev = minor; + (void)type; + (void)major; + + INFO("Matched device: %c, %d, %d\n", type, major, minor); + + return 1; +} + +// libs/namespace.c +pid_t get_init_pid(const char *name) +{ + char filename[PATH_MAX]; + FILE *fp; + pid_t ret = -1; + + snprintf(filename, sizeof(filename), + "/sys/fs/cgroup/devices/lxc/%s/cgroup.procs", name); + + fp = fopen(filename, "r"); + + if (fp != NULL) { + if (fscanf(fp, "%d", &ret) < 0) { + ERROR("Failed to read %s\n", filename); + ret = -2; + } + fclose(fp); + } else { + INFO("Unable to access %s\n", filename); + ret = errno; + } + + return ret; +} + + +pid_t get_zone_pid(const char *name, const char *target) +{ + char path[PATH_MAX]; + char cmd[PATH_MAX]; + int res = 0, len; + pid_t ret = -1; + FILE *fp; + + char *line = NULL; + size_t line_len; + + snprintf(path, PATH_MAX, + "/sys/fs/cgroup/cpuset/lxc/%s/cgroup.procs", name); + + res = access(path, F_OK | R_OK); + if (res != 0) { + ERROR("Failed to acess zone cgroup file: %s", path); + return -EINVAL; + } + + if (target == NULL) { + ERROR("Failed to lookup cmdline in zone proc"); + return -EINVAL; + } else { + len = strlen(target); + } + + fp = fopen(path, "r"); + if (fp == NULL) { + ERROR("Failed to open zone cgroup"); + return -1; + } + + while (getline(&line, &line_len, fp) != -1) { + int res; + pid_t pid; + FILE *cmdfp; + char cmdpath[PATH_MAX]; + + res = sscanf(line, "%d", &pid); + if (res != 1) { + ERROR("Failed to read %s\n", path); + res = -1; + goto out; + } + + if (pid < 0) + continue; + + snprintf(cmdpath, PATH_MAX, "/proc/%d/cmdline", pid); + + if (access(cmdpath, F_OK | R_OK) != 0) + continue; + + cmdfp = fopen(cmdpath, "r"); + if (cmdfp == NULL) { + ERROR("Unable to access %s\n", cmdpath); + continue; + } + + if (fscanf(cmdfp, "%s", cmd) < 0) { + ERROR("Failed to read cmdline - pid : %d\n", pid); + continue; + } + + fclose(cmdfp); + + if (strncmp(cmd, target, len) == 0) { + ret = pid; + break; + } + } + out: + fclose(fp); + return ret; +} + +int open_ns(pid_t pid, const char *name) +{ + int fd, ret; + char path[PATH_MAX]; + + ret = snprintf(path, PATH_MAX, "/proc/%d/ns/%s", pid, name); + if (ret < 0 || ret >= PATH_MAX) { + ERROR("Failed to namespace - pid %d, ns: %s ", pid, name); + return -EINVAL; + } + + fd = open(path, O_RDONLY); + if (fd < 0) { + ERROR("failed to open %s\n", path); + return -errno; + } + + return fd; +} +/* +void enter_to_ns(pid_t pid, char *name) +{ + int newns; + char *ns[] = { "mnt", "pid", "uts", "ipc", "net" }; + int flags[] = { + CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, CLONE_NEWIPC, + CLONE_NEWNET + }; + int size = sizeof(ns) / sizeof(char *); + int i, idx = size; + + for (i = 0; i < size; i++) { + if (strncmp(ns[i], name, strlen(ns[i])) == 0) { + idx = i; + break; + } + } + + if (idx == size) { + ERROR("Invalid namespace - ns: %s", name); + return; + } + + newns = open_ns(pid, ns[i]); + + if (setns(newns, flags[i])) { + ERROR("failed to setns"); + close(newns); + return; + } + + INFO("Enter namespace - init: %d , ns: %s", pid, name); + + close(newns); + return; +}*/ + +// vasum/libs/vt.c +#include +#include +static int is_console(int fd) +{ + char arg; + + return (isatty(fd) && + (ioctl(fd, KDGKBTYPE, &arg) == 0) && + ((arg == KB_101) || (arg == KB_84))); +} + +static int open_console(const char *path) +{ + int fd; + + fd = open(path, O_RDWR); + if (fd < 0) { + fd = open(path, O_WRONLY); + } + if (fd < 0) { + fd = open(path, O_RDONLY); + } + if (fd < 0) { + return -1; + } + + return fd; +} + +int get_console_fd(const char *path) +{ + int fd; + + if (path) { + fd = open_console(path); + if (fd >= 0) { + return fd; + } + + return -1; + } + + fd = open_console("/dev/tty0"); + if (fd >= 0) { + return fd; + } + + fd = open_console("/dev/console"); + if (fd >= 0) { + return fd; + } + + for (fd = 0; fd < 3; fd++) { + if (is_console(fd)) { + return fd; + } + } + + return -1; +} + +int vt_switch_terminal(int id) +{ + int fd, ret = -1; + + fd = get_console_fd(NULL); + if (fd < 0) { + return -1; + } + + if (ioctl(fd, VT_ACTIVATE, id) < 0) { + goto out; + } + + if (ioctl(fd, VT_WAITACTIVE, id) < 0) { + goto out; + } + + ret = 0; + out: + close(fd); + return ret; +} + +int vt_find_unused_terminal(void) +{ + int fd, nr = -1; + + fd = get_console_fd(NULL); + if (fd < 0) { + perror("Terminal open failed"); + return -1; + } + + if (ioctl(fd, VT_OPENQRY, &nr) < 0) { + perror("VT_OPENQRY failed"); + goto out; + } + + out: + close(fd); + + return nr; +} + +int vt_query_active_terminal(void) +{ + int fd, ret = -1; + struct vt_stat vtstat; + + fd = get_console_fd(NULL); + if (fd < 0) { + return -1; + } + + if (ioctl(fd, VT_GETSTATE, &vtstat) < 0) { + goto out; + } + + ret = vtstat.v_active; + out: + close(fd); + return ret; +} + +// libs/parser.h +struct unit_keyword_callback { + const char *name; + int (*func) (int nargs, char **args); +}; + +struct unit_parser { + struct unit_keyword_callback *kw; +}; + +int parse_stream(const char *name, struct unit_parser *parser); +// libs/parser.c +#define PARSER_MAXARGS 32 + +#define T_EOF 1 +#define T_STATEMENT 2 +#define T_ARGUMENT 3 +#define T_NEWLINE 7 +#define T_NEWBLOCK 8 + +struct parser_context { + struct unit_keyword_callback *kw; +}; + +struct parser_state { + char *ptr; + char *stmt; + int line; + int nexttoken; + void *context; +}; + +static void parser_init_state(struct parser_state *state, char *line) +{ + state->line = 1; + state->ptr = line; + state->nexttoken = 0; + state->stmt = NULL; + state->context = NULL; +} + +static struct unit_keyword_callback *keyword_lookup(struct parser_context *ctx, + const char *kw) +{ + int i; + + for (i = 0; ctx->kw[i].name != NULL; i++) { + if (!strcmp(ctx->kw[i].name, kw)) { + return &ctx->kw[i]; + } + } + + return NULL; +} + +static int tokenize(struct parser_state *state) +{ + char *x = state->ptr; + char *s, *ss; + + if (state->nexttoken) { + int t = state->nexttoken; + state->nexttoken = 0; + return t; + } + + retry: + state->stmt = s = x; + ss = x + 1; + resume: + while (1) { + switch (*x) { + case 0: + state->nexttoken = T_EOF; + goto textdone; + case '\\': + x++; + switch (*x) { + case 0: + goto textdone; + case 'n': + *s++ = '\n'; + break; + case 'r': + *s++ = '\r'; + break; + case 't': + *s++ = '\t'; + break; + case '\\': + *s++ = '\\'; + break; + case '\r': + /* \ -> line continuation */ + if (x[1] != '\n') { + x++; + continue; + } + case '\n': + /* \ -> line continuation */ + state->line++; + x++; + /* eat any extra whitespace */ + while ((*x == ' ') || (*x == '\t')) + x++; + continue; + default: + /* unknown escape -- just copy */ + *s++ = *x++; + } + continue; + case ',': + x++; + goto textdone; + case '=': + x++; + if (ss == x) { + goto retry; + } + goto textdone; + case ' ': + case '\t': + case '\r': + x++; + if (ss == x) { + goto retry; + } + goto textdone; + case '\n': + x++; + if (ss == x) { + state->ptr = x; + return T_NEWLINE; + } + state->nexttoken = T_NEWLINE; + goto textdone; + case '\'': + case '"': + x++; + for (;;) { + switch (*x) { + case 0: + /* unterminated quoted thing */ + state->ptr = x; + return T_EOF; + case '\'': + case '"': + x++; + goto resume; + default: + *s++ = *x++; + } + } + break; + case '[': + x++; + goto resume; + case ']': + x++; + goto resume; + case '#': + while (*x && (*x != '\n')) + x++; + if (*x == '\n') { + state->ptr = x + 1; + return T_NEWLINE; + } else { + state->ptr = x; + return T_EOF; + } + break; + default: + *s++ = *x++; + } + } + + textdone: + state->ptr = x; + *s = 0; + return T_STATEMENT; +} + +static int parse_statement(struct parser_context *ctx, int argc, char **argv, + int (*func) (int argc, char **argv)) +{ + struct parser_state state; + char *args[PARSER_MAXARGS]; + int i, nargs, done, rc; + int ret = 0; + (void)ctx; + + for (i = 0; i < argc; i++) { + done = nargs = 0; + parser_init_state(&state, argv[i]); + + while (!done) { + int token = tokenize(&state); + switch (token) { + case T_EOF: + if (nargs && func) { + rc = func(nargs, args); + if (rc < 0) { + WARN("Key word callback error"); + } + nargs = 0; + } + done = 1; + break; + case T_STATEMENT: + if (nargs < PARSER_MAXARGS) { + args[nargs++] = state.stmt; + } + break; + } + } + } + + return ret; +} + +int parse_stream_core(struct parser_context *ctx, char *s) +{ + struct unit_keyword_callback *kw; + struct parser_state state; + char *args[PARSER_MAXARGS]; + int nargs, rc; + + nargs = 0; + parser_init_state(&state, s); + + for (;;) { + int token = tokenize(&state); + switch (token) { + case T_EOF: + return 0; + case T_NEWLINE: + if (nargs) { + if ((kw = keyword_lookup(ctx, args[0])) != NULL) { + rc = parse_statement(ctx, nargs - 1, + &args[1], + kw->func); + if (rc < 0) { + return -EINVAL; + } + } + + nargs = 0; + } + break; + case T_STATEMENT: + if (nargs < PARSER_MAXARGS) { + args[nargs++] = state.stmt; + } + break; + } + } + + return 0; +} + +/* reads a file, making sure it is terminated with \n \0 */ +static char *open_stream(const char *name, unsigned int *_sz) +{ + int sz, fd; + char *data = NULL; + + fd = open(name, O_RDONLY); + if (fd < 0) + return NULL; + + sz = lseek(fd, 0, SEEK_END); + if (sz < 0) + goto oops; + + if (lseek(fd, 0, SEEK_SET) != 0) + goto oops; + + data = (char *)malloc(sz + 2); + if (data == 0) + goto oops; + + if (read(fd, data, sz) != sz) + goto oops; + + close(fd); + + data[sz] = '\n'; + data[sz + 1] = 0; + if (_sz) + *_sz = sz; + + return data; + + oops: + close(fd); + if (data != 0) + free(data); + + return NULL; +} + +int parse_stream(const char *name, struct unit_parser *parser) +{ + char *stream; + struct parser_context *ctx; + + ctx = (struct parser_context *)malloc(sizeof(struct parser_context)); + if (ctx == NULL) { + return -ENOMEM; + } + + ctx->kw = parser->kw; + + /* File open & return file context */ + stream = open_stream(name, NULL); + if (stream == NULL) { + free(ctx); + return -1; + } + + parse_stream_core(ctx, stream); + + free(stream); + free(ctx); + + return 0; +} + +// dummy-ops +static int dummy_create_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, + const char * /*template*/, int /*flags*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_destroy_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*force*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_start_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_shutdown_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*force*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_lock_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*shutdown*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_unlock_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_set_foreground(vsm_zone_h zone) +{ + if (zone == NULL) + return -VSM_ERROR_INVALID; + + if (zone->parent == zone) { + return VSM_ERROR_NONE; + } + return -VSM_ERROR_NO_OBJECT; +} + +static vsm_zone_h dummy_get_foreground(vsm_context_h ctx) +{ + if (ctx == NULL) { + errno = EINVAL; + return NULL; + } + + return ctx->root_zone; +} + +static int dummy_iterate_zone(vsm_context_h ctx, vsm_zone_iter_cb callback, void *user_data) +{ + if( callback) { + callback(ctx->root_zone, user_data); + } + return VSM_ERROR_NONE; +} + +static vsm_zone_h dummy_lookup_zone_by_name(vsm_context_h ctx, const char *name) +{ + if (strcmp(name, "") != 0) { + errno = ESRCH; + return NULL; + } + + return ctx->root_zone; +} + +static vsm_zone_h dummy_lookup_zone_by_pid(vsm_context_h ctx, pid_t /*pid*/) +{ + if (ctx == NULL) + return NULL; + + return ctx->root_zone; +} + +static int dummy_attach_zone(vsm_context_h ctx, const char *zone_name, + vsm_attach_command_s * command, + vsm_attach_options_s * opts, + pid_t * attached_process) +{ + pid_t pid; + struct vsm_attach_options_s options; + + if (command == NULL || command->exec == NULL || zone_name == NULL) { + ERROR("Invalid arguments"); + ctx->error = VSM_ERROR_INVALID; + return -VSM_ERROR_INVALID; + } + + if (strcmp("", zone_name) != 0) { + ctx->error = VSM_ERROR_INVALID; + return -VSM_ERROR_INVALID; + } + + if (opts == NULL) { + opts = &options; + opts->uid = getuid(); + opts->gid = getgid(); + opts->env_num = 0; + opts->extra_env = NULL; + } + + pid = fork(); + if (pid == 0) { + if (opts->extra_env != NULL) { + while (*opts->extra_env) + putenv(*opts->extra_env++); + } + + if (getuid() == 0 && opts->uid != 0) { + if (setuid(opts->uid) != 0) { + ERROR("Failed to set uid : %d", opts->uid); + } + } else { + WARN("setuid() is not permitted"); + } + + if (getgid() == 0 && opts->gid != 0) { + if (setgid(opts->gid) != 0) { + ERROR("Failed to set gid : %d", opts->gid); + } + } else { + WARN("setgid() is not permitted"); + } + + if (execvp(command->exec, command->argv) < 0) { + ERROR("exevp failed : %s, %s", command->exec, + strerror(errno)); + exit(EXIT_FAILURE); + } + } else { + *attached_process = pid; + } + + return VSM_ERROR_NONE; +} + +static int dummy_attach_zone_wait(vsm_context_h ctx, const char *zone_name, + vsm_attach_command_s * command, + vsm_attach_options_s * opts) +{ + pid_t pid=0; + int ret, status; + + ret = dummy_attach_zone(ctx, zone_name, command, opts, &pid); + if (ret != VSM_ERROR_NONE) { + ERROR("API Failed."); + return ret; + } + + status = wait_for_pid_status(pid); + if (status == -1) { + ctx->error = VSM_ERROR_GENERIC; + return -VSM_ERROR_GENERIC; + } + + INFO("attached process extied : pid - %d, exit code : %d", pid, + WEXITSTATUS(status)); + + return status; +} + +static vsm_zone_h dummy_join_zone(vsm_zone_h zone) +{ + if (zone == NULL) { + errno = EINVAL; + return NULL; + } + if (zone != zone->parent) { + errno = EINVAL; + return NULL; + } + + return zone; +} + +static int dummy_is_equivalent_zone(vsm_context_h /*ctx*/, pid_t /*pid*/) +{ + return 1; +} + +static int dummy_get_host_pid(vsm_zone_h zone, pid_t pid) +{ + if(zone == zone->parent) + return pid; + + return -VSM_ERROR_NO_OBJECT; +} + +static int dummy_grant_device(vsm_zone_h /*zone*/, const char * /*path*/, uint32_t /*flags*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_revoke_device(vsm_zone_h /*zone*/, const char * /*path*/) +{ + return -VSM_ERROR_NOT_SUPPORTED; +} + +static int dummy_declare_file(vsm_context_h /*ctx*/, vsm_fso_type_t /*ftype*/, + const char * /*path*/, int /*flags*/, vsm_mode_t /*mode*/) +{ + return VSM_ERROR_NONE; +} + +static int dummy_declare_link(vsm_context_h /*ctx*/, const char *source, + const char * /*target*/) +{ + int ret; + + ret = access(source, F_OK); + if (ret != 0) + return -VSM_ERROR_NO_OBJECT; + + return VSM_ERROR_NONE; +} + +struct vasum_ops dummy_ops; +static int dummy_ops_init(){ + dummy_ops.create_zone = dummy_create_zone; + dummy_ops.destroy_zone = dummy_destroy_zone; + dummy_ops.start_zone = dummy_start_zone; + dummy_ops.shutdown_zone = dummy_shutdown_zone; + dummy_ops.lock_zone = dummy_lock_zone; + dummy_ops.unlock_zone = dummy_unlock_zone; + dummy_ops.set_foreground = dummy_set_foreground; + dummy_ops.get_foreground = dummy_get_foreground; + dummy_ops.iterate_zone = dummy_iterate_zone; + dummy_ops.lookup_zone_by_name = dummy_lookup_zone_by_name; + dummy_ops.lookup_zone_by_pid = dummy_lookup_zone_by_pid; + dummy_ops.attach_zone = dummy_attach_zone; + dummy_ops.attach_zone_wait = dummy_attach_zone_wait; + dummy_ops.join_zone = dummy_join_zone; + dummy_ops.is_equivalent_zone = dummy_is_equivalent_zone; + dummy_ops.get_host_pid = dummy_get_host_pid; + dummy_ops.grant_device = dummy_grant_device; + dummy_ops.revoke_device = dummy_revoke_device; + dummy_ops.declare_file = dummy_declare_file; + dummy_ops.declare_link = dummy_declare_link; + return 0; +} +int dummy_ops_init_i = dummy_ops_init(); + +} //extern "C" diff --git a/client/wrapper-compat.h b/client/wrapper-compat.h new file mode 100644 index 0000000..90b44fb --- /dev/null +++ b/client/wrapper-compat.h @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Krzysztof Dynowski + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + + +/** + * @file + * @author Krzysztof Dynowski (k.dynowski@samsung.com) + * @brief Vasum old API compatibility functions + */ + +#ifndef __CLIENT_WRAPPER_COMPAT__ +#define __CLIENT_WRAPPER_COMPAT__ + +#include "vasum.h" +#include + +extern "C" { +typedef int (*fp_create_zone) (vsm_context_h ctx, const char *zone_name, + const char *template_name, int flag); +typedef int (*fp_destroy_zone) (vsm_context_h ctx, const char *zone_name, + int force); +typedef int (*fp_start_zone) (vsm_context_h ctx, const char *zone_name); +typedef int (*fp_shutdown_zone) (vsm_context_h ctx, const char *zone_name, + int force); +typedef int (*fp_lock_zone) (vsm_context_h ctx, const char *zone_name, + int shutdown); +typedef int (*fp_unlock_zone) (vsm_context_h ctx, const char *zone_name); +typedef int (*fp_set_foreground) (vsm_zone_h zone); +typedef vsm_zone_h(*fp_get_foreground) (vsm_context_h ctx); +typedef int (*fp_iterate_zone) (vsm_context_h ctx, vsm_zone_iter_cb callback, + void *user_data); +typedef vsm_zone_h(*fp_lookup_zone_by_name) (vsm_context_h ctx, + const char *name); +typedef vsm_zone_h(*fp_lookup_zone_by_pid) (vsm_context_h ctx, pid_t pid); +typedef int (*fp_attach_zone) (vsm_context_h ctx, const char *zone_name, + vsm_attach_command_s * command, + vsm_attach_options_s * opt, + pid_t * attached_process); +typedef int (*fp_attach_zone_wait) (vsm_context_h ctx, const char *zone_name, + vsm_attach_command_s * command, + vsm_attach_options_s * opt); +typedef vsm_zone_h(*fp_join_zone) (vsm_zone_h zone); +typedef int (*fp_is_equivalent_zone) (vsm_context_h ctx, pid_t pid); +typedef int (*fp_get_host_pid) (vsm_zone_h zone, pid_t pid); +typedef int (*fp_grant_device) (vsm_zone_h zone, const char *path, + uint32_t flags); +typedef int (*fp_revoke_device) (vsm_zone_h zone, const char *path); +typedef int (*fp_declare_file) (vsm_context_h ctx, vsm_fso_type_t ftype, + const char *path, int flags, vsm_mode_t mode); +typedef int (*fp_declare_link) (vsm_context_h ctx, const char *source, + const char *target); +struct vasum_ops { + fp_create_zone create_zone; + fp_destroy_zone destroy_zone; + fp_start_zone start_zone; + fp_shutdown_zone shutdown_zone; + fp_lock_zone lock_zone; + fp_unlock_zone unlock_zone; + fp_set_foreground set_foreground; + fp_get_foreground get_foreground; + fp_iterate_zone iterate_zone; + fp_lookup_zone_by_name lookup_zone_by_name; + fp_lookup_zone_by_pid lookup_zone_by_pid; + fp_attach_zone attach_zone; + fp_attach_zone_wait attach_zone_wait; + fp_join_zone join_zone; + fp_get_host_pid get_host_pid; + fp_is_equivalent_zone is_equivalent_zone; + fp_grant_device grant_device; + fp_revoke_device revoke_device; + fp_declare_file declare_file; + fp_declare_link declare_link; +}; + +#define SERVICEPATH "\0/domain-control/service.sock" +struct mainloop { + int epfd; + pthread_mutex_t ml_mutex; + pthread_rwlock_t lock; + struct adt_list watches; +}; +struct mxe_emple; +struct mxe_endpoint; +struct mxe_emple { + int signature; + int refcnt; + void *callback; + void *data; + struct mxe_proxy *proxy; + struct adt_list queue; +}; +struct mxe_engine { + void *data; + struct mainloop *mainloop; + pthread_rwlock_t endpoint_lock; + struct adt_list endpoints; +}; +struct mxe_endpoint { + int fd; + int type; + struct mxe_engine *engine; + pthread_rwlock_t queue_lock; + pthread_mutex_t rd_mutex; + pthread_mutex_t wr_mutex; + struct adt_list queue; + struct adt_list list; +}; + +typedef enum { + ML_EVT_IN = EPOLLIN, + ML_EVT_OUT = EPOLLOUT, + ML_EVT_RDHUP = EPOLLRDHUP, + ML_EVT_ERROR = EPOLLERR, + ML_EVT_HUP = EPOLLHUP, + ML_EVT_ET = EPOLLET +}mainloop_event; + +typedef struct vsm_context { + struct mxe_endpoint *signal_channel; + struct mxe_endpoint *manage_method_channel; + struct mxe_endpoint *unpriv_method_channel; + vsm_error_e error; + pthread_rwlock_t lock; + struct adt_list listeners; + struct vsm_zone *root_zone; + struct vsm_zone *foreground_zone; + struct adt_list sc_listeners; + struct adt_list ev_listeners; + const struct vasum_ops *vsm_ops; +} vsm_context_s; + +typedef struct vsm_zone { + struct vsm_zone *parent; + char *name; + char *type; + int terminal; + vsm_zone_state_t state; + char *rootfs_path; + pthread_rwlock_t lock; + struct adt_list children; + struct adt_list devices; + struct adt_list netdevs; + void *user_data; + struct adt_list list; + struct vsm_context *ctx; + int id; +} vsm_zone_s; + +typedef struct vsm_netdev { + struct vsm_zone *zone; + char *name; + vsm_netdev_type_t type; + struct adt_list list; +} vsm_netdev_s; + + +typedef int (*dev_enumerator)(int type, int major, int minor, void *data); +typedef int (*mainloop_callback)(int fd, mainloop_event event, void *data, struct mainloop *mainloop); + +struct mainloop *mainloop_create(void); +struct mxe_endpoint *mxe_create_client(struct mxe_engine *engine, const char * /*addr*/); +struct mxe_engine *mxe_prepare_engine(struct mainloop *mainloop, void *data); + +int wait_for_pid_status(pid_t pid); + +int vsm_add_state_changed_callback(vsm_context_h /*ctx*/, vsm_zone_state_changed_cb /*callback*/, void * /*user_data*/); +int vsm_del_state_changed_callback(vsm_context_h /*ctx*/, int /*id*/); +const char * vsm_get_zone_rootpath(vsm_zone_h /*zone*/); +const char * vsm_get_zone_name(vsm_zone_h /*zone*/); +int vsm_is_host_zone(vsm_zone_h /*zone*/); +vsm_zone_h vsm_join_zone(vsm_zone_h zone); +int vsm_canonicalize_path(const char *input_path, char **output_path); + +} //extern "C" + +#endif diff --git a/common/epoll/event-poll.cpp b/common/epoll/event-poll.cpp index dfb0385..adca814 100644 --- a/common/epoll/event-poll.cpp +++ b/common/epoll/event-poll.cpp @@ -102,7 +102,6 @@ void EventPoll::removeFD(const int fd) } bool EventPoll::dispatchIteration(const int timeoutMs) - { for (;;) { epoll_event event; diff --git a/packaging/vasum.spec b/packaging/vasum.spec index 64c3662..c2b6eb9 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -10,6 +10,7 @@ %define tty_group tty Name: vasum +Epoch: 1 Version: 0.1.1 Release: 0 Source0: %{name}-%{version}.tar.gz @@ -27,6 +28,7 @@ BuildRequires: pkgconfig(libsystemd-daemon) BuildRequires: pkgconfig(sqlite3) Requires(post): libcap-tools Requires: bridge-utils +Requires: libjson >= 0.10 %description This package provides a daemon used to manage zones - start, stop and switch @@ -115,7 +117,8 @@ fi %package client Summary: Vasum Client Group: Development/Libraries -Requires: vasum = %{version}-%{release} +Requires: vasum = %{epoch}:%{version}-%{release} +Obsoletes: vasum < 1:0 Requires(post): /sbin/ldconfig Requires(postun): /sbin/ldconfig @@ -125,7 +128,9 @@ Library interface to the vasum daemon %files client %manifest packaging/libvasum-client.manifest %defattr(644,root,root,755) -%attr(755,root,root) %{_libdir}/libvasum.so.0.0.1 +%attr(755,root,root) %{_libdir}/libvasum-client.so.0.1.1 +%{_libdir}/libvasum-client.so.0 +%attr(755,root,root) %{_libdir}/libvasum.so.0.1.1 %{_libdir}/libvasum.so.0 %post client -p /sbin/ldconfig @@ -146,6 +151,7 @@ Development package including the header files for the client library %files devel %manifest packaging/vasum.manifest %defattr(644,root,root,755) +%{_libdir}/libvasum-client.so %{_libdir}/libvasum.so %{_includedir}/vasum %{_libdir}/pkgconfig/vasum.pc diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 20ae2f9..65646ea 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -23,6 +23,8 @@ FILE(GLOB_RECURSE project_SRCS *.cpp *.hpp) FILE(GLOB_RECURSE common_SRCS ${COMMON_FOLDER}/*.cpp ${COMMON_FOLDER}/*.hpp) FILE(GLOB server_SRCS ${SERVER_FOLDER}/*.cpp ${SERVER_FOLDER}/*.hpp) FILE(GLOB client_SRCS ${CLIENT_FOLDER}/*.cpp ${CLIENT_FOLDER}/*.h) +FILE(GLOB client_SRCS_rm ${CLIENT_FOLDER}/vasum-wrapper*.cpp) +LIST(REMOVE_ITEM client_SRCS ${client_SRCS_rm}) FILE(GLOB socket_test_SRCS ${SOCKET_TEST_FOLDER}/*.cpp ${SOCKET_TEST_FOLDER}/*.hpp) FILE(GLOB main_SRC ${SERVER_FOLDER}/main.cpp) @@ -41,7 +43,7 @@ ADD_EXECUTABLE(${UT_SERVER_CODENAME} ${project_SRCS} ${common_SRCS} ${server_SRC ADD_EXECUTABLE("vasum-client-c-api-compile-test" client/client-c-api-compile-test.c) ## A stub mini-service to test socket functionality -ADD_EXECUTABLE(${SOCKET_TEST_CODENAME} ${socket_test_SRCS} ${common_SRCS}) +ADD_EXECUTABLE(${SOCKET_TEST_CODENAME} ${socket_test_SRCS} ${common_SRCS} ${client_SRCS}) ## Link libraries ############################################################## -- 2.7.4 From 2f505eb8fb9a4857173726b52f11f8764ac7d2c7 Mon Sep 17 00:00:00 2001 From: Krzysztof Dynowski Date: Sun, 3 May 2015 12:10:17 +0200 Subject: [PATCH 06/16] Vasum client wrapper epoch fix, remove unwanted logging [Bug/Feature] Missing epoch in spec, too many logging messages [Cause] N/A [Solution] Add epoch, remove unwanted logging [Verification] Build, install on target, check journal Change-Id: Ie18565a52e2d0fbf6e2089c3c122a30c5bd1e6e1 --- CMakeLists.txt | 3 +++ client/CMakeLists.txt | 6 +++--- client/vasum-client-impl.cpp | 3 --- libs/config/CMakeLists.txt | 2 +- libs/dbus/CMakeLists.txt | 2 +- libs/logger/CMakeLists.txt | 2 +- packaging/vasum.spec | 24 ++++++++++++------------ 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e960c6..05fbc53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,6 +20,9 @@ CMAKE_MINIMUM_REQUIRED (VERSION 2.6.2) PROJECT(vasum) +IF(NOT DEFINED VERSION) + SET(VERSION "0.1.1") +ENDIF(NOT DEFINED VERSION) ## pkgconfig ################################################################### INCLUDE(FindPkgConfig) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index e366e3c..47db767 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -21,7 +21,7 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") ## set client library sources (without vasum-wrapper.cpp) FILE(GLOB project_SRCS *.cpp *.hpp *.h) -FILE(GLOB project_SRCS_rm vasum-wrapper.cpp) +FILE(GLOB project_SRCS_rm vasum-wrapper.cpp wrapper-compat.* vasum.h vasum_list.h) LIST(REMOVE_ITEM project_SRCS ${project_SRCS_rm}) ## set wrapper library sources (without vasum-client.cpp) @@ -36,7 +36,7 @@ FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER} ${COMMON_FOLDER}/*.hpp ${COMMON_FOLDER}/*.cpp) ## set version highier then vasum.so.0.1.0 -SET(_LIB_VERSION_ "0.1.1") +SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") SET(PC_FILE "${PROJECT_NAME}.pc") @@ -53,7 +53,7 @@ SET_TARGET_PROPERTIES(${PROJECT_NAME}-client PROPERTIES VERSION ${_LIB_VERSION_} COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") -ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS} ${common_SRCS}) +ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${_LIB_SOVERSION_} VERSION ${_LIB_VERSION_} diff --git a/client/vasum-client-impl.cpp b/client/vasum-client-impl.cpp index 9694dd3..bbc7e9e 100644 --- a/client/vasum-client-impl.cpp +++ b/client/vasum-client-impl.cpp @@ -177,9 +177,6 @@ VsmStatus Client::coverException(const function& worker) noexcept } catch (const exception& ex) { mStatus = Status(VSMCLIENT_CUSTOM_ERROR, ex.what()); } - if (mStatus.mVsmStatus!=VSMCLIENT_SUCCESS) { - LOGE("Exception: " << mStatus.mMsg); - } return mStatus.mVsmStatus; } diff --git a/libs/config/CMakeLists.txt b/libs/config/CMakeLists.txt index 377b734..87c2af1 100644 --- a/libs/config/CMakeLists.txt +++ b/libs/config/CMakeLists.txt @@ -25,7 +25,7 @@ FILE(GLOB HEADERS *.hpp) FILE(GLOB HEADERS_SQLITE3 ${CMAKE_CURRENT_BINARY_DIR}/sqlite3/*.hpp) FILE(GLOB_RECURSE SRCS *.cpp *.hpp) -SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") SET(PC_FILE "lib${PROJECT_NAME}.pc") diff --git a/libs/dbus/CMakeLists.txt b/libs/dbus/CMakeLists.txt index cd2c06c..840b3b4 100644 --- a/libs/dbus/CMakeLists.txt +++ b/libs/dbus/CMakeLists.txt @@ -32,7 +32,7 @@ FILE(GLOB SRCS_UTILS ${COMMON_FOLDER}/utils/callback-guard.cpp ${COMMON_FOLDER}/utils/callback-wrapper.cpp) FILE(GLOB SRCS *.cpp *.hpp) -SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") SET(PC_FILE "lib${PROJECT_NAME}.pc") diff --git a/libs/logger/CMakeLists.txt b/libs/logger/CMakeLists.txt index 786f8bc..6b3352d 100644 --- a/libs/logger/CMakeLists.txt +++ b/libs/logger/CMakeLists.txt @@ -24,7 +24,7 @@ MESSAGE(STATUS "Generating makefile for the libLogger...") FILE(GLOB HEADERS *.hpp) FILE(GLOB SRCS *.cpp *.hpp) -SET(_LIB_VERSION_ "0.0.1") +SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") SET(PC_FILE "lib${PROJECT_NAME}.pc") diff --git a/packaging/vasum.spec b/packaging/vasum.spec index c2b6eb9..07b2f0c 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -128,9 +128,9 @@ Library interface to the vasum daemon %files client %manifest packaging/libvasum-client.manifest %defattr(644,root,root,755) -%attr(755,root,root) %{_libdir}/libvasum-client.so.0.1.1 +%attr(755,root,root) %{_libdir}/libvasum-client.so.%{version} %{_libdir}/libvasum-client.so.0 -%attr(755,root,root) %{_libdir}/libvasum.so.0.1.1 +%attr(755,root,root) %{_libdir}/libvasum.so.%{version} %{_libdir}/libvasum.so.0 %post client -p /sbin/ldconfig @@ -142,8 +142,8 @@ Library interface to the vasum daemon %package devel Summary: Vasum Client Devel Group: Development/Libraries -Requires: vasum = %{version}-%{release} -Requires: vasum-client = %{version}-%{release} +Requires: vasum = %{epoch}:%{version}-%{release} +Requires: vasum-client = %{epoch}:%{version}-%{release} %description devel Development package including the header files for the client library @@ -175,7 +175,7 @@ Zones support installed inside every zone. %package zone-daemon Summary: Vasum Zones Daemon Group: Security/Other -Requires: vasum-zone-support = %{version}-%{release} +Requires: vasum-zone-support = %{epoch}:%{version}-%{release} %description zone-daemon Daemon running inside every zone. @@ -191,7 +191,7 @@ Daemon running inside every zone. %package cli Summary: Vasum Command Line Interface Group: Security/Other -Requires: vasum-client = %{version}-%{release} +Requires: vasum-client = %{epoch}:%{version}-%{release} %description cli Command Line Interface for vasum. @@ -203,7 +203,7 @@ Command Line Interface for vasum. %package cli-completion Summary: Vasum Command Line Interface bash completion Group: Security/Other -Requires: vasum-cli = %{version}-%{release} +Requires: vasum-cli = %{epoch}:%{version}-%{release} #Requires: bash-completion %description cli-completion @@ -216,8 +216,8 @@ Command Line Interface bash completion. %package tests Summary: Vasum Tests Group: Development/Libraries -Requires: vasum = %{version}-%{release} -Requires: vasum-client = %{version}-%{release} +Requires: vasum = %{epoch}:%{version}-%{release} +Requires: vasum-client = %{epoch}:%{version}-%{release} Requires: python Requires: python-xml Requires: boost-test @@ -270,7 +270,7 @@ The package provides libLogger library. %files -n libLogger %defattr(644,root,root,755) %{_libdir}/libLogger.so.0 -%attr(755,root,root) %{_libdir}/libLogger.so.0.0.1 +%attr(755,root,root) %{_libdir}/libLogger.so.%{version} %package -n libLogger-devel Summary: Development logger library @@ -303,7 +303,7 @@ The package provides libSimpleDbus library. %files -n libSimpleDbus %defattr(644,root,root,755) %{_libdir}/libSimpleDbus.so.0 -%attr(755,root,root) %{_libdir}/libSimpleDbus.so.0.0.1 +%attr(755,root,root) %{_libdir}/libSimpleDbus.so.%{version} %package -n libSimpleDbus-devel Summary: Development Simple dbus library @@ -337,7 +337,7 @@ The package provides libConfig library. %files -n libConfig %defattr(644,root,root,755) %{_libdir}/libConfig.so.0 -%attr(755,root,root) %{_libdir}/libConfig.so.0.0.1 +%attr(755,root,root) %{_libdir}/libConfig.so.%{version} %package -n libConfig-devel Summary: Development Config library -- 2.7.4 From a840b130c718aab155e81e46d009f4c85f8d9f41 Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Mon, 11 May 2015 10:57:29 +0200 Subject: [PATCH 07/16] Removed unnecessary debug messages logging [Bug] Unnecessary debug messages [Cause] Listening to signals from all the dbus buses [Solution] Listen on only one dbus interface [Verification] Build with DEBUG, run on odroid. There shouldn't be debug messages about received signals from external services Change-Id: I9096b581d970da5a6bd18beca5fa8d13688ab875 --- libs/dbus/connection.cpp | 11 +++++++---- libs/dbus/connection.hpp | 6 +++++- server/host-dbus-connection.cpp | 3 ++- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/libs/dbus/connection.cpp b/libs/dbus/connection.cpp index 441174b..3485ea5 100644 --- a/libs/dbus/connection.cpp +++ b/libs/dbus/connection.cpp @@ -213,13 +213,16 @@ void DbusConnection::emitSignal(const std::string& objectPath, } DbusConnection::SubscriptionId DbusConnection::signalSubscribe(const SignalCallback& callback, - const std::string& senderBusName) + const std::string& senderBusName, + const std::string& interface, + const std::string& objectPath, + const std::string& member) { return g_dbus_connection_signal_subscribe(mConnection, senderBusName.empty() ? NULL : senderBusName.c_str(), - NULL, - NULL, - NULL, + interface.empty() ? NULL : interface.c_str(), + objectPath.empty() ? NULL : objectPath.c_str(), + member.empty() ? NULL : member.c_str(), NULL, G_DBUS_SIGNAL_FLAGS_NONE, &DbusConnection::onSignal, diff --git a/libs/dbus/connection.hpp b/libs/dbus/connection.hpp index 6603c9d..faf737c 100644 --- a/libs/dbus/connection.hpp +++ b/libs/dbus/connection.hpp @@ -125,7 +125,11 @@ public: * Empty sender means subscribe to all signals * Returns a subscription identifier that can be used to unsubscribe signal */ - SubscriptionId signalSubscribe(const SignalCallback& callback, const std::string& senderBusName); + SubscriptionId signalSubscribe(const SignalCallback& callback, + const std::string& senderBusName = "", + const std::string& interface = "", + const std::string& objectPath ="", + const std::string& member = ""); /** * Unsubscribes from a signal. diff --git a/server/host-dbus-connection.cpp b/server/host-dbus-connection.cpp index 98325ac..ad0ba0d 100644 --- a/server/host-dbus-connection.cpp +++ b/server/host-dbus-connection.cpp @@ -71,7 +71,8 @@ HostDbusConnection::HostDbusConnection() mSubscriptionId = mDbusConnection->signalSubscribe(std::bind(&HostDbusConnection::onSignalCall, this, _1, _2, _3, _4, _5), - std::string()); + std::string(), + api::dbus::INTERFACE); LOGD("Connected"); } -- 2.7.4 From cce2ad0032c89a684910440040090f1ee42aaf25 Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Mon, 11 May 2015 12:28:55 +0200 Subject: [PATCH 08/16] Doxygen fixes [Bug] Doesn't compile with clang [Cause] Doxygen parse errors [Solution] Fix doxygen comments [Verification] Compile with clang 3.5.1 Change-Id: Ifa43326293b27ad45c2f3e217f4c09d175cc5c15 --- client/vasum.h | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/client/vasum.h b/client/vasum.h index ae4f37d..13db4f7 100644 --- a/client/vasum.h +++ b/client/vasum.h @@ -2,7 +2,7 @@ * Vasum : Tizen Zone Control Framework * * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved - * + * * Contact: Keunhwan Kwak * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -159,7 +159,7 @@ API vsm_error_e vsm_last_error(vsm_context_h ctx); * @brief Get vasum error string. * \par Description: * return string pointer for vasum error string. - * \param[in] vsm_error_e error. + * \param[in] error vsm_error_e. * \return string pointer value represent to error code. * \warning Do not free returned pointer. */ @@ -342,7 +342,7 @@ typedef enum { * @brief Definition for zone events */ typedef enum { - VSM_ZONE_EVENT_NONE, /**< Zone has no event */ + VSM_ZONE_EVENT_NONE, /**< Zone has no event */ VSM_ZONE_EVENT_CREATED, /**< Zone is created */ VSM_ZONE_EVENT_DESTROYED, /**< Zone is destroted */ VSM_ZONE_EVENT_SWITCHED, /**< Foreground is switched */ @@ -368,14 +368,13 @@ typedef int (*vsm_zone_event_cb)(vsm_zone_h zone, vsm_zone_event_t event, void * * \par Description: * This API traverses all zones which are in running state, and callback function will be called on every entry. * \param[in] ctx vsm context - * \param[in] zone_name zone name string * \param[in] callback Function to be executed in iteration, which can be NULL * \param[in] user_data Parameter to be passed to callback function * \return 0 on success, or negative integer error code on error. * \retval #VSM_ERROR_NONE Successful * \retval #VSM_ERROR_OUT_OF_MEMORY Zone handle allocation failed * \retval #VSM_ERROR_GENERIC Zone initialize failed - * \remark In case of callback and is NULL, + * \remark In case of callback and is NULL, * This API refresh vsm_context which means reloading current running zone to vsm_context again. */ API int vsm_iterate_zone(vsm_context_h ctx, vsm_zone_iter_cb callback, void *user_data); @@ -384,11 +383,11 @@ API int vsm_iterate_zone(vsm_context_h ctx, vsm_zone_iter_cb callback, void *use * @brief Find zone corresponding to the name * The function vsm_lookup_zone_by_name() looks for the zone instance corresponding to the given name. * \param[in] ctx vsm context - * \param[in] path zone path to search + * \param[in] name zone name * \return Zone instance on success, or NULL on error. - * \retval vsm_zone_h Successful + * \retval vsm_zone_h Successful * \retval NULL Failed to lookup - * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. * \see vsm_create_context(), vsm_enter_eventloop() */ API vsm_zone_h vsm_lookup_zone_by_name(vsm_context_h ctx, const char *name); @@ -400,9 +399,9 @@ API vsm_zone_h vsm_lookup_zone_by_name(vsm_context_h ctx, const char *name); * \param[in] ctx vsm context * \param[in] pid Process id * \return Zone instance on success, or NULL on error. - * \retval vsm_zone_h Successful + * \retval vsm_zone_h Successful * \retval NULL Failed to lookup - * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or vsm_context_h does not have current zone status. * \see vsm_create_context(), vsm_enter_eventloop() */ API vsm_zone_h vsm_lookup_zone_by_pid(vsm_context_h ctx, pid_t pid); @@ -416,7 +415,7 @@ API vsm_zone_h vsm_lookup_zone_by_pid(vsm_context_h ctx, pid_t pid); * \return Callback handle on success, or negative error code on error. * \retval handle nonnegative handle id for callback. * \retval #VSM_ERROR_OUT_OF_MEMORY Callback hanlder allocation failed. - * \pre vsm_context_h have to bind by vsm_enter_eventloop() or callback function does not called. + * \pre vsm_context_h have to bind by vsm_enter_eventloop() or callback function does not called. * \see vsm_create_context(), vsm_enter_eventloop(), vsm_del_state_changed_callback() */ API int vsm_add_state_changed_callback(vsm_context_h ctx, vsm_zone_state_changed_cb callback, void *user_data); @@ -492,10 +491,10 @@ typedef struct vsm_attach_options_s { * @brief Launch a process in a running zone. * \par Description: * Execute specific command inside the zone with given arguments and environment - * \param[in] zone vsm_zone_h + * \param[in] zone_name vsm_zone_h * \param[in] command vsm attach command * \param[in] opt vsm attach options (can be NULL), using VSM_ATTACH_OPT_DEFAULT - * \param[out] attached process pid + * \param[out] attached_process process pid * \return On sucess 0, otherwise, a negative integer error code on error * \retval #VSM_ERROR_NONE Successful * \retval #VSM_ERROR_INVALID Invalid arguments @@ -508,7 +507,7 @@ API int vsm_attach_zone(vsm_context_h ctx, const char * zone_name, vsm_attach_co * @brief Launch a process in a running zone and wait till child process exited. * \par Description: * Execute specific command inside the zone with given arguments and environment - * \param[in] zone vsm_zone_h + * \param[in] zone_name vsm_zone_h * \param[in] command vsm attach command * \param[in] opt vsm attach options (can be NULL), using VSM_ATTACH_OPT_DEFAULT * \return On sucess waitpid exit code or attached process, or a negative error code @@ -621,7 +620,7 @@ API void * vsm_get_userdata(vsm_zone_h zone); * @brief join current process into zone. * \par Synopsys: * Change self peer credential to target zone - * \param[in] vsm_zone_h zone + * \param[in] zone vsm_zone_h * \return before vsm_zone on success, or NULL on error. * \retval vsm_zone_h before zone handle, If caller process running in host, then host handle returned. * \retval NULL invalid zone handle. @@ -637,7 +636,7 @@ API vsm_zone_h vsm_join_zone(vsm_zone_h zone); * \par Description: * get canonical file path based on current zone. * \param[in] input_path requested zone path - * \param[out] output_path string pointer for canonicalized output path + * \param[out] output_path string pointer for canonicalized output path * \return int positive string length of output_path, or negative error code on error. * \retval #VSM_ERROR_INVALID Invalid arguments. * \retval #VSM_ERROR_GENERIC gethostname() is failed. @@ -809,7 +808,7 @@ API int vsm_down_netdev(vsm_netdev_h netdev); * \par Description: * The function vsm_get_ip_addr_netdev() get ip address from a network interface * \param[in] netdev Network device to get address - * \param[in] family Address family + * \param[in] addr_family Address family * \param[out] addr Buffer to get address from a network device * \param[out] size Size of buffer * \return 0 on success, or negative integer error code on error. @@ -826,7 +825,7 @@ API int vsm_get_ip_addr_netdev(vsm_netdev_h netdev, vsm_netdev_addr_t addr_famil * \par Description: * The function vsm_set_ip_addr_netdev() set ipv4 address to a network interface * \param[in] netdev Network device to set address - * \param[in] family Address family + * \param[in] addr_family Address family * \param[in] addr IP address string to be set * \param[in] prefix prefix ( ex> 192.168.122.1/24, 24 is prefix ) * \return 0 on success, or negative integer error code on error. @@ -852,7 +851,7 @@ API int vsm_set_ip_addr_netdev(vsm_netdev_h netdev, vsm_netdev_addr_t addr_famil * \par Description: * Request permission device file node to target zone. * \param[in] zone vsm_zone_h - * \param[in] name device node path + * \param[in] path device node path * \param[in] flags requested permission O_RDWR, O_WRONLY, O_RDONLY * \return 0 on success, or negative integer error code on error. * \retval #VSM_ERROR_NONE Successful @@ -868,7 +867,7 @@ API int vsm_grant_device(vsm_zone_h zone, const char *path, uint32_t flags); * \par Description: * Revoke device node permissions from target zone. * \param[in] zone vsm_zone_h - * \param[in] name device node path + * \param[in] path device node path * \return 0 on success, or negative integer error code on error. * \retval #VSM_ERROR_NONE Successful * \retval #VSM_ERROR_INVALID Invalid arguments @@ -907,11 +906,11 @@ typedef mode_t vsm_mode_t; * @brief Declare specific file object to every zone. * \par Description: * Declare host file system to every running zone. - * In case of host target file exist, create new file in running zone. or create a new file in running zone. + * In case of host target file exist, create new file in running zone. or create a new file in running zone. * And add hook info in vsm-resource-provier for automatically link host target file to starting zone. * Smack labels are also copied as same as host labels. * \param[in] ctx vsm context - * \param[in] type Type of file system object + * \param[in] ftype Type of file system object * \param[in] path Path for the file system object * \param[in] flags Flasg * \param[in] mode mode @@ -935,7 +934,7 @@ API int vsm_declare_file(vsm_context_h ctx, vsm_fso_type_t ftype, const char *pa * \param[in] target target * \return zero on success, or negative value on error. * \retval #VSM_ERROR_NONE successful - * \retval #VSM_ERROR_INVALID Invalid provision type to db. + * \retval #VSM_ERROR_INVALID Invalid provision type to db. * \retval #VSM_ERROR_GENERIC Error in vasum server side. * \retval #VSM_ERROR_NO_OBJECT Source file is not exist in host filesystem */ -- 2.7.4 From 4c55d2d204ffaab7661bea92845836cb70ced5b5 Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Wed, 6 May 2015 11:38:03 +0200 Subject: [PATCH 09/16] Client timeout fixes: vsm_start_zone, vsm_shutdown_zone, vsm_lock_zone [Feature] Greater timeout for vsm_start_zone, vsm_shutdown_zone, vsm_lock_zone, vsm_destroy_zone [Cause] Timeout was too small [Solution] N/A [Verification] Start vasum on odroid, start zone, lock zone, shutdown zone, destroy zone Change-Id: I22c080565736abeb95a1e57653777c7d0863c7b3 --- client/host-ipc-connection.cpp | 89 +++++++++++++++++++++++------------------- client/host-ipc-connection.hpp | 6 --- 2 files changed, 48 insertions(+), 47 deletions(-) diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index 11741f6..6aa87ec 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -31,6 +31,10 @@ namespace vasum { namespace client { +namespace { + const int TIMEOUT_INFINITE = -1; +} //namespace + void HostIPCConnection::createSystem() { mClient.reset(new ipc::Client(mDispatcher.getPoll(), HOST_IPC_SOCKET)); @@ -49,21 +53,23 @@ void HostIPCConnection::create(const std::string& address) void HostIPCConnection::callGetZoneIds(api::ZoneIds& argOut) { - api::Void argVoid; - call(api::ipc::METHOD_GET_ZONE_ID_LIST, argVoid, argOut); + argOut = *mClient->callSync( + api::ipc::METHOD_GET_ZONE_ID_LIST, + std::make_shared()); } void HostIPCConnection::callGetActiveZoneId(api::ZoneId& argOut) { - api::Void argVoid; - call(api::ipc::METHOD_GET_ACTIVE_ZONE_ID, argVoid, argOut); + argOut = *mClient->callSync( + api::ipc::METHOD_GET_ACTIVE_ZONE_ID, + std::make_shared()); } void HostIPCConnection::callSetActiveZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_SET_ACTIVE_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_SET_ACTIVE_ZONE, + std::make_shared(argIn)); } void HostIPCConnection::callGetZoneInfo(const api::ZoneId& argIn, api::ZoneInfoOut& argOut) @@ -76,11 +82,8 @@ void HostIPCConnection::callGetZoneInfo(const api::ZoneId& argIn, api::ZoneInfoO void HostIPCConnection::callSetNetdevAttrs(const api::SetNetDevAttrsIn& argIn) { mClient->callSync( - api::ipc::METHOD_SET_NETDEV_ATTRS, - std::make_shared(argIn)); - - api::Void argVoid; - call(api::ipc::METHOD_SET_NETDEV_ATTRS, argIn, argVoid); + api::ipc::METHOD_SET_NETDEV_ATTRS, + std::make_shared(argIn)); } void HostIPCConnection::callGetNetdevAttrs(const api::GetNetDevAttrsIn& argIn, api::GetNetDevAttrs& argOut) @@ -100,36 +103,36 @@ void HostIPCConnection::callGetNetdevList(const api::ZoneId& argIn, api::NetDevL void HostIPCConnection::callCreateNetdevVeth(const api::CreateNetDevVethIn& argIn) { mClient->callSync( - api::ipc::METHOD_CREATE_NETDEV_VETH, - std::make_shared(argIn)); + api::ipc::METHOD_CREATE_NETDEV_VETH, + std::make_shared(argIn)); } void HostIPCConnection::callCreateNetdevMacvlan(const api::CreateNetDevMacvlanIn& argIn) { mClient->callSync( - api::ipc::METHOD_CREATE_NETDEV_MACVLAN, - std::make_shared(argIn)); + api::ipc::METHOD_CREATE_NETDEV_MACVLAN, + std::make_shared(argIn)); } void HostIPCConnection::callCreateNetdevPhys(const api::CreateNetDevPhysIn& argIn) { mClient->callSync( - api::ipc::METHOD_CREATE_NETDEV_PHYS, - std::make_shared(argIn)); + api::ipc::METHOD_CREATE_NETDEV_PHYS, + std::make_shared(argIn)); } void HostIPCConnection::callDestroyNetdev(const api::DestroyNetDevIn& argIn) { mClient->callSync( - api::ipc::METHOD_DESTROY_NETDEV, - std::make_shared(argIn)); + api::ipc::METHOD_DESTROY_NETDEV, + std::make_shared(argIn)); } void HostIPCConnection::callDeleteNetdevIpAddress(const api::DeleteNetdevIpAddressIn& argIn) { mClient->callSync( - api::ipc::METHOD_DELETE_NETDEV_IP_ADDRESS, - std::make_shared(argIn)); + api::ipc::METHOD_DELETE_NETDEV_IP_ADDRESS, + std::make_shared(argIn)); } void HostIPCConnection::callDeclareFile(const api::DeclareFileIn& argIn, api::Declaration& argOut) @@ -163,71 +166,75 @@ void HostIPCConnection::callGetDeclarations(const api::ZoneId& argIn, api::Decla void HostIPCConnection::callRemoveDeclaration(const api::RemoveDeclarationIn& argIn) { mClient->callSync( - api::ipc::METHOD_REMOVE_DECLARATION, - std::make_shared(argIn)); + api::ipc::METHOD_REMOVE_DECLARATION, + std::make_shared(argIn)); } void HostIPCConnection::callCreateZone(const api::CreateZoneIn& argIn) { mClient->callSync( - api::ipc::METHOD_CREATE_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_CREATE_ZONE, + std::make_shared(argIn)); } void HostIPCConnection::callDestroyZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_DESTROY_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_DESTROY_ZONE, + std::make_shared(argIn), + TIMEOUT_INFINITE); } void HostIPCConnection::callShutdownZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_SHUTDOWN_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_SHUTDOWN_ZONE, + std::make_shared(argIn), + TIMEOUT_INFINITE); } void HostIPCConnection::callStartZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_START_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_START_ZONE, + std::make_shared(argIn), + TIMEOUT_INFINITE); } void HostIPCConnection::callLockZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_LOCK_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_LOCK_ZONE, + std::make_shared(argIn), + TIMEOUT_INFINITE); } void HostIPCConnection::callUnlockZone(const api::ZoneId& argIn) { mClient->callSync( - api::ipc::METHOD_UNLOCK_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_UNLOCK_ZONE, + std::make_shared(argIn)); } void HostIPCConnection::callGrantDevice(const api::GrantDeviceIn& argIn) { mClient->callSync( - api::ipc::METHOD_GRANT_DEVICE, - std::make_shared(argIn)); + api::ipc::METHOD_GRANT_DEVICE, + std::make_shared(argIn)); } void HostIPCConnection::callRevokeDevice(const api::RevokeDeviceIn& argIn) { mClient->callSync( - api::ipc::METHOD_REVOKE_DEVICE, - std::make_shared(argIn)); + api::ipc::METHOD_REVOKE_DEVICE, + std::make_shared(argIn)); } void HostIPCConnection::callNotifyActiveZone(const api::NotifActiveZoneIn& argIn) { mClient->callSync( - api::ipc::METHOD_NOTIFY_ACTIVE_ZONE, - std::make_shared(argIn)); + api::ipc::METHOD_NOTIFY_ACTIVE_ZONE, + std::make_shared(argIn)); } void HostIPCConnection::callFileMoveRequest(const api::FileMoveRequestIn& argIn, diff --git a/client/host-ipc-connection.hpp b/client/host-ipc-connection.hpp index 39015f4..1497390 100644 --- a/client/host-ipc-connection.hpp +++ b/client/host-ipc-connection.hpp @@ -82,12 +82,6 @@ public: private: epoll::ThreadDispatcher mDispatcher; std::unique_ptr mClient; - - template - void call(const ipc::MethodID method, const ArgIn& argIn, ArgOut& argOut, int timeout = 5000) { - auto out = mClient->callSync(method, std::make_shared(argIn), timeout); - argOut = *out; - } }; } // namespace client -- 2.7.4 From 648b40963f63f480896486713590dac017cf79bf Mon Sep 17 00:00:00 2001 From: Dariusz Michaluk Date: Mon, 11 May 2015 16:22:53 +0200 Subject: [PATCH 10/16] Cleanup RPM spec file. Fix RPMLINT errors. [Bug/Feature] Cleanup RPM spec file. Fix RPMLINT errors. [Cause] N/A [Solution] N/A [Verification] Build, install, uninstall. Change-Id: I063dd412b1999b9cda5e2cdf3d62ee2282abca1b --- packaging/vasum.spec | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packaging/vasum.spec b/packaging/vasum.spec index 07b2f0c..d2c7fe0 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -125,6 +125,10 @@ Requires(postun): /sbin/ldconfig %description client Library interface to the vasum daemon +%post -n vasum-client -p /sbin/ldconfig + +%postun -n vasum-client -p /sbin/ldconfig + %files client %manifest packaging/libvasum-client.manifest %defattr(644,root,root,755) @@ -133,10 +137,6 @@ Library interface to the vasum daemon %attr(755,root,root) %{_libdir}/libvasum.so.%{version} %{_libdir}/libvasum.so.0 -%post client -p /sbin/ldconfig - -%postun client -p /sbin/ldconfig - ## Devel Package ############################################################### %package devel @@ -207,7 +207,7 @@ Requires: vasum-cli = %{epoch}:%{version}-%{release} #Requires: bash-completion %description cli-completion -Command Line Interface bash completion. +Command Line Interface bash completion for vasum. %files cli-completion %attr(755,root,root) %{_sysconfdir}/bash_completion.d/vasum-cli-completion.sh @@ -275,7 +275,7 @@ The package provides libLogger library. %package -n libLogger-devel Summary: Development logger library Group: Development/Libraries -Requires: libLogger = %{version}-%{release} +Requires: libLogger = %{epoch}:%{version}-%{release} %description -n libLogger-devel The package provides libLogger development tools and libs. @@ -308,7 +308,7 @@ The package provides libSimpleDbus library. %package -n libSimpleDbus-devel Summary: Development Simple dbus library Group: Development/Libraries -Requires: libSimpleDbus = %{version}-%{release} +Requires: libSimpleDbus = %{epoch}:%{version}-%{release} Requires: pkgconfig(libLogger) %description -n libSimpleDbus-devel @@ -342,7 +342,7 @@ The package provides libConfig library. %package -n libConfig-devel Summary: Development Config library Group: Development/Libraries -Requires: libConfig = %{version}-%{release} +Requires: libConfig = %{epoch}:%{version}-%{release} Requires: boost-devel Requires: pkgconfig(libLogger) Requires: libjson-devel -- 2.7.4 From d0a712acbbbe43e65eeba18dd6a4e2f29698e93b Mon Sep 17 00:00:00 2001 From: Krzysztof Dynowski Date: Tue, 12 May 2015 09:18:14 +0200 Subject: [PATCH 11/16] Vasum wrapper #3, fixes, API update [Bug/Feature] Old vasum client not compiling with wrapper [Cause] missing struct defs [Solution] #3 update wrapper API (use correct vasum.h) [Verification] Build, build old clients Change-Id: I97f21d77ed6b56d4e046c577521f839b74c31779 --- client/CMakeLists.txt | 13 +- client/vasum-client.pc.in | 12 + client/vasum-wrapper.cpp | 8 +- client/vasum.h | 203 +++-- client/vasum.pc.in | 2 +- client/vasum_list.h | 62 +- client/wrapper-compat.cpp | 1903 ++++++++++++++++++++++----------------------- client/wrapper-compat.h | 39 - packaging/vasum.spec | 1 + 9 files changed, 1118 insertions(+), 1125 deletions(-) create mode 100644 client/vasum-client.pc.in diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 47db767..253a19e 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -19,9 +19,12 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") -## set client library sources (without vasum-wrapper.cpp) +## set client library sources (without wrapper files) FILE(GLOB project_SRCS *.cpp *.hpp *.h) -FILE(GLOB project_SRCS_rm vasum-wrapper.cpp wrapper-compat.* vasum.h vasum_list.h) +FILE(GLOB project_SRCS_rm vasum-wrapper.cpp + wrapper-compat.* + vasum.h + vasum_list.h) LIST(REMOVE_ITEM project_SRCS ${project_SRCS_rm}) ## set wrapper library sources (without vasum-client.cpp) @@ -38,6 +41,7 @@ FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER} ## set version highier then vasum.so.0.1.0 SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") +SET(PC_FILE_CLIENT "${PROJECT_NAME}-client.pc") SET(PC_FILE "${PROJECT_NAME}.pc") ## Set the default ELF image symbol visibility to hidden. Using this feature @@ -53,7 +57,7 @@ SET_TARGET_PROPERTIES(${PROJECT_NAME}-client PROPERTIES VERSION ${_LIB_VERSION_} COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") -ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS}) +ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS} ${common_SRCS}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${_LIB_SOVERSION_} VERSION ${_LIB_VERSION_} @@ -72,11 +76,12 @@ TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} Config SimpleDbus) ## Generate the pc file ######################################################## +CONFIGURE_FILE(${PC_FILE_CLIENT}.in ${CMAKE_BINARY_DIR}/${PC_FILE_CLIENT} @ONLY) CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_BINARY_DIR}/${PC_FILE} @ONLY) ## Install ##################################################################### -INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE} +INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE_CLIENT} ${CMAKE_BINARY_DIR}/${PC_FILE} DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) INSTALL(TARGETS ${PROJECT_NAME}-client ${PROJECT_NAME} diff --git a/client/vasum-client.pc.in b/client/vasum-client.pc.in new file mode 100644 index 0000000..927fe89 --- /dev/null +++ b/client/vasum-client.pc.in @@ -0,0 +1,12 @@ +# Package Information for pkg-config + +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=@LIB_INSTALL_DIR@ +includedir=${prefix}/include + +Name: vasum-client +Description: Vasum library +Version: @_LIB_VERSION_@ +Libs: -L${libdir} -lvasum-client +Cflags: -I${includedir}/vasum diff --git a/client/vasum-wrapper.cpp b/client/vasum-wrapper.cpp index 2cbe806..54c195e 100644 --- a/client/vasum-wrapper.cpp +++ b/client/vasum-wrapper.cpp @@ -197,7 +197,7 @@ static void init_context_wrap(WrappedContext *w) //ctx->data = ep; } -API struct vsm_context *vsm_create_context(void) +API vsm_context_h vsm_create_context(void) { LOGS(""); callcheck(); WrappedContext *w = new WrappedContext(); @@ -207,7 +207,7 @@ API struct vsm_context *vsm_create_context(void) return ctx; } -API int vsm_cleanup_context(struct vsm_context *ctx) +API int vsm_cleanup_context(vsm_context_h ctx) { LOGS(""); callcheck(); WrappedContext *w = container_of(ctx, WrappedContext, hq_ctx); @@ -367,7 +367,7 @@ API int vsm_attach_zone(struct vsm_context *ctx, vsm_attach_options_t *opts, pid_t *attached_process) { - return ctx->vsm_ops->attach_zone(ctx, zone_name, command, opts, + return dummy_ops.attach_zone(ctx, zone_name, command, opts, attached_process); } @@ -377,7 +377,7 @@ API int vsm_attach_zone_wait(struct vsm_context *ctx, vsm_attach_command_t *command, vsm_attach_options_t *opts) { - return ctx->vsm_ops->attach_zone_wait(ctx, zone_name, command, opts); + return dummy_ops.attach_zone_wait(ctx, zone_name, command, opts); } API int vsm_iterate_zone(struct vsm_context *ctx, void (*callback)(struct vsm_zone *zone, void *user_data), void *user_data) diff --git a/client/vasum.h b/client/vasum.h index 13db4f7..0cb245e 100644 --- a/client/vasum.h +++ b/client/vasum.h @@ -1,23 +1,28 @@ /* - * Vasum : Tizen Zone Control Framework + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved * - * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Contact: Krzysztof Dynowski * - * Contact: Keunhwan Kwak + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + + +/** + * @file + * @author Krzysztof Dynowski (k.dynowski@samsung.com) + * @brief Vasum old API */ + #ifndef __VASUM_H__ #define __VASUM_H__ @@ -36,18 +41,10 @@ #ifdef __cplusplus extern "C" { #endif -/* - * @file vasum.h - * @version 0.3 - * @brief This file contains APIs of the Zone control Framework - */ /* * * Revision History: - * 2014-09-01 sungbae you First created - * 2014-10-07 sungbae you First doxygen commented - * 2015-03-19 kuenhwan Kwak doxygen revise * */ @@ -123,26 +120,26 @@ API int vsm_enter_eventloop(vsm_context_h ctx, int flags, int timeout); * @brief Enumeration for vasum error. */ typedef enum { - VSM_ERROR_NONE, /**< The operation was successful */ - VSM_ERROR_GENERIC, /**< Non-specific cause */ - VSM_ERROR_INVALID, /**< Invalid argument */ - VSM_ERROR_CANCELED, /**< The requested operation was cancelled */ - VSM_ERROR_ABORTED, /**< Operation aborted */ - VSM_ERROR_REFUSED, /**< Connection refused */ - VSM_ERROR_EXIST, /**< Target exists */ - VSM_ERROR_BUSY, /**< Resource is busy */ - VSM_ERROR_IO, /**< I/O error*/ - VSM_ERROR_TIMEOUT, /**< Timer expired */ - VSM_ERROR_OVERFLOW, /**< Value too large to be stored in data type */ - VSM_ERROR_OUT_OF_MEMORY, /**< No memory space */ - VSM_ERROR_OUT_OF_RANGE, /**< Input is out of range */ - VSM_ERROR_NOT_PERMITTED, /**< Operation not permitted */ - VSM_ERROR_NOT_IMPLEMENTED, /**< Function is not implemented yet */ - VSM_ERROR_NOT_SUPPORTED, /**< Operation is not supported */ - VSM_ERROR_ACCESS_DENIED, /**< Access privilege is not sufficient */ - VSM_ERROR_NO_OBJECT, /**< Object not found */ - VSM_ERROR_BAD_STATE, /**< Bad state */ - VSM_MAX_ERROR = VSM_ERROR_BAD_STATE + VSM_ERROR_NONE, /**< The operation was successful */ + VSM_ERROR_GENERIC, /**< Non-specific cause */ + VSM_ERROR_INVALID, /**< Invalid argument */ + VSM_ERROR_CANCELED, /**< The requested operation was cancelled */ + VSM_ERROR_ABORTED, /**< Operation aborted */ + VSM_ERROR_REFUSED, /**< Connection refused */ + VSM_ERROR_EXIST, /**< Target exists */ + VSM_ERROR_BUSY, /**< Resource is busy */ + VSM_ERROR_IO, /**< I/O error*/ + VSM_ERROR_TIMEOUT, /**< Timer expired */ + VSM_ERROR_OVERFLOW, /**< Value too large to be stored in data type */ + VSM_ERROR_OUT_OF_MEMORY, /**< No memory space */ + VSM_ERROR_OUT_OF_RANGE, /**< Input is out of range */ + VSM_ERROR_NOT_PERMITTED, /**< Operation not permitted */ + VSM_ERROR_NOT_IMPLEMENTED, /**< Function is not implemented yet */ + VSM_ERROR_NOT_SUPPORTED, /**< Operation is not supported */ + VSM_ERROR_ACCESS_DENIED, /**< Access privilege is not sufficient */ + VSM_ERROR_NO_OBJECT, /**< Object not found */ + VSM_ERROR_BAD_STATE, /**< Bad state */ + VSM_MAX_ERROR = VSM_ERROR_BAD_STATE }vsm_error_e; /** @@ -256,7 +253,7 @@ API int vsm_start_zone(vsm_context_h ctx, const char *zone_name); * \param[in] ctx vsm context * \param[in] zone_name zone name * \param[in] force option to shutdown. - * - 0 : send SIGPWR signal to init process of target zone. + * - 0 : send SIGPWR signal to init process of target zone. * - non-zero : terminate all processes in target zone. * \return 0 on success, or negative integer error code on error. * \retval #VSM_ERROR_NONE Successful @@ -326,15 +323,15 @@ API vsm_zone_h vsm_get_foreground(vsm_context_h ctx); * This definition shows the available states. */ typedef enum { - VSM_ZONE_STATE_STOPPED, /**< Zone stopped */ - VSM_ZONE_STATE_STARTING, /**< Zone is prepare for running */ - VSM_ZONE_STATE_RUNNING, /**< Zone is running on device */ - VSM_ZONE_STATE_STOPPING, /**< Zone is stopping by request */ - VSM_ZONE_STATE_ABORTING, /**< Zone is failed to start */ - VSM_ZONE_STATE_FREEZING, /**< Reserved State */ - VSM_ZONE_STATE_FROZEN, /**< Reserved State */ - VSM_ZONE_STATE_THAWED, /**< Reserved State */ - VSM_ZONE_MAX_STATE = VSM_ZONE_STATE_THAWED + VSM_ZONE_STATE_STOPPED, /**< Zone stopped */ + VSM_ZONE_STATE_STARTING, /**< Zone is prepare for running */ + VSM_ZONE_STATE_RUNNING, /**< Zone is running on device */ + VSM_ZONE_STATE_STOPPING, /**< Zone is stopping by request */ + VSM_ZONE_STATE_ABORTING, /**< Zone is failed to start */ + VSM_ZONE_STATE_FREEZING, /**< Reserved State */ + VSM_ZONE_STATE_FROZEN, /**< Reserved State */ + VSM_ZONE_STATE_THAWED, /**< Reserved State */ + VSM_ZONE_MAX_STATE = VSM_ZONE_STATE_THAWED } vsm_zone_state_t; @@ -342,11 +339,11 @@ typedef enum { * @brief Definition for zone events */ typedef enum { - VSM_ZONE_EVENT_NONE, /**< Zone has no event */ - VSM_ZONE_EVENT_CREATED, /**< Zone is created */ - VSM_ZONE_EVENT_DESTROYED, /**< Zone is destroted */ - VSM_ZONE_EVENT_SWITCHED, /**< Foreground is switched */ - VSM_ZONE_MAX_EVENT = VSM_ZONE_EVENT_SWITCHED + VSM_ZONE_EVENT_NONE, /**< Zone has no event */ + VSM_ZONE_EVENT_CREATED, /**< Zone is created */ + VSM_ZONE_EVENT_DESTROYED, /**< Zone is destroted */ + VSM_ZONE_EVENT_SWITCHED, /**< Foreground is switched */ + VSM_ZONE_MAX_EVENT = VSM_ZONE_EVENT_SWITCHED } vsm_zone_event_t; @@ -463,18 +460,18 @@ API int vsm_del_event_callback(vsm_context_h ctx, int handle); * Arguments are same as linux system-call execv() */ typedef struct vsm_attach_command_s { - char * exec; /**< Program binary path */ - char ** argv; /**< An array of argument pointers to null-terminated strings include program path */ + char * exec; /**< Program binary path */ + char ** argv; /**< An array of argument pointers to null-terminated strings include program path */ } vsm_attach_command_s; /** * @brief Zone attach option */ typedef struct vsm_attach_options_s { - uid_t uid; /**< requested uid*/ - gid_t gid; /**< requested gid*/ - int env_num; /**< requested environ count */ - char **extra_env; /**< requested environ string pointer array. */ + uid_t uid; /**< requested uid*/ + gid_t gid; /**< requested gid*/ + int env_num; /**< requested environ count */ + char **extra_env; /**< requested environ string pointer array. */ } vsm_attach_options_s; /** @@ -591,7 +588,6 @@ API vsm_zone_state_t vsm_get_zone_state(vsm_zone_h zone); */ API int vsm_get_zone_id(vsm_zone_h zone); - /** * @brief Set userdata pointer value in vsm_zone_h. * \par Description: @@ -616,6 +612,7 @@ API int vsm_set_userdata(vsm_zone_h zone, void * userdata); */ API void * vsm_get_userdata(vsm_zone_h zone); + /** * @brief join current process into zone. * \par Synopsys: @@ -698,14 +695,14 @@ API int vsm_get_host_pid(vsm_zone_h zone, pid_t pid); * @brief Types of virtual network interfaces */ typedef enum { - VSM_NETDEV_VETH, /**< Virtual Ethernet(veth), this type device will be attached to host-side network bridge */ - VSM_NETDEV_PHYS, /**< Physical device */ - VSM_NETDEV_MACVLAN /**< Mac VLAN, this type isn't implemented yet */ + VSM_NETDEV_VETH, /**< Virtual Ethernet(veth), this type device will be attached to host-side network bridge */ + VSM_NETDEV_PHYS, /**< Physical device */ + VSM_NETDEV_MACVLAN /**< Mac VLAN, this type isn't implemented yet */ } vsm_netdev_type_t; typedef enum { - VSM_NETDEV_ADDR_IPV4, /**< IPV4 Address family */ - VSM_NETDEV_ADDR_IPV6 /**< IPV6 Address family */ + VSM_NETDEV_ADDR_IPV4, /**< IPV4 Address family */ + VSM_NETDEV_ADDR_IPV6 /**< IPV6 Address family */ } vsm_netdev_addr_t; /** @@ -888,18 +885,18 @@ API int vsm_revoke_device(vsm_zone_h zone, const char *path); * @brief Definition for declare file type. */ typedef enum { - VSM_FSO_TYPE_DIR, /**< Directoy type */ - VSM_FSO_TYPE_REG, /**< Regular file type */ - VSM_FSO_TYPE_FIFO, /**< Fifo file type */ - VSM_FSO_TYPE_SOCK, /**< Socket file type */ - VSM_FSO_TYPE_DEV, /**< Device node type */ - VSM_FSO_MAX_TYPE = VSM_FSO_TYPE_DEV + VSM_FSO_TYPE_DIR, /**< Directoy type */ + VSM_FSO_TYPE_REG, /**< Regular file type */ + VSM_FSO_TYPE_FIFO, /**< Fifo file type */ + VSM_FSO_TYPE_SOCK, /**< Socket file type */ + VSM_FSO_TYPE_DEV, /**< Device node type */ + VSM_FSO_MAX_TYPE = VSM_FSO_TYPE_DEV } vsm_fso_type_t; + /** * @brief Declare file mode. */ - typedef mode_t vsm_mode_t; /** @@ -939,10 +936,62 @@ API int vsm_declare_file(vsm_context_h ctx, vsm_fso_type_t ftype, const char *pa * \retval #VSM_ERROR_NO_OBJECT Source file is not exist in host filesystem */ API int vsm_declare_link(vsm_context_h ctx , const char *source, const char *target); - /// @} +/* + Below datatypes will be opaque. +*/ +typedef struct vsm_context { + void * signal_channel; + void * manage_method_channel; + void * unpriv_method_channel; + vsm_error_e error; + pthread_rwlock_t lock; + struct adt_list listeners; + struct vsm_zone *root_zone; + struct vsm_zone *foreground_zone; + struct adt_list sc_listeners; + struct adt_list ev_listeners; + void * vsm_ops; +} vsm_context_s; + +typedef struct vsm_zone { + struct vsm_zone *parent; + char *name; + char *type; + int terminal; + vsm_zone_state_t state; + char *rootfs_path; + pthread_rwlock_t lock; + struct adt_list children; + struct adt_list devices; + struct adt_list netdevs; + void *user_data; + struct adt_list list; + struct vsm_context *ctx; + int id; +} vsm_zone_s; + +typedef struct vsm_netdev { + struct vsm_zone *zone; + char *name; + vsm_netdev_type_t type; + struct adt_list list; +} vsm_netdev_s; + +/* + Below APIs will be removed. +*/ + +typedef int (*vsm_zone_state_cb)(vsm_zone_h zone, vsm_zone_state_t state ,vsm_zone_event_t event, void *user_data); + +API int vsm_add_state_callback(vsm_context_h ctx, vsm_zone_state_cb callback, void *user_data); + +API int vsm_del_state_callback(vsm_context_h ctx, int handle); + +API int vsm_get_zone_terminal(vsm_zone_h zone); + #ifdef __cplusplus } #endif diff --git a/client/vasum.pc.in b/client/vasum.pc.in index f12abc2..2f2247b 100644 --- a/client/vasum.pc.in +++ b/client/vasum.pc.in @@ -8,5 +8,5 @@ includedir=${prefix}/include Name: vasum Description: Vasum library Version: @_LIB_VERSION_@ -Libs: -L${libdir} -lvasum-client +Libs: -L${libdir} -lvasum Cflags: -I${includedir}/vasum diff --git a/client/vasum_list.h b/client/vasum_list.h index 185287b..5e9c82e 100644 --- a/client/vasum_list.h +++ b/client/vasum_list.h @@ -2,8 +2,8 @@ #define __VASUM_ADT_LIST_H__ struct adt_list { - struct adt_list* next; - struct adt_list* prev; + struct adt_list* next; + struct adt_list* prev; }; #undef offsetof @@ -14,8 +14,8 @@ struct adt_list { #endif #define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) #define adt_iterate_list(__iterator, __list) \ for (__iterator = (__list)->next; \ @@ -23,10 +23,10 @@ struct adt_list { __iterator = (__iterator)->next) #define adt_reverse_iterate_list(__iterator, __list) \ - for (__iterator = __list; \ + for (__iterator = __list; \ (__iterator)->next != __list; \ - __iterator = (__iterator)->next); \ - for ( ; \ + __iterator = (__iterator)->next); \ + for ( ; \ __iterator != __list; \ __iterator = (__iterator)->prev) @@ -68,35 +68,35 @@ static inline void adt_unlink_list(struct adt_list* list) } static inline void adt_sort_list(struct adt_list* head, - int (*compare_func)(struct adt_list *, struct adt_list *)) + int (*compare_func)(struct adt_list *, struct adt_list *)) { - struct adt_list *it, *jt, *kt; - - if (adt_empty_list(head)) - return; - - for (it = head->next->next; it != head; it = it->next) { - for (jt = head->next; jt != it; jt = jt->next) { - if (compare_func(it, jt) < 0) { - kt = it; - it = it->prev; - adt_unlink_list(kt); - adt_link_list(jt->prev, kt); - break; - } - } - } + struct adt_list *it, *jt, *kt; + + if (adt_empty_list(head)) + return; + + for (it = head->next->next; it != head; it = it->next) { + for (jt = head->next; jt != it; jt = jt->next) { + if (compare_func(it, jt) < 0) { + kt = it; + it = it->prev; + adt_unlink_list(kt); + adt_link_list(jt->prev, kt); + break; + } + } + } } static inline struct adt_list *adt_find_list(struct adt_list* head, - int (*equal_func)(struct adt_list *, void *), void *value) + int (*equal_func)(struct adt_list *, void *), void *value) { - struct adt_list *it; - adt_iterate_list(it, head) { - if (equal_func(it, value)) - return it; - } - return NULL; + struct adt_list *it; + adt_iterate_list(it, head) { + if (equal_func(it, value)) + return it; + } + return NULL; } #endif /*!__VASUM_ADT_LIST_H__*/ diff --git a/client/wrapper-compat.cpp b/client/wrapper-compat.cpp index dcd9e38..67b34e6 100644 --- a/client/wrapper-compat.cpp +++ b/client/wrapper-compat.cpp @@ -42,6 +42,8 @@ #include #include +#define UNUSED(x) ((void)(x)) + extern "C" { // find_container_by_pid @@ -200,8 +202,8 @@ int sock_send_fd(int /*fd*/, int /*sendfd*/, void * /*data*/, size_t /*size*/ void vasum_log(int /*type*/, const char * /*tag*/, const char * /*fmt*/ , ...) { } -#define MAX_ERROR_MSG 0x1000 -#define BUF_SIZE 4096 +#define MAX_ERROR_MSG 0x1000 +#define BUF_SIZE 4096 #define SMACK_LABEL_LEN 8 #define ERROR(...) do{}while(0) @@ -211,289 +213,289 @@ void vasum_log(int /*type*/, const char * /*tag*/, const char * /*fmt*/ , ... // lib/utils.c const char *const fso_type_strtab[] = { - "Directory", - "Regular file", - "FIFO", - "Socket", - "Device node" + "Directory", + "Regular file", + "FIFO", + "Socket", + "Device node" }; const char *fso_type_to_string(vsm_fso_type_t fso) { - if (fso < 0 || fso > VSM_FSO_MAX_TYPE) { - return NULL; - } + if (fso < 0 || fso > VSM_FSO_MAX_TYPE) { + return NULL; + } - return fso_type_strtab[fso]; + return fso_type_strtab[fso]; } int wait_for_pid_status(pid_t pid) { - int status, ret; + int status, ret; again: - ret = waitpid(pid, &status, 0); - if (ret == -1) { - if (errno == EINTR) { - goto again; - } else { - ERROR("waitpid- pid : %d error : %s", pid, - strerror(errno)); - return -1; - } - } - if (ret != pid) - goto again; - return status; + ret = waitpid(pid, &status, 0); + if (ret == -1) { + if (errno == EINTR) { + goto again; + } else { + ERROR("waitpid- pid : %d error : %s", pid, + strerror(errno)); + return -1; + } + } + if (ret != pid) + goto again; + return status; } vsm_fso_type_t fso_string_to_type(char *str) { - int len; - int i; - for (i = 0; i <= VSM_FSO_MAX_TYPE; i++) { - len = strlen(fso_type_strtab[i]); - if (strncmp(str, fso_type_strtab[i], len) == 0) - return static_cast(i); - } + int len; + int i; + for (i = 0; i <= VSM_FSO_MAX_TYPE; i++) { + len = strlen(fso_type_strtab[i]); + if (strncmp(str, fso_type_strtab[i], len) == 0) + return static_cast(i); + } - return static_cast(-1); + return static_cast(-1); } int mkdir_p(const char *dir, mode_t mode) { - const char *tmp = dir; - const char *orig = dir; - char *makeme; - - do { - dir = tmp + strspn(tmp, "/"); - tmp = dir + strcspn(dir, "/"); - makeme = strndup(orig, dir - orig); - if (*makeme) { - if (mkdir(makeme, mode) && errno != EEXIST) { - free(makeme); - return -1; - } - } - free(makeme); - } while (tmp != dir); - - return 0; + const char *tmp = dir; + const char *orig = dir; + char *makeme; + + do { + dir = tmp + strspn(tmp, "/"); + tmp = dir + strcspn(dir, "/"); + makeme = strndup(orig, dir - orig); + if (*makeme) { + if (mkdir(makeme, mode) && errno != EEXIST) { + free(makeme); + return -1; + } + } + free(makeme); + } while (tmp != dir); + + return 0; } int lock_fd(int fd, int wait) { - int ret; - struct flock f; - - while (1) { - f.l_type = F_WRLCK; - f.l_whence = SEEK_SET; - f.l_start = 0; - f.l_len = 0; - - if (wait) - ret = fcntl(fd, F_SETLKW, &f); - else - ret = fcntl(fd, F_SETLK, &f); - if (ret != -1) - return 0; - if (errno == EINTR) - continue; - return -1; - } + int ret; + struct flock f; + + while (1) { + f.l_type = F_WRLCK; + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; + + if (wait) + ret = fcntl(fd, F_SETLKW, &f); + else + ret = fcntl(fd, F_SETLK, &f); + if (ret != -1) + return 0; + if (errno == EINTR) + continue; + return -1; + } } int unlock_fd(int fd) { - struct flock f; - f.l_type = F_UNLCK; - f.l_whence = SEEK_SET; - f.l_start = 0; - f.l_len = 0; - return fcntl(fd, F_SETLKW, &f); + struct flock f; + f.l_type = F_UNLCK; + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; + return fcntl(fd, F_SETLKW, &f); } int copy_smacklabel(const char * /*source*/, const char * /*dest*/) { - return 0; + return 0; } int remove_file(char *path) { - struct stat path_stat; - DIR *dp; - struct dirent *d; - int status = 0; - - if (lstat(path, &path_stat) < 0) { - if (errno != ENOENT) { - ERROR("Unable to stat : %s"); - return -1; - } - } - - if (S_ISDIR(path_stat.st_mode)) { - if ((dp = opendir(path)) == NULL) { - ERROR("Unable to opendir %s", path); - return -1; - } - - while ((d = readdir(dp)) != NULL) { - char new_path[PATH_MAX]; - if (strcmp(d->d_name, ".") == 0 || - strcmp(d->d_name, "..") == 0) - continue; - - snprintf(new_path, PATH_MAX, "%s/%s", path, d->d_name); - if (remove_file(new_path) < 0) - status = -1; - } - - if (closedir(dp) < 0) { - ERROR("Unable to close dp : %s", path); - return -1; - } - - if (rmdir(path) < 0) { - ERROR("Failed to remove dir : %s, cause: %s", path, - strerror(errno)); - return -1; - } - - } else { - if (unlink(path) < 0) { - ERROR("Unable to remove %s", path); - return -1; - } - } - - return status; + struct stat path_stat; + DIR *dp; + struct dirent *d; + int status = 0; + + if (lstat(path, &path_stat) < 0) { + if (errno != ENOENT) { + ERROR("Unable to stat : %s"); + return -1; + } + } + + if (S_ISDIR(path_stat.st_mode)) { + if ((dp = opendir(path)) == NULL) { + ERROR("Unable to opendir %s", path); + return -1; + } + + while ((d = readdir(dp)) != NULL) { + char new_path[PATH_MAX]; + if (strcmp(d->d_name, ".") == 0 || + strcmp(d->d_name, "..") == 0) + continue; + + snprintf(new_path, PATH_MAX, "%s/%s", path, d->d_name); + if (remove_file(new_path) < 0) + status = -1; + } + + if (closedir(dp) < 0) { + ERROR("Unable to close dp : %s", path); + return -1; + } + + if (rmdir(path) < 0) { + ERROR("Failed to remove dir : %s, cause: %s", path, + strerror(errno)); + return -1; + } + + } else { + if (unlink(path) < 0) { + ERROR("Unable to remove %s", path); + return -1; + } + } + + return status; } int copy_file(const char *source, const char *dest, int /*flags*/) { - int ret; - FILE *sfp, *dfp; - size_t nread, nwritten, size = BUF_SIZE; - char buffer[BUF_SIZE]; - - if ((sfp = fopen(source, "r")) == NULL) { - ERROR("Unable to open source : %s", source); - return -1; - } - - if ((dfp = fopen(dest, "w+")) == NULL) { - ERROR("Unable to open destination : %s", dest); - fclose(sfp); - return -1; - } - - while (1) { - nread = fread(buffer, 1, size, sfp); - - if (nread != size && ferror(sfp)) { - ERROR("Read failed"); - return -1; - } else if (nread == 0) { - break; - } - - nwritten = fwrite(buffer, 1, nread, dfp); - - if (nwritten != nread) { - if (ferror(dfp)) - ERROR("write fail"); - else - ERROR("Unable to write all data"); - return -1; - } - } - - fclose(sfp); - fclose(dfp); - - ret = copy_smacklabel(source, dest); - if (ret != 0) { - ERROR("Unable to setting smack lable"); - return -1; - } - return 0; -} + int ret; + FILE *sfp, *dfp; + size_t nread, nwritten, size = BUF_SIZE; + char buffer[BUF_SIZE]; -int regex_compile(regex_t * r, const char *regex_text) -{ - int status = regcomp(r, regex_text, REG_EXTENDED | REG_NEWLINE); + if ((sfp = fopen(source, "r")) == NULL) { + ERROR("Unable to open source : %s", source); + return -1; + } - if (status != 0) { - char error_message[MAX_ERROR_MSG]; + if ((dfp = fopen(dest, "w+")) == NULL) { + ERROR("Unable to open destination : %s", dest); + fclose(sfp); + return -1; + } + + while (1) { + nread = fread(buffer, 1, size, sfp); + + if (nread != size && ferror(sfp)) { + ERROR("Read failed"); + return -1; + } else if (nread == 0) { + break; + } + + nwritten = fwrite(buffer, 1, nread, dfp); + + if (nwritten != nread) { + if (ferror(dfp)) + ERROR("write fail"); + else + ERROR("Unable to write all data"); + return -1; + } + } - regerror(status, r, error_message, MAX_ERROR_MSG); - DEBUG("Regex error compiling '%s': %s\n", - regex_text, error_message); - return 1; - } + fclose(sfp); + fclose(dfp); - return 0; + ret = copy_smacklabel(source, dest); + if (ret != 0) { + ERROR("Unable to setting smack lable"); + return -1; + } + return 0; } -int regex_match(regex_t * r, const char *to_match) +int regex_compile(regex_t * r, const char *regex_text) { - const char *p = to_match; - const int n_matches = 10; - regmatch_t m[n_matches]; + int status = regcomp(r, regex_text, REG_EXTENDED | REG_NEWLINE); - while (1) { - int i = 0; - int nomatch = regexec(r, p, n_matches, m, 0); + if (status != 0) { + char error_message[MAX_ERROR_MSG]; - if (nomatch) { - DEBUG("No more matches.\n"); - return nomatch; - } - - for (i = 0; i < n_matches; i++) { - int start; - int finish; - (void)start; - (void)finish; - - if (m[i].rm_so == -1) { - break; - } - - start = m[i].rm_so + (p - to_match); - finish = m[i].rm_eo + (p - to_match); - if (i == 0) { - INFO("$& is "); - } else { - INFO("$%d is ", i); - } + regerror(status, r, error_message, MAX_ERROR_MSG); + DEBUG("Regex error compiling '%s': %s\n", + regex_text, error_message); + return 1; + } - INFO("'%.*s' (bytes %d:%d)\n", (finish - start), - to_match + start, start, finish); - } + return 0; +} - p += m[0].rm_eo; - } +int regex_match(regex_t * r, const char *to_match) +{ + const char *p = to_match; + const int n_matches = 10; + regmatch_t m[n_matches]; + + while (1) { + int i = 0; + int nomatch = regexec(r, p, n_matches, m, 0); + + if (nomatch) { + DEBUG("No more matches.\n"); + return nomatch; + } + + for (i = 0; i < n_matches; i++) { + int start; + int finish; + UNUSED(start); + UNUSED(finish); + + if (m[i].rm_so == -1) { + break; + } + + start = m[i].rm_so + (p - to_match); + finish = m[i].rm_eo + (p - to_match); + if (i == 0) { + INFO("$& is "); + } else { + INFO("$%d is ", i); + } + + INFO("'%.*s' (bytes %d:%d)\n", (finish - start), + to_match + start, start, finish); + } + + p += m[0].rm_eo; + } - return 0; + return 0; } int get_peer_pid(int fd) { - struct ucred cred; - socklen_t cr_len = sizeof(cred); - if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cr_len) < 0) { - return -1; - } - return cred.pid; + struct ucred cred; + socklen_t cr_len = sizeof(cred); + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cr_len) < 0) { + return -1; + } + return cred.pid; } pid_t gettid(void) { - return syscall(__NR_gettid); + return syscall(__NR_gettid); } int set_smacklabel_fd(int fd, const char *xattr_name, const char *label) @@ -535,471 +537,434 @@ int set_smacklabel(const char *path, const char *xattr_name, const char *label) } char *get_self_smacklabel(void) { - int ret; - int fd; - const char *attr_path = "/proc/self/attr/current"; - char buffer[SMACK_LABEL_LEN+1]; - - bzero(buffer, SMACK_LABEL_LEN+1); - - fd = open(attr_path, O_RDONLY); - if( fd < 0) { - return NULL; - } - - ret = read(fd, buffer, SMACK_LABEL_LEN+1); - close(fd); - if (ret < 0) { - return NULL; - } - - if( ret > SMACK_LABEL_LEN) { - //return NULL; - } + int ret; + int fd; + const char *attr_path = "/proc/self/attr/current"; + char buffer[SMACK_LABEL_LEN+1]; + + bzero(buffer, SMACK_LABEL_LEN+1); + + fd = open(attr_path, O_RDONLY); + if( fd < 0) { + return NULL; + } + + ret = read(fd, buffer, SMACK_LABEL_LEN+1); + close(fd); + if (ret < 0) { + return NULL; + } + + if( ret > SMACK_LABEL_LEN) { + //return NULL; + } buffer[SMACK_LABEL_LEN]=0; - return strdup(buffer); + return strdup(buffer); } int get_self_cpuset(char *name, int buf_sz) { - int fd; - int lxc_len, ret; - char cpuset_path[] = "/proc/self/cpuset"; - char current_name[NAME_MAX]; - - fd = open(cpuset_path, O_RDONLY); - if (fd < 0) { - return 0; - } - - ret = read(fd, current_name, NAME_MAX - 1); - if (ret < 0) { - close(fd); - return -1; - } - - current_name[ret - 1] = '\0'; - close(fd); - - lxc_len = sizeof("/lxc"); - if( ret < lxc_len) { - name[0] = '/'; - name[1] = 0; - return 1; - } else { - char *p; - p = current_name + lxc_len; - - while(*p != '\0') { - if(*p == '/') { - *p = '\0'; - break; - } - p++; - } - snprintf(name, buf_sz, "%s", current_name+lxc_len); - } - - return ret - lxc_len; + int fd; + int lxc_len, ret; + char cpuset_path[] = "/proc/self/cpuset"; + char current_name[NAME_MAX]; + + fd = open(cpuset_path, O_RDONLY); + if (fd < 0) { + return 0; + } + + ret = read(fd, current_name, NAME_MAX - 1); + if (ret < 0) { + close(fd); + return -1; + } + + current_name[ret - 1] = '\0'; + close(fd); + + lxc_len = sizeof("/lxc"); + if( ret < lxc_len) { + name[0] = '/'; + name[1] = 0; + return 1; + } else { + char *p; + p = current_name + lxc_len; + + while(*p != '\0') { + if(*p == '/') { + *p = '\0'; + break; + } + p++; + } + snprintf(name, buf_sz, "%s", current_name+lxc_len); + } + + return ret - lxc_len; } char * get_pid_cpuset(int pid) { - int fd; - int ret; - char cpuset_path[PATH_MAX]; - char current_name[NAME_MAX]; + int fd; + int ret; + char cpuset_path[PATH_MAX]; + char current_name[NAME_MAX]; - snprintf(cpuset_path, PATH_MAX, "/proc/%d/cpuset", pid); + snprintf(cpuset_path, PATH_MAX, "/proc/%d/cpuset", pid); - ret = access(cpuset_path, F_OK | R_OK); - if( ret != 0 ) - return NULL; + ret = access(cpuset_path, F_OK | R_OK); + if( ret != 0 ) + return NULL; - fd = open(cpuset_path, O_RDONLY); - if (fd < 0) { - return NULL; - } + fd = open(cpuset_path, O_RDONLY); + if (fd < 0) { + return NULL; + } - ret = read(fd, current_name, NAME_MAX - 1); - if (ret < 0) { - close(fd); - return NULL; - } + ret = read(fd, current_name, NAME_MAX - 1); + if (ret < 0) { + close(fd); + return NULL; + } - current_name[ret - 1] = 0; - close(fd); + current_name[ret - 1] = 0; + close(fd); - INFO("cpuset path : %s, value : %s", cpuset_path, current_name); + INFO("cpuset path : %s, value : %s", cpuset_path, current_name); - return strdup(current_name); + return strdup(current_name); } char * read_namespace_link(const char *ns, int pid) { - char ns_path[PATH_MAX]; - char buf[NAME_MAX]; - int ret; + char ns_path[PATH_MAX]; + char buf[NAME_MAX]; + int ret; - snprintf(ns_path, PATH_MAX, "/proc/%d/ns/%s", pid, ns); + snprintf(ns_path, PATH_MAX, "/proc/%d/ns/%s", pid, ns); - ret = access(ns_path, F_OK); - if(ret != 0) - return NULL; + ret = access(ns_path, F_OK); + if(ret != 0) + return NULL; - ret = readlink(ns_path, buf, NAME_MAX); - if( ret == -1 ) { - ERROR("Failed to readlink ns file - [%s]", ns_path); - return NULL; - } + ret = readlink(ns_path, buf, NAME_MAX); + if( ret == -1 ) { + ERROR("Failed to readlink ns file - [%s]", ns_path); + return NULL; + } - buf[ret] = 0; + buf[ret] = 0; - INFO("Read ns link data -pid : %d data : %s", pid, buf); + INFO("Read ns link data -pid : %d data : %s", pid, buf); - return strdup(buf); + return strdup(buf); } // libs/device.c #define DEV_ITERATE_CONTINUE 0 int dev_enumerate_nodes(const char *cname, dev_enumerator enumerator, - void *data) + void *data) { - int ret; - FILE *fp;; - char path[PATH_MAX], entry[64]; + int ret; + FILE *fp;; + char path[PATH_MAX], entry[64]; - ret = snprintf(path, sizeof(path), - "/sys/fs/cgroup/devices/lxc/%s/devices.list", cname); + ret = snprintf(path, sizeof(path), + "/sys/fs/cgroup/devices/lxc/%s/devices.list", cname); - if (ret < 0) { - ERROR("Failed to make pathname"); - return -1; - } + if (ret < 0) { + ERROR("Failed to make pathname"); + return -1; + } - fp = fopen(path, "r"); - if (fp == NULL) { - ERROR("File open failed: %s(%s)", path, strerror(errno)); - return -1; - } + fp = fopen(path, "r"); + if (fp == NULL) { + ERROR("File open failed: %s(%s)", path, strerror(errno)); + return -1; + } - while (fgets(entry, sizeof(entry), fp) != NULL) { - int major, minor; - char *next, *ptr = &entry[2]; + while (fgets(entry, sizeof(entry), fp) != NULL) { + int major, minor; + char *next, *ptr = &entry[2]; - major = strtol(ptr, &next, 10); - minor = strtol(++next, (char **)NULL, 10); + major = strtol(ptr, &next, 10); + minor = strtol(++next, (char **)NULL, 10); - ret = enumerator(entry[0], major, minor, data); - if (ret != DEV_ITERATE_CONTINUE) - break; - } + ret = enumerator(entry[0], major, minor, data); + if (ret != DEV_ITERATE_CONTINUE) + break; + } - fclose(fp); + fclose(fp); - return ret; + return ret; } int dev_terminal_enumerator(int type, int major, int minor, void *data) { - int *dev = (int*)data; + int *dev = (int*)data; + + *dev = minor; + UNUSED(type); + UNUSED(major); - *dev = minor; - (void)type; - (void)major; - - INFO("Matched device: %c, %d, %d\n", type, major, minor); + INFO("Matched device: %c, %d, %d\n", type, major, minor); - return 1; + return 1; } // libs/namespace.c pid_t get_init_pid(const char *name) { - char filename[PATH_MAX]; - FILE *fp; - pid_t ret = -1; - - snprintf(filename, sizeof(filename), - "/sys/fs/cgroup/devices/lxc/%s/cgroup.procs", name); - - fp = fopen(filename, "r"); - - if (fp != NULL) { - if (fscanf(fp, "%d", &ret) < 0) { - ERROR("Failed to read %s\n", filename); - ret = -2; - } - fclose(fp); - } else { - INFO("Unable to access %s\n", filename); - ret = errno; - } + char filename[PATH_MAX]; + FILE *fp; + pid_t ret = -1; + + snprintf(filename, sizeof(filename), + "/sys/fs/cgroup/devices/lxc/%s/cgroup.procs", name); + + fp = fopen(filename, "r"); + + if (fp != NULL) { + if (fscanf(fp, "%d", &ret) < 0) { + ERROR("Failed to read %s\n", filename); + ret = -2; + } + fclose(fp); + } else { + INFO("Unable to access %s\n", filename); + ret = errno; + } - return ret; + return ret; } pid_t get_zone_pid(const char *name, const char *target) { - char path[PATH_MAX]; - char cmd[PATH_MAX]; - int res = 0, len; - pid_t ret = -1; - FILE *fp; - - char *line = NULL; - size_t line_len; - - snprintf(path, PATH_MAX, - "/sys/fs/cgroup/cpuset/lxc/%s/cgroup.procs", name); - - res = access(path, F_OK | R_OK); - if (res != 0) { - ERROR("Failed to acess zone cgroup file: %s", path); - return -EINVAL; - } - - if (target == NULL) { - ERROR("Failed to lookup cmdline in zone proc"); - return -EINVAL; - } else { - len = strlen(target); - } - - fp = fopen(path, "r"); - if (fp == NULL) { - ERROR("Failed to open zone cgroup"); - return -1; - } - - while (getline(&line, &line_len, fp) != -1) { - int res; - pid_t pid; - FILE *cmdfp; - char cmdpath[PATH_MAX]; - - res = sscanf(line, "%d", &pid); - if (res != 1) { - ERROR("Failed to read %s\n", path); - res = -1; - goto out; - } - - if (pid < 0) - continue; - - snprintf(cmdpath, PATH_MAX, "/proc/%d/cmdline", pid); - - if (access(cmdpath, F_OK | R_OK) != 0) - continue; - - cmdfp = fopen(cmdpath, "r"); - if (cmdfp == NULL) { - ERROR("Unable to access %s\n", cmdpath); - continue; - } - - if (fscanf(cmdfp, "%s", cmd) < 0) { - ERROR("Failed to read cmdline - pid : %d\n", pid); - continue; - } - - fclose(cmdfp); - - if (strncmp(cmd, target, len) == 0) { - ret = pid; - break; - } - } + char path[PATH_MAX]; + char cmd[PATH_MAX]; + int res = 0, len; + pid_t ret = -1; + FILE *fp; + + char *line = NULL; + size_t line_len; + + snprintf(path, PATH_MAX, + "/sys/fs/cgroup/cpuset/lxc/%s/cgroup.procs", name); + + res = access(path, F_OK | R_OK); + if (res != 0) { + ERROR("Failed to acess zone cgroup file: %s", path); + return -EINVAL; + } + + if (target == NULL) { + ERROR("Failed to lookup cmdline in zone proc"); + return -EINVAL; + } else { + len = strlen(target); + } + + fp = fopen(path, "r"); + if (fp == NULL) { + ERROR("Failed to open zone cgroup"); + return -1; + } + + while (getline(&line, &line_len, fp) != -1) { + int res; + pid_t pid; + FILE *cmdfp; + char cmdpath[PATH_MAX]; + + res = sscanf(line, "%d", &pid); + if (res != 1) { + ERROR("Failed to read %s\n", path); + res = -1; + goto out; + } + + if (pid < 0) + continue; + + snprintf(cmdpath, PATH_MAX, "/proc/%d/cmdline", pid); + + if (access(cmdpath, F_OK | R_OK) != 0) + continue; + + cmdfp = fopen(cmdpath, "r"); + if (cmdfp == NULL) { + ERROR("Unable to access %s\n", cmdpath); + continue; + } + + if (fscanf(cmdfp, "%s", cmd) < 0) { + ERROR("Failed to read cmdline - pid : %d\n", pid); + continue; + } + + fclose(cmdfp); + + if (strncmp(cmd, target, len) == 0) { + ret = pid; + break; + } + } out: - fclose(fp); - return ret; + fclose(fp); + return ret; } int open_ns(pid_t pid, const char *name) { - int fd, ret; - char path[PATH_MAX]; + int fd, ret; + char path[PATH_MAX]; - ret = snprintf(path, PATH_MAX, "/proc/%d/ns/%s", pid, name); - if (ret < 0 || ret >= PATH_MAX) { - ERROR("Failed to namespace - pid %d, ns: %s ", pid, name); - return -EINVAL; - } + ret = snprintf(path, PATH_MAX, "/proc/%d/ns/%s", pid, name); + if (ret < 0 || ret >= PATH_MAX) { + ERROR("Failed to namespace - pid %d, ns: %s ", pid, name); + return -EINVAL; + } - fd = open(path, O_RDONLY); - if (fd < 0) { - ERROR("failed to open %s\n", path); - return -errno; - } + fd = open(path, O_RDONLY); + if (fd < 0) { + ERROR("failed to open %s\n", path); + return -errno; + } - return fd; + return fd; } -/* -void enter_to_ns(pid_t pid, char *name) -{ - int newns; - char *ns[] = { "mnt", "pid", "uts", "ipc", "net" }; - int flags[] = { - CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, CLONE_NEWIPC, - CLONE_NEWNET - }; - int size = sizeof(ns) / sizeof(char *); - int i, idx = size; - - for (i = 0; i < size; i++) { - if (strncmp(ns[i], name, strlen(ns[i])) == 0) { - idx = i; - break; - } - } - - if (idx == size) { - ERROR("Invalid namespace - ns: %s", name); - return; - } - - newns = open_ns(pid, ns[i]); - - if (setns(newns, flags[i])) { - ERROR("failed to setns"); - close(newns); - return; - } - - INFO("Enter namespace - init: %d , ns: %s", pid, name); - - close(newns); - return; -}*/ // vasum/libs/vt.c #include #include static int is_console(int fd) { - char arg; + char arg; - return (isatty(fd) && - (ioctl(fd, KDGKBTYPE, &arg) == 0) && - ((arg == KB_101) || (arg == KB_84))); + return (isatty(fd) && + (ioctl(fd, KDGKBTYPE, &arg) == 0) && + ((arg == KB_101) || (arg == KB_84))); } static int open_console(const char *path) { - int fd; + int fd; - fd = open(path, O_RDWR); - if (fd < 0) { - fd = open(path, O_WRONLY); - } - if (fd < 0) { - fd = open(path, O_RDONLY); - } - if (fd < 0) { - return -1; - } + fd = open(path, O_RDWR); + if (fd < 0) { + fd = open(path, O_WRONLY); + } + if (fd < 0) { + fd = open(path, O_RDONLY); + } + if (fd < 0) { + return -1; + } - return fd; + return fd; } int get_console_fd(const char *path) { - int fd; + int fd; - if (path) { - fd = open_console(path); - if (fd >= 0) { - return fd; - } + if (path) { + fd = open_console(path); + if (fd >= 0) { + return fd; + } - return -1; - } + return -1; + } - fd = open_console("/dev/tty0"); - if (fd >= 0) { - return fd; - } + fd = open_console("/dev/tty0"); + if (fd >= 0) { + return fd; + } - fd = open_console("/dev/console"); - if (fd >= 0) { - return fd; - } + fd = open_console("/dev/console"); + if (fd >= 0) { + return fd; + } - for (fd = 0; fd < 3; fd++) { - if (is_console(fd)) { - return fd; - } - } + for (fd = 0; fd < 3; fd++) { + if (is_console(fd)) { + return fd; + } + } - return -1; + return -1; } int vt_switch_terminal(int id) { - int fd, ret = -1; + int fd, ret = -1; - fd = get_console_fd(NULL); - if (fd < 0) { - return -1; - } + fd = get_console_fd(NULL); + if (fd < 0) { + return -1; + } - if (ioctl(fd, VT_ACTIVATE, id) < 0) { - goto out; - } + if (ioctl(fd, VT_ACTIVATE, id) < 0) { + goto out; + } - if (ioctl(fd, VT_WAITACTIVE, id) < 0) { - goto out; - } + if (ioctl(fd, VT_WAITACTIVE, id) < 0) { + goto out; + } - ret = 0; + ret = 0; out: - close(fd); - return ret; + close(fd); + return ret; } int vt_find_unused_terminal(void) { - int fd, nr = -1; + int fd, nr = -1; - fd = get_console_fd(NULL); - if (fd < 0) { - perror("Terminal open failed"); - return -1; - } + fd = get_console_fd(NULL); + if (fd < 0) { + perror("Terminal open failed"); + return -1; + } - if (ioctl(fd, VT_OPENQRY, &nr) < 0) { - perror("VT_OPENQRY failed"); - goto out; - } + if (ioctl(fd, VT_OPENQRY, &nr) < 0) { + perror("VT_OPENQRY failed"); + goto out; + } out: - close(fd); + close(fd); - return nr; + return nr; } int vt_query_active_terminal(void) { - int fd, ret = -1; - struct vt_stat vtstat; + int fd, ret = -1; + struct vt_stat vtstat; - fd = get_console_fd(NULL); - if (fd < 0) { - return -1; - } + fd = get_console_fd(NULL); + if (fd < 0) { + return -1; + } - if (ioctl(fd, VT_GETSTATE, &vtstat) < 0) { - goto out; - } + if (ioctl(fd, VT_GETSTATE, &vtstat) < 0) { + goto out; + } - ret = vtstat.v_active; + ret = vtstat.v_active; out: - close(fd); - return ret; + close(fd); + return ret; } // libs/parser.h @@ -1014,565 +979,565 @@ struct unit_parser { int parse_stream(const char *name, struct unit_parser *parser); // libs/parser.c -#define PARSER_MAXARGS 32 +#define PARSER_MAXARGS 32 #define T_EOF 1 #define T_STATEMENT 2 -#define T_ARGUMENT 3 +#define T_ARGUMENT 3 #define T_NEWLINE 7 #define T_NEWBLOCK 8 struct parser_context { - struct unit_keyword_callback *kw; + struct unit_keyword_callback *kw; }; struct parser_state { - char *ptr; - char *stmt; - int line; - int nexttoken; - void *context; + char *ptr; + char *stmt; + int line; + int nexttoken; + void *context; }; static void parser_init_state(struct parser_state *state, char *line) { - state->line = 1; - state->ptr = line; - state->nexttoken = 0; + state->line = 1; + state->ptr = line; + state->nexttoken = 0; state->stmt = NULL; state->context = NULL; } static struct unit_keyword_callback *keyword_lookup(struct parser_context *ctx, - const char *kw) + const char *kw) { - int i; + int i; - for (i = 0; ctx->kw[i].name != NULL; i++) { - if (!strcmp(ctx->kw[i].name, kw)) { - return &ctx->kw[i]; - } - } + for (i = 0; ctx->kw[i].name != NULL; i++) { + if (!strcmp(ctx->kw[i].name, kw)) { + return &ctx->kw[i]; + } + } - return NULL; + return NULL; } static int tokenize(struct parser_state *state) { - char *x = state->ptr; - char *s, *ss; + char *x = state->ptr; + char *s, *ss; - if (state->nexttoken) { - int t = state->nexttoken; - state->nexttoken = 0; - return t; - } + if (state->nexttoken) { + int t = state->nexttoken; + state->nexttoken = 0; + return t; + } retry: - state->stmt = s = x; - ss = x + 1; + state->stmt = s = x; + ss = x + 1; resume: - while (1) { - switch (*x) { - case 0: - state->nexttoken = T_EOF; - goto textdone; - case '\\': - x++; - switch (*x) { - case 0: - goto textdone; - case 'n': - *s++ = '\n'; - break; - case 'r': - *s++ = '\r'; - break; - case 't': - *s++ = '\t'; - break; - case '\\': - *s++ = '\\'; - break; - case '\r': - /* \ -> line continuation */ - if (x[1] != '\n') { - x++; - continue; - } - case '\n': - /* \ -> line continuation */ - state->line++; - x++; - /* eat any extra whitespace */ - while ((*x == ' ') || (*x == '\t')) - x++; - continue; - default: - /* unknown escape -- just copy */ - *s++ = *x++; - } - continue; - case ',': - x++; - goto textdone; - case '=': - x++; - if (ss == x) { - goto retry; - } - goto textdone; - case ' ': - case '\t': - case '\r': - x++; - if (ss == x) { - goto retry; - } - goto textdone; - case '\n': - x++; - if (ss == x) { - state->ptr = x; - return T_NEWLINE; - } - state->nexttoken = T_NEWLINE; - goto textdone; - case '\'': - case '"': - x++; - for (;;) { - switch (*x) { - case 0: - /* unterminated quoted thing */ - state->ptr = x; - return T_EOF; - case '\'': - case '"': - x++; - goto resume; - default: - *s++ = *x++; - } - } - break; - case '[': - x++; - goto resume; - case ']': - x++; - goto resume; - case '#': - while (*x && (*x != '\n')) - x++; - if (*x == '\n') { - state->ptr = x + 1; - return T_NEWLINE; - } else { - state->ptr = x; - return T_EOF; - } - break; - default: - *s++ = *x++; - } - } + while (1) { + switch (*x) { + case 0: + state->nexttoken = T_EOF; + goto textdone; + case '\\': + x++; + switch (*x) { + case 0: + goto textdone; + case 'n': + *s++ = '\n'; + break; + case 'r': + *s++ = '\r'; + break; + case 't': + *s++ = '\t'; + break; + case '\\': + *s++ = '\\'; + break; + case '\r': + /* \ -> line continuation */ + if (x[1] != '\n') { + x++; + continue; + } + case '\n': + /* \ -> line continuation */ + state->line++; + x++; + /* eat any extra whitespace */ + while ((*x == ' ') || (*x == '\t')) + x++; + continue; + default: + /* unknown escape -- just copy */ + *s++ = *x++; + } + continue; + case ',': + x++; + goto textdone; + case '=': + x++; + if (ss == x) { + goto retry; + } + goto textdone; + case ' ': + case '\t': + case '\r': + x++; + if (ss == x) { + goto retry; + } + goto textdone; + case '\n': + x++; + if (ss == x) { + state->ptr = x; + return T_NEWLINE; + } + state->nexttoken = T_NEWLINE; + goto textdone; + case '\'': + case '"': + x++; + for (;;) { + switch (*x) { + case 0: + /* unterminated quoted thing */ + state->ptr = x; + return T_EOF; + case '\'': + case '"': + x++; + goto resume; + default: + *s++ = *x++; + } + } + break; + case '[': + x++; + goto resume; + case ']': + x++; + goto resume; + case '#': + while (*x && (*x != '\n')) + x++; + if (*x == '\n') { + state->ptr = x + 1; + return T_NEWLINE; + } else { + state->ptr = x; + return T_EOF; + } + break; + default: + *s++ = *x++; + } + } textdone: - state->ptr = x; - *s = 0; - return T_STATEMENT; + state->ptr = x; + *s = 0; + return T_STATEMENT; } static int parse_statement(struct parser_context *ctx, int argc, char **argv, - int (*func) (int argc, char **argv)) + int (*func) (int argc, char **argv)) { - struct parser_state state; - char *args[PARSER_MAXARGS]; - int i, nargs, done, rc; - int ret = 0; - (void)ctx; - - for (i = 0; i < argc; i++) { - done = nargs = 0; - parser_init_state(&state, argv[i]); - - while (!done) { - int token = tokenize(&state); - switch (token) { - case T_EOF: - if (nargs && func) { - rc = func(nargs, args); - if (rc < 0) { - WARN("Key word callback error"); - } - nargs = 0; - } - done = 1; - break; - case T_STATEMENT: - if (nargs < PARSER_MAXARGS) { - args[nargs++] = state.stmt; - } - break; - } - } - } - - return ret; + struct parser_state state; + char *args[PARSER_MAXARGS]; + int i, nargs, done, rc; + int ret = 0; + UNUSED(ctx); + + for (i = 0; i < argc; i++) { + done = nargs = 0; + parser_init_state(&state, argv[i]); + + while (!done) { + int token = tokenize(&state); + switch (token) { + case T_EOF: + if (nargs && func) { + rc = func(nargs, args); + if (rc < 0) { + WARN("Key word callback error"); + } + nargs = 0; + } + done = 1; + break; + case T_STATEMENT: + if (nargs < PARSER_MAXARGS) { + args[nargs++] = state.stmt; + } + break; + } + } + } + + return ret; } int parse_stream_core(struct parser_context *ctx, char *s) { - struct unit_keyword_callback *kw; - struct parser_state state; - char *args[PARSER_MAXARGS]; - int nargs, rc; - - nargs = 0; - parser_init_state(&state, s); - - for (;;) { - int token = tokenize(&state); - switch (token) { - case T_EOF: - return 0; - case T_NEWLINE: - if (nargs) { - if ((kw = keyword_lookup(ctx, args[0])) != NULL) { - rc = parse_statement(ctx, nargs - 1, - &args[1], - kw->func); - if (rc < 0) { - return -EINVAL; - } - } - - nargs = 0; - } - break; - case T_STATEMENT: - if (nargs < PARSER_MAXARGS) { - args[nargs++] = state.stmt; - } - break; - } - } - - return 0; + struct unit_keyword_callback *kw; + struct parser_state state; + char *args[PARSER_MAXARGS]; + int nargs, rc; + + nargs = 0; + parser_init_state(&state, s); + + for (;;) { + int token = tokenize(&state); + switch (token) { + case T_EOF: + return 0; + case T_NEWLINE: + if (nargs) { + if ((kw = keyword_lookup(ctx, args[0])) != NULL) { + rc = parse_statement(ctx, nargs - 1, + &args[1], + kw->func); + if (rc < 0) { + return -EINVAL; + } + } + + nargs = 0; + } + break; + case T_STATEMENT: + if (nargs < PARSER_MAXARGS) { + args[nargs++] = state.stmt; + } + break; + } + } + + return 0; } /* reads a file, making sure it is terminated with \n \0 */ static char *open_stream(const char *name, unsigned int *_sz) { - int sz, fd; - char *data = NULL; + int sz, fd; + char *data = NULL; - fd = open(name, O_RDONLY); - if (fd < 0) - return NULL; + fd = open(name, O_RDONLY); + if (fd < 0) + return NULL; - sz = lseek(fd, 0, SEEK_END); - if (sz < 0) - goto oops; + sz = lseek(fd, 0, SEEK_END); + if (sz < 0) + goto oops; - if (lseek(fd, 0, SEEK_SET) != 0) - goto oops; + if (lseek(fd, 0, SEEK_SET) != 0) + goto oops; - data = (char *)malloc(sz + 2); - if (data == 0) - goto oops; + data = (char *)malloc(sz + 2); + if (data == 0) + goto oops; - if (read(fd, data, sz) != sz) - goto oops; + if (read(fd, data, sz) != sz) + goto oops; - close(fd); + close(fd); - data[sz] = '\n'; - data[sz + 1] = 0; - if (_sz) - *_sz = sz; + data[sz] = '\n'; + data[sz + 1] = 0; + if (_sz) + *_sz = sz; - return data; + return data; oops: - close(fd); - if (data != 0) - free(data); + close(fd); + if (data != 0) + free(data); - return NULL; + return NULL; } int parse_stream(const char *name, struct unit_parser *parser) { - char *stream; - struct parser_context *ctx; + char *stream; + struct parser_context *ctx; - ctx = (struct parser_context *)malloc(sizeof(struct parser_context)); - if (ctx == NULL) { - return -ENOMEM; - } + ctx = (struct parser_context *)malloc(sizeof(struct parser_context)); + if (ctx == NULL) { + return -ENOMEM; + } - ctx->kw = parser->kw; + ctx->kw = parser->kw; - /* File open & return file context */ - stream = open_stream(name, NULL); - if (stream == NULL) { - free(ctx); - return -1; - } + /* File open & return file context */ + stream = open_stream(name, NULL); + if (stream == NULL) { + free(ctx); + return -1; + } - parse_stream_core(ctx, stream); + parse_stream_core(ctx, stream); - free(stream); - free(ctx); + free(stream); + free(ctx); - return 0; + return 0; } // dummy-ops static int dummy_create_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, - const char * /*template*/, int /*flags*/) + const char * /*template*/, int /*flags*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_destroy_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*force*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_start_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_shutdown_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*force*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_lock_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/, int /*shutdown*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_unlock_zone(vsm_context_h /*ctx*/, const char * /*zone_name*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_set_foreground(vsm_zone_h zone) { - if (zone == NULL) - return -VSM_ERROR_INVALID; + if (zone == NULL) + return -VSM_ERROR_INVALID; - if (zone->parent == zone) { - return VSM_ERROR_NONE; - } - return -VSM_ERROR_NO_OBJECT; + if (zone->parent == zone) { + return VSM_ERROR_NONE; + } + return -VSM_ERROR_NO_OBJECT; } static vsm_zone_h dummy_get_foreground(vsm_context_h ctx) { - if (ctx == NULL) { - errno = EINVAL; - return NULL; - } + if (ctx == NULL) { + errno = EINVAL; + return NULL; + } - return ctx->root_zone; + return ctx->root_zone; } static int dummy_iterate_zone(vsm_context_h ctx, vsm_zone_iter_cb callback, void *user_data) { - if( callback) { - callback(ctx->root_zone, user_data); - } - return VSM_ERROR_NONE; + if( callback) { + callback(ctx->root_zone, user_data); + } + return VSM_ERROR_NONE; } static vsm_zone_h dummy_lookup_zone_by_name(vsm_context_h ctx, const char *name) { - if (strcmp(name, "") != 0) { - errno = ESRCH; - return NULL; - } + if (strcmp(name, "") != 0) { + errno = ESRCH; + return NULL; + } - return ctx->root_zone; + return ctx->root_zone; } static vsm_zone_h dummy_lookup_zone_by_pid(vsm_context_h ctx, pid_t /*pid*/) { - if (ctx == NULL) - return NULL; + if (ctx == NULL) + return NULL; - return ctx->root_zone; + return ctx->root_zone; } static int dummy_attach_zone(vsm_context_h ctx, const char *zone_name, - vsm_attach_command_s * command, - vsm_attach_options_s * opts, - pid_t * attached_process) + vsm_attach_command_s * command, + vsm_attach_options_s * opts, + pid_t * attached_process) { - pid_t pid; - struct vsm_attach_options_s options; - - if (command == NULL || command->exec == NULL || zone_name == NULL) { - ERROR("Invalid arguments"); - ctx->error = VSM_ERROR_INVALID; - return -VSM_ERROR_INVALID; - } - - if (strcmp("", zone_name) != 0) { - ctx->error = VSM_ERROR_INVALID; - return -VSM_ERROR_INVALID; - } - - if (opts == NULL) { - opts = &options; - opts->uid = getuid(); - opts->gid = getgid(); - opts->env_num = 0; - opts->extra_env = NULL; - } - - pid = fork(); - if (pid == 0) { - if (opts->extra_env != NULL) { - while (*opts->extra_env) - putenv(*opts->extra_env++); - } - - if (getuid() == 0 && opts->uid != 0) { - if (setuid(opts->uid) != 0) { - ERROR("Failed to set uid : %d", opts->uid); - } - } else { - WARN("setuid() is not permitted"); - } - - if (getgid() == 0 && opts->gid != 0) { - if (setgid(opts->gid) != 0) { - ERROR("Failed to set gid : %d", opts->gid); - } - } else { - WARN("setgid() is not permitted"); - } - - if (execvp(command->exec, command->argv) < 0) { - ERROR("exevp failed : %s, %s", command->exec, - strerror(errno)); - exit(EXIT_FAILURE); - } - } else { - *attached_process = pid; - } - - return VSM_ERROR_NONE; + pid_t pid; + struct vsm_attach_options_s options; + + if (command == NULL || command->exec == NULL || zone_name == NULL) { + ERROR("Invalid arguments"); + ctx->error = VSM_ERROR_INVALID; + return -VSM_ERROR_INVALID; + } + + if (strcmp("", zone_name) != 0) { + ctx->error = VSM_ERROR_INVALID; + return -VSM_ERROR_INVALID; + } + + if (opts == NULL) { + opts = &options; + opts->uid = getuid(); + opts->gid = getgid(); + opts->env_num = 0; + opts->extra_env = NULL; + } + + pid = fork(); + if (pid == 0) { + if (opts->extra_env != NULL) { + while (*opts->extra_env) + putenv(*opts->extra_env++); + } + + if (getuid() == 0 && opts->uid != 0) { + if (setuid(opts->uid) != 0) { + ERROR("Failed to set uid : %d", opts->uid); + } + } else { + WARN("setuid() is not permitted"); + } + + if (getgid() == 0 && opts->gid != 0) { + if (setgid(opts->gid) != 0) { + ERROR("Failed to set gid : %d", opts->gid); + } + } else { + WARN("setgid() is not permitted"); + } + + if (execvp(command->exec, command->argv) < 0) { + ERROR("exevp failed : %s, %s", command->exec, + strerror(errno)); + exit(EXIT_FAILURE); + } + } else { + *attached_process = pid; + } + + return VSM_ERROR_NONE; } static int dummy_attach_zone_wait(vsm_context_h ctx, const char *zone_name, - vsm_attach_command_s * command, - vsm_attach_options_s * opts) + vsm_attach_command_s * command, + vsm_attach_options_s * opts) { - pid_t pid=0; - int ret, status; + pid_t pid=0; + int ret, status; - ret = dummy_attach_zone(ctx, zone_name, command, opts, &pid); - if (ret != VSM_ERROR_NONE) { - ERROR("API Failed."); - return ret; - } + ret = dummy_attach_zone(ctx, zone_name, command, opts, &pid); + if (ret != VSM_ERROR_NONE) { + ERROR("API Failed."); + return ret; + } - status = wait_for_pid_status(pid); - if (status == -1) { - ctx->error = VSM_ERROR_GENERIC; - return -VSM_ERROR_GENERIC; - } + status = wait_for_pid_status(pid); + if (status == -1) { + ctx->error = VSM_ERROR_GENERIC; + return -VSM_ERROR_GENERIC; + } - INFO("attached process extied : pid - %d, exit code : %d", pid, - WEXITSTATUS(status)); + INFO("attached process extied : pid - %d, exit code : %d", pid, + WEXITSTATUS(status)); - return status; + return status; } static vsm_zone_h dummy_join_zone(vsm_zone_h zone) { - if (zone == NULL) { - errno = EINVAL; - return NULL; - } - if (zone != zone->parent) { - errno = EINVAL; - return NULL; - } + if (zone == NULL) { + errno = EINVAL; + return NULL; + } + if (zone != zone->parent) { + errno = EINVAL; + return NULL; + } - return zone; + return zone; } static int dummy_is_equivalent_zone(vsm_context_h /*ctx*/, pid_t /*pid*/) { - return 1; + return 1; } static int dummy_get_host_pid(vsm_zone_h zone, pid_t pid) { - if(zone == zone->parent) - return pid; + if(zone == zone->parent) + return pid; - return -VSM_ERROR_NO_OBJECT; + return -VSM_ERROR_NO_OBJECT; } static int dummy_grant_device(vsm_zone_h /*zone*/, const char * /*path*/, uint32_t /*flags*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_revoke_device(vsm_zone_h /*zone*/, const char * /*path*/) { - return -VSM_ERROR_NOT_SUPPORTED; + return -VSM_ERROR_NOT_SUPPORTED; } static int dummy_declare_file(vsm_context_h /*ctx*/, vsm_fso_type_t /*ftype*/, - const char * /*path*/, int /*flags*/, vsm_mode_t /*mode*/) + const char * /*path*/, int /*flags*/, vsm_mode_t /*mode*/) { - return VSM_ERROR_NONE; + return VSM_ERROR_NONE; } static int dummy_declare_link(vsm_context_h /*ctx*/, const char *source, - const char * /*target*/) + const char * /*target*/) { - int ret; + int ret; - ret = access(source, F_OK); - if (ret != 0) - return -VSM_ERROR_NO_OBJECT; + ret = access(source, F_OK); + if (ret != 0) + return -VSM_ERROR_NO_OBJECT; - return VSM_ERROR_NONE; + return VSM_ERROR_NONE; } struct vasum_ops dummy_ops; static int dummy_ops_init(){ - dummy_ops.create_zone = dummy_create_zone; - dummy_ops.destroy_zone = dummy_destroy_zone; - dummy_ops.start_zone = dummy_start_zone; - dummy_ops.shutdown_zone = dummy_shutdown_zone; - dummy_ops.lock_zone = dummy_lock_zone; - dummy_ops.unlock_zone = dummy_unlock_zone; - dummy_ops.set_foreground = dummy_set_foreground; - dummy_ops.get_foreground = dummy_get_foreground; - dummy_ops.iterate_zone = dummy_iterate_zone; - dummy_ops.lookup_zone_by_name = dummy_lookup_zone_by_name; - dummy_ops.lookup_zone_by_pid = dummy_lookup_zone_by_pid; - dummy_ops.attach_zone = dummy_attach_zone; - dummy_ops.attach_zone_wait = dummy_attach_zone_wait; - dummy_ops.join_zone = dummy_join_zone; - dummy_ops.is_equivalent_zone = dummy_is_equivalent_zone; - dummy_ops.get_host_pid = dummy_get_host_pid; - dummy_ops.grant_device = dummy_grant_device; - dummy_ops.revoke_device = dummy_revoke_device; - dummy_ops.declare_file = dummy_declare_file; - dummy_ops.declare_link = dummy_declare_link; + dummy_ops.create_zone = dummy_create_zone; + dummy_ops.destroy_zone = dummy_destroy_zone; + dummy_ops.start_zone = dummy_start_zone; + dummy_ops.shutdown_zone = dummy_shutdown_zone; + dummy_ops.lock_zone = dummy_lock_zone; + dummy_ops.unlock_zone = dummy_unlock_zone; + dummy_ops.set_foreground = dummy_set_foreground; + dummy_ops.get_foreground = dummy_get_foreground; + dummy_ops.iterate_zone = dummy_iterate_zone; + dummy_ops.lookup_zone_by_name = dummy_lookup_zone_by_name; + dummy_ops.lookup_zone_by_pid = dummy_lookup_zone_by_pid; + dummy_ops.attach_zone = dummy_attach_zone; + dummy_ops.attach_zone_wait = dummy_attach_zone_wait; + dummy_ops.join_zone = dummy_join_zone; + dummy_ops.is_equivalent_zone = dummy_is_equivalent_zone; + dummy_ops.get_host_pid = dummy_get_host_pid; + dummy_ops.grant_device = dummy_grant_device; + dummy_ops.revoke_device = dummy_revoke_device; + dummy_ops.declare_file = dummy_declare_file; + dummy_ops.declare_link = dummy_declare_link; return 0; } int dummy_ops_init_i = dummy_ops_init(); diff --git a/client/wrapper-compat.h b/client/wrapper-compat.h index 90b44fb..2527289 100644 --- a/client/wrapper-compat.h +++ b/client/wrapper-compat.h @@ -130,45 +130,6 @@ typedef enum { ML_EVT_ET = EPOLLET }mainloop_event; -typedef struct vsm_context { - struct mxe_endpoint *signal_channel; - struct mxe_endpoint *manage_method_channel; - struct mxe_endpoint *unpriv_method_channel; - vsm_error_e error; - pthread_rwlock_t lock; - struct adt_list listeners; - struct vsm_zone *root_zone; - struct vsm_zone *foreground_zone; - struct adt_list sc_listeners; - struct adt_list ev_listeners; - const struct vasum_ops *vsm_ops; -} vsm_context_s; - -typedef struct vsm_zone { - struct vsm_zone *parent; - char *name; - char *type; - int terminal; - vsm_zone_state_t state; - char *rootfs_path; - pthread_rwlock_t lock; - struct adt_list children; - struct adt_list devices; - struct adt_list netdevs; - void *user_data; - struct adt_list list; - struct vsm_context *ctx; - int id; -} vsm_zone_s; - -typedef struct vsm_netdev { - struct vsm_zone *zone; - char *name; - vsm_netdev_type_t type; - struct adt_list list; -} vsm_netdev_s; - - typedef int (*dev_enumerator)(int type, int major, int minor, void *data); typedef int (*mainloop_callback)(int fd, mainloop_event event, void *data, struct mainloop *mainloop); diff --git a/packaging/vasum.spec b/packaging/vasum.spec index d2c7fe0..606f535 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -154,6 +154,7 @@ Development package including the header files for the client library %{_libdir}/libvasum-client.so %{_libdir}/libvasum.so %{_includedir}/vasum +%{_libdir}/pkgconfig/vasum-client.pc %{_libdir}/pkgconfig/vasum.pc -- 2.7.4 From 762750f4833dc0c3da55e07a55767eed5562393f Mon Sep 17 00:00:00 2001 From: Krzysztof Dynowski Date: Tue, 12 May 2015 15:05:13 +0200 Subject: [PATCH 12/16] Vasum wrapper #4, cleanup [Bug/Feature] Cleanup folder structure [Cause] wrapper mixed with client [Solution] #4 move wrapper sources to separate folder [Verification] Build, build old clients Change-Id: I467e12d996e2c23ce0e46182c7e3d74ea2943ada --- CMakeLists.txt | 2 + client/CMakeLists.txt | 33 ++-------- tests/unit_tests/CMakeLists.txt | 2 - wrapper/CMakeLists.txt | 76 ++++++++++++++++++++++ {client => wrapper}/vasum.h | 0 {client => wrapper}/vasum.pc.in | 0 {client => wrapper}/vasum_list.h | 0 .../wrapper-compatibility.cpp | 2 +- .../wrapper-compatibility.h | 0 client/vasum-wrapper.cpp => wrapper/wrapper.cpp | 6 +- 10 files changed, 87 insertions(+), 34 deletions(-) create mode 100644 wrapper/CMakeLists.txt rename {client => wrapper}/vasum.h (100%) rename {client => wrapper}/vasum.pc.in (100%) rename {client => wrapper}/vasum_list.h (100%) rename client/wrapper-compat.cpp => wrapper/wrapper-compatibility.cpp (99%) rename client/wrapper-compat.h => wrapper/wrapper-compatibility.h (100%) rename client/vasum-wrapper.cpp => wrapper/wrapper.cpp (99%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 05fbc53..a0b6b1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -148,6 +148,7 @@ SET(ZONE_SUPPORT_FOLDER ${PROJECT_SOURCE_DIR}/zone-support) SET(ZONE_DAEMON_FOLDER ${PROJECT_SOURCE_DIR}/zone-daemon) SET(TESTS_FOLDER ${PROJECT_SOURCE_DIR}/tests) SET(CLI_FOLDER ${PROJECT_SOURCE_DIR}/cli) +SET(WRAPPER_FOLDER ${PROJECT_SOURCE_DIR}/wrapper) IF(NOT DEFINED SYSCONF_INSTALL_DIR) SET(SYSCONF_INSTALL_DIR "/etc") @@ -190,4 +191,5 @@ ADD_SUBDIRECTORY(${ZONE_SUPPORT_FOLDER}) ADD_SUBDIRECTORY(${ZONE_DAEMON_FOLDER}) ADD_SUBDIRECTORY(${TESTS_FOLDER}) ADD_SUBDIRECTORY(${CLI_FOLDER}) +ADD_SUBDIRECTORY(${WRAPPER_FOLDER}) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 253a19e..9b1d890 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -17,20 +17,10 @@ # @author Mateusz Malicki (m.malicki2@samsung.com) # +PROJECT(vasum-client) MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") -## set client library sources (without wrapper files) FILE(GLOB project_SRCS *.cpp *.hpp *.h) -FILE(GLOB project_SRCS_rm vasum-wrapper.cpp - wrapper-compat.* - vasum.h - vasum_list.h) -LIST(REMOVE_ITEM project_SRCS ${project_SRCS_rm}) - -## set wrapper library sources (without vasum-client.cpp) -FILE(GLOB wrapper_SRCS *.cpp *.hpp *.h) -FILE(GLOB wrapper_SRCS_rm vasum-client.cpp) -LIST(REMOVE_ITEM wrapper_SRCS ${wrapper_SRCS_rm}) FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp ${COMMON_FOLDER}/ipc/*.hpp ${COMMON_FOLDER}/ipc/*.cpp @@ -38,10 +28,8 @@ FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER} ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/utils/*.cpp ${COMMON_FOLDER}/*.hpp ${COMMON_FOLDER}/*.cpp) -## set version highier then vasum.so.0.1.0 SET(_LIB_VERSION_ "${VERSION}") SET(_LIB_SOVERSION_ "0") -SET(PC_FILE_CLIENT "${PROJECT_NAME}-client.pc") SET(PC_FILE "${PROJECT_NAME}.pc") ## Set the default ELF image symbol visibility to hidden. Using this feature @@ -51,13 +39,7 @@ SET(PC_FILE "${PROJECT_NAME}.pc") ADD_DEFINITIONS(-fvisibility=hidden) ## Setup target ################################################################ -ADD_LIBRARY(${PROJECT_NAME}-client SHARED ${project_SRCS} ${common_SRCS}) -SET_TARGET_PROPERTIES(${PROJECT_NAME}-client PROPERTIES - SOVERSION ${_LIB_SOVERSION_} - VERSION ${_LIB_VERSION_} - COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") - -ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS} ${common_SRCS}) +ADD_LIBRARY(${PROJECT_NAME} SHARED ${project_SRCS} ${common_SRCS}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${_LIB_SOVERSION_} VERSION ${_LIB_VERSION_} @@ -70,23 +52,20 @@ INCLUDE_DIRECTORIES(SYSTEM ${LIB_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${COMMON_FOLDER}) INCLUDE_DIRECTORIES(${LIBS_FOLDER}) INCLUDE_DIRECTORIES(${SERVER_FOLDER}) -TARGET_LINK_LIBRARIES(${PROJECT_NAME}-client ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} - Config SimpleDbus) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} Config SimpleDbus) ## Generate the pc file ######################################################## -CONFIGURE_FILE(${PC_FILE_CLIENT}.in ${CMAKE_BINARY_DIR}/${PC_FILE_CLIENT} @ONLY) CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_BINARY_DIR}/${PC_FILE} @ONLY) ## Install ##################################################################### -INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE_CLIENT} ${CMAKE_BINARY_DIR}/${PC_FILE} +INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE} DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) -INSTALL(TARGETS ${PROJECT_NAME}-client ${PROJECT_NAME} +INSTALL(TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT RuntimeLibraries) -INSTALL(FILES vasum-client.h vasum.h vasum_list.h - DESTINATION ${INCLUDE_INSTALL_DIR}/${PROJECT_NAME}) +INSTALL(FILES vasum-client.h + DESTINATION ${INCLUDE_INSTALL_DIR}/vasum) diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 65646ea..889dd91 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -23,8 +23,6 @@ FILE(GLOB_RECURSE project_SRCS *.cpp *.hpp) FILE(GLOB_RECURSE common_SRCS ${COMMON_FOLDER}/*.cpp ${COMMON_FOLDER}/*.hpp) FILE(GLOB server_SRCS ${SERVER_FOLDER}/*.cpp ${SERVER_FOLDER}/*.hpp) FILE(GLOB client_SRCS ${CLIENT_FOLDER}/*.cpp ${CLIENT_FOLDER}/*.h) -FILE(GLOB client_SRCS_rm ${CLIENT_FOLDER}/vasum-wrapper*.cpp) -LIST(REMOVE_ITEM client_SRCS ${client_SRCS_rm}) FILE(GLOB socket_test_SRCS ${SOCKET_TEST_FOLDER}/*.cpp ${SOCKET_TEST_FOLDER}/*.hpp) FILE(GLOB main_SRC ${SERVER_FOLDER}/main.cpp) diff --git a/wrapper/CMakeLists.txt b/wrapper/CMakeLists.txt new file mode 100644 index 0000000..532e693 --- /dev/null +++ b/wrapper/CMakeLists.txt @@ -0,0 +1,76 @@ +# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Mateusz Malicki (m.malicki2@samsung.com) +# + +PROJECT(vasum) +MESSAGE(STATUS "") +MESSAGE(STATUS "Generating makefile for the Vasum wrapper...") + +## set wrapper library sources (without vasum-client.cpp) +FILE(GLOB wrapper_SRCS *.cpp *.hpp *.h + ${CLIENT_FOLDER}/vasum-client-impl.hpp ${CLIENT_FOLDER}/vasum-client-impl.cpp + ${CLIENT_FOLDER}/host-ipc-connection.hpp ${CLIENT_FOLDER}/host-ipc-connection.cpp + ${CLIENT_FOLDER}/utils.hpp ${CLIENT_FOLDER}/utils.cpp) + +FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp + ${COMMON_FOLDER}/ipc/*.hpp ${COMMON_FOLDER}/ipc/*.cpp + ${COMMON_FOLDER}/ipc/internals/*.hpp ${COMMON_FOLDER}/ipc/internals/*.cpp + ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/utils/*.cpp + ${COMMON_FOLDER}/*.hpp ${COMMON_FOLDER}/*.cpp) + +SET(_LIB_VERSION_ "${VERSION}") +SET(_LIB_SOVERSION_ "0") +SET(PC_FILE "${PROJECT_NAME}.pc") + +## Set the default ELF image symbol visibility to hidden. Using this feature +## can very substantially improve linking and load times of shared object +## libraries, produce more optimized code, provide near-perfect API export +## and prevent symbol clashes +ADD_DEFINITIONS(-fvisibility=hidden) + +ADD_LIBRARY(${PROJECT_NAME} SHARED ${wrapper_SRCS} ${common_SRCS}) +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + SOVERSION ${_LIB_SOVERSION_} + VERSION ${_LIB_VERSION_} + COMPILE_DEFINITIONS HOST_IPC_SOCKET="${VSM_SERVER_IPC_SOCKET_PATH}") + +## Link libraries ############################################################## +FIND_PACKAGE(Boost COMPONENTS system filesystem) +PKG_CHECK_MODULES(LIB_DEPS REQUIRED gio-2.0 libsystemd-daemon libcap-ng) +INCLUDE_DIRECTORIES(SYSTEM ${LIB_DEPS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(${COMMON_FOLDER}) +INCLUDE_DIRECTORIES(${LIBS_FOLDER}) +INCLUDE_DIRECTORIES(${SERVER_FOLDER}) +INCLUDE_DIRECTORIES(${CLIENT_FOLDER}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${LIB_DEPS_LIBRARIES} ${Boost_LIBRARIES} + Config SimpleDbus) + +## Generate the pc file ######################################################## +CONFIGURE_FILE(${PC_FILE}.in ${CMAKE_BINARY_DIR}/${PC_FILE} @ONLY) + + +## Install ##################################################################### +INSTALL(FILES ${CMAKE_BINARY_DIR}/${PC_FILE} + DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) + +INSTALL(TARGETS ${PROJECT_NAME} + DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT RuntimeLibraries) + +INSTALL(FILES vasum.h vasum_list.h + DESTINATION ${INCLUDE_INSTALL_DIR}/${PROJECT_NAME}) diff --git a/client/vasum.h b/wrapper/vasum.h similarity index 100% rename from client/vasum.h rename to wrapper/vasum.h diff --git a/client/vasum.pc.in b/wrapper/vasum.pc.in similarity index 100% rename from client/vasum.pc.in rename to wrapper/vasum.pc.in diff --git a/client/vasum_list.h b/wrapper/vasum_list.h similarity index 100% rename from client/vasum_list.h rename to wrapper/vasum_list.h diff --git a/client/wrapper-compat.cpp b/wrapper/wrapper-compatibility.cpp similarity index 99% rename from client/wrapper-compat.cpp rename to wrapper/wrapper-compatibility.cpp index 67b34e6..d0bd082 100644 --- a/client/wrapper-compat.cpp +++ b/wrapper/wrapper-compatibility.cpp @@ -23,7 +23,7 @@ * @brief Vasum old API compatibility functions */ -#include "wrapper-compat.h" +#include "wrapper-compatibility.h" #include #include #include diff --git a/client/wrapper-compat.h b/wrapper/wrapper-compatibility.h similarity index 100% rename from client/wrapper-compat.h rename to wrapper/wrapper-compatibility.h diff --git a/client/vasum-wrapper.cpp b/wrapper/wrapper.cpp similarity index 99% rename from client/vasum-wrapper.cpp rename to wrapper/wrapper.cpp index 54c195e..c5eadbc 100644 --- a/client/vasum-wrapper.cpp +++ b/wrapper/wrapper.cpp @@ -29,13 +29,11 @@ #include #include "config.hpp" +#include "vasum-client-impl.hpp" #include "logger/logger.hpp" #include "logger/backend-journal.hpp" -#include "wrapper-compat.h" -#include "vasum-client-impl.hpp" - -#define MAX_EPOLL_EVENTS 16 +#include "wrapper-compatibility.h" struct WrappedZone { -- 2.7.4 From cbab469d4a0c6580d4794ff04e391dddd96243e7 Mon Sep 17 00:00:00 2001 From: Dariusz Michaluk Date: Tue, 12 May 2015 16:19:01 +0200 Subject: [PATCH 13/16] Rename all not associated with LXC stuff. [Bug/Feature] Rename all not associated with LXC stuff. [Cause] N/A [Solution] N/A [Verification] Build, install, run tests. Change-Id: I40bf4156e5148dc3a6f3d81bc2e7edfe81c56596 --- packaging/vasum.spec | 5 +-- server/configs/CMakeLists.txt | 7 +--- server/configs/daemon.conf.in | 2 +- server/configs/templates/default.conf | 2 +- .../{lxc-templates => templates}/template.sh | 0 .../tizen-common-wayland.sh | 0 server/zone-admin.cpp | 10 ++--- server/zone-admin.hpp | 8 ++-- server/zone-config.hpp | 6 +-- server/zone.cpp | 4 +- server/zone.hpp | 8 ++-- server/zones-manager-config.hpp | 6 +-- server/zones-manager.cpp | 2 +- tests/unit_tests/CMakeLists.txt | 4 +- .../ut-client/templates/console-dbus.conf.in | 2 +- .../ut-client/templates/console-ipc.conf.in | 2 +- .../client/configs/ut-client/test-daemon.conf.in | 2 +- tests/unit_tests/lxc/templates/CMakeLists.txt | 6 +-- tests/unit_tests/lxc/ut-zone.cpp | 48 +++++++++++----------- .../configs/ut-server/templates/default.conf | 2 +- .../server/configs/ut-server/test-daemon.conf.in | 2 +- .../configs/ut-zone-admin/templates/buggy.conf | 2 +- .../configs/ut-zone-admin/templates/missing.conf | 2 +- .../ut-zone-admin/templates/test-no-shutdown.conf | 2 +- .../configs/ut-zone-admin/templates/test.conf | 2 +- .../server/configs/ut-zone/templates/buggy.conf | 2 +- .../configs/ut-zone/templates/test-dbus.conf.in | 2 +- .../server/configs/ut-zone/templates/test.conf | 2 +- .../ut-zones-manager/templates/console.conf | 2 +- .../configs/ut-zones-manager/test-daemon.conf.in | 2 +- tests/unit_tests/server/ut-zone-admin.cpp | 4 +- tests/unit_tests/server/ut-zone-provision.cpp | 2 +- tests/unit_tests/server/ut-zone.cpp | 6 +-- 33 files changed, 77 insertions(+), 81 deletions(-) rename server/configs/{lxc-templates => templates}/template.sh (100%) rename server/configs/{lxc-templates => templates}/tizen-common-wayland.sh (100%) diff --git a/packaging/vasum.spec b/packaging/vasum.spec index 606f535..0636c53 100644 --- a/packaging/vasum.spec +++ b/packaging/vasum.spec @@ -41,10 +41,9 @@ between them. A process from inside a zone can request a switch of context %attr(755,root,root) %{_bindir}/vasum-server %dir /etc/vasum %dir /etc/vasum/zones -%dir /etc/vasum/lxc-templates %dir /etc/vasum/templates %config /etc/vasum/daemon.conf -%attr(755,root,root) /etc/vasum/lxc-templates/*.sh +%attr(755,root,root) /etc/vasum/templates/*.sh %config /etc/vasum/templates/*.conf %{_unitdir}/vasum.service %{_unitdir}/vasum.socket @@ -248,7 +247,7 @@ systemctl daemon-reload %attr(755,root,root) %{script_dir}/vsm_launch_test.py %{script_dir}/vsm_test_parser.py %config /etc/vasum/tests -%attr(755,root,root) /etc/vasum/tests/lxc-templates +%attr(755,root,root) /etc/vasum/tests/templates %{python_sitelib}/vsm_integration_tests %config /etc/dbus-1/system.d/org.tizen.vasum.tests.conf %{_unitdir}/vasum-socket-test.socket diff --git a/server/configs/CMakeLists.txt b/server/configs/CMakeLists.txt index e34137e..0e7be41 100644 --- a/server/configs/CMakeLists.txt +++ b/server/configs/CMakeLists.txt @@ -19,8 +19,8 @@ MESSAGE(STATUS "Installing configs to " ${VSM_CONFIG_INSTALL_DIR}) -FILE(GLOB admin_CONF lxc-templates/*.sh) -FILE(GLOB template_CONF templates/*.conf) +FILE(GLOB template_CONF templates/*.conf + templates/*.sh) ## Generate #################################################################### CONFIGURE_FILE(systemd/vasum.service.in @@ -43,9 +43,6 @@ INSTALL(FILES ${CMAKE_BINARY_DIR}/dbus-1/system.d/org.tizen.vasum.host.con INSTALL(DIRECTORY DESTINATION ${VSM_CONFIG_INSTALL_DIR}/zones) #TODO temporary solution -INSTALL(PROGRAMS ${admin_CONF} - DESTINATION ${VSM_CONFIG_INSTALL_DIR}/lxc-templates) - INSTALL(PROGRAMS ${template_CONF} DESTINATION ${VSM_CONFIG_INSTALL_DIR}/templates) diff --git a/server/configs/daemon.conf.in b/server/configs/daemon.conf.in index a6359fa..0800124 100644 --- a/server/configs/daemon.conf.in +++ b/server/configs/daemon.conf.in @@ -6,7 +6,7 @@ "zoneTemplateDir" : "/etc/vasum/templates/", "runMountPointPrefix" : "/var/run/zones", "defaultId" : "", - "lxcTemplatePrefix" : "/etc/vasum/lxc-templates", + "zoneTemplatePrefix" : "/etc/vasum/templates", "availableVTs" : [3, 4, 5, 6], "inputConfig" : {"enabled" : true, "device" : "gpio_keys.6", diff --git a/server/configs/templates/default.conf b/server/configs/templates/default.conf index ce88c6e..b8eb5d5 100644 --- a/server/configs/templates/default.conf +++ b/server/configs/templates/default.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "tizen-common-wayland.sh", + "zoneTemplate" : "tizen-common-wayland.sh", "initWithArgs" : [], "requestedState" : "stopped", "ipv4Gateway" : "10.0.~IP~.1", diff --git a/server/configs/lxc-templates/template.sh b/server/configs/templates/template.sh similarity index 100% rename from server/configs/lxc-templates/template.sh rename to server/configs/templates/template.sh diff --git a/server/configs/lxc-templates/tizen-common-wayland.sh b/server/configs/templates/tizen-common-wayland.sh similarity index 100% rename from server/configs/lxc-templates/tizen-common-wayland.sh rename to server/configs/templates/tizen-common-wayland.sh diff --git a/server/zone-admin.cpp b/server/zone-admin.cpp index 0f831d7..473a11c 100644 --- a/server/zone-admin.cpp +++ b/server/zone-admin.cpp @@ -46,7 +46,7 @@ const std::uint64_t DEFAULT_VCPU_PERIOD_MS = 100000; ZoneAdmin::ZoneAdmin(const std::string& zoneId, const std::string& zonesPath, - const std::string& lxcTemplatePrefix, + const std::string& zoneTemplatePrefix, const ZoneConfig& config, const ZoneDynamicConfig& dynamicConfig) : mConfig(config), @@ -60,9 +60,9 @@ ZoneAdmin::ZoneAdmin(const std::string& zoneId, if (!mZone.isDefined()) { - const std::string lxcTemplate = utils::getAbsolutePath(config.lxcTemplate, - lxcTemplatePrefix); - LOGI(mId << ": Creating zone from template: " << lxcTemplate); + const std::string zoneTemplate = utils::getAbsolutePath(config.zoneTemplate, + zoneTemplatePrefix); + LOGI(mId << ": Creating zone from template: " << zoneTemplate); utils::CStringArrayBuilder args; if (!dynamicConfig.ipv4Gateway.empty()) { args.add("--ipv4-gateway"); @@ -77,7 +77,7 @@ ZoneAdmin::ZoneAdmin(const std::string& zoneId, args.add("--vt"); args.add(vt.c_str()); } - if (!mZone.create(lxcTemplate, args.c_array())) { + if (!mZone.create(zoneTemplate, args.c_array())) { throw ZoneOperationException("Could not create zone"); } } diff --git a/server/zone-admin.hpp b/server/zone-admin.hpp index d1b179d..d154beb 100644 --- a/server/zone-admin.hpp +++ b/server/zone-admin.hpp @@ -46,14 +46,14 @@ public: /** * ZoneAdmin constructor * @param zoneId zone id - * @param zonesPath directory where zones are defined (lxc configs, rootfs etc) - * @param lxcTemplatePrefix directory where templates are stored + * @param zonesPath directory where zones are defined (configs, rootfs etc) + * @param zoneTemplatePrefix directory where templates are stored * @param config zones config * @param dynamicConfig zones dynamic config */ ZoneAdmin(const std::string& zoneId, const std::string& zonesPath, - const std::string& lxcTemplatePrefix, + const std::string& zoneTemplatePrefix, const ZoneConfig& config, const ZoneDynamicConfig& dynamicConfig); virtual ~ZoneAdmin(); @@ -85,7 +85,7 @@ public: /** * Check if the zone is stopped. It's NOT equivalent to !isRunning, - * because it checks different internal lxc states. There are other states, + * because it checks different internal zone states. There are other states, * (e.g. paused) when the zone isn't running nor stopped. * * @return Is the zone stopped? diff --git a/server/zone-config.hpp b/server/zone-config.hpp index b845ef9..aad9159 100644 --- a/server/zone-config.hpp +++ b/server/zone-config.hpp @@ -38,9 +38,9 @@ namespace vasum { struct ZoneConfig { /** - * Lxc template name (relative to lxcTemplatePrefix) + * Zone template name (relative to zoneTemplatePrefix) */ - std::string lxcTemplate; + std::string zoneTemplate; /** * Init program with args (empty means default /sbin/init) @@ -96,7 +96,7 @@ struct ZoneConfig { CONFIG_REGISTER ( - lxcTemplate, + zoneTemplate, initWithArgs, privilege, // TODO not needed? switchToDefaultAfterTimeout, // TODO move to dynamic and add an API to change diff --git a/server/zone.cpp b/server/zone.cpp index 8a1aa0b..a19fc6a 100644 --- a/server/zone.cpp +++ b/server/zone.cpp @@ -56,7 +56,7 @@ Zone::Zone(const std::string& zoneId, const std::string& zonesPath, const std::string& zoneTemplatePath, const std::string& dbPath, - const std::string& lxcTemplatePrefix, + const std::string& zoneTemplatePrefix, const std::string& baseRunMountPointPath) : mDbPath(dbPath) { @@ -75,7 +75,7 @@ Zone::Zone(const std::string& zoneId, mRunMountPoint = fs::absolute(mDynamicConfig.runMountPoint, baseRunMountPointPath).string(); } - mAdmin.reset(new ZoneAdmin(zoneId, zonesPath, lxcTemplatePrefix, mConfig, mDynamicConfig)); + mAdmin.reset(new ZoneAdmin(zoneId, zonesPath, zoneTemplatePrefix, mConfig, mDynamicConfig)); const fs::path zonePath = fs::path(zonesPath) / zoneId; mRootPath = (zonePath / fs::path("rootfs")).string(); diff --git a/server/zone.hpp b/server/zone.hpp index 6d13d85..ee1bf43 100644 --- a/server/zone.hpp +++ b/server/zone.hpp @@ -46,17 +46,17 @@ public: /** * Zone constructor * @param zoneId zone id - * @param zonesPath directory where zones are defined (lxc configs, rootfs etc) + * @param zonesPath directory where zones are defined (configs, rootfs etc) * @param zoneTemplatePath path for zones config template * @param dbPath path to dynamic config db file - * @param lxcTemplatePrefix directory where templates are stored + * @param zoneTemplatePrefix directory where templates are stored * @param baseRunMountPointPath base directory for run mount point */ Zone(const std::string& zoneId, const std::string& zonesPath, const std::string& zoneTemplatePath, const std::string& dbPath, - const std::string& lxcTemplatePrefix, + const std::string& zoneTemplatePrefix, const std::string& baseRunMountPointPath); Zone(const Zone&) = delete; Zone& operator=(const Zone&) = delete; @@ -141,7 +141,7 @@ public: /** * Check if the zone is stopped. It's NOT equivalent to !isRunning, - * because it checks different internal LXC states. There are other states, + * because it checks different internal zone states. There are other states, * (e.g. paused) when the zone isn't running nor stopped. * * @return Is the zone stopped? diff --git a/server/zones-manager-config.hpp b/server/zones-manager-config.hpp index bfc1b25..b59cfc2 100644 --- a/server/zones-manager-config.hpp +++ b/server/zones-manager-config.hpp @@ -60,9 +60,9 @@ struct ZonesManagerConfig { std::string zoneTemplateDir; /** - * Path prefix for lxc templates + * Path prefix for zone templates */ - std::string lxcTemplatePrefix; + std::string zoneTemplatePrefix; /** * VTs available for zones @@ -90,7 +90,7 @@ struct ZonesManagerConfig { zonesPath, zoneImagePath, zoneTemplateDir, - lxcTemplatePrefix, + zoneTemplatePrefix, availableVTs, inputConfig, runMountPointPrefix, diff --git a/server/zones-manager.cpp b/server/zones-manager.cpp index 953fad0..c05b1be 100644 --- a/server/zones-manager.cpp +++ b/server/zones-manager.cpp @@ -323,7 +323,7 @@ void ZonesManager::insertZone(const std::string& zoneId, const std::string& zone mConfig.zonesPath, zoneTemplatePath, mConfig.dbPath, - mConfig.lxcTemplatePrefix, + mConfig.zoneTemplatePrefix, mConfig.runMountPointPrefix)); mZones.push_back(std::move(zone)); diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 889dd91..500e7af 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -72,9 +72,9 @@ TARGET_LINK_LIBRARIES(${SOCKET_TEST_CODENAME} ${UT_SERVER_DEPS_LIBRARIES} ${Boos ## Subdirectories ############################################################## SET(VSM_TEST_CONFIG_INSTALL_DIR ${VSM_CONFIG_INSTALL_DIR}/tests) -SET(VSM_TEST_LXC_TEMPLATES_INSTALL_DIR ${VSM_CONFIG_INSTALL_DIR}/tests/lxc-templates) +SET(VSM_TEST_TEMPLATES_INSTALL_DIR ${VSM_CONFIG_INSTALL_DIR}/tests/templates) ADD_DEFINITIONS(-DVSM_TEST_CONFIG_INSTALL_DIR="${VSM_TEST_CONFIG_INSTALL_DIR}") -ADD_DEFINITIONS(-DVSM_TEST_LXC_TEMPLATES_INSTALL_DIR="${VSM_TEST_LXC_TEMPLATES_INSTALL_DIR}") +ADD_DEFINITIONS(-DVSM_TEST_TEMPLATES_INSTALL_DIR="${VSM_TEST_TEMPLATES_INSTALL_DIR}") ADD_SUBDIRECTORY(dbus/configs) ADD_SUBDIRECTORY(server/configs) diff --git a/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in b/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in index 2ff5998..c47dfaa 100644 --- a/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in +++ b/tests/unit_tests/client/configs/ut-client/templates/console-dbus.conf.in @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal-dbus.sh", + "zoneTemplate" : "minimal-dbus.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; /usr/bin/dbus-daemon --config-file=@VSM_TEST_CONFIG_INSTALL_DIR@/server/ut-zones-manager/ut-dbus.conf --fork; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in b/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in index b7b103a..7b48420 100644 --- a/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in +++ b/tests/unit_tests/client/configs/ut-client/templates/console-ipc.conf.in @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal-dbus.sh", + "zoneTemplate" : "minimal-dbus.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/client/configs/ut-client/test-daemon.conf.in b/tests/unit_tests/client/configs/ut-client/test-daemon.conf.in index 6346df3..848366a 100644 --- a/tests/unit_tests/client/configs/ut-client/test-daemon.conf.in +++ b/tests/unit_tests/client/configs/ut-client/test-daemon.conf.in @@ -6,7 +6,7 @@ "zoneImagePath" : "", "zoneTemplateDir" : "@VSM_TEST_CONFIG_INSTALL_DIR@/client/ut-client/templates/", "runMountPointPrefix" : "", - "lxcTemplatePrefix" : "@VSM_TEST_LXC_TEMPLATES_INSTALL_DIR@", + "zoneTemplatePrefix" : "@VSM_TEST_TEMPLATES_INSTALL_DIR@", "availableVTs" : [], "inputConfig" : {"enabled" : false, "device" : "/dev/doesnotexist", diff --git a/tests/unit_tests/lxc/templates/CMakeLists.txt b/tests/unit_tests/lxc/templates/CMakeLists.txt index 43db4d9..c7b98c5 100644 --- a/tests/unit_tests/lxc/templates/CMakeLists.txt +++ b/tests/unit_tests/lxc/templates/CMakeLists.txt @@ -17,7 +17,7 @@ # @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com) # -FILE(GLOB LXC_TEMPLATES *.sh) +FILE(GLOB ZONE_TEMPLATES *.sh) -INSTALL(PROGRAMS ${LXC_TEMPLATES} - DESTINATION ${VSM_TEST_LXC_TEMPLATES_INSTALL_DIR}) +INSTALL(PROGRAMS ${ZONE_TEMPLATES} + DESTINATION ${VSM_TEST_TEMPLATES_INSTALL_DIR}) diff --git a/tests/unit_tests/lxc/ut-zone.cpp b/tests/unit_tests/lxc/ut-zone.cpp index 194a2a6..e2683d6 100644 --- a/tests/unit_tests/lxc/ut-zone.cpp +++ b/tests/unit_tests/lxc/ut-zone.cpp @@ -39,16 +39,16 @@ namespace { using namespace vasum; using namespace vasum::lxc; -const std::string LXC_PATH = "/tmp/ut-lxc/"; +const std::string ZONE_PATH = "/tmp/ut-zone/"; const std::string ZONE_NAME = "ut-zone"; -const std::string TEMPLATE = VSM_TEST_LXC_TEMPLATES_INSTALL_DIR "/minimal.sh"; +const std::string ZONE_TEMPLATE = VSM_TEST_TEMPLATES_INSTALL_DIR "/minimal.sh"; const char* TEMPLATE_ARGS[] = {NULL}; struct Fixture { utils::ScopedDir mLxcDirGuard; Fixture() - : mLxcDirGuard(LXC_PATH) + : mLxcDirGuard(ZONE_PATH) { cleanup(); } @@ -60,7 +60,7 @@ struct Fixture { void cleanup() { - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); if (lxc.isDefined()) { if (lxc.getState() != LxcZone::State::STOPPED) { lxc.stop(); @@ -82,18 +82,18 @@ BOOST_FIXTURE_TEST_SUITE(LxcZoneSuite, Fixture) BOOST_AUTO_TEST_CASE(ConstructorDestructor) { - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); } BOOST_AUTO_TEST_CASE(CreateDestroy) { - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); BOOST_CHECK(!lxc.isDefined()); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); BOOST_CHECK(lxc.isDefined()); - BOOST_CHECK_EQUAL(lxc.getConfigItem("lxc.rootfs"), LXC_PATH + ZONE_NAME + "/rootfs"); + BOOST_CHECK_EQUAL(lxc.getConfigItem("lxc.rootfs"), ZONE_PATH + ZONE_NAME + "/rootfs"); BOOST_CHECK_EXCEPTION(lxc.getConfigItem("xxx"), LxcException, WhatEquals("Key not found")); BOOST_CHECK(lxc.destroy()); @@ -104,10 +104,10 @@ BOOST_AUTO_TEST_CASE(CreateDestroy) BOOST_AUTO_TEST_CASE(StartShutdown) { { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); } - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); BOOST_CHECK(lxc.getState() == LxcZone::State::STOPPED); const char* argv[] = { "/bin/sh", @@ -127,10 +127,10 @@ BOOST_AUTO_TEST_CASE(StartShutdown) BOOST_AUTO_TEST_CASE(StartStop) { { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); } - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); BOOST_CHECK(lxc.getState() == LxcZone::State::STOPPED); const char* argv[] = { "/bin/sh", @@ -152,10 +152,10 @@ BOOST_AUTO_TEST_CASE(StartStop) BOOST_AUTO_TEST_CASE(StartHasStopped) { { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); } - LxcZone lxc(LXC_PATH, ZONE_NAME); + LxcZone lxc(ZONE_PATH, ZONE_NAME); BOOST_CHECK(lxc.getState() == LxcZone::State::STOPPED); const char* argv[] = { "/bin/sh", @@ -172,8 +172,8 @@ BOOST_AUTO_TEST_CASE(StartHasStopped) BOOST_AUTO_TEST_CASE(FreezeUnfreeze) { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); const char* argv[] = { "/bin/sh", "-c", @@ -195,8 +195,8 @@ BOOST_AUTO_TEST_CASE(FreezeUnfreeze) BOOST_AUTO_TEST_CASE(FreezeStop) { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); const char* argv[] = { "/bin/sh", "-c", @@ -218,9 +218,9 @@ BOOST_AUTO_TEST_CASE(FreezeStop) BOOST_AUTO_TEST_CASE(Repeat) { - LxcZone lxc(LXC_PATH, ZONE_NAME); - BOOST_CHECK(lxc.create(TEMPLATE, TEMPLATE_ARGS)); - BOOST_CHECK(!lxc.create(TEMPLATE, TEMPLATE_ARGS));// forbidden + LxcZone lxc(ZONE_PATH, ZONE_NAME); + BOOST_CHECK(lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS)); + BOOST_CHECK(!lxc.create(ZONE_TEMPLATE, TEMPLATE_ARGS));// forbidden const char* argv[] = { "/bin/sh", "-c", diff --git a/tests/unit_tests/server/configs/ut-server/templates/default.conf b/tests/unit_tests/server/configs/ut-server/templates/default.conf index 5261493..646fcb1 100644 --- a/tests/unit_tests/server/configs/ut-server/templates/default.conf +++ b/tests/unit_tests/server/configs/ut-server/templates/default.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-server/test-daemon.conf.in b/tests/unit_tests/server/configs/ut-server/test-daemon.conf.in index 8fb9ee2..1d59bdc 100644 --- a/tests/unit_tests/server/configs/ut-server/test-daemon.conf.in +++ b/tests/unit_tests/server/configs/ut-server/test-daemon.conf.in @@ -6,7 +6,7 @@ "zoneTemplateDir" : "@VSM_TEST_CONFIG_INSTALL_DIR@/server/ut-server/templates/", "runMountPointPrefix" : "", "defaultId" : "", - "lxcTemplatePrefix" : "@VSM_TEST_LXC_TEMPLATES_INSTALL_DIR@", + "zoneTemplatePrefix" : "@VSM_TEST_TEMPLATES_INSTALL_DIR@", "availableVTs" : [], "inputConfig" : {"enabled" : false, "device" : "gpio-keys.4", diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf index 99bc05e..cff3576 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/buggy.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/foo"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf index 6c7ce34..9a37d54 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/missing.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "missing.sh", + "zoneTemplate" : "missing.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf index e4f2bf9..e0aec5b 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/test-no-shutdown.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/bin/sh"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf b/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf index 8af8d42..fea418d 100644 --- a/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf +++ b/tests/unit_tests/server/configs/ut-zone-admin/templates/test.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf b/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf index 5c98cfd..d89364d 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf +++ b/tests/unit_tests/server/configs/ut-zone/templates/buggy.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "/buggy/path", + "zoneTemplate" : "/buggy/path", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in b/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in index d2fea11..0dd101a 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in +++ b/tests/unit_tests/server/configs/ut-zone/templates/test-dbus.conf.in @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal-dbus.sh", + "zoneTemplate" : "minimal-dbus.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; /usr/bin/dbus-daemon --config-file=@VSM_TEST_CONFIG_INSTALL_DIR@/server/ut-zone/ut-dbus.conf --fork; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zone/templates/test.conf b/tests/unit_tests/server/configs/ut-zone/templates/test.conf index 38907a0..115307d 100644 --- a/tests/unit_tests/server/configs/ut-zone/templates/test.conf +++ b/tests/unit_tests/server/configs/ut-zone/templates/test.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf b/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf index 02a7dc6..2537e16 100644 --- a/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf +++ b/tests/unit_tests/server/configs/ut-zones-manager/templates/console.conf @@ -1,5 +1,5 @@ { - "lxcTemplate" : "minimal.sh", + "zoneTemplate" : "minimal.sh", "initWithArgs" : ["/bin/sh", "-c", "trap exit SIGTERM; read"], "requestedState" : "running", "ipv4Gateway" : "", diff --git a/tests/unit_tests/server/configs/ut-zones-manager/test-daemon.conf.in b/tests/unit_tests/server/configs/ut-zones-manager/test-daemon.conf.in index adea9b6..a388e6d 100644 --- a/tests/unit_tests/server/configs/ut-zones-manager/test-daemon.conf.in +++ b/tests/unit_tests/server/configs/ut-zones-manager/test-daemon.conf.in @@ -6,7 +6,7 @@ "zoneImagePath" : "", "zoneTemplateDir" : "@VSM_TEST_CONFIG_INSTALL_DIR@/server/ut-zones-manager/templates/", "runMountPointPrefix" : "", - "lxcTemplatePrefix" : "@VSM_TEST_LXC_TEMPLATES_INSTALL_DIR@", + "zoneTemplatePrefix" : "@VSM_TEST_TEMPLATES_INSTALL_DIR@", "availableVTs" : [], "inputConfig" : {"enabled" : false, "device" : "/dev/doesnotexist", diff --git a/tests/unit_tests/server/ut-zone-admin.cpp b/tests/unit_tests/server/ut-zone-admin.cpp index 3aa38d1..72bc2e6 100644 --- a/tests/unit_tests/server/ut-zone-admin.cpp +++ b/tests/unit_tests/server/ut-zone-admin.cpp @@ -43,7 +43,7 @@ const std::string TEST_NO_SHUTDOWN_CONFIG_PATH = TEMPLATES_DIR + "/test-no-shutd const std::string BUGGY_CONFIG_PATH = TEMPLATES_DIR + "/buggy.conf"; const std::string MISSING_CONFIG_PATH = TEMPLATES_DIR + "/missing.conf"; const std::string ZONES_PATH = "/tmp/ut-zones"; -const std::string LXC_TEMPLATES_PATH = VSM_TEST_LXC_TEMPLATES_INSTALL_DIR; +const std::string TEMPLATES_PATH = VSM_TEST_TEMPLATES_INSTALL_DIR; struct Fixture { utils::ScopedGlibLoop mLoop; @@ -62,7 +62,7 @@ struct Fixture { config::loadFromJsonFile(configPath, mDynamicConfig); return std::unique_ptr(new ZoneAdmin("zoneId", ZONES_PATH, - LXC_TEMPLATES_PATH, + TEMPLATES_PATH, mConfig, mDynamicConfig)); } diff --git a/tests/unit_tests/server/ut-zone-provision.cpp b/tests/unit_tests/server/ut-zone-provision.cpp index a79a260..d6a5955 100644 --- a/tests/unit_tests/server/ut-zone-provision.cpp +++ b/tests/unit_tests/server/ut-zone-provision.cpp @@ -51,7 +51,7 @@ namespace { const std::string TEST_CONFIG_PATH = VSM_TEST_CONFIG_INSTALL_DIR "/server/ut-zone-provision/test.conf"; const std::string ZONE = "ut-zone-provision-test"; const fs::path ZONES_PATH = "/tmp/ut-zones"; -const fs::path LXC_TEMPLATES_PATH = VSM_TEST_LXC_TEMPLATES_INSTALL_DIR; +const fs::path TEMPLATES_PATH = VSM_TEST_TEMPLATES_INSTALL_DIR; const fs::path ZONE_PATH = ZONES_PATH / fs::path(ZONE); const fs::path SOME_FILE_PATH = ZONE_PATH / "file.txt"; const fs::path ROOTFS_PATH = ZONE_PATH / "rootfs"; diff --git a/tests/unit_tests/server/ut-zone.cpp b/tests/unit_tests/server/ut-zone.cpp index b4938b4..2aed285 100644 --- a/tests/unit_tests/server/ut-zone.cpp +++ b/tests/unit_tests/server/ut-zone.cpp @@ -57,7 +57,7 @@ const std::string TEST_DBUS_CONFIG_PATH = TEMPLATES_DIR + "/test-dbus.conf"; const std::string BUGGY_CONFIG_PATH = TEMPLATES_DIR + "/buggy.conf"; const std::string MISSING_CONFIG_PATH = TEMPLATES_DIR + "/missing.conf"; const std::string ZONES_PATH = "/tmp/ut-zones"; -const std::string LXC_TEMPLATES_PATH = VSM_TEST_LXC_TEMPLATES_INSTALL_DIR; +const std::string TEMPLATES_PATH = VSM_TEST_TEMPLATES_INSTALL_DIR; const std::string DB_PATH = ZONES_PATH + "/vasum.db"; const std::string BRIDGE_NAME = "brtest01"; const std::string ZONE_NETDEV = "netdevtest01"; @@ -88,7 +88,7 @@ struct Fixture { ZONES_PATH, configPath, DB_PATH, - LXC_TEMPLATES_PATH, + TEMPLATES_PATH, "")); } @@ -146,7 +146,7 @@ BOOST_AUTO_TEST_CASE(StartStop) BOOST_AUTO_TEST_CASE(DbusConnection) { - mRunGuard.create("/tmp/ut-run"); // the same path as in lxc template + mRunGuard.create("/tmp/ut-run"); // the same path as in zone template auto c = create(TEST_DBUS_CONFIG_PATH); c->start(); -- 2.7.4 From 5507026ca9a60af347a96a3ca1d9345c4ffee151 Mon Sep 17 00:00:00 2001 From: Dariusz Michaluk Date: Wed, 13 May 2015 13:56:12 +0200 Subject: [PATCH 14/16] Fix vsm_create_zone timeout [Feature] Greater timeout for vsm_create_zone [Cause] Timeout was too small [Solution] N/A [Verification] Start vasum on odroid, create zone Change-Id: Ic9015f7987c986267d47b5ce55d04a9749baf85c --- client/host-ipc-connection.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index 6aa87ec..b17c6cf 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -174,7 +174,8 @@ void HostIPCConnection::callCreateZone(const api::CreateZoneIn& argIn) { mClient->callSync( api::ipc::METHOD_CREATE_ZONE, - std::make_shared(argIn)); + std::make_shared(argIn), + TIMEOUT_INFINITE); } void HostIPCConnection::callDestroyZone(const api::ZoneId& argIn) -- 2.7.4 From 27ff86f2517ac519dcb43a7ce87647eaf76d5669 Mon Sep 17 00:00:00 2001 From: Krzysztof Dynowski Date: Wed, 13 May 2015 15:32:25 +0200 Subject: [PATCH 15/16] Vasum wrapper #5, fix exported function list [Bug/Feature] exported funcs not visible [Cause] missing API keyword in declaration [Solution] #5 add API keyword [Verification] Build, build old clients, install on target Change-Id: Idd408bb59f9421d43b153117aa3d825610722283 --- wrapper/wrapper-compatibility.cpp | 78 +++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/wrapper/wrapper-compatibility.cpp b/wrapper/wrapper-compatibility.cpp index d0bd082..adb1edd 100644 --- a/wrapper/wrapper-compatibility.cpp +++ b/wrapper/wrapper-compatibility.cpp @@ -47,11 +47,11 @@ extern "C" { // find_container_by_pid -char *find_container_by_pid(pid_t /*pid*/) { +API char *find_container_by_pid(pid_t /*pid*/) { return NULL; } // get_domain_pid -pid_t get_domain_pid(const char * /*name*/, const char * /*target*/) { +API pid_t get_domain_pid(const char * /*name*/, const char * /*target*/) { return -1; } @@ -179,27 +179,27 @@ int sock_close_socket(int /*fd*/) { return 0; } // sock_connect -int sock_connect(const char * /*path*/) { +API int sock_connect(const char * /*path*/) { return 0; } // sock_create_socket -int sock_create_socket(const char * /*path*/, int /*type*/, int /*flags*/) { +API int sock_create_socket(const char * /*path*/, int /*type*/, int /*flags*/) { return 0; } // sock_monitor_address -int sock_monitor_address(char * /*buffer*/, int /*len*/, const char * /*lxcpath*/) { +API int sock_monitor_address(char * /*buffer*/, int /*len*/, const char * /*lxcpath*/) { return 0; } // sock_recv_fd (intern) -int sock_recv_fd(int /*fd*/, int * /*recvfd*/, void * /*data*/, size_t /*size*/) { +API int sock_recv_fd(int /*fd*/, int * /*recvfd*/, void * /*data*/, size_t /*size*/) { return 0; } // sock_send_fd -int sock_send_fd(int /*fd*/, int /*sendfd*/, void * /*data*/, size_t /*size*/) { +API int sock_send_fd(int /*fd*/, int /*sendfd*/, void * /*data*/, size_t /*size*/) { return 0; } // vasum_log -void vasum_log(int /*type*/, const char * /*tag*/, const char * /*fmt*/ , ...) { +API void vasum_log(int /*type*/, const char * /*tag*/, const char * /*fmt*/ , ...) { } #define MAX_ERROR_MSG 0x1000 @@ -220,7 +220,7 @@ const char *const fso_type_strtab[] = { "Device node" }; -const char *fso_type_to_string(vsm_fso_type_t fso) +API const char *fso_type_to_string(vsm_fso_type_t fso) { if (fso < 0 || fso > VSM_FSO_MAX_TYPE) { return NULL; @@ -229,7 +229,7 @@ const char *fso_type_to_string(vsm_fso_type_t fso) return fso_type_strtab[fso]; } -int wait_for_pid_status(pid_t pid) +API int wait_for_pid_status(pid_t pid) { int status, ret; @@ -249,7 +249,7 @@ int wait_for_pid_status(pid_t pid) return status; } -vsm_fso_type_t fso_string_to_type(char *str) +API vsm_fso_type_t fso_string_to_type(char *str) { int len; int i; @@ -262,7 +262,7 @@ vsm_fso_type_t fso_string_to_type(char *str) return static_cast(-1); } -int mkdir_p(const char *dir, mode_t mode) +API int mkdir_p(const char *dir, mode_t mode) { const char *tmp = dir; const char *orig = dir; @@ -284,7 +284,7 @@ int mkdir_p(const char *dir, mode_t mode) return 0; } -int lock_fd(int fd, int wait) +API int lock_fd(int fd, int wait) { int ret; struct flock f; @@ -307,7 +307,7 @@ int lock_fd(int fd, int wait) } } -int unlock_fd(int fd) +API int unlock_fd(int fd) { struct flock f; f.l_type = F_UNLCK; @@ -317,12 +317,12 @@ int unlock_fd(int fd) return fcntl(fd, F_SETLKW, &f); } -int copy_smacklabel(const char * /*source*/, const char * /*dest*/) +API int copy_smacklabel(const char * /*source*/, const char * /*dest*/) { return 0; } -int remove_file(char *path) +API int remove_file(char *path) { struct stat path_stat; DIR *dp; @@ -374,7 +374,7 @@ int remove_file(char *path) return status; } -int copy_file(const char *source, const char *dest, int /*flags*/) +API int copy_file(const char *source, const char *dest, int /*flags*/) { int ret; FILE *sfp, *dfp; @@ -424,7 +424,7 @@ int copy_file(const char *source, const char *dest, int /*flags*/) return 0; } -int regex_compile(regex_t * r, const char *regex_text) +API int regex_compile(regex_t * r, const char *regex_text) { int status = regcomp(r, regex_text, REG_EXTENDED | REG_NEWLINE); @@ -440,7 +440,7 @@ int regex_compile(regex_t * r, const char *regex_text) return 0; } -int regex_match(regex_t * r, const char *to_match) +API int regex_match(regex_t * r, const char *to_match) { const char *p = to_match; const int n_matches = 10; @@ -483,7 +483,7 @@ int regex_match(regex_t * r, const char *to_match) return 0; } -int get_peer_pid(int fd) +API int get_peer_pid(int fd) { struct ucred cred; socklen_t cr_len = sizeof(cred); @@ -493,12 +493,12 @@ int get_peer_pid(int fd) return cred.pid; } -pid_t gettid(void) +API pid_t gettid(void) { return syscall(__NR_gettid); } -int set_smacklabel_fd(int fd, const char *xattr_name, const char *label) +API int set_smacklabel_fd(int fd, const char *xattr_name, const char *label) { size_t len; int ret; @@ -517,7 +517,7 @@ int set_smacklabel_fd(int fd, const char *xattr_name, const char *label) return ret; } -int set_smacklabel(const char *path, const char *xattr_name, const char *label) +API int set_smacklabel(const char *path, const char *xattr_name, const char *label) { size_t len; int ret; @@ -535,7 +535,7 @@ int set_smacklabel(const char *path, const char *xattr_name, const char *label) } return ret; } -char *get_self_smacklabel(void) +API char *get_self_smacklabel(void) { int ret; int fd; @@ -563,7 +563,7 @@ char *get_self_smacklabel(void) return strdup(buffer); } -int get_self_cpuset(char *name, int buf_sz) +API int get_self_cpuset(char *name, int buf_sz) { int fd; int lxc_len, ret; @@ -607,7 +607,7 @@ int get_self_cpuset(char *name, int buf_sz) } -char * get_pid_cpuset(int pid) +API char * get_pid_cpuset(int pid) { int fd; int ret; @@ -639,7 +639,7 @@ char * get_pid_cpuset(int pid) return strdup(current_name); } -char * read_namespace_link(const char *ns, int pid) +API char * read_namespace_link(const char *ns, int pid) { char ns_path[PATH_MAX]; char buf[NAME_MAX]; @@ -666,7 +666,7 @@ char * read_namespace_link(const char *ns, int pid) // libs/device.c #define DEV_ITERATE_CONTINUE 0 -int dev_enumerate_nodes(const char *cname, dev_enumerator enumerator, +API int dev_enumerate_nodes(const char *cname, dev_enumerator enumerator, void *data) { int ret; @@ -704,7 +704,7 @@ int dev_enumerate_nodes(const char *cname, dev_enumerator enumerator, return ret; } -int dev_terminal_enumerator(int type, int major, int minor, void *data) +API int dev_terminal_enumerator(int type, int major, int minor, void *data) { int *dev = (int*)data; @@ -718,7 +718,7 @@ int dev_terminal_enumerator(int type, int major, int minor, void *data) } // libs/namespace.c -pid_t get_init_pid(const char *name) +API pid_t get_init_pid(const char *name) { char filename[PATH_MAX]; FILE *fp; @@ -744,7 +744,7 @@ pid_t get_init_pid(const char *name) } -pid_t get_zone_pid(const char *name, const char *target) +API pid_t get_zone_pid(const char *name, const char *target) { char path[PATH_MAX]; char cmd[PATH_MAX]; @@ -821,7 +821,7 @@ pid_t get_zone_pid(const char *name, const char *target) return ret; } -int open_ns(pid_t pid, const char *name) +API int open_ns(pid_t pid, const char *name) { int fd, ret; char path[PATH_MAX]; @@ -871,7 +871,7 @@ static int open_console(const char *path) return fd; } -int get_console_fd(const char *path) +API int get_console_fd(const char *path) { int fd; @@ -903,7 +903,7 @@ int get_console_fd(const char *path) return -1; } -int vt_switch_terminal(int id) +API int vt_switch_terminal(int id) { int fd, ret = -1; @@ -926,7 +926,7 @@ int vt_switch_terminal(int id) return ret; } -int vt_find_unused_terminal(void) +API int vt_find_unused_terminal(void) { int fd, nr = -1; @@ -947,7 +947,7 @@ int vt_find_unused_terminal(void) return nr; } -int vt_query_active_terminal(void) +API int vt_query_active_terminal(void) { int fd, ret = -1; struct vt_stat vtstat; @@ -977,7 +977,7 @@ struct unit_parser { struct unit_keyword_callback *kw; }; -int parse_stream(const char *name, struct unit_parser *parser); +API int parse_stream(const char *name, struct unit_parser *parser); // libs/parser.c #define PARSER_MAXARGS 32 @@ -1187,7 +1187,7 @@ static int parse_statement(struct parser_context *ctx, int argc, char **argv, return ret; } -int parse_stream_core(struct parser_context *ctx, char *s) +API int parse_stream_core(struct parser_context *ctx, char *s) { struct unit_keyword_callback *kw; struct parser_state state; @@ -1268,7 +1268,7 @@ static char *open_stream(const char *name, unsigned int *_sz) return NULL; } -int parse_stream(const char *name, struct unit_parser *parser) +API int parse_stream(const char *name, struct unit_parser *parser) { char *stream; struct parser_context *ctx; -- 2.7.4 From ef63fea3b86d66beecdf06e4cd314b0e92df0dd0 Mon Sep 17 00:00:00 2001 From: Mateusz Malicki Date: Thu, 14 May 2015 12:31:27 +0200 Subject: [PATCH 16/16] libIpc separated from vasum #1 (code refactor) [Feature] Code refactor a) moved vasum::utils namspace to utils namespace b) moved vasum::ipc namespace to ipc namespace c) moved vasum::epoll namespace to ipc::epoll namespace d) moved common/epoll source dir to common/ipc/epoll e) moved UtilsException to utils namespace f) moved getSystemErrorMessage to utils/exception.hpp [Cause] N/A [Solution] N/A [Verification] Build, install Change-Id: I2cda58decfdb30ec9a27f7cb65940ae8dbc7edf3 --- client/CMakeLists.txt | 2 +- client/host-ipc-connection.cpp | 2 +- client/host-ipc-connection.hpp | 6 +-- client/vasum-client-impl.cpp | 4 +- client/vasum-client-impl.hpp | 2 +- common/base-exception.hpp | 7 --- common/ipc/client.cpp | 2 - common/ipc/client.hpp | 2 - common/{ => ipc}/epoll/event-poll.cpp | 9 ++-- common/{ => ipc}/epoll/event-poll.hpp | 6 +-- common/{ => ipc}/epoll/events.cpp | 6 +-- common/{ => ipc}/epoll/events.hpp | 4 +- common/{ => ipc}/epoll/glib-dispatcher.cpp | 6 +-- common/{ => ipc}/epoll/glib-dispatcher.hpp | 6 +-- common/{ => ipc}/epoll/thread-dispatcher.cpp | 6 +-- common/{ => ipc}/epoll/thread-dispatcher.hpp | 6 +-- common/ipc/exception.hpp | 4 +- common/ipc/internals/acceptor.cpp | 2 - common/ipc/internals/acceptor.hpp | 2 - common/ipc/internals/add-peer-request.hpp | 2 - common/ipc/internals/event-queue.hpp | 2 - common/ipc/internals/finish-request.hpp | 2 - common/ipc/internals/method-request.hpp | 2 - common/ipc/internals/processor.cpp | 4 +- common/ipc/internals/processor.hpp | 2 - common/ipc/internals/remove-peer-request.hpp | 2 - common/ipc/internals/request-queue.hpp | 2 - common/ipc/internals/result-builder.hpp | 2 - common/ipc/internals/send-result-request.hpp | 2 - common/ipc/internals/signal-request.hpp | 2 - common/ipc/internals/socket.cpp | 4 +- common/ipc/internals/socket.hpp | 2 - common/ipc/ipc-gsource.cpp | 2 - common/ipc/ipc-gsource.hpp | 2 - common/ipc/method-result.cpp | 2 - common/ipc/method-result.hpp | 2 - common/ipc/result.hpp | 2 - common/ipc/service.cpp | 2 - common/ipc/service.hpp | 2 - common/ipc/types.cpp | 2 - common/ipc/types.hpp | 2 - common/netlink/netlink.cpp | 3 +- common/utils/c-array.hpp | 2 - common/utils/callback-guard.cpp | 2 - common/utils/callback-guard.hpp | 2 - common/utils/callback-wrapper.hpp | 2 - common/utils/counting-map.hpp | 2 - common/utils/environment.cpp | 7 ++- common/utils/environment.hpp | 2 - common/utils/eventfd.cpp | 4 +- common/utils/eventfd.hpp | 2 - common/{base-exception.cpp => utils/exception.cpp} | 8 +-- common/utils/exception.hpp | 14 ++++-- common/utils/execute.cpp | 6 +-- common/utils/execute.hpp | 2 - common/utils/fd-utils.cpp | 4 +- common/utils/fd-utils.hpp | 2 - common/utils/file-wait.cpp | 3 +- common/utils/file-wait.hpp | 2 - common/utils/fs.cpp | 4 +- common/utils/fs.hpp | 2 - common/utils/glib-loop.cpp | 2 - common/utils/glib-loop.hpp | 2 - common/utils/glib-utils.cpp | 2 - common/utils/glib-utils.hpp | 2 - common/utils/img.cpp | 4 +- common/utils/img.hpp | 2 - common/utils/initctl.cpp | 2 - common/utils/initctl.hpp | 2 - common/utils/latch.cpp | 2 - common/utils/latch.hpp | 2 - common/utils/make-clean.hpp | 2 - common/utils/paths.hpp | 2 - common/utils/same-thread-guard.cpp | 2 - common/utils/same-thread-guard.hpp | 2 - common/utils/scoped-gerror.cpp | 2 - common/utils/scoped-gerror.hpp | 2 - common/utils/signal.cpp | 2 - common/utils/signal.hpp | 2 - common/utils/typeinfo.cpp | 2 - common/utils/typeinfo.hpp | 2 - common/utils/value-latch.hpp | 2 - common/utils/vt.cpp | 4 +- common/utils/vt.hpp | 2 - common/utils/worker.cpp | 2 - common/utils/worker.hpp | 2 - libs/dbus/connection.cpp | 2 +- libs/dbus/connection.hpp | 2 +- server/host-ipc-connection.hpp | 4 +- server/host-ipc-definitions.hpp | 58 +++++++++++----------- server/input-monitor.cpp | 2 +- server/netdev.cpp | 3 +- server/server.cpp | 3 ++ server/zone-provision.cpp | 2 + tests/unit_tests/client/ut-client.cpp | 2 +- tests/unit_tests/config/ut-configuration.cpp | 3 +- tests/unit_tests/config/ut-dynvisit.cpp | 3 +- tests/unit_tests/config/ut-kvstore.cpp | 4 +- tests/unit_tests/dbus/ut-connection.cpp | 2 +- tests/unit_tests/epoll/ut-event-poll.cpp | 12 ++--- tests/unit_tests/ipc/ut-ipc.cpp | 10 ++-- tests/unit_tests/ipc/ut-socket.cpp | 2 +- tests/unit_tests/server/ut-input-monitor.cpp | 2 +- tests/unit_tests/server/ut-server.cpp | 14 +++--- tests/unit_tests/server/ut-zone-provision.cpp | 1 + tests/unit_tests/server/ut-zone.cpp | 7 +-- tests/unit_tests/server/ut-zones-manager.cpp | 12 ++--- .../unit_tests/socket_test_service/socket-test.cpp | 2 +- tests/unit_tests/utils/scoped-daemon.cpp | 2 - tests/unit_tests/utils/scoped-daemon.hpp | 2 - tests/unit_tests/utils/scoped-dir.cpp | 2 - tests/unit_tests/utils/scoped-dir.hpp | 2 - tests/unit_tests/utils/ut-callback-guard.cpp | 3 +- tests/unit_tests/utils/ut-counting-map.cpp | 2 +- tests/unit_tests/utils/ut-fs.cpp | 3 +- tests/unit_tests/utils/ut-glib-loop.cpp | 3 +- tests/unit_tests/utils/ut-paths.cpp | 2 +- tests/unit_tests/utils/ut-same-thread-guard.cpp | 2 +- tests/unit_tests/utils/ut-value-latch.cpp | 8 +-- tests/unit_tests/utils/ut-worker.cpp | 4 +- 120 files changed, 164 insertions(+), 284 deletions(-) rename common/{ => ipc}/epoll/event-poll.cpp (97%) rename common/{ => ipc}/epoll/event-poll.hpp (96%) rename common/{ => ipc}/epoll/events.cpp (96%) rename common/{ => ipc}/epoll/events.hpp (96%) rename common/{ => ipc}/epoll/glib-dispatcher.cpp (96%) rename common/{ => ipc}/epoll/glib-dispatcher.hpp (94%) rename common/{ => ipc}/epoll/thread-dispatcher.cpp (95%) rename common/{ => ipc}/epoll/thread-dispatcher.hpp (95%) rename common/{base-exception.cpp => utils/exception.cpp} (89%) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 9b1d890..e08c79b 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -22,7 +22,7 @@ MESSAGE(STATUS "") MESSAGE(STATUS "Generating makefile for the Client...") FILE(GLOB project_SRCS *.cpp *.hpp *.h) -FILE(GLOB common_SRCS ${COMMON_FOLDER}/epoll/*.hpp ${COMMON_FOLDER}/epoll/*.cpp +FILE(GLOB common_SRCS ${COMMON_FOLDER}/ipc/epoll/*.hpp ${COMMON_FOLDER}/ipc/epoll/*.cpp ${COMMON_FOLDER}/ipc/*.hpp ${COMMON_FOLDER}/ipc/*.cpp ${COMMON_FOLDER}/ipc/internals/*.hpp ${COMMON_FOLDER}/ipc/internals/*.cpp ${COMMON_FOLDER}/utils/*.hpp ${COMMON_FOLDER}/utils/*.cpp diff --git a/client/host-ipc-connection.cpp b/client/host-ipc-connection.cpp index b17c6cf..7444f19 100644 --- a/client/host-ipc-connection.cpp +++ b/client/host-ipc-connection.cpp @@ -40,7 +40,7 @@ void HostIPCConnection::createSystem() mClient.reset(new ipc::Client(mDispatcher.getPoll(), HOST_IPC_SOCKET)); mClient->start(); } -epoll::ThreadDispatcher& HostIPCConnection::getDispatcher() +ipc::epoll::ThreadDispatcher& HostIPCConnection::getDispatcher() { return mDispatcher; } diff --git a/client/host-ipc-connection.hpp b/client/host-ipc-connection.hpp index 1497390..52b90b7 100644 --- a/client/host-ipc-connection.hpp +++ b/client/host-ipc-connection.hpp @@ -27,7 +27,7 @@ #define VASUM_CLIENT_HOST_IPC_CONNECTION_HPP #include -#include +#include #include #include @@ -44,7 +44,7 @@ public: typedef std::function NotificationCallback; void createSystem(); void create(const std::string& address); - epoll::ThreadDispatcher& getDispatcher(); + ipc::epoll::ThreadDispatcher& getDispatcher(); void callGetZoneIds(vasum::api::ZoneIds& argOut); void callGetActiveZoneId(vasum::api::ZoneId& argOut); @@ -80,7 +80,7 @@ public: void unsubscribe(const SubscriptionId& id); private: - epoll::ThreadDispatcher mDispatcher; + ipc::epoll::ThreadDispatcher mDispatcher; std::unique_ptr mClient; }; diff --git a/client/vasum-client-impl.cpp b/client/vasum-client-impl.cpp index bbc7e9e..b9af36f 100644 --- a/client/vasum-client-impl.cpp +++ b/client/vasum-client-impl.cpp @@ -27,6 +27,7 @@ #include "vasum-client-impl.hpp" #include "utils.hpp" #include "exception.hpp" +#include "utils/exception.hpp" #include "host-ipc-connection.hpp" #include "logger/logger.hpp" @@ -42,6 +43,7 @@ #include using namespace std; +using namespace utils; using namespace vasum; namespace { @@ -194,7 +196,7 @@ VsmStatus Client::create(const string& address) noexcept }); } -epoll::EventPoll& Client::getEventPoll() noexcept +ipc::epoll::EventPoll& Client::getEventPoll() noexcept { return mHostClient.getDispatcher().getPoll(); } diff --git a/client/vasum-client-impl.hpp b/client/vasum-client-impl.hpp index da6dc8f..0b96149 100644 --- a/client/vasum-client-impl.hpp +++ b/client/vasum-client-impl.hpp @@ -69,7 +69,7 @@ public: */ VsmStatus createSystem() noexcept; - vasum::epoll::EventPoll& getEventPoll() noexcept; + ipc::epoll::EventPoll& getEventPoll() noexcept; /** * Create client. diff --git a/common/base-exception.hpp b/common/base-exception.hpp index 89b79bc..645fa41 100644 --- a/common/base-exception.hpp +++ b/common/base-exception.hpp @@ -41,13 +41,6 @@ struct VasumException: public std::runtime_error { VasumException(const std::string& error) : std::runtime_error(error) {} }; -/** - * Return string describing error number - * it is wrapper for strerror_r - */ -std::string getSystemErrorMessage(); -std::string getSystemErrorMessage(int err); - } // namespace vasum diff --git a/common/ipc/client.cpp b/common/ipc/client.cpp index 75a62ad..3fff662 100644 --- a/common/ipc/client.cpp +++ b/common/ipc/client.cpp @@ -28,7 +28,6 @@ #include "ipc/internals/socket.hpp" #include "ipc/exception.hpp" -namespace vasum { namespace ipc { Client::Client(epoll::EventPoll& eventPoll, const std::string& socketPath) @@ -139,4 +138,3 @@ void Client::removeMethod(const MethodID methodID) } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/client.hpp b/common/ipc/client.hpp index db15a4a..c76a817 100644 --- a/common/ipc/client.hpp +++ b/common/ipc/client.hpp @@ -33,7 +33,6 @@ #include -namespace vasum { namespace ipc { /** @@ -212,6 +211,5 @@ void Client::signal(const MethodID methodID, } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_CLIENT_HPP diff --git a/common/epoll/event-poll.cpp b/common/ipc/epoll/event-poll.cpp similarity index 97% rename from common/epoll/event-poll.cpp rename to common/ipc/epoll/event-poll.cpp index adca814..d43c97d 100644 --- a/common/epoll/event-poll.cpp +++ b/common/ipc/epoll/event-poll.cpp @@ -23,7 +23,7 @@ */ #include "config.hpp" -#include "epoll/event-poll.hpp" +#include "ipc/epoll/event-poll.hpp" #include "utils/fd-utils.hpp" #include "utils/exception.hpp" #include "logger/logger.hpp" @@ -33,7 +33,10 @@ #include #include -namespace vasum { +using namespace vasum; +using namespace utils; + +namespace ipc { namespace epoll { EventPoll::EventPoll() @@ -176,4 +179,4 @@ void EventPoll::removeFDInternal(const int fd) } } // namespace epoll -} // namespace vasum +} // namespace ipc diff --git a/common/epoll/event-poll.hpp b/common/ipc/epoll/event-poll.hpp similarity index 96% rename from common/epoll/event-poll.hpp rename to common/ipc/epoll/event-poll.hpp index 67614ab..5e84ee3 100644 --- a/common/epoll/event-poll.hpp +++ b/common/ipc/epoll/event-poll.hpp @@ -25,14 +25,14 @@ #ifndef COMMON_EPOLL_EVENT_POLL_HPP #define COMMON_EPOLL_EVENT_POLL_HPP -#include "epoll/events.hpp" +#include "ipc/epoll/events.hpp" #include #include #include #include -namespace vasum { +namespace ipc { namespace epoll { class EventPoll { @@ -70,6 +70,6 @@ private: } // namespace epoll -} // namespace vasum +} // namespace ipc #endif // COMMON_EPOLL_EVENT_POLL_HPP diff --git a/common/epoll/events.cpp b/common/ipc/epoll/events.cpp similarity index 96% rename from common/epoll/events.cpp rename to common/ipc/epoll/events.cpp index 1ee27e0..35952fd 100644 --- a/common/epoll/events.cpp +++ b/common/ipc/epoll/events.cpp @@ -23,11 +23,11 @@ */ #include "config.hpp" -#include "epoll/events.hpp" +#include "ipc/epoll/events.hpp" #include -namespace vasum { +namespace ipc { namespace epoll { namespace { @@ -68,4 +68,4 @@ std::string eventsToString(Events events) } } // namespace epoll -} // namespace vasum +} // namespace ipc diff --git a/common/epoll/events.hpp b/common/ipc/epoll/events.hpp similarity index 96% rename from common/epoll/events.hpp rename to common/ipc/epoll/events.hpp index 62eb00a..093542b 100644 --- a/common/epoll/events.hpp +++ b/common/ipc/epoll/events.hpp @@ -28,7 +28,7 @@ #include #include // for EPOLL* constatnts -namespace vasum { +namespace ipc { namespace epoll { typedef unsigned int Events; ///< bitmask of EPOLL* constants @@ -36,6 +36,6 @@ typedef unsigned int Events; ///< bitmask of EPOLL* constants std::string eventsToString(Events events); } // namespace epoll -} // namespace vasum +} // namespace ipc #endif // COMMON_EPOLL_EVENTS_HPP diff --git a/common/epoll/glib-dispatcher.cpp b/common/ipc/epoll/glib-dispatcher.cpp similarity index 96% rename from common/epoll/glib-dispatcher.cpp rename to common/ipc/epoll/glib-dispatcher.cpp index 9567abb..d17ea54 100644 --- a/common/epoll/glib-dispatcher.cpp +++ b/common/ipc/epoll/glib-dispatcher.cpp @@ -23,10 +23,10 @@ */ #include "config.hpp" -#include "epoll/glib-dispatcher.hpp" +#include "ipc/epoll/glib-dispatcher.hpp" #include "utils/callback-wrapper.hpp" -namespace vasum { +namespace ipc { namespace epoll { GlibDispatcher::GlibDispatcher() @@ -63,4 +63,4 @@ EventPoll& GlibDispatcher::getPoll() } } // namespace epoll -} // namespace vasum +} // namespace ipc diff --git a/common/epoll/glib-dispatcher.hpp b/common/ipc/epoll/glib-dispatcher.hpp similarity index 94% rename from common/epoll/glib-dispatcher.hpp rename to common/ipc/epoll/glib-dispatcher.hpp index 0fa7b3a..2eb58b1 100644 --- a/common/epoll/glib-dispatcher.hpp +++ b/common/ipc/epoll/glib-dispatcher.hpp @@ -25,12 +25,12 @@ #ifndef COMMON_EPOLL_GLIB_DISPATCHER_HPP #define COMMON_EPOLL_GLIB_DISPATCHER_HPP -#include "epoll/event-poll.hpp" +#include "ipc/epoll/event-poll.hpp" #include "utils/callback-guard.hpp" #include -namespace vasum { +namespace ipc { namespace epoll { /** @@ -51,6 +51,6 @@ private: } // namespace epoll -} // namespace vasum +} // namespace ipc #endif // COMMON_UTILS_GLIB_DISPATCHER_HPP diff --git a/common/epoll/thread-dispatcher.cpp b/common/ipc/epoll/thread-dispatcher.cpp similarity index 95% rename from common/epoll/thread-dispatcher.cpp rename to common/ipc/epoll/thread-dispatcher.cpp index d286c19..fcc3d17 100644 --- a/common/epoll/thread-dispatcher.cpp +++ b/common/ipc/epoll/thread-dispatcher.cpp @@ -23,9 +23,9 @@ */ #include "config.hpp" -#include "epoll/thread-dispatcher.hpp" +#include "ipc/epoll/thread-dispatcher.hpp" -namespace vasum { +namespace ipc { namespace epoll { ThreadDispatcher::ThreadDispatcher() @@ -57,4 +57,4 @@ EventPoll& ThreadDispatcher::getPoll() } } // namespace epoll -} // namespace vasum +} // namespace ipc diff --git a/common/epoll/thread-dispatcher.hpp b/common/ipc/epoll/thread-dispatcher.hpp similarity index 95% rename from common/epoll/thread-dispatcher.hpp rename to common/ipc/epoll/thread-dispatcher.hpp index 5c6c145..033967f 100644 --- a/common/epoll/thread-dispatcher.hpp +++ b/common/ipc/epoll/thread-dispatcher.hpp @@ -25,13 +25,13 @@ #ifndef COMMON_EPOLL_THREAD_DISPATCHER_HPP #define COMMON_EPOLL_THREAD_DISPATCHER_HPP -#include "epoll/event-poll.hpp" +#include "ipc/epoll/event-poll.hpp" #include "utils/eventfd.hpp" #include #include -namespace vasum { +namespace ipc { namespace epoll { /** @@ -51,6 +51,6 @@ private: }; } // namespace epoll -} // namespace vasum +} // namespace ipc #endif // COMMON_EPOLL_THREAD_DISPATCHER_HPP diff --git a/common/ipc/exception.hpp b/common/ipc/exception.hpp index 8e9a7df..3d89d3b 100644 --- a/common/ipc/exception.hpp +++ b/common/ipc/exception.hpp @@ -28,13 +28,12 @@ #include "base-exception.hpp" -namespace vasum { namespace ipc { /** * Base class for exceptions in IPC */ -struct IPCException: public VasumException { +struct IPCException: public vasum::VasumException { IPCException(const std::string& message) : VasumException(message) {} }; @@ -90,6 +89,5 @@ private: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_EXCEPTION_HPP diff --git a/common/ipc/internals/acceptor.cpp b/common/ipc/internals/acceptor.cpp index 15b9ad8..604c65a 100644 --- a/common/ipc/internals/acceptor.cpp +++ b/common/ipc/internals/acceptor.cpp @@ -27,7 +27,6 @@ #include "ipc/internals/acceptor.hpp" #include "logger/logger.hpp" -namespace vasum { namespace ipc { Acceptor::Acceptor(const std::string& socketPath, const NewConnectionCallback& newConnectionCallback) @@ -54,4 +53,3 @@ FileDescriptor Acceptor::getConnectionFD() } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/internals/acceptor.hpp b/common/ipc/internals/acceptor.hpp index a6e9ec8..9725e70 100644 --- a/common/ipc/internals/acceptor.hpp +++ b/common/ipc/internals/acceptor.hpp @@ -32,7 +32,6 @@ #include -namespace vasum { namespace ipc { /** @@ -73,6 +72,5 @@ private: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_ACCEPTOR_HPP diff --git a/common/ipc/internals/add-peer-request.hpp b/common/ipc/internals/add-peer-request.hpp index 57ec06c..bb8a81f 100644 --- a/common/ipc/internals/add-peer-request.hpp +++ b/common/ipc/internals/add-peer-request.hpp @@ -28,7 +28,6 @@ #include "ipc/types.hpp" #include "ipc/internals/socket.hpp" -namespace vasum { namespace ipc { class AddPeerRequest { @@ -47,6 +46,5 @@ public: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_ADD_PEER_REQUEST_HPP diff --git a/common/ipc/internals/event-queue.hpp b/common/ipc/internals/event-queue.hpp index b4532fd..1b13449 100644 --- a/common/ipc/internals/event-queue.hpp +++ b/common/ipc/internals/event-queue.hpp @@ -33,7 +33,6 @@ #include #include -namespace vasum { namespace ipc { @@ -119,6 +118,5 @@ bool EventQueue::isEmpty() } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_EVENT_QUEUE_HPP diff --git a/common/ipc/internals/finish-request.hpp b/common/ipc/internals/finish-request.hpp index d09a14e..934c135 100644 --- a/common/ipc/internals/finish-request.hpp +++ b/common/ipc/internals/finish-request.hpp @@ -27,7 +27,6 @@ #include -namespace vasum { namespace ipc { class FinishRequest { @@ -43,6 +42,5 @@ public: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_FINISH_REQUEST_HPP diff --git a/common/ipc/internals/method-request.hpp b/common/ipc/internals/method-request.hpp index 8ec1223..663cbde 100644 --- a/common/ipc/internals/method-request.hpp +++ b/common/ipc/internals/method-request.hpp @@ -32,7 +32,6 @@ #include "config/manager.hpp" #include -namespace vasum { namespace ipc { class MethodRequest { @@ -94,6 +93,5 @@ std::shared_ptr MethodRequest::create(const MethodID methodID, } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_METHOD_REQUEST_HPP diff --git a/common/ipc/internals/processor.cpp b/common/ipc/internals/processor.cpp index 587723c..9cb86c0 100644 --- a/common/ipc/internals/processor.cpp +++ b/common/ipc/internals/processor.cpp @@ -36,7 +36,8 @@ #include #include -namespace vasum { +using namespace utils; + namespace ipc { #define IGNORE_EXCEPTIONS(expr) \ @@ -728,4 +729,3 @@ std::ostream& operator<<(std::ostream& os, const Processor::Event& event) } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/internals/processor.hpp b/common/ipc/internals/processor.hpp index 84aaa5c..ecc3a1d 100644 --- a/common/ipc/internals/processor.hpp +++ b/common/ipc/internals/processor.hpp @@ -54,7 +54,6 @@ #include #include -namespace vasum { namespace ipc { const unsigned int DEFAULT_MAX_NUMBER_OF_PEERS = 500; @@ -684,6 +683,5 @@ void Processor::signal(const MethodID methodID, } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_PROCESSOR_HPP diff --git a/common/ipc/internals/remove-peer-request.hpp b/common/ipc/internals/remove-peer-request.hpp index 6ef8eca..c9f7ec7 100644 --- a/common/ipc/internals/remove-peer-request.hpp +++ b/common/ipc/internals/remove-peer-request.hpp @@ -30,7 +30,6 @@ #include -namespace vasum { namespace ipc { class RemovePeerRequest { @@ -50,6 +49,5 @@ public: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_REMOVE_PEER_REQUEST_HPP diff --git a/common/ipc/internals/request-queue.hpp b/common/ipc/internals/request-queue.hpp index 44306ee..810175f 100644 --- a/common/ipc/internals/request-queue.hpp +++ b/common/ipc/internals/request-queue.hpp @@ -34,7 +34,6 @@ #include #include -namespace vasum { namespace ipc { /** @@ -184,6 +183,5 @@ bool RequestQueue::removeIf(Predicate predicate) return true; } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_MESSAGE_QUEUE_HPP diff --git a/common/ipc/internals/result-builder.hpp b/common/ipc/internals/result-builder.hpp index 3fe3c49..97134e3 100644 --- a/common/ipc/internals/result-builder.hpp +++ b/common/ipc/internals/result-builder.hpp @@ -30,7 +30,6 @@ #include #include -namespace vasum { namespace ipc { class ResultBuilder { @@ -67,7 +66,6 @@ typedef std::function ResultBuilderHandler; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_RESULT_BUILDER_HPP diff --git a/common/ipc/internals/send-result-request.hpp b/common/ipc/internals/send-result-request.hpp index bc1db6c..a6ed2b4 100644 --- a/common/ipc/internals/send-result-request.hpp +++ b/common/ipc/internals/send-result-request.hpp @@ -28,7 +28,6 @@ #include "ipc/types.hpp" #include "logger/logger-scope.hpp" -namespace vasum { namespace ipc { class SendResultRequest { @@ -53,6 +52,5 @@ public: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_SEND_RESULT_REQUEST_HPP diff --git a/common/ipc/internals/signal-request.hpp b/common/ipc/internals/signal-request.hpp index dac9c4d..904d3f3 100644 --- a/common/ipc/internals/signal-request.hpp +++ b/common/ipc/internals/signal-request.hpp @@ -29,7 +29,6 @@ #include "config/manager.hpp" #include "logger/logger-scope.hpp" -namespace vasum { namespace ipc { class SignalRequest { @@ -75,6 +74,5 @@ std::shared_ptr SignalRequest::create(const MethodID methodID, } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_SIGNAL_REQUEST_HPP diff --git a/common/ipc/internals/socket.cpp b/common/ipc/internals/socket.cpp index 26e1c27..0654a4e 100644 --- a/common/ipc/internals/socket.cpp +++ b/common/ipc/internals/socket.cpp @@ -27,6 +27,7 @@ #include "ipc/exception.hpp" #include "ipc/internals/socket.hpp" #include "utils/fd-utils.hpp" +#include "utils/exception.hpp" #include "logger/logger.hpp" #include @@ -38,8 +39,8 @@ #include #include +using namespace utils; -namespace vasum { namespace ipc { namespace { @@ -225,4 +226,3 @@ Socket Socket::connectSocket(const std::string& path) } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/internals/socket.hpp b/common/ipc/internals/socket.hpp index 839afe4..65f574d 100644 --- a/common/ipc/internals/socket.hpp +++ b/common/ipc/internals/socket.hpp @@ -29,7 +29,6 @@ #include #include -namespace vasum { namespace ipc { /** @@ -114,6 +113,5 @@ private: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_INTERNALS_SOCKET_HPP diff --git a/common/ipc/ipc-gsource.cpp b/common/ipc/ipc-gsource.cpp index 1769414..d339d50 100644 --- a/common/ipc/ipc-gsource.cpp +++ b/common/ipc/ipc-gsource.cpp @@ -31,7 +31,6 @@ #include -namespace vasum { namespace ipc { namespace { @@ -205,4 +204,3 @@ void IPCGSource::finalize(GSource* gSource) } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/ipc-gsource.hpp b/common/ipc/ipc-gsource.hpp index 87057db..ed01989 100644 --- a/common/ipc/ipc-gsource.hpp +++ b/common/ipc/ipc-gsource.hpp @@ -34,7 +34,6 @@ #include -namespace vasum { namespace ipc { /** @@ -143,6 +142,5 @@ private: }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_IPC_GSOURCE_HPP diff --git a/common/ipc/method-result.cpp b/common/ipc/method-result.cpp index 826354c..ffb97a8 100644 --- a/common/ipc/method-result.cpp +++ b/common/ipc/method-result.cpp @@ -27,7 +27,6 @@ #include "ipc/method-result.hpp" #include "ipc/internals/processor.hpp" -namespace vasum { namespace ipc { MethodResult::MethodResult(Processor& processor, @@ -56,4 +55,3 @@ void MethodResult::setError(const int code, const std::string& message) } } // namespace ipc -} // namespace vasum diff --git a/common/ipc/method-result.hpp b/common/ipc/method-result.hpp index ebe9697..bd9d10f 100644 --- a/common/ipc/method-result.hpp +++ b/common/ipc/method-result.hpp @@ -29,7 +29,6 @@ #include "logger/logger.hpp" #include -namespace vasum { namespace ipc { class Processor; @@ -70,6 +69,5 @@ struct MethodHandler { }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_METHOD_RESULT_HPP diff --git a/common/ipc/result.hpp b/common/ipc/result.hpp index 0edf172..9069fd5 100644 --- a/common/ipc/result.hpp +++ b/common/ipc/result.hpp @@ -29,7 +29,6 @@ #include #include -namespace vasum { namespace ipc { template @@ -69,6 +68,5 @@ struct ResultHandler { }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_RESULT_HPP diff --git a/common/ipc/service.cpp b/common/ipc/service.cpp index d4e1b88..48d8c96 100644 --- a/common/ipc/service.cpp +++ b/common/ipc/service.cpp @@ -30,7 +30,6 @@ using namespace std::placeholders; -namespace vasum { namespace ipc { Service::Service(epoll::EventPoll& eventPoll, @@ -149,4 +148,3 @@ void Service::removeMethod(const MethodID methodID) } // namespace ipc -} // namespace vasum diff --git a/common/ipc/service.hpp b/common/ipc/service.hpp index 32b604f..8f6f62b 100644 --- a/common/ipc/service.hpp +++ b/common/ipc/service.hpp @@ -34,7 +34,6 @@ #include -namespace vasum { namespace ipc { @@ -220,6 +219,5 @@ void Service::signal(const MethodID methodID, } } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_SERVICE_HPP diff --git a/common/ipc/types.cpp b/common/ipc/types.cpp index 9854e0e..0961b35 100644 --- a/common/ipc/types.cpp +++ b/common/ipc/types.cpp @@ -29,7 +29,6 @@ #include -namespace vasum { namespace ipc { namespace { @@ -49,4 +48,3 @@ PeerID getNextPeerID() } // namespace ipc -} // namespace vasum diff --git a/common/ipc/types.hpp b/common/ipc/types.hpp index 3fec337..ab4ed00 100644 --- a/common/ipc/types.hpp +++ b/common/ipc/types.hpp @@ -29,7 +29,6 @@ #include #include -namespace vasum { namespace ipc { typedef int FileDescriptor; @@ -52,6 +51,5 @@ struct SignalHandler { }; } // namespace ipc -} // namespace vasum #endif // COMMON_IPC_TYPES_HPP diff --git a/common/netlink/netlink.cpp b/common/netlink/netlink.cpp index e5cf8a7..633276a 100644 --- a/common/netlink/netlink.cpp +++ b/common/netlink/netlink.cpp @@ -25,7 +25,7 @@ #include "config.hpp" #include "netlink.hpp" #include "utils.hpp" -#include "base-exception.hpp" +#include "utils/exception.hpp" #include "utils/make-clean.hpp" #include "utils/environment.hpp" @@ -40,6 +40,7 @@ #define PAGE_SIZE 4096 #endif +using namespace utils; using namespace vasum; namespace { diff --git a/common/utils/c-array.hpp b/common/utils/c-array.hpp index 68fa816..d238e4a 100644 --- a/common/utils/c-array.hpp +++ b/common/utils/c-array.hpp @@ -27,7 +27,6 @@ #include -namespace vasum { namespace utils { template @@ -67,7 +66,6 @@ private: typedef CArrayBuilder CStringArrayBuilder; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_C_ARRAY_HPP diff --git a/common/utils/callback-guard.cpp b/common/utils/callback-guard.cpp index b0ce7dd..c3deca1 100644 --- a/common/utils/callback-guard.cpp +++ b/common/utils/callback-guard.cpp @@ -31,7 +31,6 @@ #include -namespace vasum { namespace utils { // Reference counting class like shared_ptr but with the ability to wait for it. @@ -127,4 +126,3 @@ bool CallbackGuard::waitForTrackers(const unsigned int timeoutMs) } } // namespace utils -} // namespace vasum diff --git a/common/utils/callback-guard.hpp b/common/utils/callback-guard.hpp index d28e707..7cb299b 100644 --- a/common/utils/callback-guard.hpp +++ b/common/utils/callback-guard.hpp @@ -29,7 +29,6 @@ #include -namespace vasum { namespace utils { /** @@ -73,7 +72,6 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_CALLBACK_GUARD_HPP diff --git a/common/utils/callback-wrapper.hpp b/common/utils/callback-wrapper.hpp index fd5a4c0..fbf8455 100644 --- a/common/utils/callback-wrapper.hpp +++ b/common/utils/callback-wrapper.hpp @@ -28,7 +28,6 @@ #include "callback-guard.hpp" -namespace vasum { namespace utils { @@ -86,7 +85,6 @@ const Callback& getCallbackFromPointer(const void* pointer) } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_CALLBACK_WRAPPER_HPP diff --git a/common/utils/counting-map.hpp b/common/utils/counting-map.hpp index da5f4c7..a05f76a 100644 --- a/common/utils/counting-map.hpp +++ b/common/utils/counting-map.hpp @@ -27,7 +27,6 @@ #include -namespace vasum { namespace utils { @@ -82,7 +81,6 @@ private: } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_COUNTING_MAP_HPP diff --git a/common/utils/environment.cpp b/common/utils/environment.cpp index 209f9ba..7bd7d07 100644 --- a/common/utils/environment.cpp +++ b/common/utils/environment.cpp @@ -26,6 +26,7 @@ #include "utils/environment.hpp" #include "utils/execute.hpp" +#include "utils/exception.hpp" #include "utils/make-clean.hpp" #include "base-exception.hpp" #include "logger/logger.hpp" @@ -60,7 +61,7 @@ static inline int setns(int fd, int nstype) #endif -using namespace vasum::utils; +using namespace utils; namespace { @@ -126,7 +127,6 @@ bool fdSend(int socket, int fd) } // namespace -namespace vasum { namespace utils { @@ -223,7 +223,7 @@ int passNemaspacedFd(int nsPid, int ns, const std::function& fdFactory) int fds[2]; int ret = socketpair(PF_LOCAL, SOCK_RAW, 0, fds); if (ret == -1) { - LOGE("Can't create socket pair: " << vasum::getSystemErrorMessage()); + LOGE("Can't create socket pair: " << getSystemErrorMessage()); return -1; } bool success = executeAndWait([&, fds, nsPid, ns]() { @@ -254,4 +254,3 @@ int passNemaspacedFd(int nsPid, int ns, const std::function& fdFactory) } } // namespace utils -} // namespace vasum diff --git a/common/utils/environment.hpp b/common/utils/environment.hpp index d63ac16..b4e3194 100644 --- a/common/utils/environment.hpp +++ b/common/utils/environment.hpp @@ -31,7 +31,6 @@ #include -namespace vasum { namespace utils { @@ -63,7 +62,6 @@ bool joinToNs(int nsPid, int ns); int passNemaspacedFd(int nsPid, int ns, const std::function& fdFactory); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_ENVIRONMENT_HPP diff --git a/common/utils/eventfd.cpp b/common/utils/eventfd.cpp index d69d572..a1b45e9 100644 --- a/common/utils/eventfd.cpp +++ b/common/utils/eventfd.cpp @@ -34,7 +34,8 @@ #include #include -namespace vasum { +using namespace vasum; + namespace utils { EventFD::EventFD() @@ -71,4 +72,3 @@ void EventFD::receive() } // namespace utils -} // namespace vasum diff --git a/common/utils/eventfd.hpp b/common/utils/eventfd.hpp index b3d5027..f49bbff 100644 --- a/common/utils/eventfd.hpp +++ b/common/utils/eventfd.hpp @@ -25,7 +25,6 @@ #ifndef COMMON_UTILS_EVENTFD_HPP #define COMMON_UTILS_EVENTFD_HPP -namespace vasum { namespace utils { class EventFD { @@ -58,6 +57,5 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_EVENTFD_HPP diff --git a/common/base-exception.cpp b/common/utils/exception.cpp similarity index 89% rename from common/base-exception.cpp rename to common/utils/exception.cpp index 628296d..ae69618 100644 --- a/common/base-exception.cpp +++ b/common/utils/exception.cpp @@ -19,16 +19,16 @@ /** * @file * @author Mateusz Malicki (m.malicki2@samsung.com) - * @brief Vasum base exception implementation + * @brief Utils base exception helper implementation */ -#include "base-exception.hpp" +#include "utils/exception.hpp" #include #include #include -namespace vasum { +namespace utils { const int ERROR_MESSAGE_BUFFER_CAPACITY = 256; @@ -43,4 +43,4 @@ std::string getSystemErrorMessage(int err) return strerror_r(err, buf, sizeof(buf)); } -} // namespace vasum +} // namespace utils diff --git a/common/utils/exception.hpp b/common/utils/exception.hpp index 32f416c..49aceb8 100644 --- a/common/utils/exception.hpp +++ b/common/utils/exception.hpp @@ -29,18 +29,24 @@ #include "base-exception.hpp" -namespace vasum { +namespace utils { /** * Base class for exceptions in utils */ -struct UtilsException: public VasumException { +struct UtilsException: public vasum::VasumException { - UtilsException(const std::string& error) : VasumException(error) {} + UtilsException(const std::string& error) : vasum::VasumException(error) {} }; +/** + * Return string describing error number + * it is wrapper for strerror_r + */ +std::string getSystemErrorMessage(); +std::string getSystemErrorMessage(int err); -} // namespace vasum +} // namespace utils #endif // COMMON_UTILS_EXCEPTION_HPP diff --git a/common/utils/execute.cpp b/common/utils/execute.cpp index 4e8eebf..d030177 100644 --- a/common/utils/execute.cpp +++ b/common/utils/execute.cpp @@ -23,7 +23,7 @@ */ #include "config.hpp" -#include "base-exception.hpp" +#include "utils/exception.hpp" #include "utils/execute.hpp" #include "logger/logger.hpp" @@ -31,7 +31,6 @@ #include #include -namespace vasum { namespace utils { namespace { @@ -74,7 +73,7 @@ bool executeAndWait(const std::function& func, int& status) pid_t pid = fork(); if (pid == -1) { - LOGE("Fork failed: " << vasum::getSystemErrorMessage()); + LOGE("Fork failed: " << getSystemErrorMessage()); return false; } if (pid == 0) { @@ -128,4 +127,3 @@ bool waitPid(pid_t pid, int& status) } } // namespace utils -} // namespace vasum diff --git a/common/utils/execute.hpp b/common/utils/execute.hpp index 8f7fd56..bc5cf9d 100644 --- a/common/utils/execute.hpp +++ b/common/utils/execute.hpp @@ -28,7 +28,6 @@ #include #include -namespace vasum { namespace utils { /** @@ -55,7 +54,6 @@ bool executeAndWait(const std::function& func); bool waitPid(pid_t pid, int& status); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_EXECUTE_HPP diff --git a/common/utils/fd-utils.cpp b/common/utils/fd-utils.cpp index 17448b5..95080ff 100644 --- a/common/utils/fd-utils.cpp +++ b/common/utils/fd-utils.cpp @@ -39,7 +39,8 @@ namespace fs = boost::filesystem; namespace chr = std::chrono; -namespace vasum { +using namespace vasum; + namespace utils { namespace { @@ -202,5 +203,4 @@ unsigned int getFDNumber() } } // namespace utils -} // namespace vasum diff --git a/common/utils/fd-utils.hpp b/common/utils/fd-utils.hpp index ac32b0a..151eb1c 100644 --- a/common/utils/fd-utils.hpp +++ b/common/utils/fd-utils.hpp @@ -27,7 +27,6 @@ #include -namespace vasum { namespace utils { /** @@ -73,6 +72,5 @@ void setMaxFDNumber(unsigned int limit); unsigned int getFDNumber(); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_FD_HPP diff --git a/common/utils/file-wait.cpp b/common/utils/file-wait.cpp index f89ada6..4949314 100644 --- a/common/utils/file-wait.cpp +++ b/common/utils/file-wait.cpp @@ -30,8 +30,8 @@ #include #include +using namespace vasum; -namespace vasum { namespace utils { @@ -56,4 +56,3 @@ void waitForFile(const std::string& filename, const unsigned int timeoutMs) } // namespace utils -} // namespace vasum diff --git a/common/utils/file-wait.hpp b/common/utils/file-wait.hpp index 9029c6e..02b361e 100644 --- a/common/utils/file-wait.hpp +++ b/common/utils/file-wait.hpp @@ -28,7 +28,6 @@ #include -namespace vasum { namespace utils { @@ -38,7 +37,6 @@ void waitForFile(const std::string& filename, const unsigned int timeoutMs); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_FILE_WAIT_HPP diff --git a/common/utils/fs.cpp b/common/utils/fs.cpp index e4dcd7f..5581a29 100644 --- a/common/utils/fs.cpp +++ b/common/utils/fs.cpp @@ -45,7 +45,8 @@ namespace fs = boost::filesystem; -namespace vasum { +using namespace vasum; + namespace utils { @@ -527,4 +528,3 @@ bool createLink(const std::string& src, const std::string& dest) } } // namespace utils -} // namespace vasum diff --git a/common/utils/fs.hpp b/common/utils/fs.hpp index b2e05b6..bff2e70 100644 --- a/common/utils/fs.hpp +++ b/common/utils/fs.hpp @@ -31,7 +31,6 @@ #include -namespace vasum { namespace utils { /** @@ -149,7 +148,6 @@ bool copyFile(const std::string& src, const std::string& dest); bool createLink(const std::string& src, const std::string& dest); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_FS_HPP diff --git a/common/utils/glib-loop.cpp b/common/utils/glib-loop.cpp index dd82204..0ce15d9 100644 --- a/common/utils/glib-loop.cpp +++ b/common/utils/glib-loop.cpp @@ -30,7 +30,6 @@ #include #include -namespace vasum { namespace utils { namespace { @@ -85,4 +84,3 @@ gboolean Glib::onTimerEvent(gpointer data) } // namespace utils -} // namespace vasum diff --git a/common/utils/glib-loop.hpp b/common/utils/glib-loop.hpp index 8db43b6..0c5a459 100644 --- a/common/utils/glib-loop.hpp +++ b/common/utils/glib-loop.hpp @@ -32,7 +32,6 @@ #include -namespace vasum { namespace utils { @@ -81,7 +80,6 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_GLIB_LOOP_HPP diff --git a/common/utils/glib-utils.cpp b/common/utils/glib-utils.cpp index 93cbff9..fcd2f35 100644 --- a/common/utils/glib-utils.cpp +++ b/common/utils/glib-utils.cpp @@ -28,7 +28,6 @@ #include -namespace vasum { namespace utils { namespace { @@ -56,4 +55,3 @@ void executeInGlibThread(const VoidCallback& callback, const CallbackGuard& guar } // namespace utils -} // namespace vasum diff --git a/common/utils/glib-utils.hpp b/common/utils/glib-utils.hpp index eaeeee8..a818230 100644 --- a/common/utils/glib-utils.hpp +++ b/common/utils/glib-utils.hpp @@ -27,7 +27,6 @@ #include "utils/callback-guard.hpp" -namespace vasum { namespace utils { typedef std::function VoidCallback; @@ -39,6 +38,5 @@ void executeInGlibThread(const VoidCallback& callback, const CallbackGuard& guar } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_GLIB_UTILS_HPP diff --git a/common/utils/img.cpp b/common/utils/img.cpp index 785291c..20f6daf 100644 --- a/common/utils/img.cpp +++ b/common/utils/img.cpp @@ -27,13 +27,12 @@ #include "utils/img.hpp" #include "utils/fs.hpp" #include "utils/paths.hpp" -#include "base-exception.hpp" +#include "utils/exception.hpp" #include #include #include -namespace vasum { namespace utils { namespace { @@ -238,4 +237,3 @@ bool copyImageContents(const std::string& img, const std::string& dst) } } // namespace utils -} // namespace vasum diff --git a/common/utils/img.hpp b/common/utils/img.hpp index 8782ae2..de04fdc 100644 --- a/common/utils/img.hpp +++ b/common/utils/img.hpp @@ -25,7 +25,6 @@ #ifndef COMMON_UTILS_IMG_HPP #define COMMON_UTILS_IMG_HPP -namespace vasum { namespace utils { /** @@ -50,6 +49,5 @@ bool umountImage(const std::string& path, const std::string& loopdev); bool copyImageContents(const std::string& img, const std::string& dst); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_IMG_HPP diff --git a/common/utils/initctl.cpp b/common/utils/initctl.cpp index 5986799..55e8cfd 100644 --- a/common/utils/initctl.cpp +++ b/common/utils/initctl.cpp @@ -30,7 +30,6 @@ #include #include -namespace vasum { namespace utils { namespace { @@ -87,4 +86,3 @@ bool setRunLevel(RunLevel runLevel) } // namespace utils -} // namespace vasum diff --git a/common/utils/initctl.hpp b/common/utils/initctl.hpp index 97f4ca4..d81c7bc 100644 --- a/common/utils/initctl.hpp +++ b/common/utils/initctl.hpp @@ -26,7 +26,6 @@ #define COMMON_UTILS_INITCTL_HPP -namespace vasum { namespace utils { enum RunLevel : int { @@ -38,7 +37,6 @@ bool setRunLevel(RunLevel runLevel); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_INITCTL_HPP diff --git a/common/utils/latch.cpp b/common/utils/latch.cpp index e4b3649..4889946 100644 --- a/common/utils/latch.cpp +++ b/common/utils/latch.cpp @@ -28,7 +28,6 @@ #include -namespace vasum { namespace utils { @@ -81,4 +80,3 @@ bool Latch::empty() } // namespace utils -} // namespace vasum diff --git a/common/utils/latch.hpp b/common/utils/latch.hpp index 7ef1dd7..ad48475 100644 --- a/common/utils/latch.hpp +++ b/common/utils/latch.hpp @@ -29,7 +29,6 @@ #include -namespace vasum { namespace utils { @@ -89,7 +88,6 @@ private: } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_LATCH_HPP diff --git a/common/utils/make-clean.hpp b/common/utils/make-clean.hpp index 1d551ef..18fe6d7 100644 --- a/common/utils/make-clean.hpp +++ b/common/utils/make-clean.hpp @@ -28,7 +28,6 @@ #include #include -namespace vasum { namespace utils { template @@ -47,7 +46,6 @@ T make_clean() } } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_MAKE_CLEAN_HPP diff --git a/common/utils/paths.hpp b/common/utils/paths.hpp index b86333f..26ebde6 100644 --- a/common/utils/paths.hpp +++ b/common/utils/paths.hpp @@ -30,7 +30,6 @@ #include -namespace vasum { namespace utils { @@ -121,7 +120,6 @@ inline std::string getAbsolutePath(const std::string& path, const std::string& b } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_PATHS_HPP diff --git a/common/utils/same-thread-guard.cpp b/common/utils/same-thread-guard.cpp index 5b54c73..65621d4 100644 --- a/common/utils/same-thread-guard.cpp +++ b/common/utils/same-thread-guard.cpp @@ -30,7 +30,6 @@ #include "logger/logger.hpp" #include "logger/formatter.hpp" -namespace vasum { namespace utils { namespace { @@ -70,6 +69,5 @@ void SameThreadGuard::reset() } } // namespace utils -} // namespace vasum #endif // ENABLE_SAME_THREAD_GUARD diff --git a/common/utils/same-thread-guard.hpp b/common/utils/same-thread-guard.hpp index fd697fd..3a173b5 100644 --- a/common/utils/same-thread-guard.hpp +++ b/common/utils/same-thread-guard.hpp @@ -34,7 +34,6 @@ #include #endif -namespace vasum { namespace utils { /** @@ -74,7 +73,6 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_SAME_THREAD_GUARD_HPP diff --git a/common/utils/scoped-gerror.cpp b/common/utils/scoped-gerror.cpp index 0e4de47..92e0dd2 100644 --- a/common/utils/scoped-gerror.cpp +++ b/common/utils/scoped-gerror.cpp @@ -26,7 +26,6 @@ #include "scoped-gerror.hpp" -namespace vasum { namespace utils { ScopedGError::ScopedGError() @@ -74,4 +73,3 @@ std::ostream& operator<<(std::ostream& os, const ScopedGError& e) } } // namespace utils -} // namespace vasum diff --git a/common/utils/scoped-gerror.hpp b/common/utils/scoped-gerror.hpp index 0ee4c64..5d3bcc7 100644 --- a/common/utils/scoped-gerror.hpp +++ b/common/utils/scoped-gerror.hpp @@ -28,7 +28,6 @@ #include #include -namespace vasum{ namespace utils { class ScopedGError { @@ -73,6 +72,5 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_SCOPED_GERROR_HPP diff --git a/common/utils/signal.cpp b/common/utils/signal.cpp index 11ea8f2..2daa766 100644 --- a/common/utils/signal.cpp +++ b/common/utils/signal.cpp @@ -31,7 +31,6 @@ #include #include -namespace vasum { namespace utils { void signalBlock(const int signalToBlock) @@ -57,7 +56,6 @@ void signalBlock(const int signalToBlock) } } // namespace utils -} // namespace vasum diff --git a/common/utils/signal.hpp b/common/utils/signal.hpp index f26e365..c466688 100644 --- a/common/utils/signal.hpp +++ b/common/utils/signal.hpp @@ -25,13 +25,11 @@ #ifndef COMMON_UTILS_SIGNAL_HPP #define COMMON_UTILS_SIGNAL_HPP -namespace vasum { namespace utils { void signalBlock(const int signalsToBlock); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_SIGNAL_HPP diff --git a/common/utils/typeinfo.cpp b/common/utils/typeinfo.cpp index 0f7e574..e97aa35 100644 --- a/common/utils/typeinfo.cpp +++ b/common/utils/typeinfo.cpp @@ -29,7 +29,6 @@ #include #include -namespace vasum { namespace utils { std::string getTypeName(const std::type_info& ti) @@ -47,4 +46,3 @@ std::string getTypeName(const std::type_info& ti) } } // namespace utils -} // namespace vasum diff --git a/common/utils/typeinfo.hpp b/common/utils/typeinfo.hpp index 9faf0cb..f1c83a0 100644 --- a/common/utils/typeinfo.hpp +++ b/common/utils/typeinfo.hpp @@ -28,7 +28,6 @@ #include #include -namespace vasum { namespace utils { std::string getTypeName(const std::type_info& ti); @@ -39,7 +38,6 @@ template std::string getTypeName(const T& t) } } // namespace utils -} // namespace vasum #endif // COMMON_TYPE_INFO_HPP diff --git a/common/utils/value-latch.hpp b/common/utils/value-latch.hpp index 0e06f6f..74fc738 100644 --- a/common/utils/value-latch.hpp +++ b/common/utils/value-latch.hpp @@ -31,7 +31,6 @@ #include #include -namespace vasum { namespace utils { template @@ -121,6 +120,5 @@ T ValueLatch::get(const unsigned int timeoutMs) } } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_VALUE_LATCH_H diff --git a/common/utils/vt.cpp b/common/utils/vt.cpp index 44461e4..373a949 100644 --- a/common/utils/vt.cpp +++ b/common/utils/vt.cpp @@ -25,7 +25,7 @@ #include "config.hpp" #include "utils/vt.hpp" #include "logger/logger.hpp" -#include "base-exception.hpp" +#include "utils/exception.hpp" #include #include @@ -40,7 +40,6 @@ const std::string TTY_DEV = "/dev/tty0"; } // namespace -namespace vasum { namespace utils { bool activateVT(const int& vt) @@ -84,4 +83,3 @@ bool activateVT(const int& vt) } } // namespace utils -} // namespace vasum diff --git a/common/utils/vt.hpp b/common/utils/vt.hpp index 16f4030..a28261c 100644 --- a/common/utils/vt.hpp +++ b/common/utils/vt.hpp @@ -25,12 +25,10 @@ #ifndef COMMON_UTILS_VT_HPP #define COMMON_UTILS_VT_HPP -namespace vasum { namespace utils { bool activateVT(const int& vt); } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_VT_HPP diff --git a/common/utils/worker.cpp b/common/utils/worker.cpp index 2cb3284..7e87d33 100644 --- a/common/utils/worker.cpp +++ b/common/utils/worker.cpp @@ -35,7 +35,6 @@ #include -namespace vasum { namespace utils { @@ -183,4 +182,3 @@ void Worker::addTask(const Task& task) } // namespace utils -} // namespace vasum diff --git a/common/utils/worker.hpp b/common/utils/worker.hpp index 0d951fb..677f218 100644 --- a/common/utils/worker.hpp +++ b/common/utils/worker.hpp @@ -28,7 +28,6 @@ #include #include -namespace vasum { namespace utils { /** @@ -68,7 +67,6 @@ private: }; } // namespace utils -} // namespace vasum #endif // COMMON_UTILS_WORKER_HPP diff --git a/libs/dbus/connection.cpp b/libs/dbus/connection.cpp index 3485ea5..60b3225 100644 --- a/libs/dbus/connection.cpp +++ b/libs/dbus/connection.cpp @@ -30,7 +30,7 @@ #include "utils/glib-utils.hpp" #include "logger/logger.hpp" -using namespace vasum::utils; +using namespace utils; namespace dbus { diff --git a/libs/dbus/connection.hpp b/libs/dbus/connection.hpp index faf737c..5248d2e 100644 --- a/libs/dbus/connection.hpp +++ b/libs/dbus/connection.hpp @@ -181,7 +181,7 @@ private: : nameAcquired(acquired), nameLost(lost) {} }; - vasum::utils::CallbackGuard mGuard; + utils::CallbackGuard mGuard; GDBusConnection* mConnection; guint mNameId; diff --git a/server/host-ipc-connection.hpp b/server/host-ipc-connection.hpp index d5144fd..b5d671e 100644 --- a/server/host-ipc-connection.hpp +++ b/server/host-ipc-connection.hpp @@ -27,7 +27,7 @@ #define SERVER_HOST_IPC_CONNECTION_HPP #include "api/messages.hpp" -#include "epoll/thread-dispatcher.hpp" +#include "ipc/epoll/thread-dispatcher.hpp" #include "ipc/service.hpp" #include "ipc-callback-wrapper.hpp" @@ -84,7 +84,7 @@ public: void sendNotification(const api::Notification& notification); private: - epoll::ThreadDispatcher mDispatcher; + ipc::epoll::ThreadDispatcher mDispatcher; std::unique_ptr mService; }; diff --git a/server/host-ipc-definitions.hpp b/server/host-ipc-definitions.hpp index a54b679..0053efa 100644 --- a/server/host-ipc-definitions.hpp +++ b/server/host-ipc-definitions.hpp @@ -31,36 +31,36 @@ namespace vasum { namespace api { namespace ipc { -const vasum::ipc::MethodID METHOD_GET_ZONE_ID_LIST = 2; -const vasum::ipc::MethodID METHOD_GET_ACTIVE_ZONE_ID = 3; -const vasum::ipc::MethodID METHOD_GET_ZONE_INFO = 4; -const vasum::ipc::MethodID METHOD_SET_NETDEV_ATTRS = 5; -const vasum::ipc::MethodID METHOD_GET_NETDEV_ATTRS = 6; -const vasum::ipc::MethodID METHOD_GET_NETDEV_LIST = 7; -const vasum::ipc::MethodID METHOD_CREATE_NETDEV_VETH = 8; -const vasum::ipc::MethodID METHOD_CREATE_NETDEV_MACVLAN = 9; -const vasum::ipc::MethodID METHOD_CREATE_NETDEV_PHYS = 10; -const vasum::ipc::MethodID METHOD_DELETE_NETDEV_IP_ADDRESS = 11; -const vasum::ipc::MethodID METHOD_DESTROY_NETDEV = 12; -const vasum::ipc::MethodID METHOD_DECLARE_FILE = 13; -const vasum::ipc::MethodID METHOD_DECLARE_MOUNT = 14; -const vasum::ipc::MethodID METHOD_DECLARE_LINK = 15; -const vasum::ipc::MethodID METHOD_GET_DECLARATIONS = 16; -const vasum::ipc::MethodID METHOD_REMOVE_DECLARATION = 17; -const vasum::ipc::MethodID METHOD_SET_ACTIVE_ZONE = 18; -const vasum::ipc::MethodID METHOD_CREATE_ZONE = 19; -const vasum::ipc::MethodID METHOD_DESTROY_ZONE = 20; -const vasum::ipc::MethodID METHOD_SHUTDOWN_ZONE = 21; -const vasum::ipc::MethodID METHOD_START_ZONE = 22; -const vasum::ipc::MethodID METHOD_LOCK_ZONE = 23; -const vasum::ipc::MethodID METHOD_UNLOCK_ZONE = 24; -const vasum::ipc::MethodID METHOD_GRANT_DEVICE = 25; -const vasum::ipc::MethodID METHOD_REVOKE_DEVICE = 26; +const ::ipc::MethodID METHOD_GET_ZONE_ID_LIST = 2; +const ::ipc::MethodID METHOD_GET_ACTIVE_ZONE_ID = 3; +const ::ipc::MethodID METHOD_GET_ZONE_INFO = 4; +const ::ipc::MethodID METHOD_SET_NETDEV_ATTRS = 5; +const ::ipc::MethodID METHOD_GET_NETDEV_ATTRS = 6; +const ::ipc::MethodID METHOD_GET_NETDEV_LIST = 7; +const ::ipc::MethodID METHOD_CREATE_NETDEV_VETH = 8; +const ::ipc::MethodID METHOD_CREATE_NETDEV_MACVLAN = 9; +const ::ipc::MethodID METHOD_CREATE_NETDEV_PHYS = 10; +const ::ipc::MethodID METHOD_DELETE_NETDEV_IP_ADDRESS = 11; +const ::ipc::MethodID METHOD_DESTROY_NETDEV = 12; +const ::ipc::MethodID METHOD_DECLARE_FILE = 13; +const ::ipc::MethodID METHOD_DECLARE_MOUNT = 14; +const ::ipc::MethodID METHOD_DECLARE_LINK = 15; +const ::ipc::MethodID METHOD_GET_DECLARATIONS = 16; +const ::ipc::MethodID METHOD_REMOVE_DECLARATION = 17; +const ::ipc::MethodID METHOD_SET_ACTIVE_ZONE = 18; +const ::ipc::MethodID METHOD_CREATE_ZONE = 19; +const ::ipc::MethodID METHOD_DESTROY_ZONE = 20; +const ::ipc::MethodID METHOD_SHUTDOWN_ZONE = 21; +const ::ipc::MethodID METHOD_START_ZONE = 22; +const ::ipc::MethodID METHOD_LOCK_ZONE = 23; +const ::ipc::MethodID METHOD_UNLOCK_ZONE = 24; +const ::ipc::MethodID METHOD_GRANT_DEVICE = 25; +const ::ipc::MethodID METHOD_REVOKE_DEVICE = 26; -const vasum::ipc::MethodID METHOD_NOTIFY_ACTIVE_ZONE = 100; -const vasum::ipc::MethodID METHOD_FILE_MOVE_REQUEST = 101; -const vasum::ipc::MethodID SIGNAL_NOTIFICATION = 102; -const vasum::ipc::MethodID SIGNAL_SWITCH_TO_DEFAULT = 103; +const ::ipc::MethodID METHOD_NOTIFY_ACTIVE_ZONE = 100; +const ::ipc::MethodID METHOD_FILE_MOVE_REQUEST = 101; +const ::ipc::MethodID SIGNAL_NOTIFICATION = 102; +const ::ipc::MethodID SIGNAL_SWITCH_TO_DEFAULT = 103; const std::string FILE_MOVE_DESTINATION_NOT_FOUND = "FILE_MOVE_DESTINATION_NOT_FOUND"; const std::string FILE_MOVE_WRONG_DESTINATION = "FILE_MOVE_WRONG_DESTINATION"; diff --git a/server/input-monitor.cpp b/server/input-monitor.cpp index 68e63c0..e99906f 100644 --- a/server/input-monitor.cpp +++ b/server/input-monitor.cpp @@ -49,7 +49,7 @@ #include #include -using namespace vasum::utils; +using namespace utils; namespace fs = boost::filesystem; namespace vasum { diff --git a/server/netdev.cpp b/server/netdev.cpp index 38ccb88..b9a1389 100644 --- a/server/netdev.cpp +++ b/server/netdev.cpp @@ -26,6 +26,7 @@ #include "netdev.hpp" #include "netlink/netlink-message.hpp" #include "utils/make-clean.hpp" +#include "utils/exception.hpp" #include "utils.hpp" #include "exception.hpp" @@ -64,7 +65,7 @@ #endif using namespace std; -using namespace vasum; +using namespace utils; using namespace vasum::netlink; namespace vasum { diff --git a/server/server.cpp b/server/server.cpp index ab8cba3..95f22a0 100644 --- a/server/server.cpp +++ b/server/server.cpp @@ -34,6 +34,7 @@ #include "utils/environment.hpp" #include "utils/fs.hpp" #include "utils/signal.hpp" +#include "utils/exception.hpp" #include #include @@ -65,6 +66,8 @@ extern char** environ; +using namespace utils; + namespace vasum { diff --git a/server/zone-provision.cpp b/server/zone-provision.cpp index 1c542f7..70c3711 100644 --- a/server/zone-provision.cpp +++ b/server/zone-provision.cpp @@ -41,6 +41,8 @@ namespace fs = boost::filesystem; +using namespace utils; + namespace vasum { ZoneProvision::ZoneProvision(const std::string& rootPath, diff --git a/tests/unit_tests/client/ut-client.cpp b/tests/unit_tests/client/ut-client.cpp index adc325e..a43319c 100644 --- a/tests/unit_tests/client/ut-client.cpp +++ b/tests/unit_tests/client/ut-client.cpp @@ -46,7 +46,7 @@ #include using namespace vasum; -using namespace vasum::utils; +using namespace utils; namespace { diff --git a/tests/unit_tests/config/ut-configuration.cpp b/tests/unit_tests/config/ut-configuration.cpp index 1334966..88b6a4e 100644 --- a/tests/unit_tests/config/ut-configuration.cpp +++ b/tests/unit_tests/config/ut-configuration.cpp @@ -34,6 +34,7 @@ namespace { +using namespace utils; using namespace config; const std::string UT_PATH = "/tmp/ut-config/"; @@ -44,7 +45,7 @@ const std::string DB_PREFIX = "ut"; const int TOLERANCE = 1; struct Fixture { - vasum::utils::ScopedDir mUTDirGuard; + ScopedDir mUTDirGuard; Fixture() : mUTDirGuard(UT_PATH) {} }; diff --git a/tests/unit_tests/config/ut-dynvisit.cpp b/tests/unit_tests/config/ut-dynvisit.cpp index 2050def..bbe45e0 100644 --- a/tests/unit_tests/config/ut-dynvisit.cpp +++ b/tests/unit_tests/config/ut-dynvisit.cpp @@ -33,12 +33,13 @@ namespace { +using namespace utils; using namespace config; const std::string UT_PATH = "/tmp/ut-config/"; struct Fixture { - vasum::utils::ScopedDir mUTDirGuard; + ScopedDir mUTDirGuard; std::string dbPath; std::string dbPrefix; diff --git a/tests/unit_tests/config/ut-kvstore.cpp b/tests/unit_tests/config/ut-kvstore.cpp index 239f568..13691c7 100644 --- a/tests/unit_tests/config/ut-kvstore.cpp +++ b/tests/unit_tests/config/ut-kvstore.cpp @@ -37,7 +37,7 @@ #include using namespace config; -using namespace vasum::utils; +using namespace utils; namespace fs = boost::filesystem; namespace { @@ -45,7 +45,7 @@ namespace { const std::string UT_PATH = "/tmp/ut-config/"; struct Fixture { - vasum::utils::ScopedDir mUTDirGuard; + ScopedDir mUTDirGuard; std::string dbPath; KVStore c; diff --git a/tests/unit_tests/dbus/ut-connection.cpp b/tests/unit_tests/dbus/ut-connection.cpp index 84ea626..b427355 100644 --- a/tests/unit_tests/dbus/ut-connection.cpp +++ b/tests/unit_tests/dbus/ut-connection.cpp @@ -46,8 +46,8 @@ BOOST_AUTO_TEST_SUITE(DbusSuite) +using namespace utils; using namespace vasum; -using namespace vasum::utils; using namespace dbus; namespace { diff --git a/tests/unit_tests/epoll/ut-event-poll.cpp b/tests/unit_tests/epoll/ut-event-poll.cpp index 3a26b5e..819e959 100644 --- a/tests/unit_tests/epoll/ut-event-poll.cpp +++ b/tests/unit_tests/epoll/ut-event-poll.cpp @@ -26,18 +26,18 @@ #include "config.hpp" #include "ut.hpp" -#include "epoll/event-poll.hpp" +#include "ipc/epoll/event-poll.hpp" #include "logger/logger.hpp" #include "ipc/internals/socket.hpp" #include "utils/value-latch.hpp" #include "utils/glib-loop.hpp" -#include "epoll/glib-dispatcher.hpp" -#include "epoll/thread-dispatcher.hpp" +#include "ipc/epoll/glib-dispatcher.hpp" +#include "ipc/epoll/thread-dispatcher.hpp" using namespace vasum; -using namespace vasum::utils; -using namespace vasum::epoll; -using namespace vasum::ipc; +using namespace utils; +using namespace ipc; +using namespace ipc::epoll; namespace { diff --git a/tests/unit_tests/ipc/ut-ipc.cpp b/tests/unit_tests/ipc/ut-ipc.cpp index 6f2765b..b5edbf7 100644 --- a/tests/unit_tests/ipc/ut-ipc.cpp +++ b/tests/unit_tests/ipc/ut-ipc.cpp @@ -34,8 +34,8 @@ #include "ipc/client.hpp" #include "ipc/types.hpp" #include "ipc/result.hpp" -#include "epoll/thread-dispatcher.hpp" -#include "epoll/glib-dispatcher.hpp" +#include "ipc/epoll/thread-dispatcher.hpp" +#include "ipc/epoll/glib-dispatcher.hpp" #include "utils/glib-loop.hpp" #include "utils/latch.hpp" #include "utils/value-latch.hpp" @@ -52,9 +52,9 @@ #include using namespace vasum; -using namespace vasum::ipc; -using namespace vasum::epoll; -using namespace vasum::utils; +using namespace ipc; +using namespace epoll; +using namespace utils; using namespace std::placeholders; // Timeout for sending one message diff --git a/tests/unit_tests/ipc/ut-socket.cpp b/tests/unit_tests/ipc/ut-socket.cpp index 6f78f90..c2577ee 100644 --- a/tests/unit_tests/ipc/ut-socket.cpp +++ b/tests/unit_tests/ipc/ut-socket.cpp @@ -29,7 +29,7 @@ #include -using namespace vasum::ipc; +using namespace ipc; BOOST_AUTO_TEST_SUITE(SocketSuite) diff --git a/tests/unit_tests/server/ut-input-monitor.cpp b/tests/unit_tests/server/ut-input-monitor.cpp index 454a307..22fba47 100644 --- a/tests/unit_tests/server/ut-input-monitor.cpp +++ b/tests/unit_tests/server/ut-input-monitor.cpp @@ -46,7 +46,7 @@ using namespace vasum; -using namespace vasum::utils; +using namespace utils; namespace { diff --git a/tests/unit_tests/server/ut-server.cpp b/tests/unit_tests/server/ut-server.cpp index 8466f19..600b271 100644 --- a/tests/unit_tests/server/ut-server.cpp +++ b/tests/unit_tests/server/ut-server.cpp @@ -37,6 +37,11 @@ #include #include +using namespace utils; +using namespace vasum; +using namespace config; + + namespace { const std::string CONFIG_DIR = VSM_TEST_CONFIG_INSTALL_DIR "/server/ut-server"; @@ -48,7 +53,7 @@ const std::string ZONES_PATH = "/tmp/ut-zones"; // the same as in daemon.conf const bool AS_ROOT = true; struct Fixture { - vasum::utils::ScopedDir mZonesPathGuard; + utils::ScopedDir mZonesPathGuard; Fixture() : mZonesPathGuard(ZONES_PATH) @@ -59,8 +64,8 @@ struct Fixture { void prepare() { - vasum::utils::ScopedGlibLoop loop; - vasum::ZonesManager manager(TEST_CONFIG_PATH); + ScopedGlibLoop loop; + ZonesManager manager(TEST_CONFIG_PATH); manager.createZone("zone1", TEMPLATE_NAME); manager.createZone("zone2", TEMPLATE_NAME); manager.restoreAll(); @@ -70,9 +75,6 @@ struct Fixture { BOOST_FIXTURE_TEST_SUITE(ServerSuite, Fixture) -using namespace vasum; -using namespace config; - BOOST_AUTO_TEST_CASE(ConstructorDestructor) { std::unique_ptr s; diff --git a/tests/unit_tests/server/ut-zone-provision.cpp b/tests/unit_tests/server/ut-zone-provision.cpp index d6a5955..65a5b91 100644 --- a/tests/unit_tests/server/ut-zone-provision.cpp +++ b/tests/unit_tests/server/ut-zone-provision.cpp @@ -42,6 +42,7 @@ #include using namespace vasum; +using namespace utils; using namespace config; namespace fs = boost::filesystem; diff --git a/tests/unit_tests/server/ut-zone.cpp b/tests/unit_tests/server/ut-zone.cpp index 2aed285..755aa52 100644 --- a/tests/unit_tests/server/ut-zone.cpp +++ b/tests/unit_tests/server/ut-zone.cpp @@ -45,6 +45,7 @@ #include #include +using namespace utils; using namespace vasum; using namespace vasum::netdev; using namespace config; @@ -63,9 +64,9 @@ const std::string BRIDGE_NAME = "brtest01"; const std::string ZONE_NETDEV = "netdevtest01"; struct Fixture { - utils::ScopedGlibLoop mLoop; - utils::ScopedDir mZonesPathGuard; - utils::ScopedDir mRunGuard; + ScopedGlibLoop mLoop; + ScopedDir mZonesPathGuard; + ScopedDir mRunGuard; std::string mBridgeName; Fixture() diff --git a/tests/unit_tests/server/ut-zones-manager.cpp b/tests/unit_tests/server/ut-zones-manager.cpp index e052117..f7a4351 100644 --- a/tests/unit_tests/server/ut-zones-manager.cpp +++ b/tests/unit_tests/server/ut-zones-manager.cpp @@ -37,7 +37,7 @@ #endif //DBUS_CONNECTION #include "host-ipc-definitions.hpp" #include -#include +#include #include #include "exception.hpp" @@ -61,7 +61,7 @@ using namespace vasum; using namespace config; -using namespace vasum::utils; +using namespace utils; #ifdef DBUS_CONNECTION using namespace dbus; #endif //DBUS_CONNECTION @@ -599,7 +599,7 @@ public: } private: - epoll::ThreadDispatcher mDispatcher; + ipc::epoll::ThreadDispatcher mDispatcher; ipc::Client mClient; }; @@ -619,10 +619,10 @@ bool spinWaitFor(int timeoutMs, Predicate pred) } // namespace struct Fixture { - vasum::utils::ScopedGlibLoop mLoop; + ScopedGlibLoop mLoop; - utils::ScopedDir mZonesPathGuard; - utils::ScopedDir mRunGuard; + ScopedDir mZonesPathGuard; + ScopedDir mRunGuard; Fixture() : mZonesPathGuard(ZONES_PATH) diff --git a/tests/unit_tests/socket_test_service/socket-test.cpp b/tests/unit_tests/socket_test_service/socket-test.cpp index 2f163af..1ffc09e 100644 --- a/tests/unit_tests/socket_test_service/socket-test.cpp +++ b/tests/unit_tests/socket_test_service/socket-test.cpp @@ -36,7 +36,7 @@ #include using namespace vasum::socket_test; -using namespace vasum::ipc; +using namespace ipc; using namespace logger; // NOTE this is a single-usage program, only meant to test vasum::ipc::Socket module. diff --git a/tests/unit_tests/utils/scoped-daemon.cpp b/tests/unit_tests/utils/scoped-daemon.cpp index 19f252c..6dbe93f 100644 --- a/tests/unit_tests/utils/scoped-daemon.cpp +++ b/tests/unit_tests/utils/scoped-daemon.cpp @@ -35,7 +35,6 @@ #include -namespace vasum { namespace utils { @@ -179,4 +178,3 @@ void ScopedDaemon::stop() } // namespace utils -} // namespace vasum diff --git a/tests/unit_tests/utils/scoped-daemon.hpp b/tests/unit_tests/utils/scoped-daemon.hpp index 7d67c00..d263b4d 100644 --- a/tests/unit_tests/utils/scoped-daemon.hpp +++ b/tests/unit_tests/utils/scoped-daemon.hpp @@ -28,7 +28,6 @@ #include -namespace vasum { namespace utils { @@ -62,7 +61,6 @@ private: } // namespace utils -} // namespace vasum #endif // UNIT_TESTS_UTILS_SCOPED_DAEMON_HPP diff --git a/tests/unit_tests/utils/scoped-dir.cpp b/tests/unit_tests/utils/scoped-dir.cpp index 48b354b..ddec9b6 100644 --- a/tests/unit_tests/utils/scoped-dir.cpp +++ b/tests/unit_tests/utils/scoped-dir.cpp @@ -29,7 +29,6 @@ #include -namespace vasum { namespace utils { namespace fs = boost::filesystem; @@ -67,4 +66,3 @@ void ScopedDir::remove() } } // namespace utils -} // namespace vasum diff --git a/tests/unit_tests/utils/scoped-dir.hpp b/tests/unit_tests/utils/scoped-dir.hpp index c42dbe7..625954e 100644 --- a/tests/unit_tests/utils/scoped-dir.hpp +++ b/tests/unit_tests/utils/scoped-dir.hpp @@ -28,7 +28,6 @@ #include -namespace vasum { namespace utils { @@ -58,7 +57,6 @@ private: } // namespace utils -} // namespace vasum #endif // UNIT_TESTS_UTILS_SCOPED_DIR_HPP diff --git a/tests/unit_tests/utils/ut-callback-guard.cpp b/tests/unit_tests/utils/ut-callback-guard.cpp index 524c7d5..557d8f0 100644 --- a/tests/unit_tests/utils/ut-callback-guard.cpp +++ b/tests/unit_tests/utils/ut-callback-guard.cpp @@ -32,10 +32,9 @@ #include #include - BOOST_AUTO_TEST_SUITE(CallbackGuardSuite) -using namespace vasum::utils; +using namespace utils; const int unsigned TIMEOUT = 1000; diff --git a/tests/unit_tests/utils/ut-counting-map.cpp b/tests/unit_tests/utils/ut-counting-map.cpp index 04832db..55a0a55 100644 --- a/tests/unit_tests/utils/ut-counting-map.cpp +++ b/tests/unit_tests/utils/ut-counting-map.cpp @@ -30,7 +30,7 @@ BOOST_AUTO_TEST_SUITE(CountingMapSuite) -using namespace vasum::utils; +using namespace utils; BOOST_AUTO_TEST_CASE(Counting) { diff --git a/tests/unit_tests/utils/ut-fs.cpp b/tests/unit_tests/utils/ut-fs.cpp index cbbe14b..2cc32d0 100644 --- a/tests/unit_tests/utils/ut-fs.cpp +++ b/tests/unit_tests/utils/ut-fs.cpp @@ -34,8 +34,7 @@ #include #include -using namespace vasum; -using namespace vasum::utils; +using namespace utils; namespace { diff --git a/tests/unit_tests/utils/ut-glib-loop.cpp b/tests/unit_tests/utils/ut-glib-loop.cpp index 467fbfb..fb0292e 100644 --- a/tests/unit_tests/utils/ut-glib-loop.cpp +++ b/tests/unit_tests/utils/ut-glib-loop.cpp @@ -32,8 +32,7 @@ BOOST_AUTO_TEST_SUITE(GlibLoopSuite) -using namespace vasum; -using namespace vasum::utils; +using namespace utils; namespace { diff --git a/tests/unit_tests/utils/ut-paths.cpp b/tests/unit_tests/utils/ut-paths.cpp index e14da13..00120e8 100644 --- a/tests/unit_tests/utils/ut-paths.cpp +++ b/tests/unit_tests/utils/ut-paths.cpp @@ -32,7 +32,7 @@ BOOST_AUTO_TEST_SUITE(UtilsPathsSuite) -using namespace vasum::utils; +using namespace utils; BOOST_AUTO_TEST_CASE(CreateFilePath) { diff --git a/tests/unit_tests/utils/ut-same-thread-guard.cpp b/tests/unit_tests/utils/ut-same-thread-guard.cpp index 463c07d..f2ec471 100644 --- a/tests/unit_tests/utils/ut-same-thread-guard.cpp +++ b/tests/unit_tests/utils/ut-same-thread-guard.cpp @@ -33,7 +33,7 @@ BOOST_AUTO_TEST_SUITE(SameThreadGuardSuite) -using namespace vasum::utils; +using namespace utils; BOOST_AUTO_TEST_CASE(Simple) { diff --git a/tests/unit_tests/utils/ut-value-latch.cpp b/tests/unit_tests/utils/ut-value-latch.cpp index 2b09967..aa5b3a0 100644 --- a/tests/unit_tests/utils/ut-value-latch.cpp +++ b/tests/unit_tests/utils/ut-value-latch.cpp @@ -33,7 +33,7 @@ BOOST_AUTO_TEST_SUITE(ValueLatchSuite) -using namespace vasum::utils; +using namespace utils; namespace { @@ -106,7 +106,7 @@ BOOST_AUTO_TEST_CASE(Timeout) ValueLatch testLatch; BOOST_REQUIRE_EXCEPTION(testLatch.get(EXPECTED_TIMEOUT), - vasum::UtilsException, + UtilsException, WhatEquals("Timeout occured")); } @@ -116,7 +116,7 @@ BOOST_AUTO_TEST_CASE(MultipleSet) testLatch.set(3); BOOST_REQUIRE_EXCEPTION(testLatch.set(2), - vasum::UtilsException, + UtilsException, WhatEquals("Cannot set value multiple times")); } @@ -127,7 +127,7 @@ BOOST_AUTO_TEST_CASE(MultipleGet) testLatch.set(3); testLatch.get(TIMEOUT); BOOST_REQUIRE_EXCEPTION(testLatch.get(EXPECTED_TIMEOUT), - vasum::UtilsException, + UtilsException, WhatEquals("Timeout occured")); } diff --git a/tests/unit_tests/utils/ut-worker.cpp b/tests/unit_tests/utils/ut-worker.cpp index da2a96d..52c14fd 100644 --- a/tests/unit_tests/utils/ut-worker.cpp +++ b/tests/unit_tests/utils/ut-worker.cpp @@ -33,9 +33,9 @@ #include #include -BOOST_AUTO_TEST_SUITE(WorkerSuite) +using namespace utils; -using namespace vasum::utils; +BOOST_AUTO_TEST_SUITE(WorkerSuite) const int unsigned TIMEOUT = 1000; -- 2.7.4