Delay Creation of cache if backup database is exist
[platform/core/appfw/pkgmgr-info.git] / src / server / database / cache_db_handler.cc
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
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 "cache_db_handler.hh"
18
19 #include <shared_mutex>
20 #include <vector>
21
22 #include "cache_flag.hh"
23 #include "db_handle_provider.hh"
24 #include "utils/logging.hh"
25
26 namespace pkgmgr_server {
27 namespace database {
28
29 CacheDBHandler::CacheDBHandler(uid_t uid, int pid)
30     : AbstractDBHandler(uid, pid), uid_(uid) {}
31
32 CacheDBHandler::~CacheDBHandler() {}
33
34 bool CacheDBHandler::IsBackupDBExist() {
35   auto dbpath_list = GetDBPath();
36   for (const auto& [path, uid] : dbpath_list) {
37     auto backup_db_path = path + ".bck";
38
39     if (access(backup_db_path.c_str(), F_OK) == 0) {
40       LOG(WARNING) << "Backup database[" << backup_db_path
41           << "] created during pkg_upgrade remain, Try to delay cache creation";
42       return true;
43     }
44   }
45
46   return false;
47 }
48
49 int CacheDBHandler::Execute() {
50   SetOpType(pkgmgr_common::DBOperationType::OPERATION_TYPE_READ);
51   SetDBType(pkgmgr_common::DBType::DB_TYPE_FILE_PKGDB);
52
53   while (IsBackupDBExist())
54     sleep(1);
55
56   std::shared_lock<std::shared_mutex> s(lock_);
57
58   if (!Connect()) {
59     CacheFlag::SetStatus(CacheFlag::Status::UNPREPARED);
60     return PMINFO_R_ERROR;
61   }
62
63   const auto& conn_list = GetConnection();
64   auto lock = CacheFlag::GetWriterLock();
65   int ret = PMINFO_R_OK;
66   for (const auto& [db, uid] : conn_list) {
67     ret = DBHandleProvider::GetInst(uid)
68               .UpdateCache(db, GetPID(), uid_, false, GetLocale());
69     if (ret != PMINFO_R_OK) {
70       LOG(ERROR) << "Failed to update pkginfo cache : " << ret;
71       break;
72     }
73   }
74
75   CacheFlag::SetStatus(ret == PMINFO_R_OK ?
76       CacheFlag::Status::PREPARED :
77       CacheFlag::Status::UNPREPARED);
78
79   return ret;
80 }
81
82 }  // namespace database
83 }  // namespace pkgmgr_server