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