• 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() { return kApexSessionsDir; }
64 
ApexSession(SessionState state,std::string session_dir)65 ApexSession::ApexSession(SessionState state, std::string session_dir)
66     : state_(std::move(state)), session_dir_(std::move(session_dir)) {}
67 
GetState() const68 SessionState::State ApexSession::GetState() const { return state_.state(); }
69 
GetId() const70 int ApexSession::GetId() const { return state_.id(); }
71 
GetBuildFingerprint() const72 const std::string& ApexSession::GetBuildFingerprint() const {
73   return state_.expected_build_fingerprint();
74 }
75 
IsFinalized() const76 bool ApexSession::IsFinalized() const {
77   switch (GetState()) {
78     case SessionState::SUCCESS:
79     case SessionState::ACTIVATION_FAILED:
80     case SessionState::REVERTED:
81     case SessionState::REVERT_FAILED:
82       return true;
83     default:
84       return false;
85   }
86 }
87 
HasRollbackEnabled() const88 bool ApexSession::HasRollbackEnabled() const {
89   return state_.rollback_enabled();
90 }
91 
IsRollback() const92 bool ApexSession::IsRollback() const { return state_.is_rollback(); }
93 
GetRollbackId() const94 int ApexSession::GetRollbackId() const { return state_.rollback_id(); }
95 
GetCrashingNativeProcess() const96 const std::string& ApexSession::GetCrashingNativeProcess() const {
97   return state_.crashing_native_process();
98 }
99 
GetErrorMessage() const100 const std::string& ApexSession::GetErrorMessage() const {
101   return state_.error_message();
102 }
103 
GetChildSessionIds() const104 const google::protobuf::RepeatedField<int> ApexSession::GetChildSessionIds()
105     const {
106   return state_.child_session_ids();
107 }
108 
SetChildSessionIds(const std::vector<int> & child_session_ids)109 void ApexSession::SetChildSessionIds(
110     const std::vector<int>& child_session_ids) {
111   *(state_.mutable_child_session_ids()) = {child_session_ids.begin(),
112                                            child_session_ids.end()};
113 }
114 
115 const google::protobuf::RepeatedPtrField<std::string>
GetApexNames() const116 ApexSession::GetApexNames() const {
117   return state_.apex_names();
118 }
119 
120 const google::protobuf::RepeatedPtrField<std::string>
GetApexFileHashes() const121 ApexSession::GetApexFileHashes() const {
122   return state_.apex_file_hashes();
123 }
124 
125 const google::protobuf::RepeatedPtrField<std::string>
GetApexImages() const126 ApexSession::GetApexImages() const {
127   return state_.apex_images();
128 }
129 
GetSessionDir() const130 const std::string& ApexSession::GetSessionDir() const { return session_dir_; }
131 
SetBuildFingerprint(const std::string & fingerprint)132 void ApexSession::SetBuildFingerprint(const std::string& fingerprint) {
133   *(state_.mutable_expected_build_fingerprint()) = fingerprint;
134 }
135 
SetHasRollbackEnabled(const bool enabled)136 void ApexSession::SetHasRollbackEnabled(const bool enabled) {
137   state_.set_rollback_enabled(enabled);
138 }
139 
SetIsRollback(const bool is_rollback)140 void ApexSession::SetIsRollback(const bool is_rollback) {
141   state_.set_is_rollback(is_rollback);
142 }
143 
SetRollbackId(const int rollback_id)144 void ApexSession::SetRollbackId(const int rollback_id) {
145   state_.set_rollback_id(rollback_id);
146 }
147 
SetCrashingNativeProcess(const std::string & crashing_process)148 void ApexSession::SetCrashingNativeProcess(
149     const std::string& crashing_process) {
150   state_.set_crashing_native_process(crashing_process);
151 }
152 
SetErrorMessage(const std::string & error_message)153 void ApexSession::SetErrorMessage(const std::string& error_message) {
154   state_.set_error_message(error_message);
155 }
156 
AddApexName(const std::string & apex_name)157 void ApexSession::AddApexName(const std::string& apex_name) {
158   state_.add_apex_names(apex_name);
159 }
160 
SetApexFileHashes(const std::vector<std::string> & hashes)161 void ApexSession::SetApexFileHashes(const std::vector<std::string>& hashes) {
162   *(state_.mutable_apex_file_hashes()) = {hashes.begin(), hashes.end()};
163 }
164 
SetApexImages(const std::vector<std::string> & images)165 void ApexSession::SetApexImages(const std::vector<std::string>& images) {
166   *(state_.mutable_apex_images()) = {images.begin(), images.end()};
167 }
168 
UpdateStateAndCommit(const SessionState::State & session_state)169 Result<void> ApexSession::UpdateStateAndCommit(
170     const SessionState::State& session_state) {
171   state_.set_state(session_state);
172 
173   auto state_file_path =
174       StringPrintf("%s/%s", session_dir_.c_str(), kStateFileName);
175 
176   std::fstream state_file(state_file_path,
177                           std::ios::out | std::ios::trunc | std::ios::binary);
178   if (!state_.SerializeToOstream(&state_file)) {
179     return Error() << "Failed to write state file " << state_file_path;
180   }
181 
182   return {};
183 }
184 
DeleteSession() const185 Result<void> ApexSession::DeleteSession() const {
186   LOG(INFO) << "Deleting " << session_dir_;
187   auto path = std::filesystem::path(session_dir_);
188   std::error_code error_code;
189   std::filesystem::remove_all(path, error_code);
190   if (error_code) {
191     return Error() << "Failed to delete " << session_dir_ << " : "
192                    << error_code.message();
193   }
194   return {};
195 }
196 
operator <<(std::ostream & out,const ApexSession & session)197 std::ostream& operator<<(std::ostream& out, const ApexSession& session) {
198   return out << "[id = " << session.GetId()
199              << "; state = " << SessionState::State_Name(session.GetState())
200              << "; session_dir = " << session.GetSessionDir() << "]";
201 }
202 
GetStagedApexDirs(const std::string & staged_session_dir) const203 std::vector<std::string> ApexSession::GetStagedApexDirs(
204     const std::string& staged_session_dir) const {
205   const google::protobuf::RepeatedField<int>& child_session_ids =
206       state_.child_session_ids();
207   std::vector<std::string> dirs;
208   if (child_session_ids.empty()) {
209     dirs.push_back(staged_session_dir + "/session_" + std::to_string(GetId()));
210   } else {
211     for (auto child_session_id : child_session_ids) {
212       dirs.push_back(staged_session_dir + "/session_" +
213                      std::to_string(child_session_id));
214     }
215   }
216   return dirs;
217 }
218 
ApexSessionManager(std::string sessions_base_dir)219 ApexSessionManager::ApexSessionManager(std::string sessions_base_dir)
220     : sessions_base_dir_(std::move(sessions_base_dir)) {}
221 
Create(std::string sessions_base_dir)222 std::unique_ptr<ApexSessionManager> ApexSessionManager::Create(
223     std::string sessions_base_dir) {
224   return std::unique_ptr<ApexSessionManager>(
225       new ApexSessionManager(std::move(sessions_base_dir)));
226 }
227 
CreateSession(int session_id)228 Result<ApexSession> ApexSessionManager::CreateSession(int session_id) {
229   SessionState state;
230   // Create session directory
231   std::string session_dir =
232       sessions_base_dir_ + "/" + std::to_string(session_id);
233   OR_RETURN(CreateDirIfNeeded(session_dir, 0700));
234   state.set_id(session_id);
235 
236   return ApexSession(std::move(state), std::move(session_dir));
237 }
238 
GetSession(int session_id) const239 Result<ApexSession> ApexSessionManager::GetSession(int session_id) const {
240   auto session_dir =
241       StringPrintf("%s/%d", sessions_base_dir_.c_str(), session_id);
242 
243   auto state = OR_RETURN(ParseSessionState(session_dir));
244   return ApexSession(std::move(state), std::move(session_dir));
245 }
246 
GetSessions() const247 std::vector<ApexSession> ApexSessionManager::GetSessions() const {
248   std::vector<ApexSession> sessions;
249 
250   auto walk_status = WalkDir(sessions_base_dir_, [&](const auto& entry) {
251     if (!entry.is_directory()) {
252       return;
253     }
254 
255     std::string session_dir = entry.path();
256     auto state = ParseSessionState(session_dir);
257     if (!state.ok()) {
258       LOG(WARNING) << state.error();
259       return;
260     }
261 
262     ApexSession session(std::move(*state), std::move(session_dir));
263     sessions.push_back(std::move(session));
264   });
265 
266   if (!walk_status.ok()) {
267     LOG(WARNING) << walk_status.error();
268     return sessions;
269   }
270 
271   return sessions;
272 }
273 
GetSessionsInState(const SessionState::State & state) const274 std::vector<ApexSession> ApexSessionManager::GetSessionsInState(
275     const SessionState::State& state) const {
276   std::vector<ApexSession> sessions = GetSessions();
277   sessions.erase(std::remove_if(sessions.begin(), sessions.end(),
278                                 [&](const ApexSession& s) {
279                                   return s.GetState() != state;
280                                 }),
281                  sessions.end());
282 
283   return sessions;
284 }
285 
HasActiveSession()286 bool ApexSessionManager::HasActiveSession() {
287   for (auto& s : GetSessions()) {
288     if (!s.IsFinalized() &&
289         s.GetState() != ::apex::proto::SessionState::UNKNOWN) {
290       return true;
291     }
292   }
293   return false;
294 }
295 
DeleteFinalizedSessions()296 void ApexSessionManager::DeleteFinalizedSessions() {
297   auto sessions = GetSessions();
298   for (const ApexSession& session : sessions) {
299     if (!session.IsFinalized()) {
300       continue;
301     }
302     auto result = session.DeleteSession();
303     if (!result.ok()) {
304       LOG(WARNING) << "Failed to delete finalized session: " << session.GetId();
305     }
306   }
307 }
308 
309 }  // namespace apex
310 }  // namespace android
311