• 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 "apexd_utils.h"
20 #include "status_or.h"
21 #include "string_log.h"
22 
23 #include "session_state.pb.h"
24 
25 #include <android-base/logging.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28 
29 #include <filesystem>
30 #include <fstream>
31 #include <optional>
32 
33 using apex::proto::SessionState;
34 
35 namespace android {
36 namespace apex {
37 
38 namespace {
39 
40 static constexpr const char* kStateFileName = "state";
41 
getSessionDir(int session_id)42 std::string getSessionDir(int session_id) {
43   return kApexSessionsDir + "/" + std::to_string(session_id);
44 }
45 
getSessionStateFilePath(int session_id)46 std::string getSessionStateFilePath(int session_id) {
47   return getSessionDir(session_id) + "/" + kStateFileName;
48 }
49 
createSessionDirIfNeeded(int session_id)50 StatusOr<std::string> createSessionDirIfNeeded(int session_id) {
51   // create /data/sessions
52   auto res = createDirIfNeeded(kApexSessionsDir, 0700);
53   if (!res.Ok()) {
54     return StatusOr<std::string>(res.ErrorMessage());
55   }
56   // create /data/sessions/session_id
57   std::string sessionDir = getSessionDir(session_id);
58   res = createDirIfNeeded(sessionDir, 0700);
59   if (!res.Ok()) {
60     return StatusOr<std::string>(res.ErrorMessage());
61   }
62 
63   return StatusOr<std::string>(sessionDir);
64 }
65 
deleteSessionDir(int session_id)66 Status deleteSessionDir(int session_id) {
67   std::string session_dir = getSessionDir(session_id);
68   LOG(DEBUG) << "Deleting " << session_dir;
69   auto path = std::filesystem::path(session_dir);
70   std::error_code error_code;
71   std::filesystem::remove_all(path, error_code);
72   if (error_code) {
73     return Status::Fail(StringLog() << "Failed to delete " << session_dir
74                                     << " : " << error_code);
75   }
76   return Status::Success();
77 }
78 
79 }  // namespace
80 
ApexSession(const SessionState & state)81 ApexSession::ApexSession(const SessionState& state) : state_(state) {}
82 
CreateSession(int session_id)83 StatusOr<ApexSession> ApexSession::CreateSession(int session_id) {
84   SessionState state;
85   // Create session directory
86   auto sessionPath = createSessionDirIfNeeded(session_id);
87   if (!sessionPath.Ok()) {
88     return StatusOr<ApexSession>::MakeError(sessionPath.ErrorMessage());
89   }
90   state.set_id(session_id);
91   ApexSession session(state);
92 
93   return StatusOr<ApexSession>(std::move(session));
94 }
GetSessionFromFile(const std::string & path)95 StatusOr<ApexSession> ApexSession::GetSessionFromFile(const std::string& path) {
96   SessionState state;
97   std::fstream stateFile(path, std::ios::in | std::ios::binary);
98   if (!stateFile) {
99     return StatusOr<ApexSession>::MakeError("Failed to open " + path);
100   }
101 
102   if (!state.ParseFromIstream(&stateFile)) {
103     return StatusOr<ApexSession>::MakeError("Failed to parse " + path);
104   }
105 
106   return StatusOr<ApexSession>(ApexSession(state));
107 }
108 
GetSession(int session_id)109 StatusOr<ApexSession> ApexSession::GetSession(int session_id) {
110   auto path = getSessionStateFilePath(session_id);
111 
112   return GetSessionFromFile(path);
113 }
114 
GetSessions()115 std::vector<ApexSession> ApexSession::GetSessions() {
116   std::vector<ApexSession> sessions;
117 
118   StatusOr<std::vector<std::string>> sessionPaths = ReadDir(
119       kApexSessionsDir, [](const std::filesystem::directory_entry& entry) {
120         std::error_code ec;
121         return entry.is_directory(ec);
122       });
123 
124   if (!sessionPaths.Ok()) {
125     return sessions;
126   }
127 
128   for (const std::string& sessionDirPath : *sessionPaths) {
129     // Try to read session state
130     auto session = GetSessionFromFile(sessionDirPath + "/" + kStateFileName);
131     if (!session.Ok()) {
132       LOG(WARNING) << session.ErrorMessage();
133       continue;
134     }
135     sessions.push_back(std::move(*session));
136   }
137 
138   return sessions;
139 }
140 
GetSessionsInState(SessionState::State state)141 std::vector<ApexSession> ApexSession::GetSessionsInState(
142     SessionState::State state) {
143   auto sessions = GetSessions();
144   sessions.erase(
145       std::remove_if(sessions.begin(), sessions.end(),
146                      [&](const ApexSession &s) { return s.GetState() != state; }),
147       sessions.end());
148 
149   return sessions;
150 }
151 
GetActiveSession()152 StatusOr<std::optional<ApexSession>> ApexSession::GetActiveSession() {
153   auto sessions = GetSessions();
154   std::optional<ApexSession> ret = std::nullopt;
155   for (const ApexSession& session : sessions) {
156     if (!session.IsFinalized()) {
157       if (ret) {
158         return StatusOr<std::optional<ApexSession>>::MakeError(
159             "More than one active session");
160       }
161       ret.emplace(session);
162     }
163   }
164   return StatusOr<std::optional<ApexSession>>(std::move(ret));
165 }
166 
GetState() const167 SessionState::State ApexSession::GetState() const { return state_.state(); }
168 
GetId() const169 int ApexSession::GetId() const { return state_.id(); }
170 
IsFinalized() const171 bool ApexSession::IsFinalized() const {
172   switch (GetState()) {
173     case SessionState::SUCCESS:
174       [[fallthrough]];
175     case SessionState::ACTIVATION_FAILED:
176       [[fallthrough]];
177     case SessionState::ROLLED_BACK:
178       [[fallthrough]];
179     case SessionState::ROLLBACK_FAILED:
180       return true;
181     default:
182       return false;
183   }
184 }
185 
GetChildSessionIds() const186 const google::protobuf::RepeatedField<int> ApexSession::GetChildSessionIds()
187     const {
188   return state_.child_session_ids();
189 }
190 
SetChildSessionIds(const std::vector<int> & child_session_ids)191 void ApexSession::SetChildSessionIds(
192     const std::vector<int>& child_session_ids) {
193   *(state_.mutable_child_session_ids()) = {child_session_ids.begin(),
194                                            child_session_ids.end()};
195 }
196 
UpdateStateAndCommit(const SessionState::State & session_state)197 Status ApexSession::UpdateStateAndCommit(
198     const SessionState::State& session_state) {
199   state_.set_state(session_state);
200 
201   auto stateFilePath = getSessionStateFilePath(state_.id());
202 
203   std::fstream stateFile(stateFilePath,
204                          std::ios::out | std::ios::trunc | std::ios::binary);
205   if (!state_.SerializeToOstream(&stateFile)) {
206     return Status::Fail("Failed to write state file " + stateFilePath);
207   }
208 
209   return Status::Success();
210 }
211 
DeleteSession() const212 Status ApexSession::DeleteSession() const { return deleteSessionDir(GetId()); }
213 
operator <<(std::ostream & out,const ApexSession & session)214 std::ostream& operator<<(std::ostream& out, const ApexSession& session) {
215   return out << "[id = " << session.GetId()
216              << "; state = " << SessionState::State_Name(session.GetState())
217              << "]";
218 }
219 
220 }  // namespace apex
221 }  // namespace android
222