2 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
19 #include <sys/types.h>
20 #include <sys/mount.h>
22 #include "krate-builder.h"
24 #include <klay/exception.h>
25 #include <klay/namespace.h>
26 #include <klay/filesystem.h>
28 #define CGROUP_SUBSYSTEM "krate"
30 KrateBuilder::KrateBuilder(const runtime::User& user) :
33 runtime::File data(getManifestPath());
35 manifest.reset(xml::Parser::parseFile(data.getPath()));
39 KrateBuilder::~KrateBuilder()
43 std::string KrateBuilder::getManifestPath()
45 return "/home/" + user.getName() + "/.config/krate/krate.xml";
48 void KrateBuilder::bindFilesystemNode(const std::string& source, const std::string& target,
49 const std::string& type, const std::string& options,
53 runtime::File dir(target);
55 dir.makeDirectory(true, user.getUid(), user.getGid());
59 runtime::Mount::mountEntry(source, target, type, options);
62 void KrateBuilder::mountOwnFilesystem()
65 xml::Node::NodeList entries = manifest->evaluate("/manifest/filesystem/entry");
66 for (const xml::Node& entry : entries) {
67 bindFilesystemNode(entry.getProp("source"), entry.getProp("target"),
68 entry.getProp("type"), entry.getProp("options"));
72 bindFilesystemNode("/home/" + user.getName(),
73 "/home/" + user.getName() + "/.krate/" + user.getName(),
76 bindFilesystemNode("/home/" + user.getName() + "/.krate", "/home",
80 void KrateBuilder::enterKrate()
82 std::string path = CGROUP_SUBSYSTEM "/" + user.getName();
85 if (runtime::Cgroup::exist(CGROUP_SUBSYSTEM, path)) {
86 auto pids = runtime::Cgroup::getProcessList(CGROUP_SUBSYSTEM, path);
87 if (pids.size() > 0) {
91 runtime::Cgroup::create(CGROUP_SUBSYSTEM, path);
95 runtime::Cgroup::addProcess(CGROUP_SUBSYSTEM, path, ::getpid());
96 runtime::Namespace::unshare(CLONE_NEWNS | CLONE_NEWIPC);
98 runtime::Namespace::attach(pid);
102 void KrateBuilder::exitKrate()
104 std::string path = CGROUP_SUBSYSTEM "/" + user.getName();
105 auto pids = runtime::Cgroup::getProcessList(CGROUP_SUBSYSTEM, path);
106 if (pids.size() <= 1) {
107 runtime::Cgroup::destroy(CGROUP_SUBSYSTEM, path);