• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
MigrateToMetadataSessionsDir()80 Result<void> ApexSession::MigrateToMetadataSessionsDir() {
81   return MoveDir(kOldApexSessionsDir, kNewApexSessionsDir);
82 }
83 
CreateSession(int session_id)84 Result<ApexSession> ApexSession::CreateSession(int session_id) {
85   SessionState state;
86   // Create session directory
87   std::string session_dir = GetSessionsDir() + "/" + std::to_string(session_id);
88   if (auto status = CreateDirIfNeeded(session_dir, 0700); !status.ok()) {
89     return status.error();
90   }
91   state.set_id(session_id);
92 
93   return ApexSession(state, std::move(session_dir));
94 }
95 
GetSessionFromDir(const std::string & session_dir)96 Result<ApexSession> ApexSession::GetSessionFromDir(
97     const std::string& session_dir) {
98   auto state = ParseSessionState(session_dir);
99   if (!state.ok()) {
100     return state.error();
101   }
102   return ApexSession(*state, session_dir);
103 }
104 
GetSession(int session_id)105 Result<ApexSession> ApexSession::GetSession(int session_id) {
106   auto session_dir =
107       StringPrintf("%s/%d", GetSessionsDir().c_str(), session_id);
108 
109   return GetSessionFromDir(session_dir);
110 }
111 
GetSessions()112 std::vector<ApexSession> ApexSession::GetSessions() {
113   std::vector<ApexSession> sessions;
114 
115   Result<std::vector<std::string>> session_paths = ReadDir(
116       GetSessionsDir(), [](const std::filesystem::directory_entry& entry) {
117         std::error_code ec;
118         return entry.is_directory(ec);
119       });
120 
121   if (!session_paths.ok()) {
122     return sessions;
123   }
124 
125   for (const std::string& session_dir_path : *session_paths) {
126     // Try to read session state
127     auto session = GetSessionFromDir(session_dir_path);
128     if (!session.ok()) {
129       LOG(WARNING) << session.error();
130       continue;
131     }
132     sessions.push_back(std::move(*session));
133   }
134 
135   return sessions;
136 }
137 
GetSessionsInState(SessionState::State state)138 std::vector<ApexSession> ApexSession::GetSessionsInState(
139     SessionState::State state) {
140   auto sessions = GetSessions();
141   sessions.erase(
142       std::remove_if(sessions.begin(), sessions.end(),
143                      [&](const ApexSession &s) { return s.GetState() != state; }),
144       sessions.end());
145 
146   return sessions;
147 }
148 
GetState() const149 SessionState::State ApexSession::GetState() const { return state_.state(); }
150 
GetId() const151 int ApexSession::GetId() const { return state_.id(); }
152 
GetBuildFingerprint() const153 const std::string& ApexSession::GetBuildFingerprint() const {
154   return state_.expected_build_fingerprint();
155 }
156 
IsFinalized() const157 bool ApexSession::IsFinalized() const {
158   switch (GetState()) {
159     case SessionState::SUCCESS:
160     case SessionState::ACTIVATION_FAILED:
161     case SessionState::REVERTED:
162     case SessionState::REVERT_FAILED:
163       return true;
164     default:
165       return false;
166   }
167 }
168 
HasRollbackEnabled() const169 bool ApexSession::HasRollbackEnabled() const {
170   return state_.rollback_enabled();
171 }
172 
IsRollback() const173 bool ApexSession::IsRollback() const { return state_.is_rollback(); }
174 
GetRollbackId() const175 int ApexSession::GetRollbackId() const { return state_.rollback_id(); }
176 
GetCrashingNativeProcess() const177 const std::string& ApexSession::GetCrashingNativeProcess() const {
178   return state_.crashing_native_process();
179 }
180 
GetErrorMessage() const181 const std::string& ApexSession::GetErrorMessage() const {
182   return state_.error_message();
183 }
184 
GetChildSessionIds() const185 const google::protobuf::RepeatedField<int> ApexSession::GetChildSessionIds()
186     const {
187   return state_.child_session_ids();
188 }
189 
SetChildSessionIds(const std::vector<int> & child_session_ids)190 void ApexSession::SetChildSessionIds(
191     const std::vector<int>& child_session_ids) {
192   *(state_.mutable_child_session_ids()) = {child_session_ids.begin(),
193                                            child_session_ids.end()};
194 }
195 
196 const google::protobuf::RepeatedPtrField<std::string>
GetApexNames() const197 ApexSession::GetApexNames() const {
198   return state_.apex_names();
199 }
200 
GetSessionDir() const201 const std::string& ApexSession::GetSessionDir() const { return session_dir_; }
202 
SetBuildFingerprint(const std::string & fingerprint)203 void ApexSession::SetBuildFingerprint(const std::string& fingerprint) {
204   *(state_.mutable_expected_build_fingerprint()) = fingerprint;
205 }
206 
SetHasRollbackEnabled(const bool enabled)207 void ApexSession::SetHasRollbackEnabled(const bool enabled) {
208   state_.set_rollback_enabled(enabled);
209 }
210 
SetIsRollback(const bool is_rollback)211 void ApexSession::SetIsRollback(const bool is_rollback) {
212   state_.set_is_rollback(is_rollback);
213 }
214 
SetRollbackId(const int rollback_id)215 void ApexSession::SetRollbackId(const int rollback_id) {
216   state_.set_rollback_id(rollback_id);
217 }
218 
SetCrashingNativeProcess(const std::string & crashing_process)219 void ApexSession::SetCrashingNativeProcess(
220     const std::string& crashing_process) {
221   state_.set_crashing_native_process(crashing_process);
222 }
223 
SetErrorMessage(const std::string & error_message)224 void ApexSession::SetErrorMessage(const std::string& error_message) {
225   state_.set_error_message(error_message);
226 }
227 
AddApexName(const std::string & apex_name)228 void ApexSession::AddApexName(const std::string& apex_name) {
229   state_.add_apex_names(apex_name);
230 }
231 
UpdateStateAndCommit(const SessionState::State & session_state)232 Result<void> ApexSession::UpdateStateAndCommit(
233     const SessionState::State& session_state) {
234   state_.set_state(session_state);
235 
236   auto state_file_path =
237       StringPrintf("%s/%s", session_dir_.c_str(), kStateFileName);
238 
239   std::fstream state_file(state_file_path,
240                           std::ios::out | std::ios::trunc | std::ios::binary);
241   if (!state_.SerializeToOstream(&state_file)) {
242     return Error() << "Failed to write state file " << state_file_path;
243   }
244 
245   return {};
246 }
247 
DeleteSession() const248 Result<void> ApexSession::DeleteSession() const {
249   LOG(INFO) << "Deleting " << session_dir_;
250   auto path = std::filesystem::path(session_dir_);
251   std::error_code error_code;
252   std::filesystem::remove_all(path, error_code);
253   if (error_code) {
254     return Error() << "Failed to delete " << session_dir_ << " : "
255                    << error_code.message();
256   }
257   return {};
258 }
259 
operator <<(std::ostream & out,const ApexSession & session)260 std::ostream& operator<<(std::ostream& out, const ApexSession& session) {
261   return out << "[id = " << session.GetId()
262              << "; state = " << SessionState::State_Name(session.GetState())
263              << "; session_dir = " << session.GetSessionDir() << "]";
264 }
265 
DeleteFinalizedSessions()266 void ApexSession::DeleteFinalizedSessions() {
267   auto sessions = GetSessions();
268   for (const ApexSession& session : sessions) {
269     if (!session.IsFinalized()) {
270       continue;
271     }
272     auto result = session.DeleteSession();
273     if (!result.ok()) {
274       LOG(WARNING) << "Failed to delete finalized session: " << session.GetId();
275     }
276   }
277 }
278 
GetStagedApexDirs(const std::string & staged_session_dir) const279 std::vector<std::string> ApexSession::GetStagedApexDirs(
280     const std::string& staged_session_dir) const {
281   const google::protobuf::RepeatedField<int>& child_session_ids =
282       state_.child_session_ids();
283   std::vector<std::string> dirs;
284   if (child_session_ids.empty()) {
285     dirs.push_back(staged_session_dir + "/session_" + std::to_string(GetId()));
286   } else {
287     for (auto child_session_id : child_session_ids) {
288       dirs.push_back(staged_session_dir + "/session_" +
289                      std::to_string(child_session_id));
290     }
291   }
292   return dirs;
293 }
294 
ApexSessionManager(std::string sessions_base_dir)295 ApexSessionManager::ApexSessionManager(std::string sessions_base_dir)
296     : sessions_base_dir_(std::move(sessions_base_dir)) {}
297 
ApexSessionManager(ApexSessionManager && other)298 ApexSessionManager::ApexSessionManager(ApexSessionManager&& other) noexcept
299     : sessions_base_dir_(std::move(other.sessions_base_dir_)) {}
300 
operator =(ApexSessionManager && other)301 ApexSessionManager& ApexSessionManager::operator=(
302     ApexSessionManager&& other) noexcept {
303   sessions_base_dir_ = std::move(other.sessions_base_dir_);
304   return *this;
305 }
306 
Create(std::string sessions_base_dir)307 std::unique_ptr<ApexSessionManager> ApexSessionManager::Create(
308     std::string sessions_base_dir) {
309   return std::unique_ptr<ApexSessionManager>(
310       new ApexSessionManager(std::move(sessions_base_dir)));
311 }
312 
CreateSession(int session_id)313 Result<ApexSession> ApexSessionManager::CreateSession(int session_id) {
314   SessionState state;
315   // Create session directory
316   std::string session_dir =
317       sessions_base_dir_ + "/" + std::to_string(session_id);
318   OR_RETURN(CreateDirIfNeeded(session_dir, 0700));
319   state.set_id(session_id);
320 
321   return ApexSession(std::move(state), std::move(session_dir));
322 }
323 
GetSession(int session_id) const324 Result<ApexSession> ApexSessionManager::GetSession(int session_id) const {
325   auto session_dir =
326       StringPrintf("%s/%d", sessions_base_dir_.c_str(), session_id);
327 
328   auto state = OR_RETURN(ParseSessionState(session_dir));
329   return ApexSession(std::move(state), std::move(session_dir));
330 }
331 
GetSessions() const332 std::vector<ApexSession> ApexSessionManager::GetSessions() const {
333   std::vector<ApexSession> sessions;
334 
335   auto walk_status = WalkDir(sessions_base_dir_, [&](const auto& entry) {
336     if (!entry.is_directory()) {
337       return;
338     }
339 
340     std::string session_dir = entry.path();
341     auto state = ParseSessionState(session_dir);
342     if (!state.ok()) {
343       LOG(WARNING) << state.error();
344       return;
345     }
346 
347     ApexSession session(std::move(*state), std::move(session_dir));
348     sessions.push_back(std::move(session));
349   });
350 
351   if (!walk_status.ok()) {
352     LOG(WARNING) << walk_status.error();
353     return std::move(sessions);
354   }
355 
356   return std::move(sessions);
357 }
358 
GetSessionsInState(const SessionState::State & state) const359 std::vector<ApexSession> ApexSessionManager::GetSessionsInState(
360     const SessionState::State& state) const {
361   std::vector<ApexSession> sessions = GetSessions();
362   sessions.erase(std::remove_if(sessions.begin(), sessions.end(),
363                                 [&](const ApexSession& s) {
364                                   return s.GetState() != state;
365                                 }),
366                  sessions.end());
367 
368   return sessions;
369 }
370 
MigrateFromOldSessionsDir(const std::string & old_sessions_base_dir)371 Result<void> ApexSessionManager::MigrateFromOldSessionsDir(
372     const std::string& old_sessions_base_dir) {
373   if (old_sessions_base_dir == sessions_base_dir_) {
374     LOG(INFO)
375         << old_sessions_base_dir
376         << " is the same as the current session directory. Nothing to migrate";
377     return {};
378   }
379 
380   return MoveDir(old_sessions_base_dir, sessions_base_dir_);
381 }
382 
383 }  // namespace apex
384 }  // namespace android
385