Merge "Revert "Replace mock API"" into tizen
[platform/core/appfw/pkgmgr-info.git] / src / server / worker_thread.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 "worker_thread.hh"
18
19 #include <sqlite3.h>
20 #include <malloc.h>
21
22 #include "abstract_parcelable.hh"
23 #include "command_request_handler.hh"
24 #include "create_cache_request_handler.hh"
25 #include "create_db_request_handler.hh"
26 #include "db_handle_provider.hh"
27 #include "get_appinfo_request_handler.hh"
28 #include "get_cert_request_handler.hh"
29 #include "get_depinfo_request_handler.hh"
30 #include "get_pkginfo_request_handler.hh"
31 #include "query_request_handler.hh"
32 #include "set_cert_request_handler.hh"
33 #include "set_pkginfo_request_handler.hh"
34 #include "utils/logging.hh"
35
36 #include "pkgmgrinfo_debug.h"
37
38 #ifdef LOG_TAG
39 #undef LOG_TAG
40 #endif
41 #define LOG_TAG "PKGMGR_INFO"
42
43 #ifndef SQLITE_ENABLE_MEMORY_MANAGEMENT
44 #define SQLITE_ENABLE_MEMORY_MANAGEMENT
45 #endif
46
47 namespace pkgmgr_server {
48
49 WorkerThread::WorkerThread(unsigned int num) : stop_all_(false) {
50   threads_.reserve(num);
51   for (unsigned int i = 0; i < num; ++i)
52     threads_.emplace_back([this]() -> void { this->Run(); });
53
54   LOG(DEBUG) << num << " Worker threads are created";
55 }
56
57 WorkerThread::~WorkerThread() {
58   stop_all_ = true;
59   cv_.notify_all();
60
61   for (auto& t : threads_)
62     t.join();
63 }
64
65 bool WorkerThread::PushQueue(std::shared_ptr<PkgRequest> req) {
66   {
67     std::unique_lock<std::mutex> u(lock_);
68     queue_.push(req);
69     cv_.notify_one();
70   }
71   return true;
72 }
73
74 void WorkerThread::Run() {
75   std::unique_ptr<request_handler::AbstractRequestHandler>
76       handler[pkgmgr_common::ReqType::MAX];
77   handler[pkgmgr_common::ReqType::GET_PKG_INFO].reset(
78       new request_handler::GetPkginfoRequestHandler());
79   handler[pkgmgr_common::ReqType::GET_APP_INFO].reset(
80       new request_handler::GetAppinfoRequestHandler());
81   handler[pkgmgr_common::ReqType::SET_PKG_INFO].reset(
82       new request_handler::SetPkginfoRequestHandler());
83   handler[pkgmgr_common::ReqType::SET_CERT_INFO].reset(
84       new request_handler::SetCertRequestHandler());
85   handler[pkgmgr_common::ReqType::GET_CERT_INFO].reset(
86       new request_handler::GetCertRequestHandler());
87   handler[pkgmgr_common::ReqType::GET_PKG_DEP_INFO].reset(
88       new request_handler::GetDepinfoRequestHandler());
89   handler[pkgmgr_common::ReqType::QUERY].reset(
90       new request_handler::QueryRequestHandler());
91   handler[pkgmgr_common::ReqType::COMMAND].reset(
92       new request_handler::CommandRequestHandler());
93   handler[pkgmgr_common::ReqType::CREATE_DB].reset(
94       new request_handler::CreateDBRequestHandler());
95   handler[pkgmgr_common::ReqType::CREATE_CACHE].reset(
96       new request_handler::CreateCacheRequestHandler());
97
98   LOG(DEBUG) << "Initialize request handlers";
99   while (true) {
100     std::shared_ptr<PkgRequest> req;
101     {
102       std::unique_lock<std::mutex> u(lock_);
103       cv_.wait(u, [this] { return !this->queue_.empty() || stop_all_; });
104       if (stop_all_ && queue_.empty())
105         return;
106       req = PopQueue();
107     }
108
109     pkgmgr_common::ReqType type = req->GetRequestType();
110     LOG(WARNING) << "Request type: " << pkgmgr_common::ReqTypeToString(type)
111         << " pid: " << req->GetSenderPID();
112     if (type <= pkgmgr_common::ReqType::REQ_TYPE_NONE
113             || type >= pkgmgr_common::ReqType::MAX) {
114       LOG(ERROR) << "Request type is invalid: " << static_cast<int>(type)
115           << ",  pid:" << req->GetSenderPID();
116       SendError(req);
117
118       continue;
119     }
120
121     try {
122       handler[type]->SetPID(req->GetSenderPID());
123       if (!handler[type]->HandleRequest(req->GetData(), req->GetSize(),
124                                         locale_.GetObject()))
125         LOG(ERROR) << "Failed to handle request";
126     } catch (const std::exception& err) {
127       LOG(ERROR) << "Exception occurred: " << err.what()
128           << ", pid: " << req->GetSenderPID();
129       SendError(req);
130
131       continue;
132     } catch (...) {
133       LOG(ERROR) << "Exception occurred pid: " << req->GetSenderPID();
134       SendError(req);
135
136       continue;
137     }
138
139     std::vector<uint8_t> result_data = handler[type]->ExtractResult();
140     if (req->SendData(result_data.data(), result_data.size()) == false) {
141       LOG(ERROR) << "Failed to send response pid: " << req->GetSenderPID();
142       continue;
143     }
144     LOG(WARNING) << "Success response pid: " <<  req->GetSenderPID();
145   }
146 }
147
148 void WorkerThread::SetMemoryTrimTimer() {
149   static guint timer = 0;
150   if (timer > 0)
151     g_source_remove(timer);
152
153   timer = g_timeout_add_seconds_full(G_PRIORITY_LOW, 3,
154       TrimMemory, &timer, NULL);
155 }
156
157 gboolean WorkerThread::TrimMemory(void* data) {
158   LOG(DEBUG) << "Trim memory";
159   guint* timer = static_cast<guint*>(data);
160   sqlite3_release_memory(-1);
161   malloc_trim(0);
162   *timer = 0;
163
164   if (database::DBHandleProvider::IsCrashedWriteRequest())
165     database::DBHandleProvider::
166         GetInst(getuid()).UnsetMemoryMode(getpid());
167
168   database::DBHandleProvider::
169         GetInst(getuid()).TrimCache();
170
171   return false;
172 }
173
174 std::shared_ptr<PkgRequest> WorkerThread::PopQueue() {
175   SetMemoryTrimTimer();
176   auto req = queue_.front();
177   queue_.pop();
178   return req;
179 }
180
181 void WorkerThread::SetLocale(std::string locale) {
182   LOG(DEBUG) << "Change locale : " << locale_.GetObject()
183       << " -> "  << locale;
184   locale_.SetObject(std::move(locale));
185 }
186
187 void WorkerThread::SendError(std::shared_ptr<PkgRequest> req) {
188   pkgmgr_common::parcel::AbstractParcelable parcelable(
189       0, pkgmgr_common::parcel::ParcelableType::Unknown, PMINFO_R_ERROR);
190   tizen_base::Parcel p;
191   p.WriteParcelable(parcelable);
192   std::vector<uint8_t> raw = p.GetRaw();
193   req->SendData(&raw[0], raw.size());
194 }
195
196 }  // namespace pkgmgr_server