1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include "apexd_session.h"
18
19 #include <android-base/errors.h>
20 #include <android-base/logging.h>
21 #include <android-base/stringprintf.h>
22 #include <dirent.h>
23 #include <sys/stat.h>
24
25 #include <filesystem>
26 #include <fstream>
27 #include <optional>
28 #include <utility>
29
30 #include "apexd_utils.h"
31 #include "session_state.pb.h"
32 #include "string_log.h"
33
34 using android::base::Error;
35 using android::base::Result;
36 using android::base::StringPrintf;
37 using apex::proto::SessionState;
38
39 namespace android {
40 namespace apex {
41
42 namespace {
43
44 static constexpr const char* kStateFileName = "state";
45
ParseSessionState(const std::string & session_dir)46 static Result<SessionState> ParseSessionState(const std::string& session_dir) {
47 auto path = StringPrintf("%s/%s", session_dir.c_str(), kStateFileName);
48 SessionState state;
49 std::fstream state_file(path, std::ios::in | std::ios::binary);
50 if (!state_file) {
51 return Error() << "Failed to open " << path;
52 }
53
54 if (!state.ParseFromIstream(&state_file)) {
55 return Error() << "Failed to parse " << path;
56 }
57
58 return std::move(state);
59 }
60
61 } // namespace
62
GetSessionsDir()63 std::string GetSessionsDir() {
64 static std::string result;
65 static std::once_flag once_flag;
66 std::call_once(once_flag, [&]() {
67 auto status =
68 FindFirstExistingDirectory(kNewApexSessionsDir, kOldApexSessionsDir);
69 if (!status.ok()) {
70 LOG(FATAL) << status.error();
71 }
72 result = std::move(*status);
73 });
74 return result;
75 }
76
ApexSession(SessionState state,std::string session_dir)77 ApexSession::ApexSession(SessionState state, std::string session_dir)
78 : state_(std::move(state)), session_dir_(std::move(session_dir)) {}
79
GetState() const80 SessionState::State ApexSession::GetState() const { return state_.state(); }
81
GetId() const82 int ApexSession::GetId() const { return state_.id(); }
83
GetBuildFingerprint() const84 const std::string& ApexSession::GetBuildFingerprint() const {
85 return state_.expected_build_fingerprint();
86 }
87
IsFinalized() const88 bool ApexSession::IsFinalized() const {
89 switch (GetState()) {
90 case SessionState::SUCCESS:
91 case SessionState::ACTIVATION_FAILED:
92 case SessionState::REVERTED:
93 case SessionState::REVERT_FAILED:
94 return true;
95 default:
96 return false;
97 }
98 }
99
HasRollbackEnabled() const100 bool ApexSession::HasRollbackEnabled() const {
101 return state_.rollback_enabled();
102 }
103
IsRollback() const104 bool ApexSession::IsRollback() const { return state_.is_rollback(); }
105
GetRollbackId() const106 int ApexSession::GetRollbackId() const { return state_.rollback_id(); }
107
GetCrashingNativeProcess() const108 const std::string& ApexSession::GetCrashingNativeProcess() const {
109 return state_.crashing_native_process();
110 }
111
GetErrorMessage() const112 const std::string& ApexSession::GetErrorMessage() const {
113 return state_.error_message();
114 }
115
GetChildSessionIds() const116 const google::protobuf::RepeatedField<int> ApexSession::GetChildSessionIds()
117 const {
118 return state_.child_session_ids();
119 }
120
SetChildSessionIds(const std::vector<int> & child_session_ids)121 void ApexSession::SetChildSessionIds(
122 const std::vector<int>& child_session_ids) {
123 *(state_.mutable_child_session_ids()) = {child_session_ids.begin(),
124 child_session_ids.end()};
125 }
126
127 const google::protobuf::RepeatedPtrField<std::string>
GetApexNames() const128 ApexSession::GetApexNames() const {
129 return state_.apex_names();
130 }
131
132 const google::protobuf::RepeatedPtrField<std::string>
GetApexFileHashes() const133 ApexSession::GetApexFileHashes() const {
134 return state_.apex_file_hashes();
135 }
136
GetSessionDir() const137 const std::string& ApexSession::GetSessionDir() const { return session_dir_; }
138
SetBuildFingerprint(const std::string & fingerprint)139 void ApexSession::SetBuildFingerprint(const std::string& fingerprint) {
140 *(state_.mutable_expected_build_fingerprint()) = fingerprint;
141 }
142
SetHasRollbackEnabled(const bool enabled)143 void ApexSession::SetHasRollbackEnabled(const bool enabled) {
144 state_.set_rollback_enabled(enabled);
145 }
146
SetIsRollback(const bool is_rollback)147 void ApexSession::SetIsRollback(const bool is_rollback) {
148 state_.set_is_rollback(is_rollback);
149 }
150
SetRollbackId(const int rollback_id)151 void ApexSession::SetRollbackId(const int rollback_id) {
152 state_.set_rollback_id(rollback_id);
153 }
154
SetCrashingNativeProcess(const std::string & crashing_process)155 void ApexSession::SetCrashingNativeProcess(
156 const std::string& crashing_process) {
157 state_.set_crashing_native_process(crashing_process);
158 }
159
SetErrorMessage(const std::string & error_message)160 void ApexSession::SetErrorMessage(const std::string& error_message) {
161 state_.set_error_message(error_message);
162 }
163
AddApexName(const std::string & apex_name)164 void ApexSession::AddApexName(const std::string& apex_name) {
165 state_.add_apex_names(apex_name);
166 }
167
SetApexFileHashes(const std::vector<std::string> & hashes)168 void ApexSession::SetApexFileHashes(const std::vector<std::string>& hashes) {
169 *(state_.mutable_apex_file_hashes()) = {hashes.begin(), hashes.end()};
170 }
171
UpdateStateAndCommit(const SessionState::State & session_state)172 Result<void> ApexSession::UpdateStateAndCommit(
173 const SessionState::State& session_state) {
174 state_.set_state(session_state);
175
176 auto state_file_path =
177 StringPrintf("%s/%s", session_dir_.c_str(), kStateFileName);
178
179 std::fstream state_file(state_file_path,
180 std::ios::out | std::ios::trunc | std::ios::binary);
181 if (!state_.SerializeToOstream(&state_file)) {
182 return Error() << "Failed to write state file " << state_file_path;
183 }
184
185 return {};
186 }
187
DeleteSession() const188 Result<void> ApexSession::DeleteSession() const {
189 LOG(INFO) << "Deleting " << session_dir_;
190 auto path = std::filesystem::path(session_dir_);
191 std::error_code error_code;
192 std::filesystem::remove_all(path, error_code);
193 if (error_code) {
194 return Error() << "Failed to delete " << session_dir_ << " : "
195 << error_code.message();
196 }
197 return {};
198 }
199
operator <<(std::ostream & out,const ApexSession & session)200 std::ostream& operator<<(std::ostream& out, const ApexSession& session) {
201 return out << "[id = " << session.GetId()
202 << "; state = " << SessionState::State_Name(session.GetState())
203 << "; session_dir = " << session.GetSessionDir() << "]";
204 }
205
GetStagedApexDirs(const std::string & staged_session_dir) const206 std::vector<std::string> ApexSession::GetStagedApexDirs(
207 const std::string& staged_session_dir) const {
208 const google::protobuf::RepeatedField<int>& child_session_ids =
209 state_.child_session_ids();
210 std::vector<std::string> dirs;
211 if (child_session_ids.empty()) {
212 dirs.push_back(staged_session_dir + "/session_" + std::to_string(GetId()));
213 } else {
214 for (auto child_session_id : child_session_ids) {
215 dirs.push_back(staged_session_dir + "/session_" +
216 std::to_string(child_session_id));
217 }
218 }
219 return dirs;
220 }
221
ApexSessionManager(std::string sessions_base_dir)222 ApexSessionManager::ApexSessionManager(std::string sessions_base_dir)
223 : sessions_base_dir_(std::move(sessions_base_dir)) {}
224
ApexSessionManager(ApexSessionManager && other)225 ApexSessionManager::ApexSessionManager(ApexSessionManager&& other) noexcept
226 : sessions_base_dir_(std::move(other.sessions_base_dir_)) {}
227
operator =(ApexSessionManager && other)228 ApexSessionManager& ApexSessionManager::operator=(
229 ApexSessionManager&& other) noexcept {
230 sessions_base_dir_ = std::move(other.sessions_base_dir_);
231 return *this;
232 }
233
Create(std::string sessions_base_dir)234 std::unique_ptr<ApexSessionManager> ApexSessionManager::Create(
235 std::string sessions_base_dir) {
236 return std::unique_ptr<ApexSessionManager>(
237 new ApexSessionManager(std::move(sessions_base_dir)));
238 }
239
CreateSession(int session_id)240 Result<ApexSession> ApexSessionManager::CreateSession(int session_id) {
241 SessionState state;
242 // Create session directory
243 std::string session_dir =
244 sessions_base_dir_ + "/" + std::to_string(session_id);
245 OR_RETURN(CreateDirIfNeeded(session_dir, 0700));
246 state.set_id(session_id);
247
248 return ApexSession(std::move(state), std::move(session_dir));
249 }
250
GetSession(int session_id) const251 Result<ApexSession> ApexSessionManager::GetSession(int session_id) const {
252 auto session_dir =
253 StringPrintf("%s/%d", sessions_base_dir_.c_str(), session_id);
254
255 auto state = OR_RETURN(ParseSessionState(session_dir));
256 return ApexSession(std::move(state), std::move(session_dir));
257 }
258
GetSessions() const259 std::vector<ApexSession> ApexSessionManager::GetSessions() const {
260 std::vector<ApexSession> sessions;
261
262 auto walk_status = WalkDir(sessions_base_dir_, [&](const auto& entry) {
263 if (!entry.is_directory()) {
264 return;
265 }
266
267 std::string session_dir = entry.path();
268 auto state = ParseSessionState(session_dir);
269 if (!state.ok()) {
270 LOG(WARNING) << state.error();
271 return;
272 }
273
274 ApexSession session(std::move(*state), std::move(session_dir));
275 sessions.push_back(std::move(session));
276 });
277
278 if (!walk_status.ok()) {
279 LOG(WARNING) << walk_status.error();
280 return sessions;
281 }
282
283 return sessions;
284 }
285
GetSessionsInState(const SessionState::State & state) const286 std::vector<ApexSession> ApexSessionManager::GetSessionsInState(
287 const SessionState::State& state) const {
288 std::vector<ApexSession> sessions = GetSessions();
289 sessions.erase(std::remove_if(sessions.begin(), sessions.end(),
290 [&](const ApexSession& s) {
291 return s.GetState() != state;
292 }),
293 sessions.end());
294
295 return sessions;
296 }
297
MigrateFromOldSessionsDir(const std::string & old_sessions_base_dir)298 Result<void> ApexSessionManager::MigrateFromOldSessionsDir(
299 const std::string& old_sessions_base_dir) {
300 if (old_sessions_base_dir == sessions_base_dir_) {
301 LOG(INFO)
302 << old_sessions_base_dir
303 << " is the same as the current session directory. Nothing to migrate";
304 return {};
305 }
306
307 return MoveDir(old_sessions_base_dir, sessions_base_dir_);
308 }
309
HasActiveSession()310 bool ApexSessionManager::HasActiveSession() {
311 for (auto& s : GetSessions()) {
312 if (!s.IsFinalized() &&
313 s.GetState() != ::apex::proto::SessionState::UNKNOWN) {
314 return true;
315 }
316 }
317 return false;
318 }
319
DeleteFinalizedSessions()320 void ApexSessionManager::DeleteFinalizedSessions() {
321 auto sessions = GetSessions();
322 for (const ApexSession& session : sessions) {
323 if (!session.IsFinalized()) {
324 continue;
325 }
326 auto result = session.DeleteSession();
327 if (!result.ok()) {
328 LOG(WARNING) << "Failed to delete finalized session: " << session.GetId();
329 }
330 }
331 }
332
333 } // namespace apex
334 } // namespace android
335