• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "firmware_manager.h"
17 
18 #include <cstdlib>
19 #include <ohos_types.h>
20 #include <thread>
21 
22 #include "config_parse.h"
23 #include "dupdate_errno.h"
24 #include "dupdate_upgrade_helper.h"
25 #include "dupdate_net_manager.h"
26 #include "file_utils.h"
27 #include "firmware_callback_utils.h"
28 #include "firmware_changelog_utils.h"
29 #include "firmware_common.h"
30 #include "firmware_constant.h"
31 #include "firmware_database.h"
32 #include "firmware_event_listener.h"
33 #include "firmware_flow_manager.h"
34 #include "firmware_iexecute_mode.h"
35 #include "firmware_log.h"
36 #include "firmware_manual_check_mode.h"
37 #include "firmware_download_mode.h"
38 #include "firmware_install_apply_mode.h"
39 #include "firmware_status_cache.h"
40 #include "firmware_task_operator.h"
41 #include "firmware_update_helper.h"
42 #include "progress_thread.h"
43 #include "schedule_task.h"
44 #include "startup_schedule.h"
45 #include "string_utils.h"
46 #include "time_utils.h"
47 #include "update_helper.h"
48 
49 namespace OHOS {
50 namespace UpdateEngine {
51 constexpr int32_t INIT_DELAY_TIME = 5; // 进程启动延时时间5秒,为了安装重启之后可以看到版本号及时刷新
52 constexpr int32_t PROCESS_EXIT_DELAY_TIME = 1; // 进程退出等待时间,单位:秒
53 constexpr uint64_t PULLUP_AFTER_TERMINATE_INTERVAL = 5; // 终止升级后SA拉起间隔
54 
FirmwareManager()55 FirmwareManager::FirmwareManager() {}
56 
~FirmwareManager()57 FirmwareManager::~FirmwareManager()
58 {
59     DelayedSingleton<FirmwareEventListener>::GetInstance()->UnregisterNetChangedListener();
60 }
61 
Init(StartupReason startupReason)62 void FirmwareManager::Init(StartupReason startupReason)
63 {
64     DelayedSingleton<ConfigParse>::GetInstance()->LoadConfigInfo(); // 启动读取配置信息
65     FIRMWARE_LOGI("FirmwareManager Init");
66 
67     // 当StartupReason为PROCESS_ENV_RESET时, 会进行以下处理:
68     // 1. 删除Firmware目录(FIRMWARE_DIR_INFOS)中的所有允许删除的目录中的所有文件及子目录
69     // 2. 清空Firmware SP(FirmwarePreferencesUtil)中所有记录
70     // 3. 删除数据库(FirmwareDatabase/DownloadDatabase
71     if (startupReason == StartupReason::PROCESS_ENV_RESET) {
72         FileUtils::DestroyBaseDirectory(FIRMWARE_DIR_INFOS);
73         preferencesUtil_->RemoveAll();
74         DelayedSingleton<FirmwareDatabase>::GetInstance()->DeleteDbStore();
75     }
76     FileUtils::InitAndCreateBaseDirs(FIRMWARE_DIR_INFOS);
77 
78     std::thread initThread(&FirmwareManager::DelayInit, this, startupReason);
79     initThread.detach();
80 }
81 
DelayInit(StartupReason startupReason)82 void FirmwareManager::DelayInit(StartupReason startupReason)
83 {
84     FIRMWARE_LOGI("FirmwareManager DelayInit startupReason %{public}d", startupReason);
85     RestoreUpdate();
86     DelayedSingleton<FirmwareEventListener>::GetInstance()->RegisterNetChangedListener();
87 
88     auto eventType = CommonEventType::PROCESS_INIT;
89     if (startupReason == StartupReason::DEVICE_REBOOT) {
90         // 重启启动,延时5秒,等待系统初始化完再恢复周期提醒alarm | 执行升级结果判断  避免出现通知hap拉不起的问题
91         sleep(INIT_DELAY_TIME);
92         eventType = CommonEventType::BOOT_COMPLETE;
93     }
94 
95     // 以下两种情况会向OUC发送初始启动消息:
96     // 1. DUE启动原因为StartupReason::PROCESS_ENV_RESET,DUE缓存数据清空
97     // 2. DUE首次启动,还未向OUC发送过初始启动消息
98     NotifyInitEvent();
99 
100     // 处理 设备重启/进程初始化 事件
101     HandleEvent(eventType);
102 }
103 
RestoreUpdate()104 void FirmwareManager::RestoreUpdate()
105 {
106     FirmwareTask firmwareTask;
107     FirmwareTaskOperator().QueryTask(firmwareTask);
108     FIRMWARE_LOGI("RestoreUpdate status: %{public}d", firmwareTask.status);
109     if (firmwareTask.status == UpgradeStatus::DOWNLOAD_PAUSE) {
110         HandleBootDownloadPauseStatusProcess(firmwareTask);
111         return;
112     }
113     if (firmwareTask.status == UpgradeStatus::DOWNLOADING) {
114         HandleBootDownloadOnStatusProcess(firmwareTask);
115         return;
116     }
117     if (firmwareTask.status == UpgradeStatus::DOWNLOAD_SUCCESS) {
118         HandleBootDownloadedStatusProcess(firmwareTask);
119         return;
120     }
121 
122     if (firmwareTask.status == UpgradeStatus::INSTALLING || firmwareTask.status == UpgradeStatus::INSTALL_SUCCESS) {
123         HandleBootInstallOnStatusProcess(firmwareTask);
124         return;
125     }
126 }
127 
IsIdle()128 bool FirmwareManager::IsIdle()
129 {
130     if (DelayedSingleton<FirmwareStatusCache>::GetInstance()->IsChecking()) {
131         FIRMWARE_LOGI("FirmwareManager IsIdle checking");
132         return false;
133     }
134 
135     FirmwareTask task;
136     FirmwareTaskOperator().QueryTask(task);
137     bool isIdle = !task.isExistTask;
138     FIRMWARE_LOGI("FirmwareManager IsIdle:%{public}s", StringUtils::GetBoolStr(isIdle).c_str());
139     return isIdle;
140 }
141 
GetScheduleTasks()142 std::vector<ScheduleTask> FirmwareManager::GetScheduleTasks()
143 {
144     ScheduleTask scheduleTask;
145     return {scheduleTask};
146 }
147 
Exit()148 bool FirmwareManager::Exit()
149 {
150     FIRMWARE_LOGI("FirmwareManager Exit");
151     return true;
152 }
153 
DoCancelDownload(BusinessError & businessError)154 void FirmwareManager::DoCancelDownload(BusinessError &businessError)
155 {
156     FirmwareTask task;
157     FirmwareTaskOperator().QueryTask(task);
158     if (!task.isExistTask) {
159         FIRMWARE_LOGI("DoCancelDownload no task");
160         businessError.Build(CallResult::FAIL, "no download task to cancel!");
161         businessError.AddErrorMessage(CAST_INT(DUPDATE_ERR_DOWNLOAD_COMMON_ERROR), "no download task to cancel!");
162         return;
163     }
164     ProgressThread::isCancel_ = true;
165     return;
166 }
167 
DoTerminateUpgrade(BusinessError & businessError)168 void FirmwareManager::DoTerminateUpgrade(BusinessError &businessError)
169 {
170     ScheduleTask scheduleTask;
171     scheduleTask.startupReason = StartupReason::PROCESS_ENV_RESET;
172     scheduleTask.minDelayTime = PULLUP_AFTER_TERMINATE_INTERVAL;
173     if (!DelayedSingleton<StartupSchedule>::GetInstance()->Schedule(scheduleTask)) {
174         FIRMWARE_LOGE("DoTerminateUpgrade fail");
175         businessError.AddErrorMessage(CAST_INT(DUPDATE_ERR_INTERNAL_ERROR), "terminate upgrade error!");
176         return;
177     }
178 
179     // 主线程拉起子线程之后向OUC返回回调结果,子线程sleep 1秒之后,DUE进程退出
180     std::thread th = std::thread([this]() {
181         sleep(PROCESS_EXIT_DELAY_TIME);
182         _Exit(0);
183     });
184     th.detach();
185 }
186 
DoCheck(OnCheckComplete onCheckComplete)187 void FirmwareManager::DoCheck(OnCheckComplete onCheckComplete)
188 {
189     auto *flowManager = new FirmwareFlowManager();
190     std::shared_ptr<FirmwareIExecuteMode> executeMode =
191         std::make_shared<FirmwareManualCheckMode>([=](BusinessError &businessError, CheckResult &checkResult) {
192             FIRMWARE_LOGI("FirmwareManager DoCheck newVersionInfoResult");
193             onCheckComplete(businessError, checkResult);
194             delete flowManager;
195         });
196     flowManager->SetExecuteMode(executeMode);
197     flowManager->Start();
198 }
199 
DoDownload(const DownloadOptions & downloadOptions,BusinessError & businessError)200 void FirmwareManager::DoDownload(const DownloadOptions &downloadOptions, BusinessError &businessError)
201 {
202     auto *flowManager = new FirmwareFlowManager();
203     std::shared_ptr<FirmwareIExecuteMode> executeMode =
204         std::make_shared<FirmwareDownloadMode>(downloadOptions, businessError, [=]() {
205             FIRMWARE_LOGI("FirmwareManager DoDownload finish");
206             delete flowManager;
207         });
208     flowManager->SetExecuteMode(executeMode);
209     flowManager->Start();
210 }
211 
CanInstall(void)212 bool FirmwareManager::CanInstall(void)
213 {
214     FirmwareTask task;
215     FirmwareTaskOperator firmwareTaskOperator;
216     firmwareTaskOperator.QueryTask(task);
217     FIRMWARE_LOGI("check can install task.status:%{public}d", CAST_INT(task.status));
218     if (FirmwareUpdateHelper::GetInstallType() == InstallType::SYS_INSTALLER) {
219         return task.status == UpgradeStatus::DOWNLOAD_SUCCESS || task.status == UpgradeStatus::INSTALL_SUCCESS;
220     } else {
221         return task.status == UpgradeStatus::DOWNLOAD_SUCCESS;
222     }
223 }
224 
DoInstall(const UpgradeOptions & upgradeOptions,BusinessError & businessError,InstallType installType)225 void FirmwareManager::DoInstall(const UpgradeOptions &upgradeOptions, BusinessError &businessError,
226     InstallType installType)
227 {
228     FIRMWARE_LOGI("FirmwareManager DoInstall upgradeOptions order:%{public}d, installType = %{public}d",
229         CAST_INT(upgradeOptions.order), CAST_INT(installType));
230     if (!CanInstall()) {
231         FIRMWARE_LOGI("status can not Install");
232         return;
233     }
234     FirmwareFlowManager *flowManager = new FirmwareFlowManager();
235     std::shared_ptr<FirmwareIExecuteMode> executeMode =
236         std::make_shared<FirmwareInstallApplyMode>(upgradeOptions, businessError, installType, [=]() {
237             FIRMWARE_LOGI("FirmwareManager DoInstall finish");
238         });
239     flowManager->SetExecuteMode(executeMode);
240     flowManager->Start();
241 }
242 
DoAutoDownloadSwitchChanged(bool isDownloadSwitchOn)243 void FirmwareManager::DoAutoDownloadSwitchChanged(bool isDownloadSwitchOn)
244 {
245     FIRMWARE_LOGI("DoAutoDownloadSwitchChanged isDownloadSwitchOn %{public}s", isDownloadSwitchOn ? "on" : "off");
246     preferencesUtil_->SaveBool(Firmware::AUTO_DOWNLOAD_SWITCH, isDownloadSwitchOn);
247     FirmwareTask task;
248     FirmwareTaskOperator().QueryTask(task);
249     if (!task.isExistTask) {
250         FIRMWARE_LOGI("DoAutoDownloadSwitchChanged no task");
251         return;
252     }
253     FIRMWARE_LOGI("DoAutoDownloadSwitchChanged current task status %{public}d", task.status);
254     // 当前是否有搜索完待下载的包
255     if (task.status != UpgradeStatus::CHECK_VERSION_SUCCESS) {
256         return;
257     }
258     if (!isDownloadSwitchOn) {
259         // 开关关,发送新版本通知
260         DelayedSingleton<FirmwareCallbackUtils>::GetInstance()->NotifyEvent(
261             task.taskId, EventId::EVENT_DOWNLOAD_WAIT, UpgradeStatus::CHECK_VERSION_SUCCESS);
262     }
263 }
264 
DoClearError(BusinessError & businessError)265 void FirmwareManager::DoClearError(BusinessError &businessError)
266 {
267     FirmwareTask task;
268     FirmwareTaskOperator().QueryTask(task);
269     if (!task.isExistTask) {
270         FIRMWARE_LOGI("DoClearError has no task");
271         return;
272     }
273     if (!UpdateHelper::IsUpgradeFailed(task.status)) {
274         businessError.Build(CallResult::FAIL, "please check status before clear error");
275         businessError.AddErrorMessage(CAST_INT(DUPDATE_ERR_UPDATE_COMMON_ERROR),
276             "please check status before clear error");
277         return;
278     }
279     FirmwareUpdateHelper::ClearFirmwareInfo();
280 }
281 
HandleEvent(CommonEventType event)282 void FirmwareManager::HandleEvent(CommonEventType event)
283 {
284     FIRMWARE_LOGI("handleEvent event %{public}d", static_cast<uint32_t>(event));
285     switch (event) {
286         case CommonEventType::NET_CHANGED:
287             HandleNetChanged();
288             break;
289         case CommonEventType::BOOT_COMPLETE:
290             HandleBootComplete();
291             break;
292         default:
293             break;
294     }
295 }
296 
HandleBootComplete()297 void FirmwareManager::HandleBootComplete()
298 {
299     FIRMWARE_LOGI("HandleBootComplete");
300     FirmwareTask task;
301     FirmwareTaskOperator().QueryTask(task);
302     if (!task.isExistTask) {
303         FIRMWARE_LOGI("HandleBootComplete has no task");
304         return;
305     }
306 
307     FIRMWARE_LOGI("HandleBootComplete status %{public}d", CAST_INT(task.status));
308     if (task.status == UpgradeStatus::UPDATING) {
309         HandleBootUpdateOnStatusProcess(task);
310         return;
311     }
312 }
313 
HandleNetChanged()314 void FirmwareManager::HandleNetChanged()
315 {
316     FIRMWARE_LOGI("HandleNetChanged");
317     if (!DelayedSingleton<NetManager>::GetInstance()->IsNetAvailable()) {
318         FIRMWARE_LOGE("HandleNetChanged network not available.");
319         ProgressThread::isNoNet_ = true;
320         return;
321     }
322 
323     ProgressThread::isNoNet_ = false;
324     FirmwareTask task;
325     FirmwareTaskOperator().QueryTask(task);
326     FIRMWARE_LOGI("HandleNetChanged status %{public}d", task.status);
327 
328     if (!DelayedSingleton<NetManager>::GetInstance()->IsNetAvailable(NetType::NOT_METERED_WIFI)) {
329         return;
330     }
331 
332     if (task.status == UpgradeStatus::DOWNLOAD_PAUSE) {
333         HandleResumeDownload(task);
334         return;
335     }
336 
337     if (task.status == UpgradeStatus::CHECK_VERSION_SUCCESS) {
338         bool isDownloadSwitchOn = preferencesUtil_->ObtainBool(Firmware::AUTO_DOWNLOAD_SWITCH, false);
339         FIRMWARE_LOGI("HandleNetChanged isDownloadSwitchOn %{public}s",
340             StringUtils::GetBoolStr(isDownloadSwitchOn).c_str());
341         if (isDownloadSwitchOn) {
342             DoAutoDownload(task);
343         }
344     }
345 }
346 
347 // updater调用后正常启动
HandleBootUpdateOnStatusProcess(const FirmwareTask & task)348 void FirmwareManager::HandleBootUpdateOnStatusProcess(const FirmwareTask &task)
349 {
350     FIRMWARE_LOGI("HandleBootUpdateOnStatusProcess");
351     FirmwareResultProcess resultProcess;
352     std::map<std::string, UpdateResult> resultMap;
353     std::vector<FirmwareComponent> components;
354     FirmwareComponentOperator().QueryAll(components);
355     switch (resultProcess.GetUpdaterResult(components, resultMap)) {
356         case UpdateResultCode::SUCCESS:
357             HandleBootUpdateSuccess(task, resultMap);
358             break;
359         case UpdateResultCode::FAILURE:
360             HandleBootUpdateFail(task, resultMap);
361             break;
362         default:
363             break;
364     }
365 }
366 
HandleBootUpdateSuccess(const FirmwareTask & task,const std::map<std::string,UpdateResult> & resultMap)367 void FirmwareManager::HandleBootUpdateSuccess(const FirmwareTask &task,
368     const std::map<std::string, UpdateResult> &resultMap)
369 {
370     preferencesUtil_->SaveString(Firmware::UPDATE_ACTION, "upgrade");
371     std::vector<FirmwareComponent> components;
372     FirmwareComponentOperator().QueryAll(components);
373     std::vector<VersionComponent> versionComponents;
374     for (const auto &component : components) {
375         VersionComponent versionComponent;
376         versionComponent.componentType = CAST_INT(ComponentType::OTA);
377         versionComponent.componentId = component.componentId;
378         versionComponent.upgradeAction = UpgradeAction::UPGRADE;
379         versionComponent.displayVersion = component.targetBlDisplayVersionNumber;
380         versionComponent.innerVersion = component.targetBlVersionNumber;
381         versionComponents.push_back(versionComponent);
382     }
383 
384     DelayedSingleton<FirmwareChangelogUtils>::GetInstance()->SaveHotaCurrentVersionComponentId();
385     if (task.combinationType == CombinationType::HOTA) {
386         FIRMWARE_LOGI("notify upgrade success");
387         DelayedSingleton<FirmwareCallbackUtils>::GetInstance()->NotifyEvent(task.taskId, EventId::EVENT_UPGRADE_SUCCESS,
388             UpgradeStatus::UPDATE_SUCCESS, ErrorMessage{}, versionComponents);
389         FirmwareUpdateHelper::ClearFirmwareInfo();
390         return;
391     }
392 }
393 
HandleBootUpdateFail(const FirmwareTask & task,const std::map<std::string,UpdateResult> & resultMap)394 void FirmwareManager::HandleBootUpdateFail(const FirmwareTask &task,
395     const std::map<std::string, UpdateResult> &resultMap)
396 {
397     preferencesUtil_->SaveString(Firmware::UPDATE_ACTION, "recovery");
398     std::vector<FirmwareComponent> components;
399     FirmwareComponentOperator().QueryAll(components);
400     std::vector<VersionComponent> versionComponents;
401     for (const auto &component : components) {
402         VersionComponent versionComponent;
403         versionComponent.componentType = CAST_INT(ComponentType::OTA);
404         versionComponent.componentId = component.componentId;
405         versionComponent.upgradeAction = UpgradeAction::UPGRADE;
406         versionComponent.displayVersion = component.targetBlDisplayVersionNumber;
407         versionComponent.innerVersion = component.targetBlVersionNumber;
408         versionComponents.push_back(versionComponent);
409     }
410 
411     ErrorMessage errorMessage;
412     for (const auto &result : resultMap) {
413         if (result.second.result == UPDATER_RESULT_FAILURE) {
414             errorMessage.errorCode = CAST_INT(result.second.GetUpdateResultCode());
415             errorMessage.errorMessage = result.second.reason;
416             break;
417         }
418     }
419 
420     DelayedSingleton<FirmwareCallbackUtils>::GetInstance()->NotifyEvent(task.taskId, EventId::EVENT_UPGRADE_FAIL,
421         UpgradeStatus::UPDATE_FAIL, errorMessage, versionComponents);
422     FIRMWARE_LOGI("upgrade fail");
423     FirmwareUpdateHelper::ClearFirmwareInfo();
424 }
425 
426 // sysInstaller安装中重启,进度回退为下载完成
HandleBootInstallOnStatusProcess(FirmwareTask & task)427 void FirmwareManager::HandleBootInstallOnStatusProcess(FirmwareTask &task)
428 {
429     FIRMWARE_LOGI("HandleBootInstallOnStatusProcess");
430     FirmwareTaskOperator().UpdateProgressByTaskId(
431         task.taskId, UpgradeStatus::DOWNLOAD_SUCCESS, Firmware::ONE_HUNDRED);
432     std::vector<FirmwareComponent> firmwareComponentList;
433     FirmwareComponentOperator firmwareComponentOperator;
434     firmwareComponentOperator.QueryAll(firmwareComponentList);
435     for (const FirmwareComponent &component : firmwareComponentList) {
436         if (component.status == UpgradeStatus::INSTALLING) {
437             firmwareComponentOperator.UpdateProgressByUrl(
438                 component.url, UpgradeStatus::DOWNLOAD_SUCCESS, Firmware::ONE_HUNDRED);
439         }
440     }
441     BusinessError businessError;
442     UpgradeOptions upgradeOptions;
443     upgradeOptions.order = Order::INSTALL_AND_APPLY;
444     DoInstall(upgradeOptions, businessError, InstallType::SYS_INSTALLER);
445 }
446 
HandleBootDownloadOnStatusProcess(FirmwareTask & task)447 void FirmwareManager::HandleBootDownloadOnStatusProcess(FirmwareTask &task)
448 {
449     // 下载中重启,清除记录和数据
450     FIRMWARE_LOGI("HandleBootDownloadOnStatusProcess ClearFirmwareInfo");
451     FirmwareUpdateHelper::ClearFirmwareInfo();
452 }
453 
HandleBootDownloadPauseStatusProcess(FirmwareTask & task)454 void FirmwareManager::HandleBootDownloadPauseStatusProcess(FirmwareTask &task)
455 {
456     FirmwareUpdateHelper::ClearFirmwareInfo();
457 }
458 
HandleResumeDownload(FirmwareTask & task)459 void FirmwareManager::HandleResumeDownload(FirmwareTask &task)
460 {
461     FIRMWARE_LOGI("HandleResumeDownload");
462 }
463 
HandleBootDownloadedStatusProcess(FirmwareTask & task)464 void FirmwareManager::HandleBootDownloadedStatusProcess(FirmwareTask &task)
465 {
466     FIRMWARE_LOGI("HandleBootDownloadedStatusProcess");
467 }
468 
DoAutoDownload(const FirmwareTask & task)469 void FirmwareManager::DoAutoDownload(const FirmwareTask &task)
470 {
471     FIRMWARE_LOGI("DoAutoDownload");
472 }
473 
NotifyInitEvent()474 void FirmwareManager::NotifyInitEvent()
475 {
476     bool dueInitFlag = preferencesUtil_->ObtainBool(Constant::DUE_INIT_FLAG, false);
477     FIRMWARE_LOGI("DUE_INIT_FLAG is %{public}s", StringUtils::GetBoolStr(dueInitFlag).c_str());
478     if (!dueInitFlag) {
479         preferencesUtil_->SaveBool(Constant::DUE_INIT_FLAG, true);
480         DelayedSingleton<FirmwareCallbackUtils>::GetInstance()->NotifyEvent("", EventId::EVENT_INITIALIZE,
481             UpgradeStatus::INIT);
482     }
483 }
484 } // namespace UpdateEngine
485 } // namespace OHOS
486