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