1 /*
2 * Copyright (c) 2024 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
17 #include "js_systemload.h"
18
19 #include <functional>
20
21 #include "js_napi_utils.h"
22 #include "res_sched_client.h"
23 #include "res_sched_log.h"
24
25 namespace OHOS {
26 namespace ResourceSchedule {
27 static constexpr size_t ARG_COUNT_ONE = 1;
28 static constexpr size_t ARG_COUNT_TWO = 2;
29 static const std::string SYSTEMLOAD_LEVEL = "systemLoadChange";
30 static const int32_t ON = 1;
31 static const int32_t OFF = 0;
32
GetInstance()33 Systemload& Systemload::GetInstance()
34 {
35 static Systemload systemload;
36 return systemload;
37 }
38
~Systemload()39 Systemload::~Systemload()
40 {
41 std::lock_guard<std::mutex> autoLock(jsCallbackMapLock_);
42 jsCallBackMap_.clear();
43 }
44
SystemloadOn(napi_env env,napi_callback_info info)45 napi_value Systemload::SystemloadOn(napi_env env, napi_callback_info info)
46 {
47 return GetInstance().RegisterSystemloadCallback(env, info);
48 }
49
SystemloadOff(napi_env env,napi_callback_info info)50 napi_value Systemload::SystemloadOff(napi_env env, napi_callback_info info)
51 {
52 return GetInstance().UnRegisterSystemloadCallback(env, info);
53 }
54
GetLevel(napi_env env,napi_callback_info info)55 napi_value Systemload::GetLevel(napi_env env, napi_callback_info info)
56 {
57 return GetInstance().GetSystemloadLevel(env, info);
58 }
59
HandleErrCode(const napi_env & env,int32_t errCode)60 void Systemload::HandleErrCode(const napi_env& env, int32_t errCode)
61 {
62 if (errCode == ERR_OK) {
63 return;
64 }
65 auto iter = systemloadParamErrMsgMap.find(errCode);
66 std::string errMessage = "";
67 if (iter != systemloadParamErrMsgMap.end()) {
68 errMessage.append(iter->second);
69 }
70 napi_throw_error(env, std::to_string(errCode).c_str(), errMessage.c_str());
71 }
72
OnSystemloadLevel(napi_env env,napi_value callbackObj,int32_t level)73 void Systemload::OnSystemloadLevel(napi_env env, napi_value callbackObj, int32_t level)
74 {
75 RESSCHED_LOGI("OnSystemloadLevel asyncCallback.");
76 std::lock_guard<std::mutex> autoLock(jsCallbackMapLock_);
77 if (jsCallBackMap_.find(SYSTEMLOAD_LEVEL) == jsCallBackMap_.end()) {
78 RESSCHED_LOGE("OnSystemloadLevel cb type has not register yet.");
79 return;
80 }
81 auto& callbackList = jsCallBackMap_[SYSTEMLOAD_LEVEL];
82 auto iter = callbackList.begin();
83 bool isEqual = false;
84 for (; iter != callbackList.end(); iter++) {
85 NAPI_CALL_RETURN_VOID(env, napi_strict_equals(env, callbackObj, iter->first->GetNapiValue(), &isEqual));
86 if (isEqual) {
87 break;
88 }
89 }
90 if (!isEqual) {
91 RESSCHED_LOGE("OnSystemload level callback not found in registered array.");
92 return;
93 }
94 std::unique_ptr<SystemloadLevelCbInfo> cbInfo = std::make_unique<SystemloadLevelCbInfo>(env);
95 if (cbInfo == nullptr) {
96 RESSCHED_LOGE("OnSystemloadLevel cbInfo null.");
97 return;
98 }
99 cbInfo->result = level;
100 napi_value resourceName = nullptr;
101 NAPI_CALL_RETURN_VOID(env,
102 napi_create_string_latin1(env, "OnSystemloadLevel", NAPI_AUTO_LENGTH, &resourceName));
103
104 NAPI_CALL_RETURN_VOID(env,
105 napi_create_reference(env, iter->first->GetNapiValue(), 1, &cbInfo->callback));
106
107 SystemloadLevelCbInfo* ctx = cbInfo.get();
108 auto task = [env, ctx]() {
109 Systemload::CompleteCb(env, ctx);
110 };
111 if (napi_status::napi_ok != napi_send_event(env, task, napi_eprio_high)) {
112 RESSCHED_LOGE("failed to napi_send_event");
113 return;
114 }
115 cbInfo.release();
116 napi_value result = nullptr;
117 NAPI_CALL_RETURN_VOID(env, napi_get_null(env, &result));
118 RESSCHED_LOGI("OnSystemloadLevel asyncCallback end");
119 }
120
RegisterSystemloadCallback(napi_env env,napi_callback_info info)121 napi_value Systemload::RegisterSystemloadCallback(napi_env env, napi_callback_info info)
122 {
123 RESSCHED_LOGD("Regster Systemload Callback");
124 std::string cbType;
125 napi_value jsCallback = nullptr;
126
127 if (!CheckCallbackParam(env, info, cbType, &jsCallback, ON)) {
128 RESSCHED_LOGE("Register Systemload Callback parameter error.");
129 HandleErrCode(env, E_PARAM_ERROR);
130 return CreateJsUndefined(env);
131 }
132
133 napi_ref tempRef = nullptr;
134 napi_create_reference(env, jsCallback, 1, &tempRef);
135 std::unique_ptr<NativeReference> callbackRef;
136 callbackRef.reset(reinterpret_cast<NativeReference*>(tempRef));
137 std::lock_guard<std::mutex> autoLock(jsCallbackMapLock_);
138 if (jsCallBackMap_.find(cbType) == jsCallBackMap_.end()) {
139 jsCallBackMap_[cbType] = std::list<CallBackPair>();
140 }
141 auto& callbackList = jsCallBackMap_[cbType];
142 auto iter = callbackList.begin();
143 for (; iter != callbackList.end(); iter++) {
144 bool isEqual = false;
145 napi_strict_equals(env, jsCallback, iter->first->GetNapiValue(), &isEqual);
146 if (isEqual) {
147 RESSCHED_LOGW("Register a exist callback type.");
148 return CreateJsUndefined(env);
149 }
150 }
151 auto systemloadLevelCb = [](napi_env env, napi_value callbackObj, int32_t level) {
152 Systemload::GetInstance().OnSystemloadLevel(env, callbackObj, level);
153 };
154 sptr<SystemloadListener> systemloadListener =
155 new (std::nothrow) SystemloadListener(env, jsCallback, systemloadLevelCb);
156 if (systemloadListener == nullptr) {
157 RESSCHED_LOGE("Register Systemload listener nullptr.");
158 return CreateJsUndefined(env);
159 }
160 ResSchedClient::GetInstance().RegisterSystemloadNotifier(systemloadListener);
161 callbackList.emplace_back(std::move(callbackRef), systemloadListener);
162 return CreateJsUndefined(env);
163 }
164
UnRegisterSystemloadCallback(napi_env env,napi_callback_info info)165 napi_value Systemload::UnRegisterSystemloadCallback(napi_env env, napi_callback_info info)
166 {
167 RESSCHED_LOGD("UnRegster Systemload Callback");
168 std::string cbType;
169 napi_value jsCallback = nullptr;
170
171 if (!CheckCallbackParam(env, info, cbType, &jsCallback, OFF)) {
172 RESSCHED_LOGE("UnRegister Systemload Callback parameter error.");
173 HandleErrCode(env, E_PARAM_ERROR);
174 return CreateJsUndefined(env);
175 }
176
177 std::lock_guard<std::mutex> autoLock(jsCallbackMapLock_);
178 if (jsCallBackMap_.find(cbType) == jsCallBackMap_.end()) {
179 RESSCHED_LOGE("unRegister cbType has not registered");
180 HandleErrCode(env, E_PARAM_ERROR);
181 return CreateJsUndefined(env);
182 }
183 auto& callbackList = jsCallBackMap_[cbType];
184 bool isEqual = false;
185 for (auto iter = callbackList.begin(); iter != callbackList.end(); iter++) {
186 isEqual = false;
187 napi_strict_equals(env, jsCallback, iter->first->GetNapiValue(), &isEqual);
188 if (isEqual) {
189 ResSchedClient::GetInstance().UnRegisterSystemloadNotifier(iter->second);
190 callbackList.erase(iter);
191 break;
192 }
193 }
194 if (!isEqual) {
195 RESSCHED_LOGE("UnRegister Systemload Callback error.");
196 HandleErrCode(env, E_PARAM_ERROR);
197 return CreateJsUndefined(env);
198 }
199 return CreateJsUndefined(env);
200 }
201
GetSystemloadLevel(napi_env env,napi_callback_info info)202 napi_value Systemload::GetSystemloadLevel(napi_env env, napi_callback_info info)
203 {
204 RESSCHED_LOGI("GetSystemloadLevel, promise.");
205 std::unique_ptr<SystemloadLevelCbInfo> cbInfo = std::make_unique<SystemloadLevelCbInfo>(env);
206 if (cbInfo == nullptr) {
207 return CreateJsUndefined(env);
208 }
209 napi_value resourceName;
210 NAPI_CALL(env, napi_create_string_latin1(env, "GetSystemloadLevel", NAPI_AUTO_LENGTH, &resourceName));
211 napi_deferred deferred;
212 napi_value promise = nullptr;
213 NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
214 cbInfo->deferred = deferred;
215
216 NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName,
217 Execute,
218 Complete,
219 static_cast<void *>(cbInfo.get()),
220 &cbInfo->asyncWork));
221 NAPI_CALL(env, napi_queue_async_work(env, cbInfo->asyncWork));
222 cbInfo.release();
223 RESSCHED_LOGI("GetSystemloadLevel, promise end");
224 return promise;
225 }
226
Execute(napi_env env,void * data)227 void Systemload::Execute(napi_env env, void* data)
228 {
229 RESSCHED_LOGI("GetSystemloadLevel, worker pool thread execute.");
230 auto* cbInfo = static_cast<SystemloadLevelCbInfo*>(data);
231 if (cbInfo == nullptr) {
232 RESSCHED_LOGW("GetSystemloadLevel execute cb info is nullptr.");
233 return;
234 }
235 cbInfo->result = ResSchedClient::GetInstance().GetSystemloadLevel();
236 RESSCHED_LOGI("GetSystemloadLevel, worker pool thread execute end.");
237 }
238
Complete(napi_env env,napi_status status,void * data)239 void Systemload::Complete(napi_env env, napi_status status, void* data)
240 {
241 RESSCHED_LOGI("GetSystemloadLevel, main event thread complete.");
242 auto* info = static_cast<SystemloadLevelCbInfo*>(data);
243 if (info == nullptr) {
244 RESSCHED_LOGW("GetSystemloadLevel Complete cb info is nullptr.");
245 return;
246 }
247 std::unique_ptr<SystemloadLevelCbInfo> cbInfo(info);
248 napi_value result = nullptr;
249 napi_create_uint32(env, static_cast<uint32_t>(cbInfo->result), &result);
250 NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, cbInfo->deferred, result));
251 NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, cbInfo->asyncWork));
252 cbInfo->asyncWork = nullptr;
253 RESSCHED_LOGI("GetSystemloadLevel, main event thread complete end.");
254 }
255
CompleteCb(napi_env env,SystemloadLevelCbInfo * info)256 void Systemload::CompleteCb(napi_env env, SystemloadLevelCbInfo* info)
257 {
258 RESSCHED_LOGI("CompleteCb, main event thread complete callback.");
259 if (info == nullptr) {
260 RESSCHED_LOGW("Complete cb info is nullptr.");
261 return;
262 }
263 std::unique_ptr<SystemloadLevelCbInfo> cbInfo(info);
264 napi_value callback = nullptr;
265 napi_value undefined = nullptr;
266 napi_value result = nullptr;
267 napi_value callResult = nullptr;
268 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined));
269 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, cbInfo->callback, &callback));
270 napi_create_uint32(env, static_cast<uint32_t>(cbInfo->result), &result);
271 // call js callback
272 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, 1, &result, &callResult));
273 if (cbInfo->callback != nullptr) {
274 NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, cbInfo->callback));
275 cbInfo->callback = nullptr;
276 }
277 RESSCHED_LOGI("CompleteCb, main event thread complete end.");
278 }
279
CheckCallbackParam(napi_env env,napi_callback_info info,std::string & cbType,napi_value * jsCallback,int32_t status)280 bool Systemload::CheckCallbackParam(napi_env env, napi_callback_info info,
281 std::string &cbType, napi_value *jsCallback,
282 int32_t status)
283 {
284 if (jsCallback == nullptr) {
285 RESSCHED_LOGE("Input callback is nullptr.");
286 return false;
287 }
288 size_t argc = ARG_COUNT_TWO;
289 napi_value argv[ARG_COUNT_TWO] = { 0 };
290 NAPI_CALL_BASE(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr), false);
291 if (status == ON && argc != ARG_COUNT_TWO) {
292 RESSCHED_LOGE("Parameter error. The type of \"number of parameters\" must be 2");
293 return false;
294 }
295 if (!ConvertFromJsValue(env, argv[0], cbType)) {
296 RESSCHED_LOGE("Parameter error. The type of \"type\" must be string");
297 return false;
298 }
299 if (cbType != SYSTEMLOAD_LEVEL) {
300 RESSCHED_LOGE("Parameter error. The type of \"type\" must be systemLoadChange");
301 return false;
302 }
303 *jsCallback = argv[ARG_COUNT_ONE];
304 if (*jsCallback == nullptr) {
305 RESSCHED_LOGE("listenerObj is nullptr");
306 return false;
307 }
308 bool isCallable = false;
309 napi_is_callable(env, *jsCallback, &isCallable);
310 if (status == ON && !isCallable) {
311 RESSCHED_LOGE("Parameter error. The type of \"callback\" must be Callback");
312 return false;
313 }
314 return true;
315 }
316 } // ResourceSchedule
317 } // OHOS