From 93aac5b48070827d917edf849a9e1bb7747be464 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 27 Jan 2022 10:29:02 +0800 Subject: [PATCH 01/29] add work scheduler Signed-off-by: chenming --- bundle.json | 9 +- frameworks/BUILD.gn | 69 +++ frameworks/extension/BUILD.gn | 65 +++ .../extension/include/iwork_scheduler.h | 36 ++ .../include/js_work_scheduler_extension.h | 56 ++ .../js_work_scheduler_extension_context.h | 31 ++ .../include/work_scheduler_extension.h | 53 ++ .../work_scheduler_extension_context.h | 31 ++ .../work_scheduler_extension_module_loader.h | 36 ++ .../src/js_work_scheduler_extension.cpp | 187 +++++++ .../js_work_scheduler_extension_context.cpp | 58 +++ .../src/work_scheduler_extension.cpp | 73 +++ .../src/work_scheduler_extension_context.cpp | 24 + ...work_scheduler_extension_module_loader.cpp | 33 ++ frameworks/include/iwork_conn.h | 40 ++ frameworks/include/iwork_sched_service.h | 55 ++ .../include/work_condition.h | 2 +- frameworks/include/work_info.h | 74 +++ frameworks/include/workscheduler_srv_client.h | 61 +++ frameworks/src/work_info.cpp | 375 ++++++++++++++ frameworks/src/workscheduler_srv_client.cpp | 183 +++++++ .../constanttest => frameworks/test}/BUILD.gn | 24 +- frameworks/test/unittest/BUILD.gn | 46 ++ .../test/unittest/include/workinfo_test.h | 33 ++ .../test/unittest/src/workinfo_test.cpp | 214 ++++++++ ...cheduler.d.ts => @ohos.workScheduler.d.ts} | 0 interfaces/kits/js/BUILD.gn | 38 +- interfaces/kits/js/napi/include/common.h | 71 +++ .../kits/js/napi/include/get_work_status.h | 28 + .../js/napi/include/is_last_work_time_out.h | 28 + .../kits/js/napi/include/obtain_all_works.h | 28 + interfaces/kits/js/napi/include/start_work.h | 28 + .../js/napi/include/stop_and_clear_works.h | 29 ++ interfaces/kits/js/napi/include/stop_work.h | 28 + .../kits/js/napi/include/workscheduler_napi.h | 4 +- interfaces/kits/js/napi/src/common.cpp | 264 ++++++++++ .../kits/js/napi/src/get_work_status.cpp | 121 +++++ .../js/napi/src/is_last_work_time_out.cpp | 124 +++++ .../kits/js/napi/src/obtain_all_works.cpp | 114 +++++ interfaces/kits/js/napi/src/start_work.cpp | 51 ++ .../kits/js/napi/src/stop_and_clear_works.cpp | 33 ++ interfaces/kits/js/napi/src/stop_work.cpp | 60 +++ .../kits/js/napi/src/workscheduler_napi.cpp | 94 ++-- .../js/napi/work_scheduler_extension/BUILD.gn | 52 ++ .../work_scheduler_extension.js | 25 + .../work_scheduler_extension_module.cpp | 59 +++ .../work_scheduler_extension_context/BUILD.gn | 54 ++ .../work_scheduler_extension_context.js | 24 + ...ork_scheduler_extension_context_module.cpp | 59 +++ sa_profile/1904.xml | 2 +- sa_profile/BUILD.gn | 6 +- sa_profile/etc/work_scheduler_service.cfg | 1 - services/BUILD.gn | 49 +- .../conditions/battery_level_listener.h | 54 ++ .../conditions/battery_status_listener.h | 54 ++ .../include/conditions/charger_listener.h | 53 ++ .../conditions/common_event_detector.h | 30 ++ .../include/conditions/network_listener.h | 52 ++ .../include/conditions/power_listener.h | 55 ++ .../include/conditions/storage_listener.h | 54 ++ .../include/conditions/timer_listener.h | 47 ++ services/native/include/detector_value.h | 35 ++ services/native/include/icondition_listener.h | 37 ++ services/native/include/ipolicy_filter.h | 33 ++ services/native/include/ipolicy_listener.h | 36 ++ .../include/policy/app_removed_listener.h | 50 ++ .../native/include/policy/memory_policy.h | 44 ++ .../native/include/policy/thermal_policy.h | 39 ++ services/native/include/policy_type.h | 34 ++ services/native/include/work_conn_manager.h | 45 ++ services/native/include/work_event_handler.h | 44 ++ services/native/include/work_policy_manager.h | 81 +++ services/native/include/work_queue.h | 57 +++ .../native/include/work_queue_event_handler.h | 42 ++ services/native/include/work_queue_manager.h | 56 ++ .../include/work_scheduler_connection.h | 35 ++ .../native/include/work_scheduler_service.h | 72 ++- services/native/include/work_status.h | 69 +++ .../src/conditions/battery_level_listener.cpp | 94 ++++ .../conditions/battery_status_listener.cpp | 96 ++++ .../src/conditions/charger_listener.cpp | 125 +++++ .../src/conditions/network_listener.cpp | 90 ++++ .../native/src/conditions/power_listener.cpp | 93 ++++ .../src/conditions/storage_listener.cpp | 93 ++++ .../native/src/conditions/timer_listener.cpp | 59 +++ .../src/policy/app_removed_listener.cpp | 85 +++ services/native/src/policy/memory_policy.cpp | 80 +++ services/native/src/policy/thermal_policy.cpp | 68 +++ services/native/src/work_conn_manager.cpp | 64 +++ services/native/src/work_event_handler.cpp | 51 ++ services/native/src/work_policy_manager.cpp | 312 ++++++++++++ services/native/src/work_queue.cpp | 195 +++++++ .../native/src/work_queue_event_handler.cpp | 43 ++ services/native/src/work_queue_manager.cpp | 143 ++++++ .../native/src/work_scheduler_connection.cpp | 37 ++ .../native/src/work_scheduler_service.cpp | 409 ++++++++++++++- services/native/src/work_status.cpp | 250 +++++++++ services/native/test/BUILD.gn | 20 + services/native/test/unittest/BUILD.gn | 55 ++ .../unittest/include/workscheduler_test.h | 33 ++ .../test/unittest/src/workscheduler_test.cpp | 482 ++++++++++++++++++ services/zidl/include/work_conn_proxy.h | 40 ++ services/zidl/include/work_conn_stub.h | 39 ++ .../zidl/include/work_sched_service_proxy.h | 48 ++ .../zidl/include/work_sched_service_stub.h | 48 ++ services/zidl/include/work_scheduler_proxy.h | 45 ++ services/zidl/include/work_scheduler_stub.h | 40 ++ .../zidl/include/work_scheduler_stub_imp.h | 43 ++ services/zidl/src/work_conn_proxy.cpp | 72 +++ services/zidl/src/work_conn_stub.cpp | 61 +++ .../zidl/src/work_sched_service_proxy.cpp | 251 +++++++++ services/zidl/src/work_sched_service_stub.cpp | 193 +++++++ services/zidl/src/work_scheduler_proxy.cpp | 56 ++ services/zidl/src/work_scheduler_stub.cpp | 39 ++ services/zidl/src/work_scheduler_stub_imp.cpp | 48 ++ test/constanttest/constant_test.cpp | 210 -------- utils/dump/BUILD.gn | 53 ++ utils/dump/include/event_publisher.h | 35 ++ utils/dump/include/shell_command.h | 58 +++ .../include/workscheduler_shell_command.h | 37 ++ utils/dump/src/event_publisher.cpp | 137 +++++ utils/dump/src/main.cpp | 25 + utils/dump/src/shell_command.cpp | 85 +++ .../dump/src/workscheduler_shell_command.cpp | 99 ++++ utils/{ => native}/BUILD.gn | 10 +- utils/native/include/delayed_sp_singleton.h | 75 +++ utils/native/include/work_sched_common.h | 95 ++++ utils/native/include/work_sched_errors.h | 3 + utils/native/include/work_sched_hilog.h | 106 ++-- utils/native/src/work_sched_hilog.cpp | 44 ++ workscheduler.gni | 4 +- 131 files changed, 9227 insertions(+), 399 deletions(-) create mode 100644 frameworks/BUILD.gn create mode 100644 frameworks/extension/BUILD.gn create mode 100644 frameworks/extension/include/iwork_scheduler.h create mode 100644 frameworks/extension/include/js_work_scheduler_extension.h create mode 100644 frameworks/extension/include/js_work_scheduler_extension_context.h create mode 100644 frameworks/extension/include/work_scheduler_extension.h create mode 100644 frameworks/extension/include/work_scheduler_extension_context.h create mode 100644 frameworks/extension/include/work_scheduler_extension_module_loader.h create mode 100644 frameworks/extension/src/js_work_scheduler_extension.cpp create mode 100644 frameworks/extension/src/js_work_scheduler_extension_context.cpp create mode 100644 frameworks/extension/src/work_scheduler_extension.cpp create mode 100644 frameworks/extension/src/work_scheduler_extension_context.cpp create mode 100644 frameworks/extension/src/work_scheduler_extension_module_loader.cpp create mode 100644 frameworks/include/iwork_conn.h create mode 100644 frameworks/include/iwork_sched_service.h rename {interfaces/innerkits/native => frameworks}/include/work_condition.h (98%) create mode 100644 frameworks/include/work_info.h create mode 100644 frameworks/include/workscheduler_srv_client.h create mode 100644 frameworks/src/work_info.cpp create mode 100644 frameworks/src/workscheduler_srv_client.cpp rename {test/constanttest => frameworks/test}/BUILD.gn (58%) create mode 100644 frameworks/test/unittest/BUILD.gn create mode 100644 frameworks/test/unittest/include/workinfo_test.h create mode 100644 frameworks/test/unittest/src/workinfo_test.cpp rename interfaces/kits/js/{@ohos.workscheduler.d.ts => @ohos.workScheduler.d.ts} (100%) create mode 100644 interfaces/kits/js/napi/include/common.h create mode 100644 interfaces/kits/js/napi/include/get_work_status.h create mode 100644 interfaces/kits/js/napi/include/is_last_work_time_out.h create mode 100644 interfaces/kits/js/napi/include/obtain_all_works.h create mode 100644 interfaces/kits/js/napi/include/start_work.h create mode 100644 interfaces/kits/js/napi/include/stop_and_clear_works.h create mode 100644 interfaces/kits/js/napi/include/stop_work.h create mode 100644 interfaces/kits/js/napi/src/common.cpp create mode 100644 interfaces/kits/js/napi/src/get_work_status.cpp create mode 100644 interfaces/kits/js/napi/src/is_last_work_time_out.cpp create mode 100644 interfaces/kits/js/napi/src/obtain_all_works.cpp create mode 100644 interfaces/kits/js/napi/src/start_work.cpp create mode 100644 interfaces/kits/js/napi/src/stop_and_clear_works.cpp create mode 100644 interfaces/kits/js/napi/src/stop_work.cpp create mode 100644 interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn create mode 100644 interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension.js create mode 100644 interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension_module.cpp create mode 100644 interfaces/kits/js/napi/work_scheduler_extension_context/BUILD.gn create mode 100644 interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context.js create mode 100644 interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context_module.cpp create mode 100644 services/native/include/conditions/battery_level_listener.h create mode 100644 services/native/include/conditions/battery_status_listener.h create mode 100644 services/native/include/conditions/charger_listener.h create mode 100644 services/native/include/conditions/common_event_detector.h create mode 100644 services/native/include/conditions/network_listener.h create mode 100644 services/native/include/conditions/power_listener.h create mode 100644 services/native/include/conditions/storage_listener.h create mode 100644 services/native/include/conditions/timer_listener.h create mode 100644 services/native/include/detector_value.h create mode 100644 services/native/include/icondition_listener.h create mode 100644 services/native/include/ipolicy_filter.h create mode 100644 services/native/include/ipolicy_listener.h create mode 100644 services/native/include/policy/app_removed_listener.h create mode 100644 services/native/include/policy/memory_policy.h create mode 100644 services/native/include/policy/thermal_policy.h create mode 100644 services/native/include/policy_type.h create mode 100644 services/native/include/work_conn_manager.h create mode 100644 services/native/include/work_event_handler.h create mode 100644 services/native/include/work_policy_manager.h create mode 100644 services/native/include/work_queue.h create mode 100644 services/native/include/work_queue_event_handler.h create mode 100644 services/native/include/work_queue_manager.h create mode 100644 services/native/include/work_scheduler_connection.h create mode 100644 services/native/include/work_status.h create mode 100644 services/native/src/conditions/battery_level_listener.cpp create mode 100644 services/native/src/conditions/battery_status_listener.cpp create mode 100644 services/native/src/conditions/charger_listener.cpp create mode 100644 services/native/src/conditions/network_listener.cpp create mode 100644 services/native/src/conditions/power_listener.cpp create mode 100644 services/native/src/conditions/storage_listener.cpp create mode 100644 services/native/src/conditions/timer_listener.cpp create mode 100644 services/native/src/policy/app_removed_listener.cpp create mode 100644 services/native/src/policy/memory_policy.cpp create mode 100644 services/native/src/policy/thermal_policy.cpp create mode 100644 services/native/src/work_conn_manager.cpp create mode 100644 services/native/src/work_event_handler.cpp create mode 100644 services/native/src/work_policy_manager.cpp create mode 100644 services/native/src/work_queue.cpp create mode 100644 services/native/src/work_queue_event_handler.cpp create mode 100644 services/native/src/work_queue_manager.cpp create mode 100644 services/native/src/work_scheduler_connection.cpp create mode 100644 services/native/src/work_status.cpp create mode 100644 services/native/test/BUILD.gn create mode 100644 services/native/test/unittest/BUILD.gn create mode 100644 services/native/test/unittest/include/workscheduler_test.h create mode 100644 services/native/test/unittest/src/workscheduler_test.cpp create mode 100644 services/zidl/include/work_conn_proxy.h create mode 100644 services/zidl/include/work_conn_stub.h create mode 100644 services/zidl/include/work_sched_service_proxy.h create mode 100644 services/zidl/include/work_sched_service_stub.h create mode 100644 services/zidl/include/work_scheduler_proxy.h create mode 100644 services/zidl/include/work_scheduler_stub.h create mode 100644 services/zidl/include/work_scheduler_stub_imp.h create mode 100644 services/zidl/src/work_conn_proxy.cpp create mode 100644 services/zidl/src/work_conn_stub.cpp create mode 100644 services/zidl/src/work_sched_service_proxy.cpp create mode 100644 services/zidl/src/work_sched_service_stub.cpp create mode 100644 services/zidl/src/work_scheduler_proxy.cpp create mode 100644 services/zidl/src/work_scheduler_stub.cpp create mode 100644 services/zidl/src/work_scheduler_stub_imp.cpp delete mode 100644 test/constanttest/constant_test.cpp create mode 100644 utils/dump/BUILD.gn create mode 100644 utils/dump/include/event_publisher.h create mode 100644 utils/dump/include/shell_command.h create mode 100644 utils/dump/include/workscheduler_shell_command.h create mode 100644 utils/dump/src/event_publisher.cpp create mode 100644 utils/dump/src/main.cpp create mode 100644 utils/dump/src/shell_command.cpp create mode 100644 utils/dump/src/workscheduler_shell_command.cpp rename utils/{ => native}/BUILD.gn (80%) create mode 100644 utils/native/include/delayed_sp_singleton.h create mode 100644 utils/native/include/work_sched_common.h create mode 100644 utils/native/src/work_sched_hilog.cpp diff --git a/bundle.json b/bundle.json index fbff838..7333464 100644 --- a/bundle.json +++ b/bundle.json @@ -38,11 +38,16 @@ "//foundation/resourceschedule/work_scheduler/sa_profile:worksched_sa_profile", "//foundation/resourceschedule/work_scheduler/sa_profile:work_scheduler_service_init", "//foundation/resourceschedule/work_scheduler/interfaces/kits/js:workscheduler", - "//foundation/resourceschedule/work_scheduler/interfaces/kits/js:workscheduler_js" + "//foundation/resourceschedule/work_scheduler/frameworks:workschedclient", + "//foundation/resourceschedule/work_scheduler/frameworks/extension:workschedextension", + "//foundation/resourceschedule/work_scheduler/utils/dump:workscheduler_target", + "//foundation/resourceschedule/work_scheduler/interfaces/kits/js/napi/work_scheduler_extension:workschedulerextension_napi", + "//foundation/resourceschedule/work_scheduler/interfaces/kits/js/napi/work_scheduler_extension_context:workschedulerextensioncontext_napi" ], "inner_kits": [], "test": [ - "//foundation/resourceschedule/work_scheduler/test/constanttest:constanttest" + "//foundation/resourceschedule/work_scheduler/frameworks/test:workschedinnerkits_test", + "//foundation/resourceschedule/work_scheduler/services/native/test:worksched_native_test" ] } } diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn new file mode 100644 index 0000000..234f45f --- /dev/null +++ b/frameworks/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +config("worksched_private_config") { + include_dirs = [ + "${worksched_service_path}/zidl/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/src/", + "//foundation/ace/napi/native_engine" + ] +} + +config("worksched_public_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("workschedclient") { + sources = [ + "${worksched_frameworks_path}/src/work_info.cpp", + "${worksched_frameworks_path}/src/workscheduler_srv_client.cpp", + # "${worksched_frameworks_path}/src/work_scheduler_extension_context.cpp", + # "${worksched_frameworks_path}/src/work_scheduler_extension.cpp", + # "${worksched_frameworks_path}/src/js_work_scheduler_extension.cpp", + # "${worksched_frameworks_path}/src/js_work_scheduler_extension_context.cpp", + "${worksched_service_path}/zidl/src/work_conn_proxy.cpp", + "${worksched_service_path}/zidl/src/work_sched_service_proxy.cpp", + # "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", + # "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp" + ] + + configs = [ ":worksched_private_config" ] + + public_configs = [ ":worksched_public_config" ] + + deps = [ + "${worksched_utils_path}:workschedutils", + # "${worksched_frameworks_path}/extension:workschedextension", + "//third_party/jsoncpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/ace/napi:ace_napi", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native" + ] + + external_deps = [ + "safwk:system_ability_fwk", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "hiviewdfx_hilog_native:libhilog", + "appexecfwk_standard:appexecfwk_core", + "ability_runtime:app_manager", + "ability_runtime:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "napi:ace_napi" + ] + + part_name = "${worksched_native_part_name}" +} \ No newline at end of file diff --git a/frameworks/extension/BUILD.gn b/frameworks/extension/BUILD.gn new file mode 100644 index 0000000..0e05084 --- /dev/null +++ b/frameworks/extension/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +config("worksched_private_config") { + include_dirs = [ + "${worksched_service_path}/zidl/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/src/", + "//foundation/ace/napi/native_engine" + ] +} + +config("worksched_public_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("workschedextension") { + sources = [ + "src/work_scheduler_extension_context.cpp", + "src/work_scheduler_extension.cpp", + "src/js_work_scheduler_extension.cpp", + "src/js_work_scheduler_extension_context.cpp", + "src/work_scheduler_extension_module_loader.cpp", + "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", + "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp" + ] + + configs = [ ":worksched_private_config" ] + + public_configs = [ ":worksched_public_config" ] + + deps = [ + "${worksched_utils_path}:workschedutils", + "//third_party/jsoncpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/ace/napi:ace_napi", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native" + ] + + external_deps = [ + "safwk:system_ability_fwk", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "hiviewdfx_hilog_native:libhilog", + "appexecfwk_standard:appexecfwk_core", + "ability_runtime:app_manager", + "ability_runtime:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "napi:ace_napi" + ] + + part_name = "${worksched_native_part_name}" +} \ No newline at end of file diff --git a/frameworks/extension/include/iwork_scheduler.h b/frameworks/extension/include/iwork_scheduler.h new file mode 100644 index 0000000..812c8c1 --- /dev/null +++ b/frameworks/extension/include/iwork_scheduler.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ZIDL_I_WORK_SCHED_H +#define OHOS_ZIDL_I_WORK_SCHED_H + +#include +#include + +namespace OHOS { +namespace WorkScheduler { + +class IWorkScheduler : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.WorkScheduler.IWorkScheduler"); + + virtual void OnWorkStart() = 0; + + virtual void OnWorkStop() = 0; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // OHOS_ZIDL_I_WORK_SCHED_H + diff --git a/frameworks/extension/include/js_work_scheduler_extension.h b/frameworks/extension/include/js_work_scheduler_extension.h new file mode 100644 index 0000000..81ec17c --- /dev/null +++ b/frameworks/extension/include/js_work_scheduler_extension.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JS_WORKSCHED_EXTENSION_H +#define JS_WORKSCHED_EXTENSION_H + +#include "work_scheduler_extension.h" + +#include "js_runtime.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +class JsWorkSchedulerExtension : public WorkSchedulerExtension { +public: + JsWorkSchedulerExtension(AbilityRuntime::JsRuntime& jsRuntime); + virtual ~JsWorkSchedulerExtension() override; + + static JsWorkSchedulerExtension* Create(const std::unique_ptr& runtime); + + void Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + void OnStart(const AAFwk::Want& want) override; + + sptr OnConnect(const AAFwk::Want& want) override; + + void OnDisconnect(const AAFwk::Want& want) override; + + void OnStop() override; + + void OnWorkStart() override; + + void OnWorkStop() override; +private: + void GetSrcPath(std::string &srcPath); + AbilityRuntime::JsRuntime& jsRuntime_; + std::unique_ptr jsObj_; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // JS_WORKSCHED_EXTENSION_H \ No newline at end of file diff --git a/frameworks/extension/include/js_work_scheduler_extension_context.h b/frameworks/extension/include/js_work_scheduler_extension_context.h new file mode 100644 index 0000000..37cbb45 --- /dev/null +++ b/frameworks/extension/include/js_work_scheduler_extension_context.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JS_WORKSCHED_EXTENSION_CONTEXT_H +#define JS_WORKSCHED_EXTENSION_CONTEXT_H + +#include + +#include "native_engine.h" +#include "work_scheduler_extension_context.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +NativeValue* CreateJsWorkSchedulerExtensionContext(NativeEngine& engine, + std::shared_ptr context); +} // namespace WorkScheduler +} // namespace OHOS +#endif // JS_WORKSCHED_EXTENSION_H \ No newline at end of file diff --git a/frameworks/extension/include/work_scheduler_extension.h b/frameworks/extension/include/work_scheduler_extension.h new file mode 100644 index 0000000..d5f325d --- /dev/null +++ b/frameworks/extension/include/work_scheduler_extension.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_EXTENSION_H +#define WORKSCHED_EXTENSION_H + +#include +#include "ability_local_record.h" +#include "ohos_application.h" +#include "ability_handler.h" +#include "runtime.h" +#include "extension_base.h" +#include "work_scheduler_extension_context.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerExtension : public AbilityRuntime::ExtensionBase { +public: + WorkSchedulerExtension() = default; + virtual ~WorkSchedulerExtension() = default; + + std::shared_ptr CreateAndInitContext( + const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + void Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + static WorkSchedulerExtension* Create(const std::unique_ptr& runtime); + + virtual void OnWorkStart(); + + virtual void OnWorkStop(); +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // WORKSCHED_EXTENSION_H \ No newline at end of file diff --git a/frameworks/extension/include/work_scheduler_extension_context.h b/frameworks/extension/include/work_scheduler_extension_context.h new file mode 100644 index 0000000..ca98181 --- /dev/null +++ b/frameworks/extension/include/work_scheduler_extension_context.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_EXTENSION_CONTEXT_H +#define WORKSCHED_EXTENSION_CONTEXT_H + +#include "extension_context.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerExtensionContext : public AbilityRuntime::ExtensionContext { +public: + WorkSchedulerExtensionContext(); + + virtual ~WorkSchedulerExtensionContext(); +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // WORKSCHED_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/extension/include/work_scheduler_extension_module_loader.h b/frameworks/extension/include/work_scheduler_extension_module_loader.h new file mode 100644 index 0000000..9f78832 --- /dev/null +++ b/frameworks/extension/include/work_scheduler_extension_module_loader.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_WORKSCHED_EXTENSION_MODULE_LOADER_H +#define FOUNDATION_WORKSCHED_EXTENSION_MODULE_LOADER_H + +#include "extension_module_loader.h" + +namespace OHOS::WorkScheduler { +class WorkSchedulerExtensionModuleLoader : public AbilityRuntime::ExtensionModuleLoader, + public Singleton { + DECLARE_SINGLETON(WorkSchedulerExtensionModuleLoader); + +public: + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The Extension instance. + */ + virtual AbilityRuntime::Extension *Create(const std::unique_ptr& runtime) const override; +}; +} +#endif // FOUNDATION_WORKSCHED_EXTENSION_MODULE_LOADER_H \ No newline at end of file diff --git a/frameworks/extension/src/js_work_scheduler_extension.cpp b/frameworks/extension/src/js_work_scheduler_extension.cpp new file mode 100644 index 0000000..a6cfd7a --- /dev/null +++ b/frameworks/extension/src/js_work_scheduler_extension.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_work_scheduler_extension.h" + +#include "runtime.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "work_scheduler_extension.h" +#include "js_work_scheduler_extension_context.h" +#include "work_scheduler_stub_imp.h" + + +namespace OHOS { +namespace WorkScheduler { +JsWorkSchedulerExtension* JsWorkSchedulerExtension::Create(const std::unique_ptr& runtime) +{ + return new JsWorkSchedulerExtension(static_cast(*runtime)); +} + +JsWorkSchedulerExtension::JsWorkSchedulerExtension(AbilityRuntime::JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} +JsWorkSchedulerExtension::~JsWorkSchedulerExtension() = default; + +void JsWorkSchedulerExtension::Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + WS_HILOGI("enter"); + WorkSchedulerExtension::Init(record, application, handler, token); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + WS_HILOGI(" JsWorkSchedulerExtension Failed to get srcPath"); + return; + } + + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + WS_HILOGI(" JsWorkSchedulerExtension::Init moduleName:%{public}s,srcPath:%{public}s.", + moduleName.c_str(), srcPath.c_str()); + AbilityRuntime::HandleScope handleScope(jsRuntime_); + auto& engine = jsRuntime_.GetNativeEngine(); + + jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); + if (jsObj_ == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get jsObj_"); + return; + } + WS_HILOGI(" JsWorkSchedulerExtension::Init ConvertNativeValueTo."); + NativeObject* obj = AbilityRuntime::ConvertNativeValueTo(jsObj_->Get()); + if (obj == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get JsWorkSchedulerExtension object"); + return; + } + + auto context = GetContext(); + if (context == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get context"); + return; + } + WS_HILOGI("WorkSchedulerExtension ::Init CreateJsStaticSubscriberExtensionContext."); + NativeValue* contextObj = CreateJsWorkSchedulerExtensionContext(engine, context); + auto shellContextRef = jsRuntime_.LoadSystemModule("application.StaticSubscriberExtensionContext", + &contextObj, 1); + contextObj = shellContextRef->Get(); + WS_HILOGI("WorkSchedulerExtension JsStaticSubscriberExtension::Init Bind."); + context->Bind(jsRuntime_, shellContextRef.release()); + WS_HILOGI("WorkSchedulerExtension JsStaticSubscriberExtension::SetProperty."); + obj->SetProperty("context", contextObj); + WS_HILOGI("WorkSchedulerExtension JsStaticSubscriberExtension::Init end."); +} + +void JsWorkSchedulerExtension::OnStart(const AAFwk::Want& want) +{ + AbilityRuntime::Extension::OnStart(want); + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + WS_HILOGI("WorkSchedulerExtension %{public}s end.", __func__); +} + +void JsWorkSchedulerExtension::OnStop() +{ + AbilityRuntime::Extension::OnStop(); + WS_HILOGI("WorkSchedulerExtension %{public}s end.", __func__); +} + +sptr JsWorkSchedulerExtension::OnConnect(const AAFwk::Want& want) +{ + AbilityRuntime::Extension::OnConnect(want); + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + sptr remoteObject = new (std::nothrow) WorkSchedulerStubImp( + std::static_pointer_cast(shared_from_this())); + WS_HILOGI("WorkSchedulerExtension %{public}s end. ", __func__); + return remoteObject->AsObject(); +} + +void JsWorkSchedulerExtension::OnDisconnect(const AAFwk::Want& want) +{ + AbilityRuntime::Extension::OnDisconnect(want); + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + WS_HILOGI("WorkSchedulerExtension %{public}s end.", __func__); +} + +void JsWorkSchedulerExtension::OnWorkStart() +{ + WorkSchedulerExtension::OnWorkStart(); + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + // if (data == nullptr) { + // //HILOG_ERROR("%{public}s common event data == nullptr", __func__); + // return; + // } + + AbilityRuntime::HandleScope handleScope(jsRuntime_); + NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* jCommonEventData = nativeEngine.CreateObject(); + // NativeObject* commonEventData = AbilityRuntime::ConvertNativeValueTo(jCommonEventData); + // Want want = data->GetWant(); + // commonEventData->SetProperty("event", nativeEngine.CreateString(want.GetAction().c_str(), want.GetAction().size())); + // commonEventData->SetProperty("bundleName", nativeEngine.CreateString(want.GetBundle().c_str(), + // want.GetBundle().size())); + // commonEventData->SetProperty("code", nativeEngine.CreateNumber(data->GetCode())); + // commonEventData->SetProperty("data", nativeEngine.CreateString(data->GetData().c_str(), data->GetData().size())); + // napi_value napiParams = AppExecFwk::WrapWantParams(reinterpret_cast(&nativeEngine), want.GetParams()); + // NativeValue* nativeParams = reinterpret_cast(napiParams); + // commonEventData->SetProperty("parameters", nativeParams); + + NativeValue* argv[] = {jCommonEventData}; + if (!jsObj_) { + WS_HILOGI("WorkSchedulerExtension Not found StaticSubscriberExtension.js"); + return; + } + + NativeValue* value = jsObj_->Get(); + NativeObject* obj = AbilityRuntime::ConvertNativeValueTo(value); + if (obj == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get StaticSubscriberExtension object"); + return; + } + + NativeValue* method = obj->GetProperty("onWorkStart"); + if (method == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get onCommonEventTriggered from StaticSubscriberExtension object"); + return; + } + nativeEngine.CallFunction(value, method, argv, 1); + WS_HILOGI("WorkSchedulerExtension %{public}s end.", __func__); +} + +void JsWorkSchedulerExtension::OnWorkStop() +{ +} + +void JsWorkSchedulerExtension::GetSrcPath(std::string &srcPath) +{ + if (!Extension::abilityInfo_->isStageBasedModel) { + /* temporary compatibility api8 + config.json */ + srcPath.append(Extension::abilityInfo_->package); + srcPath.append("/assets/js/"); + if (!Extension::abilityInfo_->srcPath.empty()) { + srcPath.append(Extension::abilityInfo_->srcPath); + } + srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); + return; + } + + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/extension/src/js_work_scheduler_extension_context.cpp b/frameworks/extension/src/js_work_scheduler_extension_context.cpp new file mode 100644 index 0000000..695e91a --- /dev/null +++ b/frameworks/extension/src/js_work_scheduler_extension_context.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_work_scheduler_extension_context.h" + +//#include "hilog_wrapper.h" + +#include "js_extension_context.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { +namespace { +class JsWorkSchedulerExtensionContext final { +public: + explicit JsWorkSchedulerExtensionContext(const std::shared_ptr& context) + : context_(context) {} + ~JsWorkSchedulerExtensionContext() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + //HILOG_INFO("JsStaticSubscriberExtensionContext::Finalizer is called"); + std::unique_ptr( + static_cast(data)); + } +private: + std::weak_ptr context_; +}; +} // namespace + +NativeValue* CreateJsWorkSchedulerExtensionContext(NativeEngine& engine, + std::shared_ptr context) +{ + //HILOG_INFO("CreateJsStaticSubscriberExtensionContext begin"); + NativeValue *objValue = AbilityRuntime::CreateJsExtensionContext(engine, context); + NativeObject *object = AbilityRuntime::ConvertNativeValueTo(objValue); + + std::unique_ptr jsContext = + std::make_unique(context); + object->SetNativePointer(jsContext.release(), JsWorkSchedulerExtensionContext::Finalizer, nullptr); + return objValue; +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/frameworks/extension/src/work_scheduler_extension.cpp b/frameworks/extension/src/work_scheduler_extension.cpp new file mode 100644 index 0000000..37925a2 --- /dev/null +++ b/frameworks/extension/src/work_scheduler_extension.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_extension.h" + +#include "ability_loader.h" +#include "extension_base.cpp" +//#include "hilog_wrapper.h" +// #include "work_sched_hilog.h" +#include "js_work_scheduler_extension.h" +//#include "static_subscriber_extension_context.h" + +namespace OHOS { +namespace WorkScheduler { +WorkSchedulerExtension* WorkSchedulerExtension::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new WorkSchedulerExtension(); + } + // WS_HILOGI(MODULE_SERVICE, "WorkSchedulerExtension :Create runtime"); + switch (runtime->GetLanguage()) { + case AbilityRuntime::Runtime::Language::JS: + return JsWorkSchedulerExtension::Create(runtime); + default: + return new WorkSchedulerExtension(); + } +} + +void WorkSchedulerExtension::Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + // WS_HILOGI(MODULE_SERVICE, "WorkSchedulerExtension begin init"); + ExtensionBase::Init(record, application, handler, token); +} + +std::shared_ptr WorkSchedulerExtension::CreateAndInitContext( + const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + std::shared_ptr context = + ExtensionBase::CreateAndInitContext(record, application, handler, token); + if (record == nullptr) { + // WS_HILOGI(MODULE_SERVICE, "WorkSchedulerExtension CreateAndInitContext record is nullptr"); + return context; + } + return context; +} + +void WorkSchedulerExtension::OnWorkStart() { + +} + +void WorkSchedulerExtension::OnWorkStop() { + +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/extension/src/work_scheduler_extension_context.cpp b/frameworks/extension/src/work_scheduler_extension_context.cpp new file mode 100644 index 0000000..47edff3 --- /dev/null +++ b/frameworks/extension/src/work_scheduler_extension_context.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_extension_context.h" + +namespace OHOS { +namespace WorkScheduler { + WorkSchedulerExtensionContext::WorkSchedulerExtensionContext() {} + + WorkSchedulerExtensionContext::~WorkSchedulerExtensionContext() {} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/extension/src/work_scheduler_extension_module_loader.cpp b/frameworks/extension/src/work_scheduler_extension_module_loader.cpp new file mode 100644 index 0000000..851a20b --- /dev/null +++ b/frameworks/extension/src/work_scheduler_extension_module_loader.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_extension_module_loader.h" + +#include "work_scheduler_extension.h" + +namespace OHOS::WorkScheduler { +WorkSchedulerExtensionModuleLoader::WorkSchedulerExtensionModuleLoader() = default; +WorkSchedulerExtensionModuleLoader::~WorkSchedulerExtensionModuleLoader() = default; + +AbilityRuntime::Extension *WorkSchedulerExtensionModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return WorkSchedulerExtension::Create(runtime); +} + +extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() +{ + return &WorkSchedulerExtensionModuleLoader::GetInstance(); +} +} // namespace OHOS::WorkScheduler \ No newline at end of file diff --git a/frameworks/include/iwork_conn.h b/frameworks/include/iwork_conn.h new file mode 100644 index 0000000..b6a7ed0 --- /dev/null +++ b/frameworks/include/iwork_conn.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_IWORK_CONN_H +#define WORKSCHED_ZIDL_IWORK_CONN_H + +#include +#include +#include + +#include "work_info.h" + +namespace OHOS { +namespace WorkScheduler { +class IWorkConn : public IRemoteBroker { +public: + enum { + ON_WORK_START = 0, + ON_WORK_STOP, + }; + virtual void OnWorkStart(WorkInfo& workInfo) = 0; + virtual void OnWorkStop(WorkInfo& workInfo) = 0; + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.workscheduler.iworkconn"); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_IWORK_CONN_H \ No newline at end of file diff --git a/frameworks/include/iwork_sched_service.h b/frameworks/include/iwork_sched_service.h new file mode 100644 index 0000000..8e8fa7c --- /dev/null +++ b/frameworks/include/iwork_sched_service.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H +#define WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H + +#include +#include +#include +#include + +#include "work_info.h" + +namespace OHOS { +namespace WorkScheduler { +class IWorkSchedService : public IRemoteBroker { +public: + enum { + START_WORK = 0, + STOP_WORK, + STOP_AND_CANCEL_WORK, + STOP_AND_CLEAR_WORKS, + IS_LAST_WORK_TIMEOUT, + OBTAIN_ALL_WORKS, + GET_WORK_STATUS, + DUMP_INFO + }; + + virtual bool StartWork(WorkInfo& workInfo) = 0; + virtual bool StopWork(WorkInfo& workInfo) = 0; + virtual bool StopAndCancelWork(WorkInfo& workInfo) = 0; + virtual bool StopAndClearWorks() = 0; + virtual bool IsLastWorkTimeout(int32_t workId) = 0; + virtual std::list> ObtainAllWorks(int32_t &uid, int32_t &pid) = 0; + virtual std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workId) = 0; + virtual bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.workscheduler.iworkschedservice"); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H \ No newline at end of file diff --git a/interfaces/innerkits/native/include/work_condition.h b/frameworks/include/work_condition.h similarity index 98% rename from interfaces/innerkits/native/include/work_condition.h rename to frameworks/include/work_condition.h index 0491c41..201be40 100644 --- a/interfaces/innerkits/native/include/work_condition.h +++ b/frameworks/include/work_condition.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/include/work_info.h b/frameworks/include/work_info.h new file mode 100644 index 0000000..3cfb34e --- /dev/null +++ b/frameworks/include/work_info.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_INNERKITS_WORK_INFO_H +#define WORKSCHED_INNERKITS_WORK_INFO_H + +#include +#include +#include +#include +#include +#include "json/json.h" + +#include "work_condition.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkInfo : public Parcelable { +public: + explicit WorkInfo(); + ~WorkInfo(); + void SetWorkId(int32_t workId); + void SetElement(std::string bundleName, std::string abilityName); + void RequestPersisted(bool persisted); + void RequestNetworkType(WorkCondition::Network condition); + void RequestChargerType(bool isCharging, WorkCondition::Charger condition); + void RequestBatteryLevel(int32_t battLevel); + void RequestBatteryStatus(WorkCondition::BatteryStatus condition); + void RequestStorageLevel(WorkCondition::Storage condition); + void RequestRepeatCycle(uint32_t timeInterval, uint32_t cycle); + void RequestRepeatCycle(uint32_t timeInterval); + + int32_t GetWorkId(); + std::string GetBundleName(); + std::string GetAbilityName(); + bool IsPersisted(); + WorkCondition::Network GetNetworkType(); + WorkCondition::Charger GetChargerType(); + int32_t GetBatteryLevel(); + WorkCondition::BatteryStatus GetBatteryStatus(); + WorkCondition::Storage GetStorageLevel(); + bool IsRepeat(); + uint32_t GetTimeInterval(); + + std::shared_ptr>> GetConditionMap(); + + bool Marshalling(Parcel &parcel) const override; + static WorkInfo *Unmarshalling(Parcel &parcel); + void Dump(std::string &result); + std::string ParseToJsonStr(); + bool ParseFromJson(const Json::Value value); +private: + int32_t workId_; + std::string bundleName_; + std::string abilityName_; + bool persisted_; + std::map> conditionMap_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_INNERKITS_WORK_INFO_H \ No newline at end of file diff --git a/frameworks/include/workscheduler_srv_client.h b/frameworks/include/workscheduler_srv_client.h new file mode 100644 index 0000000..57975d4 --- /dev/null +++ b/frameworks/include/workscheduler_srv_client.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHEDDULER_SRV_CLIENT_H +#define WORKSCHEDDULER_SRV_CLIENT_H + +#include +#include + +#include "iwork_sched_service.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerSrvClient final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(WorkSchedulerSrvClient) + +public: + DISALLOW_COPY_AND_MOVE(WorkSchedulerSrvClient); + + bool StartWork(WorkInfo& workInfo); + bool StopWork(WorkInfo& workInfo); + bool StopAndCancelWork(WorkInfo& workInfo); + bool StopAndClearWorks(); + ErrCode IsLastWorkTimeout(int32_t workId, bool &result); + ErrCode GetWorkStatus(int32_t workId, std::shared_ptr &workInfo); + ErrCode ObtainAllWorks(std::list> &workInfos); + bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + +private: + class WorkSchedulerDeathRecipient : public IRemoteObject::DeathRecipient { + public: + WorkSchedulerDeathRecipient() = default; + ~WorkSchedulerDeathRecipient() = default; + void OnRemoteDied(const wptr& remote); + private: + DISALLOW_COPY_AND_MOVE(WorkSchedulerDeathRecipient); + }; + + ErrCode Connect(); + sptr iWorkSchedService_ {nullptr}; + sptr deathRecipient_ {nullptr}; + void ResetProxy(const wptr& remote); + std::mutex mutex_; +}; + +} +} +#endif // WORKSCHEDDULER_SRV_CLIENT_H + diff --git a/frameworks/src/work_info.cpp b/frameworks/src/work_info.cpp new file mode 100644 index 0000000..ee821a2 --- /dev/null +++ b/frameworks/src/work_info.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_info.h" + +#include "work_sched_common.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +WorkInfo::WorkInfo() +{ +} + +WorkInfo::~WorkInfo() +{ +} + +void WorkInfo::SetWorkId(int32_t workId) +{ + workId_ = workId; +} + +void WorkInfo::SetElement(string bundleName, string abilityName) +{ + bundleName_ = bundleName; + abilityName_ = abilityName; +} + +void WorkInfo::RequestPersisted(bool persisted) +{ + persisted_ = persisted; +} + +void WorkInfo::RequestNetworkType(WorkCondition::Network condition) +{ + shared_ptr networkCondition = make_shared(); + networkCondition->enumVal = static_cast(condition); + conditionMap_.emplace(WorkCondition::Type::NETWORK, networkCondition); +} + +void WorkInfo::RequestChargerType(bool isCharging, WorkCondition::Charger condition) +{ + shared_ptr chargerCondition = make_shared(); + chargerCondition->boolVal = isCharging; + chargerCondition->enumVal = static_cast(condition); + conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); +} + +void WorkInfo::RequestBatteryLevel(int32_t battLevel) +{ + shared_ptr batteryLevelCondition = make_shared(); + batteryLevelCondition->intVal = battLevel; + conditionMap_.emplace(WorkCondition::Type::BATTERY_LEVEL, batteryLevelCondition); +} + +void WorkInfo::RequestBatteryStatus(WorkCondition::BatteryStatus condition) +{ + shared_ptr batteryCondition = make_shared(); + batteryCondition->enumVal = static_cast(condition); + conditionMap_.emplace(WorkCondition::Type::BATTERY_STATUS, batteryCondition); +} + +void WorkInfo::RequestStorageLevel(WorkCondition::Storage condition) +{ + shared_ptr storageCondition = make_shared(); + storageCondition->enumVal = static_cast(condition); + conditionMap_.emplace(WorkCondition::Type::STORAGE, storageCondition); +} + +void WorkInfo::RequestRepeatCycle(uint32_t timeInterval, uint32_t cycle) +{ + shared_ptr repeatCycle = make_shared(); + repeatCycle->uintVal = timeInterval; + repeatCycle->intVal = cycle; + repeatCycle->boolVal = false; + conditionMap_.emplace(WorkCondition::Type::TIMER, repeatCycle); +} + +void WorkInfo::RequestRepeatCycle(uint32_t timeInterval) +{ + shared_ptr repeatCycle = make_shared(); + repeatCycle->uintVal = timeInterval; + repeatCycle->boolVal = true; + conditionMap_.emplace(WorkCondition::Type::TIMER, repeatCycle); +} + +int32_t WorkInfo::GetWorkId() +{ + return workId_; +} + +string WorkInfo::GetBundleName() +{ + return bundleName_; +} + +string WorkInfo::GetAbilityName() +{ + return abilityName_; +} + +bool WorkInfo::IsPersisted() +{ + return persisted_; +} + +WorkCondition::Network WorkInfo::GetNetworkType() +{ + if (conditionMap_.count(WorkCondition::Type::NETWORK) > 0) { + int enumVal = conditionMap_.at(WorkCondition::Type::NETWORK)->enumVal; + WorkCondition::Network network = WorkCondition::Network(enumVal); + return WorkCondition::Network(network); + } + return WorkCondition::Network::NETWORK_UNKNOWN; +} + +WorkCondition::Charger WorkInfo::GetChargerType() +{ + if (conditionMap_.count(WorkCondition::Type::CHARGER) > 0) { + int enumVal = conditionMap_.at(WorkCondition::Type::CHARGER)->enumVal; + WorkCondition::Charger charger = WorkCondition::Charger(enumVal); + return WorkCondition::Charger(charger); + } + return WorkCondition::Charger::CHARGER_UNKNOWN; +} + +int32_t WorkInfo::GetBatteryLevel() +{ + if (conditionMap_.count(WorkCondition::Type::BATTERY_LEVEL) > 0) { + return conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal; + } + return 0; +} + +WorkCondition::BatteryStatus WorkInfo::GetBatteryStatus() +{ + if (conditionMap_.count(WorkCondition::Type::BATTERY_STATUS) > 0) { + int enumVal = conditionMap_.at(WorkCondition::Type::BATTERY_STATUS)->enumVal; + WorkCondition::BatteryStatus battery = WorkCondition::BatteryStatus(enumVal); + return WorkCondition::BatteryStatus(battery); + } + return WorkCondition::BatteryStatus::BATTERY_UNKNOWN; +} + +WorkCondition::Storage WorkInfo::GetStorageLevel() +{ + if (conditionMap_.count(WorkCondition::Type::STORAGE) > 0) { + int enumVal = conditionMap_.at(WorkCondition::Type::STORAGE)->enumVal; + WorkCondition::Storage storage = WorkCondition::Storage(enumVal); + return WorkCondition::Storage(storage); + } + return WorkCondition::Storage::STORAGE_UNKNOWN; +} + +bool WorkInfo::IsRepeat() +{ + if (conditionMap_.count(WorkCondition::Type::TIMER) > 0) { + return conditionMap_.at(WorkCondition::Type::TIMER)->boolVal; + } + return false; +} + +uint32_t WorkInfo::GetTimeInterval() +{ + if (conditionMap_.count(WorkCondition::Type::TIMER) > 0) { + return conditionMap_.at(WorkCondition::Type::TIMER)->uintVal; + } + return -1; +} + +shared_ptr>> WorkInfo::GetConditionMap() +{ + return make_shared>>(conditionMap_); +} + +bool WorkInfo::Marshalling(Parcel &parcel) const +{ + bool ret = false; + ret = parcel.WriteInt32(workId_); + ret = ret && parcel.WriteString(bundleName_); + ret = ret && parcel.WriteString(abilityName_); + ret = ret && parcel.WriteBool(persisted_); + ret = ret && parcel.WriteUint32(conditionMap_.size()); + for (auto it : conditionMap_) { + switch (it.first) { + case WorkCondition::Type::NETWORK: + case WorkCondition::Type::BATTERY_STATUS: + case WorkCondition::Type::STORAGE: { + ret = ret && parcel.WriteInt32(it.first); + ret = ret && parcel.WriteInt32(it.second->enumVal); + break; + } + case WorkCondition::Type::CHARGER: { + ret = ret && parcel.WriteInt32(it.first); + ret = ret && parcel.WriteBool(it.second->boolVal); + ret = ret && parcel.WriteInt32(it.second->enumVal); + break; + } + case WorkCondition::Type::BATTERY_LEVEL: { + ret = ret && parcel.WriteInt32(it.first); + ret = ret && parcel.WriteInt32(it.second->intVal); + break; + } + case WorkCondition::Type::TIMER: { + ret = ret && parcel.WriteInt32(it.first); + ret = ret && parcel.WriteUint32(it.second->uintVal); + ret = ret && parcel.WriteBool(it.second->boolVal); + if (!it.second->boolVal) { + ret = ret && parcel.WriteInt32(it.second->intVal); + } + break; + } + default: { + ret = false; + } + } + } + return ret; +} + +WorkInfo *WorkInfo::Unmarshalling(Parcel &parcel) +{ + auto *read = new WorkInfo(); + read->workId_ = parcel.ReadInt32(); + read->bundleName_ = parcel.ReadString(); + read->abilityName_ = parcel.ReadString(); + read->persisted_ = parcel.ReadBool(); + size_t mapsize = parcel.ReadUint32(); + read->conditionMap_ = map>(); + for (size_t i = 0; i < mapsize; i++) { + int32_t key = parcel.ReadInt32(); + auto condition = make_shared(); + switch (key) { + case WorkCondition::Type::NETWORK: + case WorkCondition::Type::BATTERY_STATUS: + case WorkCondition::Type::STORAGE: { + condition->enumVal = parcel.ReadInt32(); + break; + } + case WorkCondition::Type::CHARGER: { + condition->boolVal = parcel.ReadBool(); + condition->enumVal = parcel.ReadInt32(); + break; + } + case WorkCondition::Type::BATTERY_LEVEL: { + condition->intVal = parcel.ReadInt32(); + break; + } + case WorkCondition::Type::TIMER: { + condition->uintVal = parcel.ReadUint32(); + condition->boolVal = parcel.ReadBool(); + if (!condition->boolVal) { + condition->intVal = parcel.ReadInt32(); + } + break; + } + default: { + } + } + read->conditionMap_.emplace(WorkCondition::Type(key), condition); + } + return read; +} + +string WorkInfo::ParseToJsonStr() +{ + Json::Value root; + root["workId"] = workId_; + root["bundleName"] = bundleName_; + root["abilityName"] = abilityName_; + root["persisted"] = persisted_; + Json::Value conditions; + for (auto it : conditionMap_) { + switch (it.first) { + case WorkCondition::Type::NETWORK: { + conditions["network"] = it.second->enumVal; + break; + } + case WorkCondition::Type::CHARGER: { + conditions["isCharging"] = it.second->boolVal; + conditions["chargerType"] = it.second->enumVal; + break; + } + case WorkCondition::Type::BATTERY_LEVEL: { + conditions["batteryLevel"] = it.second->intVal; + break; + } + case WorkCondition::Type::BATTERY_STATUS: { + conditions["batteryStatus"] = it.second->enumVal; + break; + } + case WorkCondition::Type::STORAGE: { + conditions["storage"] = it.second->enumVal; + break; + } + case WorkCondition::Type::TIMER: { + conditions["timer"] = it.second->uintVal; + conditions["repeat"] = it.second->boolVal; + if (!it.second->boolVal) { + conditions["cycle"] = it.second->intVal; + } + break; + } + default: {} + } + } + root["conditions"] = conditions; + Json::StreamWriterBuilder writerBuilder; + ostringstream os; + unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + jsonWriter->write(root, &os); + string result = os.str(); + return result; +} + +bool WorkInfo::ParseFromJson(const Json::Value value) +{ + if (value.empty()) { + return false; + } + if (!value.isMember("workId") || !value.isMember("bundleName") || !value.isMember("abilityName")) { + return false; + } + this->workId_ = value["workId"].asInt(); + this->bundleName_ = value["bundleName"].asString(); + this->abilityName_ = value["abilityName"].asString(); + this->persisted_ = value["persisted"].asBool(); + Json::Value conditions = value["conditions"]; + if (conditions.isMember("network")) { + this->RequestNetworkType(WorkCondition::Network(conditions["network"].asInt())); + } + if (conditions.isMember("isCharging") && conditions.isMember("chargerType")) { + this->RequestChargerType(conditions["isCharging"].asBool(), WorkCondition::Charger(conditions["chargerType"].asInt())); + } + if (conditions.isMember("batteryLevel")) { + this->RequestBatteryLevel(conditions["batteryLevel"].asInt()); + } + if (conditions.isMember("batteryStatus")) { + this->RequestBatteryStatus(WorkCondition::BatteryStatus(conditions["batteryStatus"].asInt())); + } + if (conditions.isMember("storage")) { + this->RequestStorageLevel(WorkCondition::Storage(conditions["storage"].asInt())); + } + if (conditions.isMember("timer") && conditions.isMember("repeat")) { + if (!conditions["repeat"].asBool()) { + this->RequestRepeatCycle(conditions["timer"].asInt()); + } else { + if (conditions.isMember("cycle")) { + this->RequestRepeatCycle(conditions["timer"].asInt(), conditions["cycle"].asInt()); + } + } + } + return true; +} + +void WorkInfo::Dump(string &result) +{ + result.append(ParseToJsonStr()); +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/frameworks/src/workscheduler_srv_client.cpp b/frameworks/src/workscheduler_srv_client.cpp new file mode 100644 index 0000000..c35cc7c --- /dev/null +++ b/frameworks/src/workscheduler_srv_client.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "workscheduler_srv_client.h" + +#include +#include +#include +#include +#include +#include + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +WorkSchedulerSrvClient::WorkSchedulerSrvClient() {} +WorkSchedulerSrvClient::~WorkSchedulerSrvClient() +{ + if (iWorkSchedService_ != nullptr) { + auto remoteObject = iWorkSchedService_->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + } +} + +ErrCode WorkSchedulerSrvClient::Connect() +{ + std::lock_guard lock(mutex_); + if (iWorkSchedService_ != nullptr) { + return ERR_OK; + } + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + WS_HILOGE("%{public}s failed to get registry!", __func__); + return E_GET_SYSTEM_ABILITY_MANAGER_FAILED_WORKSCHED; + } + sptr remoteObject_ = sam->CheckSystemAbility(WORK_SCHEDULE_SERVICE_ID); + if (remoteObject_ == nullptr) { + WS_HILOGE("GetSystemAbility failed!"); + return E_GET_WORKSCHED_SERVICE_FALIED; + } + deathRecipient_ = sptr(new WorkSchedulerDeathRecipient()); + if (deathRecipient_ == nullptr) { + WS_HILOGE("%{public}s failed to create WorkScheduelrDeathRecipient!", __func__); + return ERR_NO_MEMORY; + } + if ((remoteObject_->IsProxyObject()) && (!remoteObject_->AddDeathRecipient(deathRecipient_))) { + WS_HILOGE("%{public}s Add death recipient to WorkSchedulerService failed!", __func__); + return E_ADD_WORK_SCHED_DEATH_RECIPIENT_FAILED; + } + iWorkSchedService_ = iface_cast(remoteObject_); + WS_HILOGD("%{public}s Connecting WorkSchedService success.", __func__); + return ERR_OK; +} + +void WorkSchedulerSrvClient::ResetProxy(const wptr& remote) +{ + std::lock_guard lock(mutex_); + if (iWorkSchedService_ == nullptr) { + return; + } + auto serviceRemote = iWorkSchedService_->AsObject(); + if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) { + serviceRemote->RemoveDeathRecipient(deathRecipient_); + iWorkSchedService_ = nullptr; + } +} + +void WorkSchedulerSrvClient::WorkSchedulerDeathRecipient::OnRemoteDied(const wptr& remote) +{ + if (remote == nullptr) { + WS_HILOGE("WorkSchedulerDeathRecipient::OnRemoteDied failed, remote is nullptr"); + return; + } + WorkSchedulerSrvClient::GetInstance().ResetProxy(remote); + WS_HILOGD("WorkSchedulerDeathRecipient::Recv death notice."); +} + +bool WorkSchedulerSrvClient::StartWork(WorkInfo& workInfo) +{ + WS_HILOGD("%{public}s.", __func__); + if (Connect() != ERR_OK) { + WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + return false; + } + return iWorkSchedService_->StartWork(workInfo); +} + +bool WorkSchedulerSrvClient::StopWork(WorkInfo& workInfo) +{ + WS_HILOGD("%{public}s.", __func__); + if (Connect() != ERR_OK) { + WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + return false; + } + return iWorkSchedService_->StopWork(workInfo); +} + +bool WorkSchedulerSrvClient::StopAndCancelWork(WorkInfo& workInfo) +{ + WS_HILOGD("%{public}s.", __func__); + if (Connect() != ERR_OK) { + WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + return false; + } + return iWorkSchedService_->StopAndCancelWork(workInfo); +} + +bool WorkSchedulerSrvClient::StopAndClearWorks() +{ + WS_HILOGD("%{public}s.", __func__); + if (Connect() != ERR_OK) { + WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + return false; + } + return iWorkSchedService_->StopAndClearWorks(); +} + +ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) +{ + WS_HILOGD("%{public}s.", __func__); + ErrCode errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + result = iWorkSchedService_->IsLastWorkTimeout(workId); + return ERR_OK; +} + +ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list> &workInfos) +{ + WS_HILOGD("%{public}s.", __func__); + ErrCode errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + int32_t uid = IPCSkeleton::GetCallingUid(); + int32_t pid = IPCSkeleton::GetCallingPid(); + workInfos = iWorkSchedService_->ObtainAllWorks(uid, pid); + return ERR_OK; +} + +ErrCode WorkSchedulerSrvClient::GetWorkStatus(int32_t workId, std::shared_ptr &workInfo) { + WS_HILOGD("%{public}s.", __func__); + ErrCode code = Connect(); + if (code != ERR_OK) { + return code; + } + int32_t uid = IPCSkeleton::GetCallingUid(); + workInfo = iWorkSchedService_->GetWorkStatus(uid, workId); + if (workInfo == nullptr) { + return E_INNER_ERR; + } + return ERR_OK; +} + +bool WorkSchedulerSrvClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + WS_HILOGD("%{public}s", __func__); + if (Connect() != ERR_OK) { + WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + dumpInfo.push_back("Connect() failed, errno:" + std::to_string(Connect())); + return false; + } + iWorkSchedService_->ShellDump(dumpOption, dumpInfo); + return true; +} +} // OHOS +} // WorkScheduler \ No newline at end of file diff --git a/test/constanttest/BUILD.gn b/frameworks/test/BUILD.gn similarity index 58% rename from test/constanttest/BUILD.gn rename to frameworks/test/BUILD.gn index 427ff52..22f96a8 100644 --- a/test/constanttest/BUILD.gn +++ b/frameworks/test/BUILD.gn @@ -14,27 +14,7 @@ import("//build/test.gni") import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") -module_output_path = "work_scheduler/constanttest" -ohos_systemtest("WorkSchedulerConstantTest") { - module_out_path = module_output_path - - sources = [ "constant_test.cpp" ] - - include_dirs = [ "${worksched_native_innerkits_path}/native/include" ] - - cflags = [] - - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } - - deps = [ "//third_party/googletest:gtest_main" ] - - external_deps = [ "utils_base:utils" ] -} - -group("constanttest") { +group("workschedinnerkits_test") { testonly = true - - deps = [ ":WorkSchedulerConstantTest" ] + deps = [ "unittest:unittest" ] } diff --git a/frameworks/test/unittest/BUILD.gn b/frameworks/test/unittest/BUILD.gn new file mode 100644 index 0000000..40ec80c --- /dev/null +++ b/frameworks/test/unittest/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +module_output_path = "${worksched_native_part_name}/worksched_native" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +ohos_unittest("test_workinfo") { + module_out_path = module_output_path + sources = [ "src/workinfo_test.cpp" ] + configs = [ ":module_private_config" ] + + deps = [ + "${worksched_frameworks_path}:workschedclient", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":test_workinfo" ] +} diff --git a/frameworks/test/unittest/include/workinfo_test.h b/frameworks/test/unittest/include/workinfo_test.h new file mode 100644 index 0000000..2178214 --- /dev/null +++ b/frameworks/test/unittest/include/workinfo_test.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKINFO_TEST_H +#define WORKINFO_TEST_H + +#include + +namespace OHOS { +namespace WorkScheduler { +class WorkInfoTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKINFO_TEST_H \ No newline at end of file diff --git a/frameworks/test/unittest/src/workinfo_test.cpp b/frameworks/test/unittest/src/workinfo_test.cpp new file mode 100644 index 0000000..a7b3ee6 --- /dev/null +++ b/frameworks/test/unittest/src/workinfo_test.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "workinfo_test.h" + +#include "work_info.h" + +using namespace testing::ext; +using namespace OHOS::WorkScheduler; +using namespace OHOS; +using namespace std; + +void WorkInfoTest::SetUpTestCase(void) +{ +} + +void WorkInfoTest::TearDownTestCase(void) +{ +} + +void WorkInfoTest::SetUp() +{ +} + +void WorkInfoTest::TearDown() +{ +} + +/** + * @tc.name WorkInfoTest001 + * @tc.desc Set WorkId to WorkInfo + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest001, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + EXPECT_EQ(workInfo.GetWorkId(), 1); +} + +/** + * @tc.name WorkInfoTest002 + * @tc.desc Set bundleName and abilityName to WorkInfo + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest002, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.SetElement("bundle_name", "ability_name"); + EXPECT_EQ(workInfo.GetBundleName(), "bundle_name"); + EXPECT_EQ(workInfo.GetAbilityName(), "ability_name"); +} + +/** + * @tc.name WorkInfoTest003 + * @tc.desc Set workInfo persisted + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest003, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestPersisted(true); + EXPECT_EQ(workInfo.IsPersisted(), true); + workInfo.RequestPersisted(false); + EXPECT_EQ(workInfo.IsPersisted(), false); +} + +/** + * @tc.name WorkInfoTest004 + * @tc.desc Set workInfo charger condition charging + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest004, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGER_CHARGING); +} + +/** + * @tc.name WorkInfoTest005 + * @tc.desc Set workInfo charger condiiton discharging + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest005, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_DISCHARGING); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGER_DISCHARGING); +} + +/** + * @tc.name WorkInfoTest006 + * @tc.desc Set workInfo battery condition battery changed + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest006, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_CHANGED); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_CHANGED); +} + +/** + * @tc.name WorkInfoTest007 + * @tc.desc Set workInfo battery condition battery low + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest007, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_LOW); +} + +/** + * @tc.name WorkInfoTest008 + * @tc.desc Set workInfo battery condition battery okey + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest008, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_OKEY); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_OKEY); +} + +/** + * @tc.name WorkInfoTest009 + * @tc.desc Set workInfo storage condition storage full + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest009, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_FULL); +} + +/** + * @tc.name WorkInfoTest010 + * @tc.desc Set workInfo storage condition storage low + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest010, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LOW); +} + +/** + * @tc.name WorkInfoTest011 + * @tc.desc Set workInfo storage condition storage ok + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest011, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_OK); +} + +/** + * @tc.name WorkInfoTest012 + * @tc.desc Set workInfo network condition + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest012, TestSize.Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestNetworkType(WorkCondition::NetWork::WIFI_CONNECTED); + EXPECT_EQ(workInfo.GetNetworkType(), WorkCondition::NetWork::WIFI_CONNECTED); +} + +/** + * @tc.name WorkInfoTest013 + * @tc.desc Set workInfo repeat time condition repeat count 3 + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest013, TestSize.Level0) +{ + uint32_t timeInterval = 120; + WorkInfo workInfo = WorkInfo(); + workInfo.RequestRepeatCycle(timeInterval, 3); + EXPECT_EQ(workInfo.GetTimeInterval(), timeInterval); + EXPECT_EQ(workInfo.IsRepeat(), false); +} + +/** + * @tc.name WorkInfoTest014 + * @tc.desc Set workInfo repeat time condition repeat + * @tc.type FUNC + */ +HWTEST_F (WorkInfoTest, WorkInfoTest014, TestSize.Level0) +{ + uint32_t timeInterval = 120; + WorkInfo workInfo = WorkInfo(); + workInfo.RequestRepeatCycle(timeInterval); + EXPECT_EQ(workInfo.GetTimeInterval(), timeInterval); + EXPECT_EQ(workInfo.IsRepeat(), true); +} \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.workscheduler.d.ts b/interfaces/kits/js/@ohos.workScheduler.d.ts similarity index 100% rename from interfaces/kits/js/@ohos.workscheduler.d.ts rename to interfaces/kits/js/@ohos.workScheduler.d.ts diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index ac4f3bd..6ab8141 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -15,34 +15,40 @@ import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") -js_declaration("workscheduler_js") { - part_name = "${worksched_native_part_name}" - sources = [ "./@ohos.workscheduler.d.ts" ] -} - -ohos_copy("worksched_declaration") { - sources = [ "./@ohos.workscheduler.d.ts" ] - outputs = [ target_out_dir + "/$target_name/" ] - module_source_dir = target_out_dir + "/$target_name" - module_install_name = "" +config("worksched_public_config") { + include_dirs = [ "${worksched_root_path}/interfaces/kits/js/napi/include" ] } ohos_shared_library("workscheduler") { - include_dirs = [ - "${worksched_native_innerkits_path}/native/include", - "${worksched_root_path}/interfaces/kits/js/napi/include", - ] + public_configs = [ ":worksched_public_config" ] sources = [ + "${worksched_root_path}/interfaces/kits/js/napi/src/common.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/get_work_status.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/is_last_work_time_out.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/obtain_all_works.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/start_work.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/stop_and_clear_works.cpp", + "${worksched_root_path}/interfaces/kits/js/napi/src/stop_work.cpp", "${worksched_root_path}/interfaces/kits/js/napi/src/workscheduler_napi.cpp", ] - deps = [ "${worksched_utils_path}:workschedutils" ] + deps = [ + "${worksched_frameworks_path}:workschedclient", + "${worksched_utils_path}:workschedutils", + ] external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ipc:ipc_core", "hiviewdfx_hilog_native:libhilog", - "napi:ace_napi", "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + "ces_standard:cesfwk_innerkits", + "napi:ace_napi" ] relative_install_dir = "module" diff --git a/interfaces/kits/js/napi/include/common.h b/interfaces/kits/js/napi/include/common.h new file mode 100644 index 0000000..bf36dde --- /dev/null +++ b/interfaces/kits/js/napi/include/common.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_COMMON +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_COMMON + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "work_info.h" + +namespace OHOS { +namespace WorkScheduler { +struct CallbackPromiseInfo { + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + bool isCallback = false; + int errorCode = 0; +}; + +class WorkContext { +public: + int workId; + int32_t networkType; + bool isDeepIdle; + int32_t idleWaitTime; + int32_t isCharging; + int32_t chargingType; + int32_t batteryLevel; + int32_t batteryStatus; + int32_t storageRequest; + bool isRepeat; + bool isPersisted; + int32_t repeatCycleTime; + int32_t repeatCount; + std::string bundleName; + std::string abilityName; +}; + +class Common { +public: + static napi_value NapiGetNull(napi_env env); + static WorkInfo ParseWorkInfo(WorkContext &workContext); + static void GetWorkInfo(napi_env env, napi_value objValue, WorkContext &workContext); + static int32_t GetIntProperty(napi_env env, napi_value object, const std::string &propertyName); + static bool GetBoolProperty(napi_env env, napi_value object, const std::string &propertyName); + static int32_t GetBoolToIntProperty(napi_env env, napi_value object, const std::string &propertyName); + static std::string GetStringProperty(napi_env env, napi_value object, const std::string &propertyName); + static bool MatchValueType(napi_env env, napi_value value, napi_valuetype targetType); + static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + static void PaddingCallbackPromiseInfo( + const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); + static napi_value GetNapiWorkInfo(napi_env env, std::shared_ptr &workInfo); + static napi_value GetCallbackErrorValue(napi_env env, int errCode); + static void SetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result); + static napi_value SetPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); + static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/get_work_status.h b/interfaces/kits/js/napi/include/get_work_status.h new file mode 100644 index 0000000..5dec1f2 --- /dev/null +++ b/interfaces/kits/js/napi/include/get_work_status.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_GET_WORK_STATUS +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_GET_WORK_STATUS + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value GetWorkStatus(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/is_last_work_time_out.h b/interfaces/kits/js/napi/include/is_last_work_time_out.h new file mode 100644 index 0000000..4613f74 --- /dev/null +++ b/interfaces/kits/js/napi/include/is_last_work_time_out.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value IsLastWorkTimeOut(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/obtain_all_works.h b/interfaces/kits/js/napi/include/obtain_all_works.h new file mode 100644 index 0000000..428255d --- /dev/null +++ b/interfaces/kits/js/napi/include/obtain_all_works.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value ObtainAllWorks(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/start_work.h b/interfaces/kits/js/napi/include/start_work.h new file mode 100644 index 0000000..1e59ba2 --- /dev/null +++ b/interfaces/kits/js/napi/include/start_work.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value StartWork(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/stop_and_clear_works.h b/interfaces/kits/js/napi/include/stop_and_clear_works.h new file mode 100644 index 0000000..1c7704b --- /dev/null +++ b/interfaces/kits/js/napi/include/stop_and_clear_works.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_AND_CLEAR_WORKS +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_AND_CLEAR_WORKS + +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value StopAndClearWorks(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/stop_work.h b/interfaces/kits/js/napi/include/stop_work.h new file mode 100644 index 0000000..881b9e4 --- /dev/null +++ b/interfaces/kits/js/napi/include/stop_work.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace WorkScheduler { + napi_value StopWork(napi_env env, napi_callback_info info); +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/include/workscheduler_napi.h b/interfaces/kits/js/napi/include/workscheduler_napi.h index 69be5cf..a88c983 100644 --- a/interfaces/kits/js/napi/include/workscheduler_napi.h +++ b/interfaces/kits/js/napi/include/workscheduler_napi.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -49,7 +49,7 @@ napi_module _module = { .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, - .nm_modname = "workscheduler", + .nm_modname = "workScheduler", .nm_priv = ((void *)0), .reserved = {0} }; diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp new file mode 100644 index 0000000..cc73f0e --- /dev/null +++ b/interfaces/kits/js/napi/src/common.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include "common.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +const int NAME_MAXIMUM_LIMIT = 128; +const int RESULT_PARAMS_NUM = 2; + +napi_value Common::NapiGetNull(napi_env env) +{ + napi_value result = nullptr; + napi_get_null(env, &result); + return result; +} + +WorkInfo Common::ParseWorkInfo(WorkContext &workContext) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(workContext.workId); + workInfo.SetElement(workContext.bundleName, workContext.abilityName); + if (workContext.networkType != -1) { + workInfo.RequestNetworkType(WorkCondition::Network(workContext.networkType)); + } + if (workContext.isCharging == 0) { + workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGER_UNPLUGGED); + } else if (workContext.isCharging == 1 && workContext.chargingType != -1) { + workInfo.RequestChargerType(true, WorkCondition::Charger(workContext.chargingType)); + } else if (workContext.isCharging == 1 && workContext.chargingType == -1) { + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); + } + if (workContext.batteryLevel != -1) { + workInfo.RequestBatteryLevel(workContext.batteryLevel); + } + if (workContext.batteryStatus != -1) { + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus(workContext.batteryStatus)); + } + if (workContext.storageRequest != -1) { + workInfo.RequestStorageLevel(WorkCondition::Storage(workContext.storageRequest)); + } + if (workContext.repeatCycleTime != -1 && workContext.repeatCount != -1) { + workInfo.RequestRepeatCycle(workContext.repeatCycleTime, workContext.repeatCount); + } + workInfo.RequestPersisted(workContext.isPersisted); + return workInfo; +} + +void Common::GetWorkInfo(napi_env env, napi_value objValue, WorkContext &workContext) +{ + workContext.workId = Common::GetIntProperty(env, objValue, "workId"); + workContext.bundleName = Common::GetStringProperty(env, objValue, "bundleName"); + workContext.abilityName = Common::GetStringProperty(env, objValue, "abilityName"); + workContext.networkType = Common::GetIntProperty(env, objValue, "networkType"); + workContext.chargingType = Common::GetIntProperty(env, objValue, "chargerType"); + workContext.batteryLevel = Common::GetIntProperty(env, objValue, "batteryLevel"); + workContext.batteryStatus = Common::GetIntProperty(env, objValue, "batteryStatus"); + workContext.storageRequest = Common::GetIntProperty(env, objValue, "storageRequest"); + workContext.isCharging = Common::GetBoolToIntProperty(env, objValue, "isCharging"); + workContext.isPersisted = Common::GetBoolProperty(env, objValue, "isPersisted"); + workContext.isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); + workContext.repeatCycleTime = Common::GetIntProperty(env, objValue, "repeatCycleTime"); + workContext.repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); + workContext.isDeepIdle = Common::GetBoolProperty(env, objValue, "isDeepIdle"); + workContext.idleWaitTime = Common::GetIntProperty(env, objValue, "idleWaitTime"); +} + +int32_t Common::GetIntProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + int32_t intValue = -1; + napi_value value = nullptr; + napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); + if (getNameStatus == napi_ok) { + napi_status getIntStatus = napi_get_value_int32(env, value, &intValue); + if (getIntStatus == napi_ok) { + return intValue; + } + } + return intValue; +} + +bool Common::GetBoolProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + bool boolValue = false; + napi_value value = nullptr; + napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); + if (getNameStatus == napi_ok) { + napi_status getIntStatus = napi_get_value_bool(env, value, &boolValue); + if (getIntStatus == napi_ok) { + return boolValue; + } + } + return boolValue; +} + +int32_t Common::GetBoolToIntProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + bool boolValue = false; + napi_value value = nullptr; + napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); + if (getNameStatus == napi_ok) { + napi_status getIntStatus = napi_get_value_bool(env, value, &boolValue); + if (getIntStatus == napi_ok) { + return boolValue ? 1 : 0; + } + } + return -1; +} + +std::string Common::GetStringProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + napi_value value = nullptr; + napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); + if (getNameStatus == napi_ok) { + char chars[NAME_MAXIMUM_LIMIT] = {0}; + size_t charLength = 0; + napi_status getStringStatus = + napi_get_value_string_utf8(env, value, chars, NAME_MAXIMUM_LIMIT, &charLength); + if (getStringStatus == napi_ok && charLength > 0) { + return std::string(chars, charLength); + } + } + return ""; +} + +bool Common::MatchValueType(napi_env env, napi_value value, napi_valuetype targetType) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + return valueType == targetType; +} + +napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) +{ + if (callback) { + return Common::NapiGetNull(env); + } else { + napi_value promise = nullptr; + napi_deferred deferred = nullptr; + napi_create_promise(env, &deferred, &promise); + napi_resolve_deferred(env, deferred, Common::NapiGetNull(env)); + return promise; + } +} + +void Common::PaddingCallbackPromiseInfo( + const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise) +{ + if (callback) { + info.callback = callback; + info.isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + info.deferred = deferred; + info.isCallback = false; + } +} + +napi_value Common::GetNapiWorkInfo(napi_env env, std::shared_ptr &workInfo) +{ + if (workInfo == nullptr) { + return NapiGetNull(env); + } + napi_value napiWork = nullptr; + napi_create_object(env, &napiWork); + napi_value napiWorkId = nullptr; + napi_value napiBundleName = nullptr; + napi_value napiAbilityName = nullptr; + napi_value napiNetworkType = nullptr; + napi_value napiChargingType = nullptr; + napi_value napiBatteryLevel = nullptr; + napi_value napiBatteryStatus = nullptr; + napi_value napiStorageRequest = nullptr; + napi_value napiIsPersisted = nullptr; + napi_create_int32(env, workInfo->GetWorkId(), &napiWorkId); + napi_create_string_utf8(env, workInfo->GetBundleName().c_str(), workInfo->GetBundleName().length(), &napiBundleName); + napi_create_string_utf8(env, workInfo->GetAbilityName().c_str(), workInfo->GetAbilityName().length(), &napiAbilityName); + napi_create_int32(env, static_cast(workInfo->GetNetworkType()), &napiNetworkType); + napi_create_int32(env, static_cast(workInfo->GetChargerType()), &napiChargingType); + napi_create_int32(env, workInfo->GetBatteryLevel(), &napiBatteryLevel); + napi_create_int32(env, static_cast(workInfo->GetBatteryStatus()), &napiBatteryStatus); + napi_create_int32(env, static_cast(workInfo->GetStorageLevel()), &napiStorageRequest); + napi_get_boolean(env, workInfo->IsPersisted(), &napiIsPersisted); + napi_set_named_property(env, napiWork, "workId", napiWorkId); + napi_set_named_property(env, napiWork, "bundleName", napiBundleName); + napi_set_named_property(env, napiWork, "abilityName", napiAbilityName); + napi_set_named_property(env, napiWork, "networkType", napiNetworkType); + napi_set_named_property(env, napiWork, "chargingType", napiChargingType); + napi_set_named_property(env, napiWork, "batteryLevel", napiBatteryLevel); + napi_set_named_property(env, napiWork, "batteryStatus", napiBatteryStatus); + napi_set_named_property(env, napiWork, "storageRequest", napiStorageRequest); + napi_set_named_property(env, napiWork, "isPersisted", napiIsPersisted); + return napiWork; +} + +napi_value Common::GetCallbackErrorValue(napi_env env, int errCode) +{ + if (errCode == ERR_OK) { + return NapiGetNull(env); + } + napi_value result = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_set_named_property(env, result, "data", eCode)); + return result; +} + +void Common::SetCallback( + const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) +{ + napi_value undefined = nullptr; + napi_get_undefined(env, &undefined); + + napi_value callback = nullptr; + napi_value resultout = nullptr; + napi_get_reference_value(env, callbackIn, &callback); + napi_value results[RESULT_PARAMS_NUM] = {nullptr}; + results[0] = GetCallbackErrorValue(env, errorCode); + results[1] = result; + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, RESULT_PARAMS_NUM, &results[0], &resultout)); +} + +napi_value Common::SetPromise( + const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result) +{ + if (info.errorCode == ERR_OK) { + napi_resolve_deferred(env, info.deferred, result); + } else { + napi_value res = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, info.errorCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &res)); + NAPI_CALL(env, napi_set_named_property(env, res, "data", eCode)); + napi_reject_deferred(env, info.deferred, res); + } + return result; +} + +void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result) +{ + if (info.isCallback) { + SetCallback(env, info.callback, info.errorCode, result); + } else { + SetPromise(env, info, result); + } +} +} +} diff --git a/interfaces/kits/js/napi/src/get_work_status.cpp b/interfaces/kits/js/napi/src/get_work_status.cpp new file mode 100644 index 0000000..2b42af2 --- /dev/null +++ b/interfaces/kits/js/napi/src/get_work_status.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "get_work_status.h" +#include "common.h" +#include "work_sched_hilog.h" +#include "workscheduler_srv_client.h" + +namespace OHOS { +namespace WorkScheduler { + +static const int32_t WORK_ID_INDEX = 0; +static const int32_t CALLBACK_INDEX = 1; +static const int32_t GET_WORK_STATUS_MIN_PARAMS = 1; +static const int32_t GET_WORK_STATUS_MAX_PARAMS = 2; + +struct GetWorkStatusParamsInfo { + int32_t workId; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoGetWorkStatus { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + int32_t workId; + std::shared_ptr workInfo; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetWorkStatusParamsInfo ¶ms) +{ + size_t argc = GET_WORK_STATUS_MAX_PARAMS; + napi_value argv[GET_WORK_STATUS_MAX_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + bool paramsCheck = (argc == GET_WORK_STATUS_MIN_PARAMS) || (argc == GET_WORK_STATUS_MAX_PARAMS); + NAPI_ASSERT(env, paramsCheck, "Wrong number of arguments"); + + // argv[0] : workId + bool matchFlag = Common::MatchValueType(env, argv[WORK_ID_INDEX], napi_number); + NAPI_ASSERT(env, matchFlag, "Type error, Should is number"); + napi_get_value_int32(env, argv[WORK_ID_INDEX], ¶ms.workId); + + // argv[1]: callback + if (argc == GET_WORK_STATUS_MAX_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[CALLBACK_INDEX], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[CALLBACK_INDEX], 1, ¶ms.callback); + } + return Common::NapiGetNull(env); +} + +napi_value GetWorkStatus(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + + // Get params. + GetWorkStatusParamsInfo params; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + napi_value promise = nullptr; + AsyncCallbackInfoGetWorkStatus *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetWorkStatus {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + asynccallbackinfo->workId = params.workId; + WS_HILOGD("asynccallbackinfo->workId: %{public}d", asynccallbackinfo->workId); + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "GetWorkStatus", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoGetWorkStatus *asynccallbackinfo = (AsyncCallbackInfoGetWorkStatus *)data; + asynccallbackinfo->info.errorCode = + WorkSchedulerSrvClient::GetInstance().GetWorkStatus(asynccallbackinfo->workId, asynccallbackinfo->workInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoGetWorkStatus *asynccallbackinfo = (AsyncCallbackInfoGetWorkStatus *)data; + if (asynccallbackinfo != nullptr) { + napi_value result = Common::GetNapiWorkInfo(env, asynccallbackinfo->workInfo); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/is_last_work_time_out.cpp b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp new file mode 100644 index 0000000..c7aebf2 --- /dev/null +++ b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "common.h" +#include "work_sched_hilog.h" +#include "workscheduler_srv_client.h" + +namespace OHOS { +namespace WorkScheduler { + +static const int32_t WORK_ID_INDEX = 0; +static const int32_t CALLBACK_INDEX = 1; +static const int32_t IS_LAST_WORK_TIME_OUT_MIN_PARAMS = 1; +static const int32_t IS_LAST_WORK_TIME_OUT_MAX_PARAMS = 2; + +struct IsLastWorkTimeOutParamsInfo { + int32_t workId; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackIsLastWorkTimeOut { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + int32_t workId; + bool result; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, IsLastWorkTimeOutParamsInfo ¶ms) +{ + size_t argc = IS_LAST_WORK_TIME_OUT_MAX_PARAMS; + napi_value argv[IS_LAST_WORK_TIME_OUT_MAX_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + bool paramsCheck = (argc == IS_LAST_WORK_TIME_OUT_MAX_PARAMS) || (argc == IS_LAST_WORK_TIME_OUT_MIN_PARAMS); + NAPI_ASSERT(env, paramsCheck, "Wrong number of arguments"); + + // argv[0] : workId + bool matchFlag = Common::MatchValueType(env, argv[WORK_ID_INDEX], napi_number); + NAPI_ASSERT(env, matchFlag, "Type error, Should is number"); + napi_get_value_int32(env, argv[WORK_ID_INDEX], ¶ms.workId); + + // argv[1]: callback + if (argc == IS_LAST_WORK_TIME_OUT_MAX_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[CALLBACK_INDEX], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[CALLBACK_INDEX], 1, ¶ms.callback); + } + return Common::NapiGetNull(env); +} + +napi_value IsLastWorkTimeOut(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + + // Get params. + IsLastWorkTimeOutParamsInfo params; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + napi_value promise = nullptr; + AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = + new (std::nothrow) AsyncCallbackIsLastWorkTimeOut {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + asynccallbackinfo->workId = params.workId; + WS_HILOGD("asynccallbackinfo->workId: %{public}d", asynccallbackinfo->workId); + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "IsLastWorkTimeOut", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = (AsyncCallbackIsLastWorkTimeOut *)data; + asynccallbackinfo->info.errorCode = + WorkSchedulerSrvClient::GetInstance().IsLastWorkTimeout(asynccallbackinfo->workId, asynccallbackinfo->result); + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = (AsyncCallbackIsLastWorkTimeOut *)data; + if (asynccallbackinfo != nullptr) { + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_get_boolean(env, asynccallbackinfo->result, &result); + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/obtain_all_works.cpp b/interfaces/kits/js/napi/src/obtain_all_works.cpp new file mode 100644 index 0000000..a511185 --- /dev/null +++ b/interfaces/kits/js/napi/src/obtain_all_works.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "obtain_all_works.h" +#include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" +#include "common.h" + +namespace OHOS { +namespace WorkScheduler { + +static const int32_t CALLBACK_INDEX = 0; +static const int32_t OBTAIN_ALL_WORKS_MIN_PARAMS = 0; +static const int32_t OBTAIN_ALL_WORKS_MAX_PARAMS = 1; + +struct AsyncCallbackInfoObtainAllWorks { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + std::list> workInfoList; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_ref &callback) +{ + size_t argc = OBTAIN_ALL_WORKS_MAX_PARAMS; + napi_value argv[OBTAIN_ALL_WORKS_MAX_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + bool paramsCheck = (argc == OBTAIN_ALL_WORKS_MIN_PARAMS) || (argc == OBTAIN_ALL_WORKS_MAX_PARAMS); + NAPI_ASSERT(env, paramsCheck, "Wrong number of arguments"); + + // argv[0]: callback + if (argc == OBTAIN_ALL_WORKS_MAX_PARAMS) { + napi_create_reference(env, argv[CALLBACK_INDEX], 1, &callback); + } + return Common::NapiGetNull(env); +} + +napi_value ObtainAllWorks(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + // Get params. + napi_ref callback = nullptr; + if (ParseParameters(env, info, callback) == nullptr) { + return Common::JSParaError(env, callback); + } + + napi_value promise = nullptr; + AsyncCallbackInfoObtainAllWorks *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoObtainAllWorks {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "ObtainAllWorks", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoObtainAllWorks *asynccallbackinfo = (AsyncCallbackInfoObtainAllWorks *)data; + asynccallbackinfo->info.errorCode = + WorkSchedulerSrvClient::GetInstance().ObtainAllWorks(asynccallbackinfo->workInfoList); + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoObtainAllWorks *asynccallbackinfo = (AsyncCallbackInfoObtainAllWorks *)data; + if (asynccallbackinfo != nullptr) { + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_create_array(env, &result); + int count = 0; + for (auto workInfo : asynccallbackinfo->workInfoList) { + napi_value napiWork = Common::GetNapiWorkInfo(env, workInfo); + napi_set_element(env, result, count, napiWork); + count++; + } + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/start_work.cpp b/interfaces/kits/js/napi/src/start_work.cpp new file mode 100644 index 0000000..eb7a761 --- /dev/null +++ b/interfaces/kits/js/napi/src/start_work.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "start_work.h" +#include "work_sched_hilog.h" +#include "workscheduler_srv_client.h" +#include "common.h" + +namespace OHOS { +namespace WorkScheduler { + +static const int32_t WORK_INFO_INDEX = 0; +static const int32_t START_WORK_PARAMS = 1; + +napi_value StartWork(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + + // Check params. + size_t argc = START_WORK_PARAMS; + napi_value argv[START_WORK_PARAMS] = {0}; + napi_get_cb_info(env, info, &argc, argv, NULL, NULL); + NAPI_ASSERT(env, argc == START_WORK_PARAMS, "parameter error!"); + bool matchFlag = Common::MatchValueType(env, argv[WORK_INFO_INDEX], napi_object); + NAPI_ASSERT(env, matchFlag, "Type error, Should is object"); + + // Create work info. + auto workContext = (std::make_unique()).release(); + Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], *workContext); + WorkInfo workInfo = Common::ParseWorkInfo(*workContext); + + // Call service. + bool result = WorkSchedulerSrvClient::GetInstance().StartWork(workInfo); + napi_value napiValue = nullptr; + NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + return napiValue; + WS_HILOGD("%{public}s: return", __func__); +} +} +} diff --git a/interfaces/kits/js/napi/src/stop_and_clear_works.cpp b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp new file mode 100644 index 0000000..a0747d3 --- /dev/null +++ b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "stop_and_clear_works.h" +#include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { + +napi_value StopAndClearWorks(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + napi_value napiValue = nullptr; + bool result = WorkSchedulerSrvClient::GetInstance().StopAndClearWorks(); + NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + WS_HILOGD("%{public}s: call result: %{public}s", __func__, result ? "true" : "false"); + return napiValue; + WS_HILOGD("%{public}s: return", __func__); +} +} +} diff --git a/interfaces/kits/js/napi/src/stop_work.cpp b/interfaces/kits/js/napi/src/stop_work.cpp new file mode 100644 index 0000000..32d092c --- /dev/null +++ b/interfaces/kits/js/napi/src/stop_work.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "stop_work.h" +#include "common.h" +#include "work_sched_hilog.h" +#include "workscheduler_srv_client.h" + +namespace OHOS { +namespace WorkScheduler { +static const int32_t WORK_INFO_INDEX = 0; +static const int32_t NEED_CANCEL_INDEX = 1; +static const int32_t STOP_WORK_PARAMS = 2; + +napi_value StopWork(napi_env env, napi_callback_info info) +{ + WS_HILOGD("%{public}s: enter", __func__); + + // Check params. + size_t argc = STOP_WORK_PARAMS; + napi_value argv[STOP_WORK_PARAMS] = {0}; + napi_get_cb_info(env, info, &argc, argv, NULL, NULL); + NAPI_ASSERT(env, argc == STOP_WORK_PARAMS, "parameter error!"); + bool matchFlag = Common::MatchValueType(env, argv[WORK_INFO_INDEX], napi_object); + NAPI_ASSERT(env, matchFlag, "Type error, Should is object"); + matchFlag = Common::MatchValueType(env, argv[NEED_CANCEL_INDEX], napi_boolean); + NAPI_ASSERT(env, matchFlag, "Type error, Should is boolean"); + + // get params + auto workContext = (std::make_unique()).release(); + Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], *workContext); + WorkInfo workInfo = Common::ParseWorkInfo(*workContext); + bool needCancel = false; + napi_get_value_bool(env, argv[NEED_CANCEL_INDEX], &needCancel); + + // call service. + bool result = false; + if (needCancel) { + result = WorkSchedulerSrvClient::GetInstance().StopAndCancelWork(workInfo); + } else { + result = WorkSchedulerSrvClient::GetInstance().StopWork(workInfo); + } + napi_value napiValue = nullptr; + NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + return napiValue; + WS_HILOGD("%{public}s: return", __func__); +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/workscheduler_napi.cpp b/interfaces/kits/js/napi/src/workscheduler_napi.cpp index c39f61a..a251ac6 100644 --- a/interfaces/kits/js/napi/src/workscheduler_napi.cpp +++ b/interfaces/kits/js/napi/src/workscheduler_napi.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,11 +14,19 @@ */ #include "workscheduler_napi.h" + +#include "get_work_status.h" +#include "is_last_work_time_out.h" +#include "start_work.h" +#include "stop_and_clear_works.h" +#include "stop_work.h" +#include "obtain_all_works.h" #include "work_condition.h" #include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { + EXTERN_C_START static const uint8_t ARG_FIRST = 1; @@ -30,7 +38,17 @@ napi_ref storageRequestConstructor_ = nullptr; napi_value Init(napi_env env, napi_value exports) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); + WS_HILOGD("%{public}s: enter", __func__); + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("startWork", StartWork), + DECLARE_NAPI_FUNCTION("stopWork", StopWork), + DECLARE_NAPI_FUNCTION("getWorkStatus", GetWorkStatus), + DECLARE_NAPI_FUNCTION("obtainAllWorks", ObtainAllWorks), + DECLARE_NAPI_FUNCTION("stopAndClearWorks", StopAndClearWorks), + DECLARE_NAPI_FUNCTION("isLastWorkTimeOut", IsLastWorkTimeOut), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); // Init constant value. InitNetworkType(env, exports); @@ -43,7 +61,6 @@ napi_value Init(napi_env env, napi_value exports) napi_value InitNetworkType(napi_env env, napi_value exports) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); napi_value network_type_any; napi_value network_type_mobile; napi_value network_type_wifi; @@ -55,12 +72,9 @@ napi_value InitNetworkType(napi_env env, napi_value exports) napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ANY), &network_type_any); napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_MOBILE), &network_type_mobile); napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI), &network_type_wifi); - napi_create_uint32(env, - static_cast(WorkCondition::Network::NETWORK_TYPE_BLUETOOTH), &network_type_bluetooth); - napi_create_uint32(env, - static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI_P2P), &network_type_wifi_p2p); - napi_create_uint32(env, - static_cast(WorkCondition::Network::NETWORK_TYPE_ETHERNET), &network_type_ethernet); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_BLUETOOTH), &network_type_bluetooth); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI_P2P), &network_type_wifi_p2p); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ETHERNET), &network_type_ethernet); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("NETWORK_TYPE_ANY", network_type_any), @@ -72,21 +86,17 @@ napi_value InitNetworkType(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, - EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &networkTypeConstructor_); - napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, - EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &networkTypeConstructor_); napi_set_named_property(env, exports, "NetworkType", result); return exports; - - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: return", __func__); } napi_value EnumNetworkTypeConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); + WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; napi_value args[ARG_FIRST] = { 0 }; napi_value jsthis = nullptr; @@ -94,17 +104,16 @@ napi_value EnumNetworkTypeConstructor(napi_env env, napi_callback_info info) napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - WS_HILOGD(MODULE_JS_NAPI, "EnumNetworkTypeConstructor %{public}d", status); + WS_HILOGD("EnumNetworkTypeConstructor %{public}d", status); if (status != napi_ok) { return nullptr; } - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: return", __func__); + WS_HILOGD("%{public}s: return", __func__); return jsthis; } napi_value InitChargingType(napi_env env, napi_value exports) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); napi_value charging_plugged_any; napi_value charging_plugged_ac; napi_value charging_plugged_usb; @@ -114,8 +123,7 @@ napi_value InitChargingType(napi_env env, napi_value exports) napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY), &charging_plugged_any); napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_AC), &charging_plugged_ac); napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_USB), &charging_plugged_usb); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS), - &charging_plugged_wireless); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS), &charging_plugged_wireless); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("CHARGING_PLUGGED_ANY", charging_plugged_any), @@ -125,8 +133,7 @@ napi_value InitChargingType(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "ChargingType", NAPI_AUTO_LENGTH, - EnumChargingTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "ChargingType", NAPI_AUTO_LENGTH, EnumChargingTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &chargingTypeConstructor_); napi_set_named_property(env, exports, "ChargingType", result); return exports; @@ -134,7 +141,6 @@ napi_value InitChargingType(napi_env env, napi_value exports) napi_value EnumChargingTypeConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); size_t argc = 0; napi_value args[ARG_FIRST] = { 0 }; napi_value jsthis = nullptr; @@ -142,28 +148,24 @@ napi_value EnumChargingTypeConstructor(napi_env env, napi_callback_info info) napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - WS_HILOGD(MODULE_JS_NAPI, "EnumChargingTypeConstructor %{public}d", status); + WS_HILOGD("EnumChargingTypeConstructor %{public}d", status); if (status != napi_ok) { return nullptr; } - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: return", __func__); + WS_HILOGD("%{public}s: return", __func__); return jsthis; } napi_value InitBatteryStatus(napi_env env, napi_value exports) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); napi_value battery_status_low; napi_value battery_status_okay; napi_value battery_status_low_or_okay; int32_t refCount = 1; - napi_create_uint32(env, - static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW), &battery_status_low); - napi_create_uint32(env, - static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY), &battery_status_okay); - napi_create_uint32(env, - static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY), &battery_status_low_or_okay); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW), &battery_status_low); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY), &battery_status_okay); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY), &battery_status_low_or_okay); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("BATTERY_STATUS_LOW", battery_status_low), @@ -172,8 +174,7 @@ napi_value InitBatteryStatus(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "BatteryStatus", NAPI_AUTO_LENGTH, - EnumBatteryStatusConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "BatteryStatus", NAPI_AUTO_LENGTH, EnumBatteryStatusConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &batteryStatusConstructor_); napi_set_named_property(env, exports, "BatteryStatus", result); return exports; @@ -181,7 +182,7 @@ napi_value InitBatteryStatus(napi_env env, napi_value exports) napi_value EnumBatteryStatusConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); + WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; napi_value args[ARG_FIRST] = { 0 }; napi_value jsthis = nullptr; @@ -189,28 +190,24 @@ napi_value EnumBatteryStatusConstructor(napi_env env, napi_callback_info info) napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - WS_HILOGD(MODULE_JS_NAPI, "EnumBatteryStatusConstructor %{public}d", status); + WS_HILOGD("EnumBatteryStatusConstructor %{public}d", status); if (status != napi_ok) { return nullptr; } - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: return", __func__); + WS_HILOGD("%{public}s: return", __func__); return jsthis; } napi_value InitStorageRequest(napi_env env, napi_value exports) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); napi_value storage_level_low; napi_value storage_level_okay; napi_value storage_level_low_or_okay; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW), - &storage_level_low); - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_OKAY), - &storage_level_okay); - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY), - &storage_level_low_or_okay); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW), &storage_level_low); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_OKAY), &storage_level_okay); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY), &storage_level_low_or_okay); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("STORAGE_LEVEL_LOW", storage_level_low), @@ -227,7 +224,7 @@ napi_value InitStorageRequest(napi_env env, napi_value exports) napi_value EnumStorageRequestConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: enter", __func__); + WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; napi_value args[ARG_FIRST] = { 0 }; napi_value jsthis = nullptr; @@ -235,11 +232,11 @@ napi_value EnumStorageRequestConstructor(napi_env env, napi_callback_info info) napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - WS_HILOGD(MODULE_JS_NAPI, "EnumStorageRequestConstructor %{public}d", status); + WS_HILOGD("EnumStorageRequestConstructor %{public}d", status); if (status != napi_ok) { return nullptr; } - WS_HILOGD(MODULE_JS_NAPI, "%{public}s: return", __func__); + WS_HILOGD("%{public}s: return", __func__); return jsthis; } @@ -251,5 +248,6 @@ __attribute__((constructor)) void RegisterModule(void) napi_module_register(&_module); } EXTERN_C_END + } } \ No newline at end of file diff --git a/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn new file mode 100644 index 0000000..7222e02 --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + + +ts2abc_gen_abc("gen_work_scheduler_extension_abc") { + src_js = rebase_path("work_scheduler_extension.js") + dst_file = rebase_path(target_out_dir + "/work_scheduler_extension.abc") + in_puts = [ "work_scheduler_extension.js" ] + out_puts = [ target_out_dir + "/work_scheduler_extension.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("work_scheduler_extension_js") { + input = "work_scheduler_extension.js" + output = target_out_dir + "/work_scheduler_extension.o" +} + +gen_js_obj("work_scheduler_extension_abc") { + input = get_label_info(":gen_work_scheduler_extension_abc", + "target_out_dir") + "/work_scheduler_extension.abc" + output = target_out_dir + "/work_scheduler_extension_abc.o" + dep = ":gen_work_scheduler_extension_abc" +} + +ohos_shared_library("workschedulerextension_napi") { + sources = [ "work_scheduler_extension_module.cpp" ] + + deps = [ + ":work_scheduler_extension_abc", + ":work_scheduler_extension_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module" + part_name = "${worksched_native_part_name}" + subsystem_name = "resourceschedule" +} diff --git a/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension.js b/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension.js new file mode 100644 index 0000000..7736cff --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension.js @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class WorkSchedulerExtension { + onWorkStart() { + console.log('MyWorkSchedulerExtension onWorkStart'); + } + onWorkStop() { + console.log('MyWorkSchedulerExtension onWorkStop'); + } +} + +export default WorkSchedulerExtension \ No newline at end of file diff --git a/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension_module.cpp b/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension_module.cpp new file mode 100644 index 0000000..c9c37a7 --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension/work_scheduler_extension_module.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_work_scheduler_extension_js_start[]; +extern const char _binary_work_scheduler_extension_js_end[]; +extern const char _binary_work_scheduler_extension_abc_start[]; +extern const char _binary_work_scheduler_extension_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_WorkSchedulerExtension_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "WorkSchedulerExtension", + .fileName = "libworkschedulerextension_napi.so/WorkSchedulerExtension.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_WorkSchedulerExtension_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_work_scheduler_extension_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_work_scheduler_extension_js_end - + _binary_work_scheduler_extension_js_start; + } +} + +// WorkSchedulerExtension JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_WorkSchedulerExtension_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_work_scheduler_extension_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_work_scheduler_extension_abc_end - + _binary_work_scheduler_extension_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/work_scheduler_extension_context/BUILD.gn b/interfaces/kits/js/napi/work_scheduler_extension_context/BUILD.gn new file mode 100644 index 0000000..513168e --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension_context/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + + +ts2abc_gen_abc("gen_work_scheduler_extension_context_abc") { + src_js = rebase_path("work_scheduler_extension_context.js") + dst_file = + rebase_path(target_out_dir + "/work_scheduler_extension_context.abc") + in_puts = [ "work_scheduler_extension_context.js" ] + out_puts = [ target_out_dir + "/work_scheduler_extension_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("work_scheduler_extension_context_js") { + input = "work_scheduler_extension_context.js" + output = target_out_dir + "/work_scheduler_extension_context.o" +} + +gen_js_obj("work_scheduler_extension_context_abc") { + input = get_label_info(":gen_work_scheduler_extension_context_abc", + "target_out_dir") + + "/work_scheduler_extension_context.abc" + output = target_out_dir + "/work_scheduler_extension_context_abc.o" + dep = ":gen_work_scheduler_extension_context_abc" +} + +ohos_shared_library("workschedulerextensioncontext_napi") { + sources = [ "work_scheduler_extension_context_module.cpp" ] + + deps = [ + ":work_scheduler_extension_context_abc", + ":work_scheduler_extension_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module" + part_name = "${worksched_native_part_name}" + subsystem_name = "resourceschedule" +} diff --git a/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context.js b/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context.js new file mode 100644 index 0000000..0a6957a --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context.js @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var ExtensionContext = requireNapi("application.ExtensionContext") + +class WorkSchedulerExtensionContext extends ExtensionContext { + constructor(obj) { + super(obj); + } +} + +export default WorkSchedulerExtensionContext \ No newline at end of file diff --git a/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context_module.cpp b/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context_module.cpp new file mode 100644 index 0000000..54e9d0f --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension_context/work_scheduler_extension_context_module.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_work_scheduler_extension_context_js_start[]; +extern const char _binary_work_scheduler_extension_context_js_end[]; +extern const char _binary_work_scheduler_extension_context_abc_start[]; +extern const char _binary_work_scheduler_extension_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_WorkSchedulerExtensionContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "WorkSchedulerExtensionContext", + .fileName = "libworkschedulerextensioncontext_napi.so/WorkSchedulerExtensionContext.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_WorkSchedulerExtensionContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_work_scheduler_extension_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_work_scheduler_extension_context_js_end - + _binary_work_scheduler_extension_context_js_start; + } +} + +// WorkSchedulerExtensionContext JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_WorkSchedulerExtensionContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_work_scheduler_extension_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_work_scheduler_extension_context_abc_end - + _binary_work_scheduler_extension_context_abc_start; + } +} diff --git a/sa_profile/1904.xml b/sa_profile/1904.xml index 958b9e7..edb1b0c 100644 --- a/sa_profile/1904.xml +++ b/sa_profile/1904.xml @@ -21,4 +21,4 @@ false 1 - \ No newline at end of file + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index cac1e49..c58842a 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,8 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") import("//build/ohos/sa_profile/sa_profile.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") ohos_prebuilt_etc("work_scheduler_service_init") { source = "etc/work_scheduler_service.cfg" @@ -23,4 +23,4 @@ ohos_prebuilt_etc("work_scheduler_service_init") { ohos_sa_profile("worksched_sa_profile") { sources = [ "1904.xml" ] part_name = "${worksched_native_part_name}" -} \ No newline at end of file +} diff --git a/sa_profile/etc/work_scheduler_service.cfg b/sa_profile/etc/work_scheduler_service.cfg index c1c874c..d1aad81 100644 --- a/sa_profile/etc/work_scheduler_service.cfg +++ b/sa_profile/etc/work_scheduler_service.cfg @@ -2,7 +2,6 @@ "jobs" : [{ "name" : "boot", "cmds" : [ - "exec /system/bin/sleep 5", "start work_scheduler_service" ] } diff --git a/services/BUILD.gn b/services/BUILD.gn index f80d5c7..309b78d 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -13,23 +13,66 @@ import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") +config("worksched_private_config") { + include_dirs = [ "${worksched_service_path}/zidl/include" ] +} + config("worksched_public_config") { include_dirs = [ "native/include" ] } ohos_shared_library("workschedservice") { - sources = [ "native/src/work_scheduler_service.cpp" ] + sources = [ + "native/src/conditions/battery_level_listener.cpp", + "native/src/conditions/battery_status_listener.cpp", + "native/src/conditions/charger_listener.cpp", + "native/src/conditions/network_listener.cpp", + "native/src/conditions/power_listener.cpp", + "native/src/conditions/storage_listener.cpp", + "native/src/conditions/timer_listener.cpp", + "native/src/policy/app_removed_listener.cpp", + "native/src/policy/memory_policy.cpp", + "native/src/policy/thermal_policy.cpp", + "native/src/work_conn_manager.cpp", + "native/src/work_event_handler.cpp", + "native/src/work_policy_manager.cpp", + "native/src/work_queue.cpp", + "native/src/work_queue_event_handler.cpp", + "native/src/work_queue_manager.cpp", + "native/src/work_scheduler_service.cpp", + "native/src/work_status.cpp", + "zidl/src//work_conn_stub.cpp", + "zidl/src/work_sched_service_stub.cpp", + "zidl/src/work_scheduler_proxy.cpp", + "native/src/work_scheduler_connection.cpp" + ] + + configs = [ ":worksched_private_config" ] public_configs = [ ":worksched_public_config" ] - deps = [ "${worksched_utils_path}:workschedutils" ] + deps = [ + "${worksched_frameworks_path}:workschedclient", + "${worksched_frameworks_path}/extension:workschedextension", + "${worksched_utils_path}:workschedutils", + "//third_party/jsoncpp", + ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "battery_manager_native:batterysrv_client", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", + "ability_runtime:app_manager" + # "thermal_manager_native:thermalsrv_client", ] part_name = "${worksched_native_part_name}" diff --git a/services/native/include/conditions/battery_level_listener.h b/services/native/include/conditions/battery_level_listener.h new file mode 100644 index 0000000..aca84de --- /dev/null +++ b/services/native/include/conditions/battery_level_listener.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkQueueManager; +class BatteryLevelListener; +class BatteryLevelEventSubscriber : public CommonEventSubscriber { +public: + BatteryLevelEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryLevelListener &listener); + ~BatteryLevelEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + BatteryLevelListener &listener_; +}; +class BatteryLevelListener : public IConditionListener { +public: + BatteryLevelListener(std::shared_ptr workQueueManager); + ~BatteryLevelListener(); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/battery_status_listener.h b/services/native/include/conditions/battery_status_listener.h new file mode 100644 index 0000000..5fed547 --- /dev/null +++ b/services/native/include/conditions/battery_status_listener.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkQueueManager; +class BatteryStatusListener; +class BatteryStatusEventSubscriber : public CommonEventSubscriber { +public: + BatteryStatusEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryStatusListener &listener); + ~BatteryStatusEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + BatteryStatusListener &listener_; +}; +class BatteryStatusListener : public IConditionListener { +public: + BatteryStatusListener(std::shared_ptr workQueueManager); + ~BatteryStatusListener(); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/charger_listener.h b/services/native/include/conditions/charger_listener.h new file mode 100644 index 0000000..43a0e1d --- /dev/null +++ b/services/native/include/conditions/charger_listener.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkQueueManager; +class ChargerListener; +class ChargerEventSubscriber : public CommonEventSubscriber { +public: + ChargerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, ChargerListener &listener); + ~ChargerEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + ChargerListener &listener_; +}; +class ChargerListener : public IConditionListener { +public: + ChargerListener(std::shared_ptr workQueueManager); + ~ChargerListener(); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/common_event_detector.h b/services/native/include/conditions/common_event_detector.h new file mode 100644 index 0000000..c8b69c7 --- /dev/null +++ b/services/native/include/conditions/common_event_detector.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H +#define WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H + +namespace OHOS { +namespace WorkScheduler { +class CommonEventDetector { +// 从BMS中获取应用数据 +// 判断应用是否有权限进行注册 +// 注册静态广播回调 +// 从静态广播回调应用 +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H \ No newline at end of file diff --git a/services/native/include/conditions/network_listener.h b/services/native/include/conditions/network_listener.h new file mode 100644 index 0000000..72659e5 --- /dev/null +++ b/services/native/include/conditions/network_listener.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class NetworkListener; +class NetworkEventSubscriber : public CommonEventSubscriber { +public: + NetworkEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener); + ~NetworkEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + NetworkListener &listener_; +}; +class NetworkListener : public IConditionListener { +public: + NetworkListener(std::shared_ptr workQueueManager); + ~NetworkListener(); + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/power_listener.h b/services/native/include/conditions/power_listener.h new file mode 100644 index 0000000..1421ad1 --- /dev/null +++ b/services/native/include/conditions/power_listener.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkQueueManager; +class PowerListener; +class PowerEventSubscriber : public CommonEventSubscriber { +public: + PowerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, PowerListener &listener); + ~PowerEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + PowerListener &listener_; +}; +class PowerListener : public IConditionListener { +public: + PowerListener(std::shared_ptr workQueueManager); + ~PowerListener(); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; + +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/storage_listener.h b/services/native/include/conditions/storage_listener.h new file mode 100644 index 0000000..30ff76a --- /dev/null +++ b/services/native/include/conditions/storage_listener.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H + +#include + +#include "icondition_listener.h" +#include "common_event_subscriber.h" +#include "work_queue_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkQueueManager; +class StorageListener; +class StorageEventSubscriber : public CommonEventSubscriber { +public: + StorageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener); + ~StorageEventSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + StorageListener &listener_; +}; +class StorageListener : public IConditionListener { +public: + StorageListener(std::shared_ptr workQueueManager); + ~StorageListener(); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/timer_listener.h b/services/native/include/conditions/timer_listener.h new file mode 100644 index 0000000..6b9abf6 --- /dev/null +++ b/services/native/include/conditions/timer_listener.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H +#define WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H + +#include +#include + +#include "icondition_listener.h" +#include "work_queue_manager.h" +#include "work_queue_event_handler.h" +#include "work_scheduler_service.h" + +namespace OHOS { +using namespace AppExecFwk; +namespace WorkScheduler { +class TimerListener : public IConditionListener { +public: + TimerListener(std::shared_ptr workQueueManager); + ~TimerListener() = default; + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workQueueManager_; + std::shared_ptr eventRunner_; + std::shared_ptr handler_; + const std::string TIMER_LISTENER = "TimerListener"; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/detector_value.h b/services/native/include/detector_value.h new file mode 100644 index 0000000..defcc28 --- /dev/null +++ b/services/native/include/detector_value.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_CONDITION_VALUE_H +#define WORK_SCHED_SERVICES_CONDITION_VALUE_H + +#include +#include + +namespace OHOS { +namespace WorkScheduler { +struct DetectorValue { + int32_t intVal; + time_t timeVal; + bool boolVal; + std::string strVal; + DetectorValue(int32_t intVal, time_t timeVal, bool boolVal, const std::string &strVal) + : intVal(intVal), timeVal(timeVal), boolVal(boolVal) {} +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_CONDITION_VALUE_H diff --git a/services/native/include/icondition_listener.h b/services/native/include/icondition_listener.h new file mode 100644 index 0000000..d6d824b --- /dev/null +++ b/services/native/include/icondition_listener.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_ICONDITION_LISTENER_H +#define WORK_SCHED_SERVICES_ICONDITION_LISTENER_H + +#include + +#include "work_condition.h" +#include "detector_value.h" + +namespace OHOS { +namespace WorkScheduler { +class IConditionListener { +public: + virtual ~IConditionListener() = default; + virtual void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) = 0; + virtual bool Start(); + virtual bool Stop(); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_ICONDITION_DETECTOR_H \ No newline at end of file diff --git a/services/native/include/ipolicy_filter.h b/services/native/include/ipolicy_filter.h new file mode 100644 index 0000000..220b7f0 --- /dev/null +++ b/services/native/include/ipolicy_filter.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_IPOLICY_FILTER_H +#define WORK_SCHED_SERVICES_IPOLICY_FILTER_H + +#include + +namespace OHOS { +namespace WorkScheduler { +class IPolicyFilter { +public: + virtual ~IPolicyFilter() = default; + virtual int32_t Check(int32_t currentIsRunning); + static const int32_t CANNOT_RUNNING_MORE = -1; + static const int32_t MAX_RUNNING_COUNT = 5; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_IPOLICY_FILTER_H \ No newline at end of file diff --git a/services/native/include/ipolicy_listener.h b/services/native/include/ipolicy_listener.h new file mode 100644 index 0000000..ef90be7 --- /dev/null +++ b/services/native/include/ipolicy_listener.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H +#define WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H + +#include + +#include "detector_value.h" +#include "policy_type.h" + +namespace OHOS { +namespace WorkScheduler { +class IPolicyListener { +public: + virtual ~IPolicyListener() = default; + virtual void OnPolicyChanged(PolicyType policyType, std::shared_ptr detectorVal) = 0; + virtual bool Start(); + virtual bool Stop(); +}; +} // namesapce WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H \ No newline at end of file diff --git a/services/native/include/policy/app_removed_listener.h b/services/native/include/policy/app_removed_listener.h new file mode 100644 index 0000000..fcb3fff --- /dev/null +++ b/services/native/include/policy/app_removed_listener.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WORK_SCHED_SERVICES_POLICY_APP_REMOVED_LISTENER_H +#define WORK_SCHED_SERVICES_POLICY_APP_REMOVED_LISTENER_H + +#include "ipolicy_listener.h" +#include "common_event_subscriber.h" +#include "work_policy_manager.h" + +namespace OHOS { +using namespace EventFwk; +namespace WorkScheduler { +class WorkPolicyManager; +class AppRemovedListener; +class AppRemovedSubscriber : public CommonEventSubscriber { +public: + AppRemovedSubscriber(const CommonEventSubscribeInfo &subscribeInfo, AppRemovedListener &listener); + ~AppRemovedSubscriber() override = default; + void OnReceiveEvent(const CommonEventData &data) override; +private: + AppRemovedListener &listener_; +}; +class AppRemovedListener : public IPolicyListener { +public: + AppRemovedListener(std::shared_ptr workPolicyManager); + ~AppRemovedListener(); + + void OnPolicyChanged(PolicyType policyType, std::shared_ptr detectorVal) override; + bool Start() override; + bool Stop() override; +private: + std::shared_ptr workPolicyManager_; + std::shared_ptr commonEventSubscriber = nullptr; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_POLICY_APP_REMOVED_LISTENER_H \ No newline at end of file diff --git a/services/native/include/policy/memory_policy.h b/services/native/include/policy/memory_policy.h new file mode 100644 index 0000000..0b9c37a --- /dev/null +++ b/services/native/include/policy/memory_policy.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H +#define WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H + +#include "ipolicy_filter.h" +#include +#include "work_policy_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class MemoryPolicy : public IPolicyFilter { +public: + MemoryPolicy(std::shared_ptr workPolicyManager); + ~MemoryPolicy(); + int32_t Check(int32_t currentIsRunning) override; + int32_t GetMaxRunningCountByMemory(); + + const int32_t MEM_LEFT_CRUCIAL = 600 * 1024; + const int32_t MEM_LEFT_WARNING = 1 * 1024 * 1024; + const int32_t MEM_LEFT_LOW = 2 * 1024 * 1024; + const int32_t COUNT_MEMORY_CRUCIAL = 0; + const int32_t COUNT_MEMORY_WARNING = 1; + const int32_t COUNT_MEMORY_LOW = 3; + const int32_t COUNT_MEMORY_NORMAL = 5; +private: + std::shared_ptr workPolicyManager_; +}; +} +} + +#endif // WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H \ No newline at end of file diff --git a/services/native/include/policy/thermal_policy.h b/services/native/include/policy/thermal_policy.h new file mode 100644 index 0000000..29dd2e3 --- /dev/null +++ b/services/native/include/policy/thermal_policy.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H +#define WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H + +#include "ipolicy_filter.h" + +#include "work_policy_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class ThermalPolicy : public IPolicyFilter { +public: + ThermalPolicy(std::shared_ptr workPolicyManager); + ~ThermalPolicy(); + int32_t Check(int32_t currentIsRunning) override; +private: + std::shared_ptr workPolicyManager_; + // const int32_t MAX_RUNNING_COUNT_COOL = MAX_RUNNING_COUNT; + // const int32_t MAX_RUNNING_COUNT_HOT = 3; + // const int32_t MAX_RUNNING_COUNT_OVERHEATED = 1; + // int32_t current_max_running_count = MAX_RUNNING_COUNT_COOL; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H \ No newline at end of file diff --git a/services/native/include/policy_type.h b/services/native/include/policy_type.h new file mode 100644 index 0000000..629b7b6 --- /dev/null +++ b/services/native/include/policy_type.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_POLICY_TYPE_H +#define WORK_SCHED_SERVICES_POLICY_TYPE_H + +namespace OHOS { +namespace WorkScheduler { +enum PolicyType { + IDLE = 0, + TIMER, + APP_REMOVED +}; + +enum IdleStatus { + IDLE_START = 0, + IDLE_STOP +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_POLICY_TYPE_H \ No newline at end of file diff --git a/services/native/include/work_conn_manager.h b/services/native/include/work_conn_manager.h new file mode 100644 index 0000000..d3f7a50 --- /dev/null +++ b/services/native/include/work_conn_manager.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_CONN_MANAGER_H +#define WORK_SCHED_SERVICES_WORK_CONN_MANAGER_H + +#include +#include +#include + +#include "work_status.h" +#include "work_conn_proxy.h" + +namespace OHOS { +using namespace Utils; +namespace WorkScheduler { +class WorkConnection { +public: + void OnWorkStart(std::shared_ptr workInfo); + void OnWorkStop(std::shared_ptr workInfo); +}; +class WorkConnManager { +public: + void StartWork(std::shared_ptr workStatus); + void StopWork(std::shared_ptr workStatus); +private: + std::map> connMap_; + std::unique_ptr timer_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_CONN_MANAGER_H \ No newline at end of file diff --git a/services/native/include/work_event_handler.h b/services/native/include/work_event_handler.h new file mode 100644 index 0000000..a9739db --- /dev/null +++ b/services/native/include/work_event_handler.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_EVENT_HANDLER_H +#define WORK_SCHED_SERVICES_WORK_EVENT_HANDLER_H + +#include +#include +#include +#include "work_scheduler_service.h" + + +namespace OHOS { +namespace WorkScheduler { +class WorkEventHandler : public AppExecFwk::EventHandler { +public: + enum { + RETRIGGER_MSG = 0, + }; + WorkEventHandler(const std::shared_ptr& runner, + const wptr& service); + ~WorkEventHandler() = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) override; + +private: + wptr service_; + +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_EVENT_HANDLER_H \ No newline at end of file diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h new file mode 100644 index 0000000..a85530e --- /dev/null +++ b/services/native/include/work_policy_manager.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_POLICY_MANAGER_H +#define WORK_SCHED_SERVICES_POLICY_MANAGER_H + +#include +#include +#include +#include + +#include "policy_type.h" +#include "work_queue.h" +#include "work_info.h" +#include "work_status.h" +#include "work_sched_common.h" +#include "work_conn_manager.h" +#include "work_scheduler_service.h" +#include "ipolicy_filter.h" + + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerService; +class WorkEventHandler; + +class WorkPolicyManager { +public: + const size_t MAX_WORK_COUNT_PER_UID = 200; + explicit WorkPolicyManager(const wptr& wss); + ~WorkPolicyManager() = default; + bool Init(); + bool AddListener(); + void AddPolicyFilter(std::shared_ptr filter); + bool AddWork(std::shared_ptr workStatus, int32_t uid); + bool RemoveWork(std::shared_ptr workStatus, int32_t uid); + bool StopWork(std::shared_ptr workStatus, int32_t uid); + bool CancelWork(std::shared_ptr workStatus, int32_t uid); + bool StopAndClearWorks(int32_t uid); + bool IsLastWorkTimeout(int32_t workId, int32_t uid); + std::shared_ptr FindWorkStatus(WorkInfo& workInfo, int32_t uid); + void OnConditionReady(std::shared_ptr>> workStatusVector); + void OnPolicyChanged(PolicyType policyType, std::shared_ptr detectorVal); + std::list> ObtainAllWorks(int32_t &uid); + std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workInfo); + std::list> GetAllWorkStatus(int32_t &uid); + void Dump(std::string& result); + int32_t currentRunningCount = 0; + void CheckWorkToRun(); + void SendRetrigger(int64_t delayTime); + +private: + const wptr wss_; + std::shared_ptr workConnManager_; + std::map> uidQueueMap_; + std::shared_ptr conditionReadyQueue_; + std::list> policyFilters_; + int32_t runningWorkCount = 0; + int32_t GetMaxRunningCount(); + int32_t GetRunningCount(); + void RemoveByBundle(std::string bundle); + std::shared_ptr handler_; + std::mutex mutex_; + +}; +} +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_POLICY_MANAGER_H \ No newline at end of file diff --git a/services/native/include/work_queue.h b/services/native/include/work_queue.h new file mode 100644 index 0000000..58351a9 --- /dev/null +++ b/services/native/include/work_queue.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_QUEUE_H +#define WORK_SCHED_SERVICES_WORK_QUEUE_H + +#include +#include + +#include "work_status.h" +#include "detector_value.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueue { +public: + explicit WorkQueue() = default; + ~WorkQueue() = default; + std::vector> OnConditionChanged( + WorkCondition::Type type, std::shared_ptr conditionVal); + void Push(std::shared_ptr>> workStatusVector); + void Push(std::shared_ptr workStatus); + std::shared_ptr GetWorkToRunByPriority(); + bool Remove(std::shared_ptr workStatus); + bool Contains(std::shared_ptr workId); + std::shared_ptr Find(std::string workId); + size_t GetSize(); + bool StopWork(std::shared_ptr workStatus); + bool CancelWork(std::shared_ptr workStatus); + std::list> GetWorkList(); + void RemoveUnReady(); + int32_t GetRunningCount(); + void GetWorkIdStr(std::string& result); + void Dump(std::string& result); +private: + std::list> workList_; +}; +class WorkComp { +public: + bool operator () (const std::shared_ptr w1, const std::shared_ptr w2); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_QUEUE_H \ No newline at end of file diff --git a/services/native/include/work_queue_event_handler.h b/services/native/include/work_queue_event_handler.h new file mode 100644 index 0000000..427787b --- /dev/null +++ b/services/native/include/work_queue_event_handler.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_QUEUE_EVENT_HANDLER_H +#define WORK_SCHED_SERVICES_WORK_QUEUE_EVENT_HANDLER_H + +#include +#include + +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueueEventHandler : public AppExecFwk::EventHandler { +public: + enum { + TIMER_TICK = 0, + }; + WorkQueueEventHandler(const std::shared_ptr& runner, + std::shared_ptr manager); + ~WorkQueueEventHandler() = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) override; + +private: + std::shared_ptr manager_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_QUEUE_EVENT_HANDLER_H \ No newline at end of file diff --git a/services/native/include/work_queue_manager.h b/services/native/include/work_queue_manager.h new file mode 100644 index 0000000..bb96dba --- /dev/null +++ b/services/native/include/work_queue_manager.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H +#define WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H + +#include +#include +#include + +#include "delayed_sp_singleton.h" +#include "work_queue.h" +#include "work_status.h" +#include "work_sched_common.h" +#include "icondition_listener.h" +#include "work_scheduler_service.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerService; +class WorkQueueManager : std::enable_shared_from_this { +public: + explicit WorkQueueManager(const wptr& wss); + ~WorkQueueManager() = default; + bool Init(); + bool AddListener(WorkCondition::Type type, std::shared_ptr listener); + bool AddWork(std::shared_ptr workStatus); + bool RemoveWork(std::shared_ptr workStatus); + bool StopWork(std::shared_ptr workStatus); + bool CancelWork(std::shared_ptr workStatus); + + void OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal); + bool StopAndClearWorks(std::list> workList); + void Dump(std::string& result); +private: + const wptr wss_; + std::map> queueMap_; + std::map> listenerMap_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H \ No newline at end of file diff --git a/services/native/include/work_scheduler_connection.h b/services/native/include/work_scheduler_connection.h new file mode 100644 index 0000000..b9aa3cc --- /dev/null +++ b/services/native/include/work_scheduler_connection.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H +#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H + +#include "ability_connect_callback_stub.h" +#include "work_scheduler_proxy.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerConnection : public AAFwk::AbilityConnectionStub { +public: + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; +private: + sptr proxy_ = nullptr; +}; +} // namespace +} // namespace OHOS +#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 42bf7d8..197d12a 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,26 +16,78 @@ #ifndef WORK_SCHED_SERVICES_WORK_SCHEDULER_SERVICES_H #define WORK_SCHED_SERVICES_WORK_SCHEDULER_SERVICES_H -#include "refbase.h" -#include "singleton.h" -#include "system_ability.h" -#include "system_ability_definition.h" +#include +#include +#include +#include +#include +#include +#include + +#include "ability_manager_interface.h" +#include "delayed_sp_singleton.h" +#include "work_sched_service_stub.h" +#include "work_policy_manager.h" +#include "work_info.h" +#include "work_status.h" +#include "work_queue_manager.h" +#include "work_event_handler.h" namespace OHOS { namespace WorkScheduler { -class WorkSchedulerService final : public SystemAbility, - public std::enable_shared_from_this { - DISALLOW_COPY_AND_MOVE(WorkSchedulerService); +class WorkQueueManager; +class WorkPolicyManager; +class WorkSchedulerService final : public SystemAbility, public WorkSchedServiceStub { DECLARE_SYSTEM_ABILITY(WorkSchedulerService); - DECLARE_DELAYED_SINGLETON(WorkSchedulerService); + DECLARE_DELAYED_SP_SINGLETON(WorkSchedulerService); public: - WorkSchedulerService(const int32_t systemAbilityId, bool runOnCreate); virtual void OnStart() override; virtual void OnStop() override; + bool StartWork(WorkInfo& workInfo) override; + bool StopWork(WorkInfo& workInfo) override; + bool StopAndCancelWork(WorkInfo& workInfo) override; + bool StopAndClearWorks() override; + bool IsLastWorkTimeout(int32_t workId) override; + std::list> ObtainAllWorks(int32_t &uid, int32_t &pid) override; + std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workId) override; + bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; + + int32_t CreateNodeDir(std::string dir); + int32_t CreateNodeFile(std::string filePath); + + void OnConditionReady(std::shared_ptr>> workStatusVector); + + std::shared_ptr GetHandler() { + return handler_; + } + + std::shared_ptr GetWorkQueueManager() { + return workQueueManager_; + } + + std::shared_ptr GetWorkPolicyManager() { + return workPolicyManager_; + } private: + const char* PERSISTED_FILE_PATH = "/data/workscheduler/persisted"; + const char* PERSISTED_PATH = "/data/workscheduler/"; + const char* PERSISTED_FILE = "persisted"; bool Init(); + bool WorkQueueManagerInit(); + bool WorkPolicyManagerInit(); + std::shared_ptr workQueueManager_; + std::shared_ptr workPolicyManager_; + std::map> persistedMap_; bool ready_ {false}; + void RefreshPersistedWorks(); + std::list> ReadPersistedWorks(); + void InitPersistedWork(WorkInfo& workInfo); + std::shared_ptr handler_; + std::shared_ptr eventRunner_; + void DumpAllInfo(std::vector &dumpInfo); + void DumpWorkQueueInfo(std::vector &dumpInfo); + void DumpWorkPolicyInfo(std::vector &dumpInfo); }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/include/work_status.h b/services/native/include/work_status.h new file mode 100644 index 0000000..0831675 --- /dev/null +++ b/services/native/include/work_status.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_SERVICES_WORK_STATUS_H +#define WORK_SCHED_SERVICES_WORK_STATUS_H + +#include +#include + +#include "timer.h" +#include "work_info.h" + +namespace OHOS { +using namespace Utils; +namespace WorkScheduler { +class WorkStatus { +public: + enum Status { + WAIT_CONDITION = 0, + CONDITION_READY, + POLICY_PENDING, + RUNNING, + REMOVED + }; + const int32_t DEFAULT_PRIORITY = 100; + WorkStatus(WorkInfo &workInfo, int32_t uid); + ~WorkStatus(); + + static std::string MakeWorkId(int32_t workId, int32_t uid); + + std::string workId_; + std::string bundleName_; + std::string abilityName_; + bool persisted_; + int32_t priority_; + std::map> conditionMap_; + std::shared_ptr workInfo_; + + bool IsReady(); + bool IsRunning(); + bool IsRepeating(); + bool IsLastWorkTimeout(); + void OnConditionChanged(WorkCondition::Type &type, std::shared_ptr value); + void MarkRound(); + void MarkStatus(Status status); + Status GetStatus(); + void Dump(std::string& result); +private: + Status currentStatus_; + time_t baseTime_; + bool lastTimeout_ {false}; + void MarkTimeout(); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_SERVICES_WORK_STATUS_H \ No newline at end of file diff --git a/services/native/src/conditions/battery_level_listener.cpp b/services/native/src/conditions/battery_level_listener.cpp new file mode 100644 index 0000000..bfbf109 --- /dev/null +++ b/services/native/src/conditions/battery_level_listener.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/battery_level_listener.h" + +#include +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" +#include "battery_info.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +BatteryLevelEventSubscriber::BatteryLevelEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryLevelListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void BatteryLevelEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED) { + WS_HILOGI("Condition changed: BATTERY_CHANGED"); + if (data.GetCode() == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_CAPACITY) { + int battCap = atoi(data.GetData().c_str()); + listener_.OnConditionChanged(WorkCondition::Type::BATTERY_LEVEL, + make_shared(battCap, 0, 0, string())); + } + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +shared_ptr CreateBatteryEventSubscriber(BatteryLevelListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +BatteryLevelListener::BatteryLevelListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +BatteryLevelListener::~BatteryLevelListener() +{ + this->Stop(); +} + +bool BatteryLevelListener::Start() +{ + WS_HILOGI("BatteryLevelListener Start"); + this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool BatteryLevelListener::Stop() +{ + WS_HILOGI("BatteryLevelListener Stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void BatteryLevelListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/battery_status_listener.cpp b/services/native/src/conditions/battery_status_listener.cpp new file mode 100644 index 0000000..0051d90 --- /dev/null +++ b/services/native/src/conditions/battery_status_listener.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/battery_status_listener.h" + +#include +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" +#include "battery_info.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +BatteryStatusEventSubscriber::BatteryStatusEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryStatusListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void BatteryStatusEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == CommonEventSupport::COMMON_EVENT_BATTERY_LOW) { + WS_HILOGI("Condition changed: BATTERY_STATUS_LOW"); + listener_.OnConditionChanged(WorkCondition::Type::BATTERY_STATUS, + make_shared(WorkCondition::BATTERY_STATUS_LOW, 0, 0, string())); + } else if (action == CommonEventSupport::COMMON_EVENT_BATTERY_OKAY) { + WS_HILOGI("Condition changed: BATTERY_STATUS_OKAY"); + listener_.OnConditionChanged(WorkCondition::Type::BATTERY_STATUS, + make_shared(WorkCondition::BATTERY_STATUS_OKAY, 0, 0, string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +shared_ptr CreateBatteryEventSubscriber(BatteryStatusListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_LOW); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +BatteryStatusListener::BatteryStatusListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +BatteryStatusListener::~BatteryStatusListener() +{ + this->Stop(); +} + +bool BatteryStatusListener::Start() +{ + WS_HILOGI("BatteryStatusListener Start"); + this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool BatteryStatusListener::Stop() +{ + WS_HILOGI("BatteryStatusListener Stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void BatteryStatusListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/charger_listener.cpp b/services/native/src/conditions/charger_listener.cpp new file mode 100644 index 0000000..86d05d2 --- /dev/null +++ b/services/native/src/conditions/charger_listener.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/charger_listener.h" + +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" +#include "battery_info.h" + +using namespace std; +using namespace OHOS::PowerMgr; + +namespace OHOS { +namespace WorkScheduler { +ChargerEventSubscriber::ChargerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, ChargerListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void ChargerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + int code = data.GetCode(); + if (code == BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + int type = atoi(data.GetData().c_str()); + switch(type) { + case static_cast(BatteryPluggedType::PLUGGED_TYPE_AC): + WS_HILOGI("Condition changed: CHARGER_PLUGGED_AC"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + make_shared(WorkCondition::CHARGER_PLUGGED_AC, 0, 0, string())); + break; + case static_cast(BatteryPluggedType::PLUGGED_TYPE_USB): + WS_HILOGI("Condition changed: CHARGER_PLUGGED_USB"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + make_shared(WorkCondition::CHARGER_PLUGGED_USB, 0, 0, string())); + break; + case static_cast(BatteryPluggedType::PLUGGED_TYPE_WIRELESS): + WS_HILOGI("Condition changed: CHARGER_WIRELESS"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + make_shared(WorkCondition::CHARGER_PLUGGED_WIRELESS, 0, 0, string())); + break; + default: + break; + } + } + } else if (action == CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) { + int code = data.GetCode(); + if (code == BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + int type = atoi(data.GetData().c_str()); + switch(type) { + case static_cast(BatteryPluggedType::PLUGGED_TYPE_NONE): + case static_cast(BatteryPluggedType::PLUGGED_TYPE_BUTT): + WS_HILOGI("Condition changed: CHARGER_PLUGGED_UNPLUGGED"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + make_shared(WorkCondition::CHARGER_UNPLUGGED, 0, 0, string())); + break; + default: + break; + } + } + } +} + +shared_ptr CreateChargerEventSubscriber(ChargerListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skills = MatchingSkills(); + skills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + skills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); + CommonEventSubscribeInfo info(skills); + return make_shared(info, listener); +} + +ChargerListener::ChargerListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +ChargerListener::~ChargerListener() +{ + this->Stop(); +} + +bool ChargerListener::Start() +{ + WS_HILOGI("ChargerListener start"); + this->commonEventSubscriber = CreateChargerEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool ChargerListener::Stop() +{ + WS_HILOGI("ChargerListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void ChargerListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/network_listener.cpp b/services/native/src/conditions/network_listener.cpp new file mode 100644 index 0000000..b990063 --- /dev/null +++ b/services/native/src/conditions/network_listener.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/network_listener.h" + +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" + +using namespace std; +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace WorkScheduler { +NetworkEventSubscriber::NetworkEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void NetworkEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE) { + WS_HILOGI("Condition changed: WIFI_CONN_STATE"); + listener_.OnConditionChanged(WorkCondition::Type::NETWORK, + make_shared(WorkCondition::NETWORK_TYPE_WIFI, 0, 0, string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +shared_ptr CreateNetworkEventSubscriber(NetworkListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +NetworkListener::NetworkListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +NetworkListener::~NetworkListener() +{ + this->Stop(); +} + +bool NetworkListener::Start() +{ + WS_HILOGI("NetworkListener start"); + this->commonEventSubscriber = CreateNetworkEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool NetworkListener::Stop() +{ + WS_HILOGI("NetworkListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void NetworkListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/power_listener.cpp b/services/native/src/conditions/power_listener.cpp new file mode 100644 index 0000000..39a14e6 --- /dev/null +++ b/services/native/src/conditions/power_listener.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/power_listener.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +PowerEventSubscriber::PowerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, PowerListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void PowerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + WS_HILOGI("Condition changed: POWER_CONNECTED"); + listener_.OnConditionChanged(WorkCondition::Type::POWER, + make_shared(WorkCondition::POWER_CONNECTED, 0, 0, string())); + } else if (action == CommonEventSupport::COMMON_EVENT_CHARGING) { + WS_HILOGI("Condition changed: POWER_DISCONNECTED"); + listener_.OnConditionChanged(WorkCondition::Type::POWER, + make_shared(WorkCondition::POWER_DISCONNECTED, 0, 0, string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +shared_ptr CreatePowerEventSubscriber(PowerListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +PowerListener::PowerListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +PowerListener::~PowerListener() +{ + this->Stop(); +} + +bool PowerListener::Start() +{ + WS_HILOGI("PowerListener start"); + this->commonEventSubscriber = CreatePowerEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool PowerListener::Stop() +{ + WS_HILOGI("PowerListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void PowerListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/storage_listener.cpp b/services/native/src/conditions/storage_listener.cpp new file mode 100644 index 0000000..f821c86 --- /dev/null +++ b/services/native/src/conditions/storage_listener.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/storage_listener.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +StorageEventSubscriber::StorageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void StorageEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + if (action == CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW) { + WS_HILOGI("Condition changed: STORAGE_LOW"); + listener_.OnConditionChanged(WorkCondition::Type::STORAGE, + make_shared(WorkCondition::STORAGE_LEVEL_LOW, 0, 0, string())); + } else if (action == CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK) { + WS_HILOGI("Condition changed: STORAGE_OK"); + listener_.OnConditionChanged(WorkCondition::Type::STORAGE, + make_shared(WorkCondition::STORAGE_LEVEL_OKAY, 0, 0, string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +shared_ptr CreateStorageEventSubscriber(StorageListener &listener) +{ + WS_HILOGI("%{public}s", __func__); + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_FULL); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +StorageListener::StorageListener(shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +StorageListener::~StorageListener() +{ + this->Stop(); +} + +bool StorageListener::Start() +{ + WS_HILOGI("StorageListener start"); + this->commonEventSubscriber = CreateStorageEventSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool StorageListener::Stop() +{ + WS_HILOGI("StorageListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void StorageListener::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/timer_listener.cpp b/services/native/src/conditions/timer_listener.cpp new file mode 100644 index 0000000..1eebda9 --- /dev/null +++ b/services/native/src/conditions/timer_listener.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "conditions/timer_listener.h" + +#include "work_queue_event_handler.h" + +using namespace std; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace WorkScheduler { +TimerListener::TimerListener(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +void TimerListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr conditionVal) +{ + workQueueManager_->OnConditionChanged(conditionType, conditionVal); +} + +bool TimerListener::Start() +{ + if (!eventRunner_) { + eventRunner_ = EventRunner::Create(TIMER_LISTENER); + if (eventRunner_ == nullptr) { + WS_HILOGD("Init failed due to create EventHandler"); + return false; + } + } + if (!handler_) { + handler_ = make_shared(eventRunner_, workQueueManager_); + } + handler_->SendEvent(InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), 30000); + return true; +} +bool TimerListener::Stop() +{ + if (handler_ != nullptr) { + handler_->RemoveEvent(WorkQueueEventHandler::TIMER_TICK); + } + return true; +} +} +} \ No newline at end of file diff --git a/services/native/src/policy/app_removed_listener.cpp b/services/native/src/policy/app_removed_listener.cpp new file mode 100644 index 0000000..f4cdf2a --- /dev/null +++ b/services/native/src/policy/app_removed_listener.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "policy/app_removed_listener.h" + +#include "common_event_support.h" +#include "common_event_manager.h" +#include "matching_skills.h" +#include "want.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +AppRemovedSubscriber::AppRemovedSubscriber(const CommonEventSubscribeInfo &subscribeInfo, AppRemovedListener &listener) + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void AppRemovedSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + const string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED + || action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) { + WS_HILOGI("Policy changed: APP_REMOVED"); + string bundle = data.GetWant().GetBundle(); + auto detectorVal = make_shared(PolicyType::APP_REMOVED, 0, 0, bundle); + listener_.OnPolicyChanged(PolicyType::APP_REMOVED, detectorVal); + } +} + +shared_ptr CreateAppRemovedSubscriber(AppRemovedListener &listener) +{ + MatchingSkills skill = MatchingSkills(); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + CommonEventSubscribeInfo info(skill); + return make_shared(info, listener); +} + +AppRemovedListener::AppRemovedListener(std::shared_ptr workPolicyManager) +{ + workPolicyManager_ = workPolicyManager; +} + +AppRemovedListener::~AppRemovedListener() +{ + this->Stop(); +} + +bool AppRemovedListener::Start() +{ + this->commonEventSubscriber = CreateAppRemovedSubscriber(*this); + return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool AppRemovedListener::Stop() +{ + if (this->commonEventSubscriber != nullptr) { + bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void AppRemovedListener::OnPolicyChanged(PolicyType policyType, shared_ptr detectorVal) +{ + workPolicyManager_->OnPolicyChanged(policyType, detectorVal); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp new file mode 100644 index 0000000..2741dc9 --- /dev/null +++ b/services/native/src/policy/memory_policy.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "policy/memory_policy.h" +#include + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +MemoryPolicy::MemoryPolicy(shared_ptr workPolicyManager) +{ + workPolicyManager_ = workPolicyManager; +} +MemoryPolicy::~MemoryPolicy() +{ +} + +void GetMemAvailable(int32_t mem_available) { + FILE *fp; + fp = fopen("/proc/meminfo", "r"); + if (fp == NULL) { + mem_available = IPolicyFilter::CANNOT_RUNNING_MORE; + } + char buf[128]; + int buff_len = 128; + const char mem_name[] = "MemAvailable"; + char name[20]; + int32_t value = -1; + while (NULL != fgets(buf, buff_len, fp)) { + sscanf(buf, "%s%d", name, &value); + string sname = name; + if (sname.find(mem_name) != string::npos) { + mem_available = value; + break; + } + } + fclose(fp); +} + +int32_t MemoryPolicy::GetMaxRunningCountByMemory() +{ + WS_HILOGI("MemoryPolicy::%{public}s", __func__); + int32_t mem_available = -1; + GetMemAvailable(mem_available); + WS_HILOGI("mem_available: %{public}d", mem_available); + if (mem_available > 0 && mem_available < MEM_LEFT_CRUCIAL) { + WS_HILOGI("mem_available < %{public}d", MEM_LEFT_CRUCIAL); + return COUNT_MEMORY_CRUCIAL; + } + if (mem_available >= MEM_LEFT_CRUCIAL && mem_available < MEM_LEFT_WARNING) { + WS_HILOGI("%{public}d < mem_available < %{public}d", MEM_LEFT_CRUCIAL, MEM_LEFT_WARNING); + return COUNT_MEMORY_WARNING; + } + if (mem_available >= MEM_LEFT_WARNING && mem_available < MEM_LEFT_LOW) { + WS_HILOGI("%{public}d < mem_available < %{public}d", MEM_LEFT_WARNING, MEM_LEFT_LOW); + return COUNT_MEMORY_LOW; + } + WS_HILOGI("memory left normal"); + return COUNT_MEMORY_NORMAL; +} +int32_t MemoryPolicy::Check(int32_t currentIsRunning) +{ + WS_HILOGI("MemoryPolicy::%{public}s(%{public}d)", __func__, currentIsRunning); + int32_t maxRunning = GetMaxRunningCountByMemory(); + return maxRunning > currentIsRunning ? maxRunning : CANNOT_RUNNING_MORE; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/policy/thermal_policy.cpp b/services/native/src/policy/thermal_policy.cpp new file mode 100644 index 0000000..de8053b --- /dev/null +++ b/services/native/src/policy/thermal_policy.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "policy/thermal_policy.h" + +// #include "thermal_mgr_client.h" + +using namespace std; +// using namespace OHOS::PowerMgr; + +namespace OHOS { +namespace WorkScheduler { +ThermalPolicy::ThermalPolicy(shared_ptr workPolicyManager) +{ + workPolicyManager_ = workPolicyManager; +} +ThermalPolicy::~ThermalPolicy() +{ +} +int32_t ThermalPolicy::Check(int32_t currentIsRunning) +{ + WS_HILOGI("ThermalPolicy::%{public}s", __func__); + /* + auto& thermalMgrClient = ThermalMgrClient::GetInstance(); + ThermalLevel thermalLevel = thermalMgrClient.GetThermalLevel(); + switch (thermalLevel) { + case ThermalLevel::COOL: + { + WS_HILOGI("ThermalLevel COOL | WARM"); + current_max_running_count = MAX_RUNNING_COUNT_COOL; + break; + } + case ThermalLevel::WARM: + case ThermalLevel::WARNING: + case ThermalLevel::HOT: + { + WS_HILOGI("ThermalLevel WARNING | HOT"); + current_max_running_count = MAX_RUNNING_COUNT_HOT; + break; + } + case ThermalLevel::OVERHEATED: + case ThermalLevel::EMERGENCY: + { + WS_HILOGI("ThermalLevel OVERHEATED | EMERGENCY"); + current_max_running_count = MAX_RUNNING_COUNT_OVERHEATED; + break; + } + default: + { + break; + } + } */ + // return current_max_running_count > currentIsRunning ? current_max_running_count : CANNOT_RUNNING_MORE; + return 5; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_conn_manager.cpp b/services/native/src/work_conn_manager.cpp new file mode 100644 index 0000000..44c1f5c --- /dev/null +++ b/services/native/src/work_conn_manager.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_conn_manager.h" + +#include +#include "ability_manager_client.h" +#include "work_sched_common.h" + +using namespace std; +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace WorkScheduler { +void WorkConnection::OnWorkStart(shared_ptr workInfo) +{ + WS_HILOGD("OnWorkStart, %{public}s/%{public}s : %{public}d", + workInfo->GetBundleName().c_str(), workInfo->GetAbilityName().c_str(), workInfo->GetWorkId()); + // AbilityManagerClient::GetInstance()->ConnectAbility(); +} + +void WorkConnection::OnWorkStop(shared_ptr workInfo) +{ + WS_HILOGD("OnWorkStop, %{public}s/%{public}s : %{public}d", + workInfo->GetBundleName().c_str(), workInfo->GetAbilityName().c_str(), workInfo->GetWorkId()); +} + +void WorkConnManager::StartWork(shared_ptr workStatus) +{ + WS_HILOGD("StartWork, id: %{public}s, bundleName: %{public}s, abilityName: %{public}s", + workStatus->workId_.c_str(), workStatus->bundleName_.c_str(), workStatus->abilityName_.c_str()); + auto workConn = make_shared(); + connMap_.emplace(workStatus->workId_, workConn); + workConn->OnWorkStart(workStatus->workInfo_); + workStatus->MarkStatus(WorkStatus::Status::RUNNING); +} + +void WorkConnManager::StopWork(shared_ptr workStatus) +{ + WS_HILOGI("StopWork come in, workStatus ID: %{public}s", workStatus->workId_.c_str()); + if (connMap_.count(workStatus->workId_) == 0) { + WS_HILOGD("work id(%{public}s) is not key in connMap_", workStatus->workId_.c_str()); + return; + } + auto workConn = connMap_.at(workStatus->workId_); + WS_HILOGD("work stop: %{public}s/%{public}s id: %{public}s", + workStatus->workInfo_->GetBundleName().c_str(), workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); + workConn->OnWorkStop(workStatus->workInfo_); + connMap_.erase(workStatus->workId_); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_event_handler.cpp b/services/native/src/work_event_handler.cpp new file mode 100644 index 0000000..9403c27 --- /dev/null +++ b/services/native/src/work_event_handler.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_event_handler.h" + +#include "work_sched_common.h" +#include "work_policy_manager.h" + +using namespace std; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace WorkScheduler { +WorkEventHandler::WorkEventHandler(const shared_ptr& runner, + const wptr& service) : EventHandler(runner), service_(service) +{ + WS_HILOGD("WorkEventHandler::WorkEventHandler instance created."); +} + +void WorkEventHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer& event) +{ + WS_HILOGD("WorkEventHandler::%{public}s in", __func__); + auto wssptr = service_.promote(); + if (wssptr == nullptr) { + WS_HILOGE("service.promote() returns nullptr"); + return; + } + WS_HILOGD("WorkEventHandler::%{public}s, eventid = %{public}d", __func__, + event->GetInnerEventId()); + switch (event->GetInnerEventId()) { + case RETRIGGER_MSG: { + wssptr->GetWorkPolicyManager()->CheckWorkToRun(); + break; + } + } +} + +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp new file mode 100644 index 0000000..cbf250e --- /dev/null +++ b/services/native/src/work_policy_manager.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_policy_manager.h" + +#include +#include +#include +#include +#include +#include "bundle_mgr_proxy.h" +#include "work_scheduler_service.h" +#include "work_event_handler.h" + +using namespace std; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace WorkScheduler { +namespace { +const int64_t delayTime = 10000; +} +WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) +{ + conditionReadyQueue_ = std::make_shared(); +} + +bool WorkPolicyManager::Init() +{ + WS_HILOGI("WorkPolicyManager::%{public}s come in", __func__); + workConnManager_ = make_shared(); + auto wmsptr = wss_.promote(); + if (wmsptr == nullptr) { + WS_HILOGE("WorkPolicyManager::%{public}s failed due to wmsptr is nullptr", __func__); + return false; + } + handler_ = wmsptr->GetHandler(); + if (handler_ == nullptr) { + WS_HILOGE("WorkPolicyManager::%{public}s failed due to handler_ is nullptr", __func__); + return false; + } + WS_HILOGD("WorkPolicyManager::%{public}s success", __func__); + return true; +} + +void WorkPolicyManager::AddPolicyFilter(shared_ptr filter) +{ + policyFilters_.emplace_back(filter); +} + +bool WorkPolicyManager::AddWork(shared_ptr workStatus, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s workStatus ID: %{public}s, uid: %{public}d", + __func__, workStatus->workId_.c_str(), uid); + if (uidQueueMap_.count(uid) > 0) { + WS_HILOGD("uidQueue(%{public}d) exists", uid); + if (!uidQueueMap_.at(uid)->Contains(make_shared(workStatus->workId_)) + && uidQueueMap_.at(uid)->GetSize() >= MAX_WORK_COUNT_PER_UID) { + WS_HILOGE("each uid only can be added %{public}d works", MAX_WORK_COUNT_PER_UID); + return false; + } + WS_HILOGI("push workStatus ID: %{public}s to uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); + uidQueueMap_.at(uid)->Push(workStatus); + } else { + WS_HILOGD("uidQueue(%{public}d) not exists, create", uid); + uidQueueMap_.emplace(uid, make_shared()); + WS_HILOGI("push workStatus ID: %{public}s to uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); + uidQueueMap_.at(uid)->Push(workStatus); + } + return true; +} + +bool WorkPolicyManager::RemoveWork(shared_ptr workStatus, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (uidQueueMap_.count(uid) > 0) { + WS_HILOGD("Remove workStatus ID: %{public}s form uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); + return uidQueueMap_.at(uid)->Remove(workStatus); + } + return false; +} + +shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (uidQueueMap_.count(uid) > 0) { + return uidQueueMap_.at(uid)->Find(WorkStatus::MakeWorkId(workInfo.GetWorkId(), uid)); + } + return nullptr; +} + +bool WorkPolicyManager::StopWork(shared_ptr workStatus, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (uidQueueMap_.count(uid) > 0 && uidQueueMap_.at(uid)->StopWork(workStatus)) { + workConnManager_->StopWork(workStatus); + } + CheckWorkToRun(); + return true; +} + +bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (uidQueueMap_.count(uid) > 0) { + bool ret = uidQueueMap_.at(uid)->Remove(workStatus); + return ret; + } + return true; +} + +bool WorkPolicyManager::StopAndClearWorks(int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + bool result = true; + if (uidQueueMap_.count(uid) > 0) { + auto queue = uidQueueMap_.at(uid); + for (auto it : queue->GetWorkList()) { + bool ret = StopWork(it, uid); + ret = ret & CancelWork(it, uid); + if (!ret) { + result = false; + } + } + } + return result; +} + +bool WorkPolicyManager::IsLastWorkTimeout(int32_t workId, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + string workIdStr = WorkStatus::MakeWorkId(workId, uid); + if (uidQueueMap_.count(uid) > 0) { + return uidQueueMap_.at(uid)->Find(workIdStr)->IsLastWorkTimeout(); + } + return false; +} + +void WorkPolicyManager::OnConditionReady(shared_ptr>> workStatusVector) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + for (auto it : *workStatusVector) { + it->MarkStatus(WorkStatus::Status::POLICY_PENDING); + } + conditionReadyQueue_->Push(workStatusVector); + CheckWorkToRun(); +} + +int32_t WorkPolicyManager::GetMaxRunningCount() +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + int32_t currentMaxRunning = IPolicyFilter::MAX_RUNNING_COUNT; + for (auto policyFilter : policyFilters_) { + if (!policyFilter->Check(currentRunningCount)) { + break; + } + } + return currentMaxRunning; +} + +int32_t WorkPolicyManager::GetRunningCount() +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + int32_t count = 0; + auto it = uidQueueMap_.begin(); + while(it != uidQueueMap_.end()) { + count += it->second->GetRunningCount(); + it++; + } + return count; +} + +void WorkPolicyManager::OnPolicyChanged(PolicyType policyType, shared_ptr detectorVal) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + switch (policyType) { + case PolicyType::APP_REMOVED: { + this->RemoveByBundle(detectorVal->strVal); + break; + } + default: {} + } + CheckWorkToRun(); +} + +void WorkPolicyManager::RemoveByBundle(string bundle) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + WS_HILOGE("fail to get system ability mgr."); + return; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + WS_HILOGE("fail to get bundle manager proxy."); + return; + } + sptr bundleMgr = iface_cast(remoteObject); + BundleInfo bundleInfo; + if (bundleMgr->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { + auto ws = wss_.promote(); + for (auto it : uidQueueMap_.at(bundleInfo.uid)->GetWorkList()) { + ws->StopAndCancelWork(*(it->workInfo_)); + } + } +} + +void WorkPolicyManager::CheckWorkToRun() +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + conditionReadyQueue_->RemoveUnReady(); + for (auto it : uidQueueMap_) { + it.second->RemoveUnReady(); + } + std::lock_guard lock(mutex_); + // auto handler = handler_.lock(); + if (handler_ == nullptr) { + WS_HILOGE("handler lock() returns nullptr"); + return; + } + handler_->RemoveEvent(WorkEventHandler::RETRIGGER_MSG); + auto topWork = conditionReadyQueue_->GetWorkToRunByPriority(); + if (topWork == nullptr) { + WS_HILOGD("no condition ready work not running, return."); + return; + } + WS_HILOGD("topWork ID: %{public}s", topWork->workId_.c_str()); + if (GetRunningCount() < GetMaxRunningCount()) { + WS_HILOGD("running count < max running count"); + workConnManager_->StartWork(topWork); + SendRetrigger(1000); + } else { + WS_HILOGD("trigger delay: %{public}lld", delayTime); + SendRetrigger(delayTime); + } + WS_HILOGD("WorkPolicyManager::%{public}s out", __func__); +} + +void WorkPolicyManager::SendRetrigger(int64_t delaytime) { + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + // auto handler = handler_.lock(); + if (handler_ == nullptr) { + return; + } + WS_HILOGD("WorkPolicyManager::%{public}s ,delay = %{public}lld", __func__, + delayTime); + handler_->SendEvent(InnerEvent::Get(WorkEventHandler::RETRIGGER_MSG, 0), delaytime); +} + +list> WorkPolicyManager::ObtainAllWorks(int32_t &uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + list> allWorks; + if (uidQueueMap_.count(uid) > 0) { + auto queue = uidQueueMap_.at(uid); + auto allWorkStatus = queue->GetWorkList(); + for (auto it : allWorkStatus) { + allWorks.emplace_back(it->workInfo_); + } + } + return allWorks; +} + +shared_ptr WorkPolicyManager::GetWorkStatus(int32_t &uid, int32_t &workId) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (uidQueueMap_.count(uid) > 0) { + auto queue = uidQueueMap_.at(uid); + auto workStatus = queue->Find(string("u") + to_string(uid) + "_" + to_string(workId)); + return workStatus->workInfo_; + } + return nullptr; +} + +list> WorkPolicyManager::GetAllWorkStatus(int32_t &uid) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + list> allWorks; + if (uidQueueMap_.count(uid) > 0) { + allWorks = uidQueueMap_.at(uid)->GetWorkList(); + } + return allWorks; +} + +void WorkPolicyManager::Dump(string& result) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + result.append("1. workPolicyManager conditionReadyQueue:\n"); + conditionReadyQueue_->Dump(result); + result.append("\n"); + result.append("2. workPolicyManager uidQueueMap:\n"); + for (auto it : uidQueueMap_) { + result.append("uid: " + std::to_string(it.first) + ":\n"); + it.second->Dump(result); + } +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp new file mode 100644 index 0000000..aae288b --- /dev/null +++ b/services/native/src/work_queue.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_queue.h" +#include "work_condition.h" +#include "work_sched_common.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +vector> WorkQueue::OnConditionChanged(WorkCondition::Type type, + shared_ptr conditionVal) +{ + shared_ptr value = make_shared(); + switch (type) { + case WorkCondition::Type::NETWORK: + case WorkCondition::Type::CHARGER: + case WorkCondition::Type::POWER: + case WorkCondition::Type::BATTERY_STATUS: + case WorkCondition::Type::STORAGE: { + value->enumVal = conditionVal->intVal; + break; + } + case WorkCondition::Type::BATTERY_LEVEL: { + value->intVal = conditionVal->intVal; + break; + } + case WorkCondition::Type::TIMER: { + value->longVal = conditionVal->timeVal; + break; + } + default: {} + } + vector> result; + for (auto it : workList_) { + it->OnConditionChanged(type, value); + if (it->IsReady()) { + result.emplace_back(it); + } + } + return result; +} + +void WorkQueue::Push(shared_ptr>> workStatusVector) +{ + for (auto it : *workStatusVector) { + Push(it); + } + workList_.sort(WorkComp()); +} + +void WorkQueue::Push(shared_ptr workStatus) +{ + if (this->Contains(make_shared(workStatus->workId_))) { + for (auto it : workList_) { + if (it->workId_.compare(workStatus->workId_) == 0) { + it = workStatus; + return; + } + } + return; + } + workList_.push_back(workStatus); +} + +bool WorkQueue::Remove(shared_ptr workStatus) +{ + for (auto it : workList_) { + if (workStatus == it) { + workList_.remove(it); + return true; + } + } + return true; +} + +size_t WorkQueue::GetSize() +{ + return workList_.size(); +} + +bool WorkQueue::Contains(std::shared_ptr workId) +{ + for (auto it : workList_) { + if (workId->compare(it->workId_) == 0) { + return true; + } + } + return false; +} + +shared_ptr WorkQueue::Find(string workId) +{ + for (auto it : workList_) { + if (it->workId_ == workId) { + return it; + } + } + return nullptr; +} + +shared_ptr WorkQueue::GetWorkToRunByPriority() +{ + workList_.sort(WorkComp()); + // shared_ptr workStatus = workList_.front(); + auto work = workList_.begin(); + shared_ptr workStatus = nullptr; + while (work != workList_.end()) { + if ((*work)->GetStatus() == WorkStatus::POLICY_PENDING) { + workStatus = *work; + break; + } + work++; + } + return workStatus; +} + +bool WorkQueue::StopWork(shared_ptr workStatus) +{ + bool ret = false; + for (auto work : workList_) { + if (work->workId_ == workStatus->workId_) { + if (workStatus->IsRepeating()) { + workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } else { + workStatus->MarkStatus(WorkStatus::Status::REMOVED); + } + ret = true; + } + } + RemoveUnReady(); + return ret; +} + +bool WorkQueue::CancelWork(shared_ptr workStatus) +{ + workList_.remove(workStatus); + return true; +} + +list> WorkQueue::GetWorkList() +{ + return workList_; +} + +void WorkQueue::RemoveUnReady() +{ + workList_.remove_if([](shared_ptr value){ + return (value->GetStatus() == WorkStatus::Status::WAIT_CONDITION) + || (value->GetStatus() == WorkStatus::Status::REMOVED);}); +} + +int32_t WorkQueue::GetRunningCount() +{ + int32_t count = 0; + for (shared_ptr work : workList_) { + if (work->IsRunning()) { + count++; + } + } + return count; +} + +void WorkQueue::GetWorkIdStr(string& result) { + for (auto it : workList_) { + result.append(it->workId_ + ", "); + } +} + +void WorkQueue::Dump(string& result) +{ + for (auto it : workList_) { + it->Dump(result); + } +} + +bool WorkComp::operator () (const shared_ptr w1, const shared_ptr w2) +{ + return w1->priority_ >= w2->priority_; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_queue_event_handler.cpp b/services/native/src/work_queue_event_handler.cpp new file mode 100644 index 0000000..7efd6ad --- /dev/null +++ b/services/native/src/work_queue_event_handler.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_queue_event_handler.h" + +#include "work_sched_common.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +WorkQueueEventHandler::WorkQueueEventHandler(const shared_ptr& runner, + shared_ptr manager) : AppExecFwk::EventHandler(runner) +{ + manager_ = manager; + WS_HILOGD("WorkQueueEventHandler::WorkQueueEventHandler instance created."); +} + +void WorkQueueEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::InnerEvent::Pointer& event) +{ + WS_HILOGD("WorkQueueEventHandler::%{public}s, eventId: %{public}d", __func__, event->GetInnerEventId()); + switch(event->GetInnerEventId()) { + case TIMER_TICK: { + manager_->OnConditionChanged(WorkCondition::Type::TIMER, make_shared(0, 0, 0, string())); + SendEvent(AppExecFwk::InnerEvent::Get(TIMER_TICK, 0), 600000); + break; + } + } +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp new file mode 100644 index 0000000..3ce4597 --- /dev/null +++ b/services/native/src/work_queue_manager.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_queue_manager.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +WorkQueueManager::WorkQueueManager(const wptr& wss) : wss_(wss) +{ +} + +bool WorkQueueManager::Init() +{ + return true; +} + +bool WorkQueueManager::AddListener(WorkCondition::Type type, shared_ptr listener) +{ + if (listenerMap_.count(type) > 0) { + return false; + } + listenerMap_.emplace(type, listener); + return true; +} + +bool WorkQueueManager::AddWork(shared_ptr workStatus) +{ + WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + auto map = workStatus->workInfo_->GetConditionMap(); + for (auto it : *map) { + if (queueMap_.count(it.first) == 0) { + queueMap_.emplace(it.first, make_shared()); + listenerMap_.at(it.first)->Start(); + } + queueMap_.at(it.first)->Push(workStatus); + } + return true; +} + +bool WorkQueueManager::RemoveWork(shared_ptr workStatus) +{ + WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + auto map = workStatus->workInfo_->GetConditionMap(); + for (auto it : *map) { + if (queueMap_.count(it.first) > 0) { + queueMap_.at(it.first)->Remove(workStatus); + } + if (queueMap_.count(it.first) == 0) { + listenerMap_.at(it.first)->Stop(); + } + } + return true; +} + +bool WorkQueueManager::StopWork(shared_ptr workStatus) +{ + WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + bool ret = false; + for (auto it : queueMap_) { + ret = ret || it.second->StopWork(workStatus); + } + return ret; +} + +bool WorkQueueManager::CancelWork(shared_ptr workStatus) +{ + WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + bool ret = false; + for (auto it : queueMap_) { + ret = it.second->CancelWork(workStatus); + if (ret) { + RemoveWork(workStatus); + } + } + return ret; +} + +void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + if (queueMap_.count(conditionType) > 0) { + shared_ptr workQueue = queueMap_.at(conditionType); + auto readyWorkVector = workQueue->OnConditionChanged(conditionType, conditionVal); + if (readyWorkVector.size() == 0) { + return; + } + for (auto it : readyWorkVector) { + it->MarkStatus(WorkStatus::Status::CONDITION_READY); + } + auto ws = wss_.promote(); + ws->OnConditionReady(make_shared>>(readyWorkVector)); + } +} + +bool WorkQueueManager::StopAndClearWorks(list> workList) +{ + for (auto &it : workList) { + if (StopWork(it) && CancelWork(it)) { + continue; + } else { + return false; + } + } + return true; +} + +void WorkQueueManager::Dump(string& result) +{ + string conditionType[] = {"workId", "bundle_name", "ability_name", + "network", "charging", "power", "battery_status", "battery_level", + "storage", "timer", "timer_round", "unknown"}; + int size = sizeof(conditionType); + for (auto it : queueMap_) { + int type = it.first; + if (type < size) { + result.append(conditionType[type]); + } else { + result.append(conditionType[size - 1]); + } + result.append(" : "); + result.append("["); + string workIdStr; + it.second->GetWorkIdStr(workIdStr); + result.append(workIdStr); + result.append("]\n"); + } +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/services/native/src/work_scheduler_connection.cpp b/services/native/src/work_scheduler_connection.cpp new file mode 100644 index 0000000..4126284 --- /dev/null +++ b/services/native/src/work_scheduler_connection.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_connection.h" + +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +void WorkSchedulerConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + WS_HILOGI("WorkSchedulerExtension enter"); + proxy_ = (new (std::nothrow) WorkSchedulerProxy(remoteObject)); + proxy_->OnWorkStart(); + WS_HILOGI("WorkSchedulerExtension end"); +} + +void WorkSchedulerConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + WS_HILOGI("WorkSchedulerExtension enter"); + WS_HILOGI("WorkSchedulerExtension end"); +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index f628a6b..72bb5cb 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,14 +14,50 @@ */ #include "work_scheduler_service.h" -#include "work_sched_hilog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "json/json.h" +#include "bundle_mgr_proxy.h" + +#include "conditions/network_listener.h" +#include "conditions/power_listener.h" +#include "conditions/charger_listener.h" +#include "conditions/battery_status_listener.h" +#include "conditions/battery_level_listener.h" +#include "conditions/storage_listener.h" +#include "conditions/timer_listener.h" +#include "policy/thermal_policy.h" +#include "policy/memory_policy.h" +#include "work_sched_common.h" +#include "work_scheduler_connection.h" + +using namespace std; +using namespace OHOS::AppExecFwk; namespace OHOS { namespace WorkScheduler { namespace { const std::string WORKSCHEDULER_SERVICE_NAME = "WorkSchedulerService"; -const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( - DelayedSingleton::GetInstance().get()); +auto wss = DelayedSpSingleton::GetInstance(); +const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(wss.GetRefPtr()); +static const string ALL_INFO = "All"; +static const string WORK_QUEUE_INFO = "WorkQueue"; +static const string WORK_POLICY_INFO = "WorkPolicy"; +static const string EXTENSION = "Extension"; } WorkSchedulerService::WorkSchedulerService() : SystemAbility(WORK_SCHEDULE_SERVICE_ID, true) {} @@ -30,19 +66,374 @@ WorkSchedulerService::~WorkSchedulerService() {} void WorkSchedulerService::OnStart() { - WS_HILOGI(MODULE_SERVICE, "OnStart enter."); + WS_HILOGE("OnStart enter."); if (ready_) { - WS_HILOGI(MODULE_SERVICE, "OnStart is ready, nothing to do."); + WS_HILOGE("OnStart is ready, nothing to do."); return; } + if (!Init()) { + WS_HILOGE("OnStart call init failed!"); + return; + } + + if (!Publish(DelayedSpSingleton::GetInstance())) { + WS_HILOGE("OnStart register to system ability manager failed!"); + return; + } + + list> persistedWorks = ReadPersistedWorks(); + for (auto it : persistedWorks) { + InitPersistedWork(*it); + } + ready_ = true; - WS_HILOGI(MODULE_SERVICE, "OnStart and add system ability success."); + WS_HILOGE("OnStart and add system ability success."); +} + +list> WorkSchedulerService::ReadPersistedWorks() +{ + WS_HILOGD("WorkSchedulerService::%{public}s enter", __func__); + list> workInfos; + ifstream fin; + fin.open(PERSISTED_FILE_PATH, ios::in); + if (!fin.is_open()) { + WS_HILOGE("cannot open file %{public}s", PERSISTED_FILE_PATH); + return workInfos; + } + char buffer[256]; + ostringstream os; + while (!fin.eof()) { + fin.getline(buffer, 256); + os << buffer; + } + string data = os.str(); + JSONCPP_STRING errs; + Json::Value root; + Json::CharReaderBuilder readerBuilder; + const unique_ptr jsonReader(readerBuilder.newCharReader()); + bool res = jsonReader->parse(data.c_str(), data.c_str() + data.length(), &root, &errs); + if (!res || !errs.empty()) { + return workInfos; + } + for (auto it : root.getMemberNames()) { + Json::Value workJson = root[it]; + shared_ptr workInfo = make_shared(); + if (workInfo->ParseFromJson(workJson)) { + workInfos.emplace_back(workInfo); + } + } + return workInfos; } void WorkSchedulerService::OnStop() { - WS_HILOGI(MODULE_SERVICE, "stop service."); + WS_HILOGI("stop service."); + eventRunner_.reset(); + handler_.reset(); +} + +bool WorkSchedulerService::Init() +{ + WS_HILOGE("WorkSchedulerService::Init() come in"); + if (!WorkQueueManagerInit()) { + WS_HILOGE("init failed due to work queue manager init."); + return false; + } + if (!eventRunner_) { + eventRunner_ = AppExecFwk::EventRunner::Create(WORKSCHEDULER_SERVICE_NAME); + } + if (eventRunner_ == nullptr) { + WS_HILOGE("Init failed due to create EventRunner"); + return false; + } + if (!handler_) { + handler_ = std::make_shared(eventRunner_, wss); + WS_HILOGD("handler make shared."); + } + + if (!WorkPolicyManagerInit()) { + WS_HILOGE("init failed due to work policy manager init."); + return false; + } + + WS_HILOGI("init success."); + return true; +} + +bool WorkSchedulerService::WorkQueueManagerInit() +{ + WS_HILOGE("WorkQueueManagerInit come in"); + if (workQueueManager_ == nullptr) { + workQueueManager_ = make_shared(wss); + } + + auto networkListener = make_shared(workQueueManager_); + auto powerListener = make_shared(workQueueManager_); + auto chargerListener = make_shared(workQueueManager_); + auto batteryStatusListener = make_shared(workQueueManager_); + auto batteryLevelListener = make_shared(workQueueManager_); + auto storageListener = make_shared(workQueueManager_); + auto timerListener = make_shared(workQueueManager_); + bool ret = workQueueManager_->AddListener(WorkCondition::Type::NETWORK, networkListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::POWER, powerListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::CHARGER, chargerListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_STATUS, batteryStatusListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_LEVEL, batteryLevelListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::STORAGE, storageListener); + ret = ret && workQueueManager_->AddListener(WorkCondition::Type::TIMER, timerListener); + + WS_HILOGI("work queue manager init success: %{public}s", to_string(ret).c_str()); + return ret; +} + +bool WorkSchedulerService::WorkPolicyManagerInit() +{ + WS_HILOGE("WorkPolicyManagerInit come in"); + if (workPolicyManager_ == nullptr) { + workPolicyManager_ = make_shared(wss); + } + if (!workPolicyManager_->Init()) { + WS_HILOGE("work policy manager init failed!"); + return false; + } + + auto thermalFilter = make_shared(workPolicyManager_); + auto memoryFilter = make_shared(workPolicyManager_); + workPolicyManager_->AddPolicyFilter(thermalFilter); + workPolicyManager_->AddPolicyFilter(memoryFilter); + WS_HILOGI("work policy manager init success."); + return true; +} + +bool WorkSchedulerService::StartWork(WorkInfo& workInfo) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + WS_HILOGD("WorkSchedulerService::%{public}s workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", + __func__, workInfo.GetBundleName().c_str(), workInfo.GetAbilityName().c_str(), workInfo.GetWorkId(), uid); + shared_ptr workStatus = make_shared(workInfo, uid); + if (workInfo.IsPersisted()) { + persistedMap_.emplace(workStatus->workId_, make_shared(workInfo)); + RefreshPersistedWorks(); + } + bool ret = false; + if (workPolicyManager_->AddWork(workStatus, uid)) { + ret = workQueueManager_->AddWork(workStatus); + } else { + WS_HILOGE("WorkPolicyManager->AddWork return false"); + } + return ret; +} + +void WorkSchedulerService::InitPersistedWork(WorkInfo& workInfo) +{ + WS_HILOGD("%{public}s come in", __func__); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + WS_HILOGE("fail to get system ability mgr."); + return; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + WS_HILOGE("fail to get bundle manager proxy."); + return; + } + sptr bundleMgr = iface_cast(remoteObject); + BundleInfo bundleInfo; + if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { + shared_ptr workStatus = make_shared(workInfo, bundleInfo.uid); + if (workPolicyManager_->AddWork(workStatus, bundleInfo.uid)) { + workQueueManager_->AddWork(workStatus); + } + } + WS_HILOGD("%{public}s come out", __func__); +} + +bool WorkSchedulerService::StopWork(WorkInfo& workInfo) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + shared_ptr workStatus = workPolicyManager_->FindWorkStatus(workInfo, uid); + if (workStatus != nullptr && workPolicyManager_->StopWork(workStatus, uid) + && workQueueManager_->StopWork(workStatus)) { + return true; + } + return false; +} + +bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + shared_ptr workStatus = workPolicyManager_->FindWorkStatus(workInfo, uid); + if (workStatus != nullptr && workPolicyManager_->StopWork(workStatus, uid) + && workQueueManager_->StopWork(workStatus)) { + if (workInfo.IsPersisted()) { + persistedMap_.erase(workStatus->workId_); + RefreshPersistedWorks(); + } + return workQueueManager_->CancelWork(workStatus) + && workPolicyManager_->CancelWork(workStatus, uid); + } + return true; +} + +bool WorkSchedulerService::StopAndClearWorks() +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + return workQueueManager_->StopAndClearWorks(workPolicyManager_->GetAllWorkStatus(uid)) + && workPolicyManager_->StopAndClearWorks(uid); +} + +bool WorkSchedulerService::IsLastWorkTimeout(int32_t workId) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + return workPolicyManager_->IsLastWorkTimeout(workId, uid); +} + +void WorkSchedulerService::OnConditionReady(shared_ptr>> workStatusVector) +{ + workPolicyManager_->OnConditionReady(workStatusVector); +} + +list> WorkSchedulerService::ObtainAllWorks(int32_t &uid, int32_t &pid) +{ + return workPolicyManager_->ObtainAllWorks(uid); +} + +shared_ptr WorkSchedulerService::GetWorkStatus(int32_t &uid, int32_t &workId) +{ + return workPolicyManager_->GetWorkStatus(uid, workId); +} + +bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector &dumpInfo) +{ + if (dumpOption[1] == ALL_INFO) { + DumpAllInfo(dumpInfo); + } else if (dumpOption[1] == EXTENSION) { + Want want; + want.SetElementName("com.example.myapplication", "com.example.myapplication.ServiceAbility2"); + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + return false; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); + return false; + } + sptr abilityMgr_ = iface_cast(remoteObject); + if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { + WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); + return false; + } + + sptr connection(new (std::nothrow) WorkSchedulerConnection()); + abilityMgr_->ConnectAbility(want, connection, nullptr); + return true; + } else if (dumpOption[1] == WORK_QUEUE_INFO) { + DumpWorkQueueInfo(dumpInfo); + } else if (dumpOption[1] == WORK_POLICY_INFO) { + DumpWorkPolicyInfo(dumpInfo); + } else { + WS_HILOGI("Dump need right param."); + dumpInfo.push_back(string("dump need right param.")); + return false; + } + return true; +} + +void WorkSchedulerService::DumpWorkQueueInfo(vector &dumpInfo) +{ + string workQueueInfo; + workQueueInfo.append("================Work Queue Infos================\n"); + if (workQueueManager_ != nullptr) { + workQueueManager_->Dump(workQueueInfo); + dumpInfo.push_back(workQueueInfo); + } +} + +void WorkSchedulerService::DumpWorkPolicyInfo(vector &dumpInfo) +{ + string workPolicyInfo; + workPolicyInfo.append("================Work Policy Infos================\n"); + if (workPolicyManager_ != nullptr) { + workPolicyManager_->Dump(workPolicyInfo); + dumpInfo.push_back(workPolicyInfo); + } +} + +void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) +{ + DumpWorkQueueInfo(dumpInfo); + DumpWorkPolicyInfo(dumpInfo); +} + +void WorkSchedulerService::RefreshPersistedWorks() +{ + WS_HILOGD("%{public}s come in", __func__); + Json::Value root; + for (auto &it : persistedMap_) { + auto workInfo = it.second; + string data = workInfo->ParseToJsonStr(); + JSONCPP_STRING errs; + Json::Value workJson; + Json::CharReaderBuilder readerBuilder; + const unique_ptr jsonReader(readerBuilder.newCharReader()); + bool res = jsonReader->parse(data.c_str(), data.c_str() + data.length(), &workJson, &errs); + if (res && errs.empty()) { + root[it.first] = workJson; + } + } + Json::StreamWriterBuilder writerBuilder; + ostringstream os; + unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + jsonWriter->write(root, &os); + string result = os.str(); + WS_HILOGD("Work JSON os result %{public}s", result.c_str()); + CreateNodeDir(PERSISTED_PATH); + CreateNodeFile(PERSISTED_FILE_PATH); + ofstream fout; + fout.open(PERSISTED_FILE_PATH, ios::out); + fout<workInfo_ = make_shared(workInfo); + this->workId_ = MakeWorkId(workInfo.GetWorkId(), uid); + this->bundleName_ = workInfo.GetBundleName(); + this->abilityName_ = workInfo.GetAbilityName(); + this->baseTime_ = getCurrentTime(); + if (workInfo.GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { + auto workTimerCondition = workInfo.GetConditionMap()->at(WorkCondition::Type::TIMER); + if (workTimerCondition->boolVal) { + shared_ptr timeCondition = make_shared(); + timeCondition->uintVal = workTimerCondition->uintVal; + if (workTimerCondition->boolVal) { + timeCondition->intVal = 1; + } else { + timeCondition->intVal = workTimerCondition->intVal; + } + conditionMap_.emplace(WorkCondition::Type::TIMER, timeCondition); + } + } + if (workInfo.GetConditionMap()->count(WorkCondition::Type::CHARGER) > 0) { + shared_ptr chargerCondition = make_shared(); + chargerCondition->enumVal = -1; + BatteryPluggedType pluggedType = BatterySrvClient::GetInstance().GetPluggedType(); + switch(pluggedType) { + case BatteryPluggedType::PLUGGED_TYPE_NONE: + chargerCondition->boolVal = false; + chargerCondition->enumVal = WorkCondition::Charger::CHARGER_UNPLUGGED; + break; + case BatteryPluggedType::PLUGGED_TYPE_AC: + chargerCondition->boolVal = true; + chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_AC; + break; + case BatteryPluggedType::PLUGGED_TYPE_USB: + chargerCondition->boolVal = true; + chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_USB; + break; + case BatteryPluggedType::PLUGGED_TYPE_WIRELESS: + chargerCondition->boolVal = true; + chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS; + break; + default: + break; + } + if (chargerCondition->enumVal != -1) { + conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); + } + } + this->persisted_ = workInfo.IsPersisted(); + this->priority_ = DEFAULT_PRIORITY; + this->currentStatus_ = WAIT_CONDITION; +} + +WorkStatus::~WorkStatus() +{ +} + +void WorkStatus::OnConditionChanged(WorkCondition::Type &type, shared_ptr value) +{ + if (workInfo_->GetConditionMap()->count(type) > 0) { + if (conditionMap_.count(type) > 0) { + conditionMap_.at(type) = value; + } else { + conditionMap_.emplace(type, value); + } + } + if (IsReady()) { + MarkStatus(Status::CONDITION_READY); + } +} + +string WorkStatus::MakeWorkId(int32_t workId, int32_t uid) +{ + return string("u") + to_string(uid) + "_" + to_string(workId); +} + +void WorkStatus::MarkTimeout() +{ + lastTimeout_ = true; +} + +void WorkStatus::MarkStatus(Status status) +{ + currentStatus_ = status; + WS_HILOGD("WorkStatus::%{public}s, ID: %{public}s mark status to: %{public}d", __func__, workId_.c_str(), status); + if (status == Status::RUNNING) { + if (workInfo_->GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { + auto workTimerCondition = workInfo_->GetConditionMap()->at(WorkCondition::Type::TIMER); + if (workTimerCondition->boolVal) { + if (workTimerCondition->boolVal) { + workTimerCondition->intVal = 1; + } else { + workTimerCondition->intVal--; + } + } + } + } +} + +void WorkStatus::MarkRound() +{ + +} + +bool WorkStatus::IsReady() +{ + auto workConditionMap = workInfo_->GetConditionMap(); + for (auto it : *workConditionMap) { + if (conditionMap_.count(it.first) > 0) { + switch (it.first) { + case WorkCondition::Type::NETWORK: + case WorkCondition::Type::BATTERY_STATUS: + case WorkCondition::Type::STORAGE: { + if (workConditionMap->at(it.first)->enumVal != conditionMap_.at(it.first)->enumVal) { + return false; + } + break; + } + case WorkCondition::Type::CHARGER: { + auto conditionSet = workConditionMap->at(it.first); + auto conditionCurrent = conditionMap_.at(it.first); + if (conditionSet->boolVal) { + if (conditionCurrent->enumVal != conditionSet->enumVal + && conditionSet->enumVal != static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY)) { + return false; + } + } else { + if (conditionCurrent->enumVal != static_cast(WorkCondition::Charger::CHARGER_UNPLUGGED)) { + return false; + } + } + break; + } + case WorkCondition::Type::BATTERY_LEVEL: { + if (workConditionMap->at(it.first)->intVal > PowerMgr::BatterySrvClient::GetInstance().GetCapacity()) { + return false; + } + break; + } + case WorkCondition::Type::TIMER: { + bool repeat = workConditionMap->at(WorkCondition::Type::TIMER)->boolVal; + int32_t cycleLeft = workConditionMap->at(WorkCondition::Type::TIMER)->intVal; + if (!repeat) { + if (cycleLeft == 0) { + return false; + } + } + uint32_t intervalTime = workConditionMap->at(WorkCondition::Type::TIMER)->uintVal; + if (baseTime_ + static_cast(intervalTime) >= getCurrentTime()) { + return false; + } + break; + } + default: + break; + } + } else { + return false; + } + } + return true; +} + +bool WorkStatus::IsRunning() +{ + return currentStatus_ == RUNNING; +} + +bool WorkStatus::IsLastWorkTimeout() +{ + return lastTimeout_; +} + +bool WorkStatus::IsRepeating() +{ + if (workInfo_->GetConditionMap()->at(WorkCondition::Type::TIMER)->boolVal) { + return true; + } else { + return workInfo_->GetConditionMap()->at(WorkCondition::Type::TIMER)->intVal > 0; + } +} + +WorkStatus::Status WorkStatus::GetStatus() +{ + return currentStatus_; +} + +void WorkStatus::Dump(string& result) +{ + result.append("{\n"); + result.append(string("\"workId\":") + workId_ + ",\n"); + result.append(string("\"bundleName\":") + bundleName_ + ",\n"); + result.append(string("\"priority\":") + to_string(priority_) + ",\n"); + result.append(string("\"isPersisted\":") + to_string(persisted_) + ",\n"); + result.append(string("\"conditionMap\":{\n")); + if (conditionMap_.count(WorkCondition::Type::NETWORK) > 0) { + result.append(string("\"networkType\":") + to_string(conditionMap_.at(WorkCondition::Type::NETWORK)->enumVal) + ",\n"); + } + if (conditionMap_.count(WorkCondition::Type::CHARGER) > 0) { + result.append(string("\"isCharging\":") + (conditionMap_.at(WorkCondition::Type::CHARGER)->boolVal ? "true" : "false") + ",\n"); + result.append(string("\"chargerType\":") + to_string(conditionMap_.at(WorkCondition::Type::CHARGER)->enumVal) + ",\n"); + } + if (conditionMap_.count(WorkCondition::Type::BATTERY_LEVEL) > 0) { + result.append(string("\"batteryLevel\":") + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal) + ",\n"); + } + if (conditionMap_.count(WorkCondition::Type::BATTERY_STATUS) > 0) { + result.append(string("\"batteryStatus\":") + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_STATUS)->enumVal) + ",\n"); + } + if (conditionMap_.count(WorkCondition::Type::STORAGE) > 0) { + result.append(string("\"storageLevel\":") + to_string(conditionMap_.at(WorkCondition::Type::STORAGE)->enumVal) + ",\n"); + } + result.append("},\n\"workInfo\":\n"); + workInfo_->Dump(result); + result.append("}\n"); + WS_HILOGD("%s", result.c_str()); +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/native/test/BUILD.gn b/services/native/test/BUILD.gn new file mode 100644 index 0000000..3b7a21e --- /dev/null +++ b/services/native/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +group("worksched_native_test") { + testonly = true + deps = [ "unittest:unittest_service" ] +} diff --git a/services/native/test/unittest/BUILD.gn b/services/native/test/unittest/BUILD.gn new file mode 100644 index 0000000..083a5c6 --- /dev/null +++ b/services/native/test/unittest/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +module_output_path = "${worksched_native_part_name}/worksched_native" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${worksched_service_path}/zidl/include", + ] +} + +ohos_unittest("test_workscheduler") { + module_out_path = module_output_path + sources = [ "src/workscheduler_test.cpp" ] + configs = [ ":module_private_config" ] + deps = [ + "${worksched_frameworks_path}:workschedclient", + "${worksched_service_path}:workschedservice", + "${worksched_utils_path}:workschedutils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "resourceschedule" + part_name = "${worksched_native_part_name}" +} + +group("unittest_service") { + testonly = true + deps = [ ":test_workscheduler" ] +} diff --git a/services/native/test/unittest/include/workscheduler_test.h b/services/native/test/unittest/include/workscheduler_test.h new file mode 100644 index 0000000..73fdd2b --- /dev/null +++ b/services/native/test/unittest/include/workscheduler_test.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKINFO_TEST_H +#define WORKINFO_TEST_H + +#include + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKINFO_TEST_H \ No newline at end of file diff --git a/services/native/test/unittest/src/workscheduler_test.cpp b/services/native/test/unittest/src/workscheduler_test.cpp new file mode 100644 index 0000000..5b869b1 --- /dev/null +++ b/services/native/test/unittest/src/workscheduler_test.cpp @@ -0,0 +1,482 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "workscheduler_test.h" + +#include +#include +#include +#include +#include + +#include "want.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "iwork_sched_service.h" +#include "work_scheduler_service.h" +#include "workscheduler_srv_client.h" +using namespace testing::ext; +using namespace OHOS::WorkScheduler; +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +using namespace OHOS; +using namespace std; + +void WorkSchedulerTest::SetUpTestCase(void) +{ +} + +void WorkSchedulerTest::TearDownTestCase(void) +{ +} + +void WorkSchedulerTest::SetUp() +{ +} + +void WorkSchedulerTest::TearDown() +{ +} + +/** + * @tc.name WorkSchedulerTest001 + * @tc.desc WorkScheduler start & stopAndCancel work info with CHARGER_CHARGING + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest001, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST001 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST001 come out"); +} + +/** + * @tc.name WorkSchedulerTest002 + * @tc.desc WorkScheduler start & stopAndCancel work info with CHARGER_DISCHARGING + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest002, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST002 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_DISCHARGING); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST002 come out"); +} + +/** + * @tc.name WorkSchedulerTest003 + * @tc.desc WorkScheduler start & stop work info with BATTERY_CHANGED + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest003, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST003 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_CHANGED); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST003 come out"); +} + +/** + * @tc.name WorkSchedulerTest004 + * @tc.desc WorkScheduler start & stop work info with BATTERY_LOW + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest004, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST004 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST004 come out"); +} + +/** + * @tc.name WorkSchedulerTest005 + * @tc.desc WorkScheduler start & stop work info with BATTERY_OKEY + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest005, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST005 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_OKEY); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST005 come out"); +} + +/** + * @tc.name WorkSchedulerTest006 + * @tc.desc WorkScheduler start & stop work info with STORAGE_FULL + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest006, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST006 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST006 come out"); +} + +/** + * @tc.name WorkSchedulerTest007 + * @tc.desc WorkScheduler start & stop work info with STORAGE_LOW + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest007, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST007 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST007 come out"); +} + +/** + * @tc.name WorkSchedulerTest008 + * @tc.desc WorkScheduler start & stop work info with STORAGE_OK + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchdulerTest008, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST008 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + bool stopRet = wsc.StopAndCancelWork(workInfo); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST008 come out"); +} + +/** + * @tc.name WorkSchedulerTest009 + * @tc.desc Test WorkSchedulerService#ObtainAllWorks() when app has 1 work in queue + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest009, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST009 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 1); + bool stopRet = wsc.StopAndClearWorks(); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST009 come out"); +} + +/** + * @tc.name WorkSchedulerTest010 + * @tc.desc Test WorkSchedulerService#ObtainAllWorks() when app has 3 works in queue + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest010, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST010 come in"); + WorkInfo workInfo1 = WorkInfo(); + workInfo1.SetWorkId(1); + workInfo1.SetElement("com.test.bundlename", "abilityname"); + workInfo1.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); + WorkInfo workInfo2 = WorkInfo(); + workInfo2.SetWorkId(2); + workInfo2.SetElement("com.test.bundlename", "abilityname"); + workInfo2.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); + WorkInfo workInfo3 = WorkInfo(); + workInfo3.SetWorkId(3); + workInfo3.SetElement("com.test.bundlename", "abilityname"); + workInfo3.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet1 = wsc.StartWork(workInfo1); + EXPECT_TRUE(startRet1); + bool startRet2 = wsc.StartWork(workInfo2); + EXPECT_TRUE(startRet2); + bool startRet3 = wsc.StartWork(workInfo3); + EXPECT_TRUE(startRet3); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 3); + bool stopRet = wsc.StopAndClearWorks(); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST010 come out"); +} + +/** + * @tc.name WorkSchedulerTest011 + * @tc.desc Test WorkSchedulerService#StopWork + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest011, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST011 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + shared_ptr want = make_shared(); + want->SetAction(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); + shared_ptr event = make_shared(*want); + auto publishResult = CommonEventManager::PublishCommonEvent(*event); + EXPECT_TRUE(publishResult); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 1); + bool stopRet = wsc.StopWork(workInfo); + EXPECT_TRUE(stopRet); + bool ret = wsc.StopAndClearWorks(); + EXPECT_TRUE(ret); + WS_HILOGD(MODULE_SERVICE, "TEST011 come out"); +} + +/** + * @tc.name WorkSchedulerTest012 + * @tc.desc Test WorkSchedulerService#ObtainAllWorks will get the same workInfo + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest012, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST012 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 1); + auto work = list.back(); + EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); + EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); + EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); + bool stopRet = wsc.StopWork(workInfo); + EXPECT_TRUE(stopRet); + bool ret = wsc.StopAndClearWorks(); + EXPECT_TRUE(ret); + WS_HILOGD(MODULE_SERVICE, "TEST012 come out"); +} + +/** + * @tc.name WorkSchedulerTest013 + * @tc.desc Test WorkSchedulerService#ObtainAllWorks will get the same workInfo + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest013, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST013 come in"); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(1); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 1); + auto work = list.back(); + EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); + EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); + EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); + EXPECT_EQ(work->GetBatteryStatus(), workInfo.GetBatteryStatus()); + WS_HILOGD(MODULE_SERVICE, "TEST013 BF call StopWork"); + bool stopRet = wsc.StopWork(workInfo); + WS_HILOGD(MODULE_SERVICE, "TEST013 AF call StopWork returns: %{public}s", stopRet ? "true" : "false"); + EXPECT_TRUE(stopRet); + WS_HILOGD(MODULE_SERVICE, "TEST013 BF call StopAndClearWorks"); + bool ret = wsc.StopAndClearWorks(); + WS_HILOGD(MODULE_SERVICE, "TEST013 AF call StopAndClearWorks returns: %{public}s", ret ? "true" : "false"); + EXPECT_TRUE(ret); + WS_HILOGD(MODULE_SERVICE, "TEST013 come out"); +} + +/** + * @tc.name WorkSchedulerTest014 + * @tc.desc Test WorkSchedulerService#RequestPersisted true to set persisted work + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest014, TestSize.Level0) +{ + WS_HILOGD(MODULE_SERVICE, "TEST014 come in"); + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + int32_t workId = wsc.ObtainAllWorks().size() + 1; + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(workId); + workInfo.SetElement("com.test.bundlename", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); + workInfo.RequestPersisted(true); + bool startRet = wsc.StartWork(workInfo); + EXPECT_TRUE(startRet); + auto list = wsc.ObtainAllWorks(); + EXPECT_TRUE(list.size() == 1); + auto work = list.back(); + EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); + EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); + EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); + EXPECT_EQ(work->GetBatteryStatus(), workInfo.GetBatteryStatus()); + bool stopRet = wsc.StopWork(workInfo); + EXPECT_TRUE(stopRet); + bool ret = wsc.StopAndClearWorks(); + EXPECT_TRUE(ret); + WS_HILOGD(MODULE_SERVICE, "TEST014 come out"); +} + +/** + * @tc.name WorkSchedulerTest015 + * @tc.desc Test WorkSchedulerService + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest015, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WorkSchedulerTest015 enter"; + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + int32_t workId = wsc.ObtainAllWorks().size() + 1; + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(workId); + workInfo.SetElement("ohos.samples.flashlight", "abilityname"); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); + workInfo.RequestPersisted(true); + bool startRet = wsc.StartWork(workInfo); + WS_HILOGD(MODULE_SERVICE, "TEST015 StartWork result: %{public}s", startRet ? "TRUE" : "FALSE"); + EXPECT_TRUE(startRet); + auto list = wsc.ObtainAllWorks(); + WS_HILOGD(MODULE_SERVICE, "TEST015 obtain all works size: %{public}d", list.size()); + EXPECT_TRUE(list.size() > 0); + bool stopRet = wsc.StopWork(workInfo); + EXPECT_TRUE(stopRet); + bool ret = wsc.StopAndClearWorks(); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "WorkSchedulerTest015 return"; +} + +/** + * @tc.name WorkSchedulerTest016 + * @tc.desc Test WorkSchedulerService + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest016, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WorkSchedulerTest016 enter"; + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + WorkInfo workInfo_0 = WorkInfo(); + workInfo_0.SetWorkId(0); + workInfo_0.SetElement("ohos.samples.demo", "abilityName0"); + workInfo_0.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); + WorkInfo workInfo_1 = WorkInfo(); + workInfo_1.SetWorkId(1); + workInfo_1.SetElement("ohos.samples.demo", "abilityName1"); + workInfo_1.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); + bool startRet0 = wsc.StartWork(workInfo_0); + EXPECT_TRUE(startRet0); + bool startRet1 = wsc.StartWork(workInfo_1); + EXPECT_TRUE(startRet1); + shared_ptr want = make_shared(); + want->SetAction(CommonEventSupport::COMMON_EVENT_CHARGING); + shared_ptr event = make_shared(*want); + auto publishResult = CommonEventManager::PublishCommonEvent(*event); + EXPECT_TRUE(publishResult); + GTEST_LOG_(INFO) << "Send COMMON_EVENT_CHARGING already"; + GTEST_LOG_(INFO) << "sleep 6 sec..."; + sleep(6); + GTEST_LOG_(INFO) << "workInfo_0 call stop work"; + bool stopRet0 = wsc.StopWork(workInfo_0); + EXPECT_TRUE(stopRet0); + GTEST_LOG_(INFO) << "sleep 10 sec..."; + sleep(10); + GTEST_LOG_(INFO) << "workInfo_1 call stop work"; + bool stopRet1 = wsc.StopWork(workInfo_1); + EXPECT_TRUE(stopRet1); + sleep(4); + bool ret = wsc.StopAndClearWorks(); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "WorkSchedulerTest016 return"; +} + +/** + * @tc.name WorkSchedulerTest017 + * @tc.desc Test WorkSchedulerService + * @tc.type FUNC + */ +HWTEST_F (WorkSchedulerTest, WorkSchedulerTest017, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WorkSchedulerTest017 enter"; + auto& wsc = WorkSchedulerSrvClient::GetInstance(); + WorkInfo workInfo = WorkInfo(); + workInfo.SetWorkId(0); + workInfo.SetElement("com.samples.demo", "abilityName"); + workInfo.RequestRepeatCycle(600); + bool ret = wsc.StartWork(workInfo); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "sleep 70s..."; + sleep(70); + wsc.StopAndCancelWork(workInfo); + GTEST_LOG_(INFO) << "Stop and clear workInfo"; + EXPECT_TRUE(ret); + sleep(25); + GTEST_LOG_(INFO) << "WorkSchedulerTest017 END"; +} \ No newline at end of file diff --git a/services/zidl/include/work_conn_proxy.h b/services/zidl/include/work_conn_proxy.h new file mode 100644 index 0000000..5cd2eab --- /dev/null +++ b/services/zidl/include/work_conn_proxy.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_WORK_CONN_PROXY_H +#define WORKSCHED_ZIDL_WORK_CONN_PROXY_H + +#include +#include + +#include "iwork_conn.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkConnProxy : public IRemoteProxy { +public: + explicit WorkConnProxy(const sptr& impl) : IRemoteProxy(impl) {} + ~WorkConnProxy() = default; + DISALLOW_COPY_AND_MOVE(WorkConnProxy); + + virtual void OnWorkStart(WorkInfo& workInfo); + virtual void OnWorkStop(WorkInfo& workInfo); +private: + static inline BrokerDelegator delegator_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_WORK_CONN_PROXY_H \ No newline at end of file diff --git a/services/zidl/include/work_conn_stub.h b/services/zidl/include/work_conn_stub.h new file mode 100644 index 0000000..4a1947e --- /dev/null +++ b/services/zidl/include/work_conn_stub.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_WORK_CONN_STUB_H +#define WORKSCHED_ZIDL_WORK_CONN_STUB_H + +#include +#include + +#include "iwork_conn.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkConnStub : public IRemoteStub { +public: + WorkConnStub() = default; + virtual ~WorkConnStub() = default; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + DISALLOW_COPY_AND_MOVE(WorkConnStub); + + int32_t OnWorkStartStub(MessageParcel& data); + int32_t OnWorkStopStub(MessageParcel& data); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_WORK_CONN_STUB_H \ No newline at end of file diff --git a/services/zidl/include/work_sched_service_proxy.h b/services/zidl/include/work_sched_service_proxy.h new file mode 100644 index 0000000..e5fe6bf --- /dev/null +++ b/services/zidl/include/work_sched_service_proxy.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H +#define WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H + +#include +#include +#include + +#include "iwork_sched_service.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedServiceProxy : public IRemoteProxy { +public: + explicit WorkSchedServiceProxy(const sptr& impl) : + IRemoteProxy(impl) {} + ~WorkSchedServiceProxy() = default; + DISALLOW_COPY_AND_MOVE(WorkSchedServiceProxy); + + virtual bool StartWork(WorkInfo& workInfo) override; + virtual bool StopWork(WorkInfo& workInfo) override; + virtual bool StopAndCancelWork(WorkInfo& workInfo) override; + virtual bool StopAndClearWorks() override; + virtual bool IsLastWorkTimeout(int32_t workId) override; + virtual std::list> ObtainAllWorks(int32_t &uid, int32_t &pid) override; + virtual std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workId) override; + virtual bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H \ No newline at end of file diff --git a/services/zidl/include/work_sched_service_stub.h b/services/zidl/include/work_sched_service_stub.h new file mode 100644 index 0000000..611fc41 --- /dev/null +++ b/services/zidl/include/work_sched_service_stub.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H +#define WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H + +#include +#include +#include +#include + +#include "iwork_sched_service.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedServiceStub : public IRemoteStub { +public: + WorkSchedServiceStub() = default; + virtual ~WorkSchedServiceStub() = default; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + DISALLOW_COPY_AND_MOVE(WorkSchedServiceStub); + + int32_t StartWorkStub(MessageParcel& data); + int32_t StopWorkStub(MessageParcel& data); + int32_t StopAndCancelWorkStub(MessageParcel& data); + int32_t StopAndClearWorksStub(MessageParcel& data); + int32_t IsLastWorkTimeoutStub(MessageParcel& data); + std::list> ObtainAllWorksStub(MessageParcel& data); + std::shared_ptr GetWorkStatusStub(MessageParcel& data); +private: + ErrCode ShellDumpStub(MessageParcel& data, MessageParcel& reply); +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H \ No newline at end of file diff --git a/services/zidl/include/work_scheduler_proxy.h b/services/zidl/include/work_scheduler_proxy.h new file mode 100644 index 0000000..7000074 --- /dev/null +++ b/services/zidl/include/work_scheduler_proxy.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ZIDL_WORK_SCHED_PROXY_H +#define OHOS_ZIDL_WORK_SCHED_PROXY_H + +#include +#include "iwork_scheduler.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerProxy : public IRemoteProxy { +public: + explicit WorkSchedulerProxy(const sptr& remote) + : IRemoteProxy(remote) {} + + virtual ~WorkSchedulerProxy() {} + + void OnWorkStart() override; + + void OnWorkStop() override; + +private: + static constexpr int COMMAND_ON_WORK_START = MIN_TRANSACTION_ID; + static constexpr int COMMAND_ON_WORK_STOP = MIN_TRANSACTION_ID + 1; + + static inline BrokerDelegator delegator_; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // OHOS_ZIDL_WORK_SCHED_PROXY_H + diff --git a/services/zidl/include/work_scheduler_stub.h b/services/zidl/include/work_scheduler_stub.h new file mode 100644 index 0000000..72badc3 --- /dev/null +++ b/services/zidl/include/work_scheduler_stub.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ZIDL_WORK_SCHED_STUB_H +#define OHOS_ZIDL_WORK_SCHED_STUB_H + +#include +#include "iwork_scheduler.h" +#include "work_scheduler_extension.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerStub : public IRemoteStub { +public: + WorkSchedulerStub() {} + + virtual ~WorkSchedulerStub() {} + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +private: + static constexpr int COMMAND_ON_WORK_START = MIN_TRANSACTION_ID; + static constexpr int COMMAND_ON_WORK_STOP = MIN_TRANSACTION_ID + 1; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // OHOS_ZIDL_WORK_SCHED_STUB_H + diff --git a/services/zidl/include/work_scheduler_stub_imp.h b/services/zidl/include/work_scheduler_stub_imp.h new file mode 100644 index 0000000..9e32e07 --- /dev/null +++ b/services/zidl/include/work_scheduler_stub_imp.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ZIDL_WORK_SCHED_STUB_IMP_H +#define OHOS_ZIDL_WORK_SCHED_STUB_IMP_H + +#include +#include "js_work_scheduler_extension.h" +#include "work_scheduler_stub.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +// using AbilityRuntime::JsWorkSchedulerExtension; +class WorkSchedulerStubImp : public WorkSchedulerStub { +public: + explicit WorkSchedulerStubImp(const std::shared_ptr& extension) + : extension_(extension) {} + + virtual ~WorkSchedulerStubImp() {} + + void OnWorkStart() override; + + void OnWorkStop() override; +private: + std::weak_ptr extension_; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // OHOS_ZIDL_WORK_SCHED_STUB_IMP_H + diff --git a/services/zidl/src/work_conn_proxy.cpp b/services/zidl/src/work_conn_proxy.cpp new file mode 100644 index 0000000..f2882d9 --- /dev/null +++ b/services/zidl/src/work_conn_proxy.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_conn_proxy.h" + +#include +#include +#include + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +void WorkConnProxy::OnWorkStart(WorkInfo& workInfo) +{ + sptr remote = Remote(); + RETURN_IF(remote == nullptr); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkConnProxy::GetDescriptor())) { + WS_HILOGE("WorkConnProxy::%{public}s write descriptor failed!", __func__); + return; + } + + WRITE_PARCEL_WITHOUT_RET(data, Parcelable, &workInfo); + + int ret = remote->SendRequest(static_cast(IWorkConn::ON_WORK_START), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkConnProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret); + return; + } +} + +void WorkConnProxy::OnWorkStop(WorkInfo& workInfo) +{ + sptr remote = Remote(); + RETURN_IF(remote == nullptr); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkConnProxy::GetDescriptor())) { + WS_HILOGE("WorkConnProxy::%{public}s write descriptor failed!", __func__); + return; + } + + WRITE_PARCEL_WITHOUT_RET(data, Parcelable, &workInfo); + + int ret = remote->SendRequest(static_cast(IWorkConn::ON_WORK_STOP), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkConnProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret); + return; + } +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/zidl/src/work_conn_stub.cpp b/services/zidl/src/work_conn_stub.cpp new file mode 100644 index 0000000..0c57ac4 --- /dev/null +++ b/services/zidl/src/work_conn_stub.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_conn_stub.h" + +#include + +#include "work_sched_common.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +int WorkConnStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WS_HILOGD("WorkConnStub::OnRemoteRequest, cmd = %u, flags = %d", code, option.GetFlags()); + u16string descriptor = WorkConnStub::GetDescriptor(); + u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + WS_HILOGE("WorkConnStub::OnRemoteRequest failed, descriptor is not matched!"); + return E_GET_WORKSCHED_SERVICE_FALIED; + } + + switch (code) { + case static_cast(IWorkConn::ON_WORK_START): { + return OnWorkStartStub(data); + } + case static_cast(IWorkConn::ON_WORK_STOP): { + return OnWorkStopStub(data); + } + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + + return ERR_OK; +} + +int32_t WorkConnStub::OnWorkStartStub(MessageParcel& data) +{ + return ERR_OK; +} + +int32_t WorkConnStub::OnWorkStopStub(MessageParcel& data) +{ + return ERR_OK; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp new file mode 100644 index 0000000..88d6d14 --- /dev/null +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_sched_service_proxy.h" + +#include +#include +#include + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +bool WorkSchedServiceProxy::StartWork(WorkInfo& workInfo) +{ + WS_HILOGI("proxy Call StartWork come in"); + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return false; + } + + WRITE_PARCEL_WITH_RET(data, Parcelable, &workInfo, false); + + int ret = remote->SendRequest(static_cast(IWorkSchedService::START_WORK), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, error code: %{public}d", __func__, ret); + return false; + } + bool result = false; + READ_PARCEL_WITH_RET(reply, Bool, result, false); + WS_HILOGE("after result : %{public}s ", std::to_string(result).c_str()); + return result; +} + +bool WorkSchedServiceProxy::StopWork(WorkInfo& workInfo) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return false; + } + + WRITE_PARCEL_WITH_RET(data, Parcelable, &workInfo, false); + + int ret = remote->SendRequest(static_cast(IWorkSchedService::STOP_WORK), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return false; + } + bool result = false; + READ_PARCEL_WITH_RET(reply, Bool, result, false); + return result; +} + +bool WorkSchedServiceProxy::StopAndCancelWork(WorkInfo& workInfo) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return false; + } + + WRITE_PARCEL_WITH_RET(data, Parcelable, &workInfo, false); + int ret = remote->SendRequest(static_cast(IWorkSchedService::STOP_AND_CANCEL_WORK), data, reply, option); + + if (ret != ERR_OK) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return false; + } + bool result = false; + READ_PARCEL_WITH_RET(reply, Bool, result, false); + return result; +} + +bool WorkSchedServiceProxy::StopAndClearWorks() +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return false; + } + + int ret = remote->SendRequest(static_cast(IWorkSchedService::STOP_AND_CLEAR_WORKS), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return false; + } + bool result = false; + READ_PARCEL_WITH_RET(reply, Bool, result, false); + return result; +} + +bool WorkSchedServiceProxy::IsLastWorkTimeout(int32_t workId) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return false; + } + + WRITE_PARCEL_WITHOUT_RET(data, Int32, workId); + int ret = remote->SendRequest(static_cast(IWorkSchedService::IS_LAST_WORK_TIMEOUT), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return false; + } + bool result = false; + READ_PARCEL_WITH_RET(reply, Bool, result, false); + return result; +} + +std::list> WorkSchedServiceProxy::ObtainAllWorks(int32_t &uid, int32_t &pid) +{ + WS_HILOGD("BUGOAWF function %{public}s invoked.", __func__); + WS_HILOGD("%{public}s uid: %{public}d, pid: %{public}d", __func__, uid, pid); + std::list> workInfos; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, workInfos); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("WorkSchedServiceProxy::%{public}s write descriptor failed!", __func__); + return workInfos; + } + + WRITE_PARCEL_WITHOUT_RET(data, Int32, uid); + WRITE_PARCEL_WITHOUT_RET(data, Int32, pid); + + WS_HILOGD("BUGOAWF static_cast to int OBTAIN_ALL_WORKS: %{public}d", static_cast(IWorkSchedService::OBTAIN_ALL_WORKS)); + WS_HILOGD("BUGOAWF SendRequest code: %{public}d, uint: %{public}u", static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), static_cast(IWorkSchedService::OBTAIN_ALL_WORKS)); + int ret = remote->SendRequest(static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return workInfos; + } + + int32_t worksize = 0; + READ_PARCEL_WITHOUT_RET(reply, Int32, worksize); + WS_HILOGD("BUGOAWF WSSP ObtainAllWorks worksize from read parcel is: %{public}d", worksize); + for (int32_t i = 0; i < worksize; i++) { + WorkInfo *workInfo; + workInfo = reply.ReadParcelable(); + WS_HILOGD("WP read from parcel, workInfo ID: %{public}d", workInfo->GetWorkId()); + workInfos.emplace_back(std::make_shared(*workInfo)); + } + WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s return list size: %{public}d", __func__, workInfos.size()); + WS_HILOGD("BUGOAWF WSSP function %{public}s invoked END.", __func__); + return workInfos; +} + +std::shared_ptr WorkSchedServiceProxy::GetWorkStatus(int32_t &uid, int32_t &workId) +{ + WS_HILOGD("%{public}s enter, workId: %{public}d", __func__, workId); + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, nullptr); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("%{public}s wirte descriptor failed!", __func__); + return nullptr; + } + WRITE_PARCEL_WITHOUT_RET(data, Int32, uid); + WRITE_PARCEL_WITHOUT_RET(data, Int32, workId); + int ret = remote->SendRequest(static_cast(IWorkSchedService::GET_WORK_STATUS), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("%{pulbic}s SendRequest is failed, err code: %{public}d", __func__, ret); + return nullptr; + } + WorkInfo *workInfo; + workInfo = reply.ReadParcelable(); + return std::make_shared(*workInfo); +} + +bool WorkSchedServiceProxy::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(WorkSchedServiceProxy::GetDescriptor())) { + WS_HILOGE("%{public}s write descriptor failed!", __func__); + return false; + } + if (!data.WriteStringVector(dumpOption)) { + WS_HILOGE("[ShellDump] fail: write option failed."); + return false; + } + int ret = remote->SendRequest(static_cast(IWorkSchedService::DUMP_INFO), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + return false; + } + if (!reply.ReadBool()) { + WS_HILOGE("[ShellDump] fail: read result failed."); + return false; + } + if (!reply.ReadStringVector(&dumpInfo)) { + WS_HILOGE("[ShellDump] fail: read dumpInfo failed."); + return false; + } + WS_HILOGE("success."); + return true; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/zidl/src/work_sched_service_stub.cpp b/services/zidl/src/work_sched_service_stub.cpp new file mode 100644 index 0000000..47c0116 --- /dev/null +++ b/services/zidl/src/work_sched_service_stub.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_sched_service_stub.h" + +#include +#include + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +int WorkSchedServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + WS_HILOGD("BUGOAWF WorkSchedServiceStub::OnRemoteRequest, cmd = %{public}u, flags = %{public}d", code, option.GetFlags()); + std::u16string descriptor = WorkSchedServiceStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + WS_HILOGE("BUGOAWF WorkSchedServiceStub::OnRemoteRequest failed, descriptor is not matched!"); + return E_GET_WORKSCHED_SERVICE_FALIED; + } + switch (code) { + case static_cast(IWorkSchedService::START_WORK): { + WS_HILOGI("call StartWorkStub"); + int32_t ret = StartWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_WORK): { + WS_HILOGI("call StopWorkStub"); + int32_t ret = StopWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_AND_CANCEL_WORK): { + WS_HILOGI("call StopAndCancelWorkStub"); + int32_t ret = StopAndCancelWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_AND_CLEAR_WORKS): { + WS_HILOGI("call StopAndClearWorksStub"); + int32_t ret = StopAndClearWorksStub(data); + WS_HILOGD("%{public}s ret is ERR_OK ? %{public}s", __func__, (ret == ERR_OK) ? "true" : "false"); + bool wret = reply.WriteBool(ret == ERR_OK); + WS_HILOGD("%{public}s wret is: %{public}s", __func__, wret ? "true" : "false"); + return ret; + } + case static_cast(IWorkSchedService::IS_LAST_WORK_TIMEOUT): { + WS_HILOGI("call IsLastWorkTimeoutStub"); + int32_t ret = IsLastWorkTimeoutStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::OBTAIN_ALL_WORKS): { + WS_HILOGI("BUGOAWF call ObtainAllWorksStub"); + std::list> workInfos = ObtainAllWorksStub(data); + size_t worksize = workInfos.size(); + WS_HILOGD("BUFOAWF OBTAIN_ALL_WORKS worksize returns %{public}d", worksize); + reply.WriteInt32(worksize); + WS_HILOGD("WP reply write worksize: %{public}d", worksize); + for (auto workInfo : workInfos) { + reply.WriteParcelable(&*workInfo); + // workInfo->Marshalling(reply); + WS_HILOGD("WP reply write workInfo, ID: %{public}d", workInfo->GetWorkId()); + } + return ERR_OK; + } + case static_cast(IWorkSchedService::GET_WORK_STATUS): { + WS_HILOGI("call GetWorkStatus"); + auto workInfo = GetWorkStatusStub(data); + reply.WriteParcelable(&*workInfo); + return ERR_OK; + } + case static_cast(IWorkSchedService::DUMP_INFO): { + return ShellDumpStub(data, reply); + } + default: { + WS_HILOGD("BUGOAWF OnRemoteRequest switch default, code: %{public}u", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + + return ERR_OK; +} + +int32_t WorkSchedServiceStub::StartWorkStub(MessageParcel& data) +{ + WorkInfo* pw = data.ReadParcelable(); + WorkInfo& workInfo = *pw; + if (!StartWork(workInfo)) { + WS_HILOGE("StartWork failed"); + return E_START_WORK_FAILED; + } + WS_HILOGE("call StartWork success"); + return ERR_OK; +} + +int32_t WorkSchedServiceStub::StopWorkStub(MessageParcel& data) +{ + WorkInfo* pw = data.ReadParcelable(); + WorkInfo& workInfo = *pw; + if (!StopWork(workInfo)) { + return E_STOP_WORK_FAILED; + } + return ERR_OK; +} + +int32_t WorkSchedServiceStub::StopAndCancelWorkStub(MessageParcel& data) +{ + WorkInfo* pw = data.ReadParcelable(); + WorkInfo& workInfo = *pw; + if (!StopAndCancelWork(workInfo)) { + return E_STOP_AND_CANCEL_WORK_FAILED; + } + return ERR_OK; +} + +int32_t WorkSchedServiceStub::StopAndClearWorksStub(MessageParcel& data) +{ + WS_HILOGD("WSSS %{public}s come in", __func__); + if (!StopAndClearWorks()) { + WS_HILOGD("WSSS %{public}s return E_STOP_AND_CLEAR_WORKS_FAILED", __func__); + return E_STOP_AND_CLEAR_WORKS_FAILED; + } + WS_HILOGD("WSSS %{public}s return ERR_OK and come out", __func__); + return ERR_OK; +} + +int32_t WorkSchedServiceStub::IsLastWorkTimeoutStub(MessageParcel& data) +{ + int32_t workId = data.ReadInt32(); + if (!IsLastWorkTimeout(workId)) { + return E_IS_LAST_WORK_TIMEOUT_FALSE; + } + return ERR_OK; +} + +std::list> WorkSchedServiceStub::ObtainAllWorksStub(MessageParcel& data) +{ + WS_HILOGD("WorkSchedServiceStub %{public}s enter", __func__); + int32_t pid = 0, uid = 0; + READ_PARCEL_WITHOUT_RET(data, Int32, uid); + READ_PARCEL_WITHOUT_RET(data, Int32, pid); + WS_HILOGD("WorkSchedServiceStub %{public}s: uid: %{public}d, pid: %{public}d", __func__, uid, pid); + WS_HILOGD("WorkSchedServiceStub %{public}s return", __func__); + return ObtainAllWorks(uid, pid); +} + +std::shared_ptr WorkSchedServiceStub::GetWorkStatusStub(MessageParcel& data) +{ + WS_HILOGD("WorkSchedServiceStub %{public}s enter", __func__); + int32_t uid; + int32_t workId; + READ_PARCEL_WITHOUT_RET(data, Int32, uid); + READ_PARCEL_WITHOUT_RET(data, Int32, workId); + return GetWorkStatus(uid, workId); +} + +ErrCode WorkSchedServiceStub::ShellDumpStub(MessageParcel& data, MessageParcel& reply) +{ + std::vector dumpOption; + if (!data.ReadStringVector(&dumpOption)) { + WS_HILOGD("[HandleShellDump] fail: read dumpOption failed."); + return ERR_INVALID_DATA; + } + std::vector workSchedulerInfo; + bool result = ShellDump(dumpOption, workSchedulerInfo); + if (!reply.WriteBool(result)) { + WS_HILOGD("WorkSchedServiceStub::%{public}s write result fail.", __func__); + return ERR_INVALID_DATA; + } + if (!reply.WriteStringVector(workSchedulerInfo)) { + WS_HILOGD("WorkSchedServiceStub::%{public}s write workscheduler fail.", __func__); + return ERR_INVALID_DATA; + } + return ERR_OK; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/services/zidl/src/work_scheduler_proxy.cpp b/services/zidl/src/work_scheduler_proxy.cpp new file mode 100644 index 0000000..df25de5 --- /dev/null +++ b/services/zidl/src/work_scheduler_proxy.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_proxy.h" + +namespace OHOS { +namespace WorkScheduler { +void WorkSchedulerProxy::OnWorkStart() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + // data.WriteParcelable(inData); + + Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); + + // ErrCode ec = reply.ReadInt32(); + // if (FAILED(ec)) { + // return ec; + // } + + // return ERR_OK; +} + +void WorkSchedulerProxy::OnWorkStop() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + // data.WriteParcelable(inData); + + Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); + + // ErrCode ec = reply.ReadInt32(); + // if (FAILED(ec)) { + // return ec; + // } + + // return ERR_OK; +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/services/zidl/src/work_scheduler_stub.cpp b/services/zidl/src/work_scheduler_stub.cpp new file mode 100644 index 0000000..5438233 --- /dev/null +++ b/services/zidl/src/work_scheduler_stub.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_stub.h" + +namespace OHOS { +namespace WorkScheduler { +int WorkSchedulerStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + switch (code) { + case COMMAND_ON_WORK_START: { + OnWorkStart(); + return ERR_NONE; + } + case COMMAND_ON_WORK_STOP: { + OnWorkStop(); + return ERR_NONE; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + return ERR_TRANSACTION_FAILED; +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/services/zidl/src/work_scheduler_stub_imp.cpp b/services/zidl/src/work_scheduler_stub_imp.cpp new file mode 100644 index 0000000..8b90255 --- /dev/null +++ b/services/zidl/src/work_scheduler_stub_imp.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_scheduler_stub_imp.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace WorkScheduler { +void WorkSchedulerStubImp::OnWorkStart() +{ + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension != nullptr) { + extension->OnWorkStart(); + WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); + // return 0; + } + WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); + // return -1; +} + +void WorkSchedulerStubImp::OnWorkStop() +{ + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension != nullptr) { + extension->OnWorkStop(); + WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); + // return 0; + } + WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); + // return -1; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/test/constanttest/constant_test.cpp b/test/constanttest/constant_test.cpp deleted file mode 100644 index 5e6cbf2..0000000 --- a/test/constanttest/constant_test.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define private public -#define protected public - -#include "work_condition.h" - -#undef private -#undef protected - -#include - -using namespace testing::ext; - -namespace OHOS { -namespace WorkScheduler { -class ConstantTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); -}; - -void ConstantTest::SetUpTestCase() -{} - -void ConstantTest::TearDownTestCase() -{} - -void ConstantTest::SetUp() -{} - -void ConstantTest::TearDown() -{} - -/* - * @tc.number: ConstantTest_GetNetworkType_001 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_001, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_ANY, 0); -} - -/* - * @tc.number: ConstantTest_GetNetworkType_002 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_002, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_MOBILE, 1); -} - -/* - * @tc.number: ConstantTest_GetNetworkType_003 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_003, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_WIFI, 2); -} - -/* - * @tc.number: ConstantTest_GetNetworkType_004 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_004, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_BLUETOOTH, 3); -} - -/* - * @tc.number: ConstantTest_GetNetworkType_005 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_005, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_WIFI_P2P, 4); -} - -/* - * @tc.number: ConstantTest_GetNetworkType_006 - * @tc.name: Get Network Type - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_GetNetworkType_006, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Network::NETWORK_TYPE_ETHERNET, 5); -} - -/* - * @tc.number: ConstantTest_ChargingType_001 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_ChargingType_001, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Charger::CHARGER_PLUGGED_ANY, 0); -} - -/* - * @tc.number: ConstantTest_ChargingType_002 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_ChargingType_002, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Charger::CHARGER_PLUGGED_AC, 1); -} - -/* - * @tc.number: ConstantTest_ChargingType_003 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_CHARGING_PLUGGED_USB_003, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Charger::CHARGER_PLUGGED_USB, 2); -} - -/* - * @tc.number: ConstantTest_ChargingType_004 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_CHARGING_PLUGGED_WIRELESS_004, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS, 3); -} - -/* - * @tc.number: ConstantTest_BatteryStatus_001 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_BatteryStatus_001, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW, 0); -} - -/* - * @tc.number: ConstantTest_BatteryStatus_002 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_BatteryStatus_002, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY, 1); -} - -/* - * @tc.number: ConstantTest_BatteryStatus_003 - * @tc.name: Get Battery Status - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_BatteryStatus_003, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY, 2); -} - -/* - * @tc.number: ConstantTest_StorageRequest_001 - * @tc.name: Get Storage Request - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_StorageRequest_001, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Storage::STORAGE_LEVEL_LOW, 0); -} - -/* - * @tc.number: ConstantTest_StorageRequest_002 - * @tc.name: Get Storage Request - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_StorageRequest_002, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Storage::STORAGE_LEVEL_OKAY, 1); -} - -/* - * @tc.number: ConstantTest_StorageRequest_003 - * @tc.name: Get Storage Request - * @tc.desc: - */ -HWTEST_F(ConstantTest, ConstantTest_StorageRequest_003, Function | MediumTest | Level0) -{ - EXPECT_EQ(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY, 2); -} -} // namespace BackgroundTaskMgr -} // namespace OHOS \ No newline at end of file diff --git a/utils/dump/BUILD.gn b/utils/dump/BUILD.gn new file mode 100644 index 0000000..151825e --- /dev/null +++ b/utils/dump/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") + +group("workscheduler_target") { + deps = [ ":workscheduler" ] +} + +ohos_executable("workscheduler") { + include_dirs = [ "include" ] + + sources = [ + "src/event_publisher.cpp", + "src/main.cpp", + "src/shell_command.cpp", + "src/workscheduler_shell_command.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${worksched_frameworks_path}:workschedclient", + "${worksched_utils_path}:workschedutils", + ] + + external_deps = [ + "ability_runtime:want", + "battery_manager_native:batterysrv_client", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "utils_base:utils", + ] + + install_enable = true + part_name = "${worksched_native_part_name}" +} diff --git a/utils/dump/include/event_publisher.h b/utils/dump/include/event_publisher.h new file mode 100644 index 0000000..4e69539 --- /dev/null +++ b/utils/dump/include/event_publisher.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_UTILS_DUMP_EVENT_PUBLISHER_H +#define WORK_SCHED_UTILS_DUMP_EVENT_PUBLISHER_H + +#include +#include + +namespace OHOS { +namespace WorkScheduler { +class EventPublisher { +public: + explicit EventPublisher() = default; + ~EventPublisher() = default; + void PublishEvent(const std::vector &dumpOption, std::vector &dumpInfo); + void PublishNetworkEvent(const std::vector &dumpOption, std::vector &dumpInfo); + void PublishChargingEvent(const std::vector &dumpOption, std::vector &dumpInfo); + void PublishStorageEvent(const std::vector &dumpOption, std::vector &dumpInfo); +}; +} +} +#endif // WORK_SCHED_UTILS_DUMP_EVENT_PUBLISHER_H \ No newline at end of file diff --git a/utils/dump/include/shell_command.h b/utils/dump/include/shell_command.h new file mode 100644 index 0000000..d8d3540 --- /dev/null +++ b/utils/dump/include/shell_command.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_UTILS_DUMP_SHELL_CMD_H +#define WORK_SCHED_UTILS_DUMP_SHELL_CMD_H + +#include +#include +#include +#include + +#include "errors.h" + +namespace OHOS { +namespace WorkScheduler { +class ShellCommand { +public: + ShellCommand(int argc, char *argv[], std::string name); + + ErrCode OnCommand(); + std::string ExecCommand(); + std::string GetCommandErrorMsg() const; + + virtual ErrCode CreateCommandMap() = 0; + virtual ErrCode CreateMessageMap() = 0; + virtual ErrCode init() = 0; + +protected: + static constexpr int MIN_ARGUMENT_NUMBER = 2; + + int argc_; + char **argv_; + + std::string cmd_; + std::vector argList_; + + std::string name_; + std::map> commandMap_; + std::map messageMap_; + + std::string resultReceiver_ = ""; +}; +} // namespace WorkScheduler +} // namespace OHOS + +#endif // WORK_SCHED_UTILS_DUMP_SHELL_CMD_H \ No newline at end of file diff --git a/utils/dump/include/workscheduler_shell_command.h b/utils/dump/include/workscheduler_shell_command.h new file mode 100644 index 0000000..00efa21 --- /dev/null +++ b/utils/dump/include/workscheduler_shell_command.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_UTILS_WORK_SCHED_DUMP_SHELL_CMD_H +#define WORK_SCHED_UTILS_WORK_SCHED_DUMP_SHELL_CMD_H + +#include "shell_command.h" +#include "workscheduler_srv_client.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerShellCommand : public ShellCommand { +public: + WorkSchedulerShellCommand(int argc, char *argv[]); + +private: + ErrCode CreateCommandMap() override; + ErrCode CreateMessageMap() override; + ErrCode init() override; + ErrCode RunAsHelpCommand(); + ErrCode RunAsDumpCommand(); +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // WORK_SCHED_UTILS_WORK_SCHED_DUMP_SHELL_CMD_H \ No newline at end of file diff --git a/utils/dump/src/event_publisher.cpp b/utils/dump/src/event_publisher.cpp new file mode 100644 index 0000000..1fc0405 --- /dev/null +++ b/utils/dump/src/event_publisher.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "event_publisher.h" + +#include +#include + +#include "battery_srv_client.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "want.h" + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +namespace { + static const std::string NETWORK = "network"; + static const std::string EV_NETWORK_TYPE_WIFI = "wifi"; + static const std::string CHARGING = "charging"; + static const std::string EV_CHARGING_TYPE_USB = "usb"; + static const std::string EV_CHARGING_TYPE_AC = "ac"; + static const std::string EV_CHARGING_TYPE_WIRELESS = "wireless"; + static const std::string EV_CHARGING_TYPE_NONE = "none"; + static const std::string STORAGE = "storage"; + static const std::string EV_STORAGE_LOW = "low"; + static const std::string EV_STORAGE_OKAY = "ok"; + static const std::string HELP = "help"; + static const std::string HELP_MSG = + "usage: workscheduler dump -E []\n" + "options list:\n" + " help help menu\n" + " network wifi (TMP)publish COMMON_EVENT_WIFI_CONN_STATE event\n" + " charging usb publish usb charging event\n" + " charging ac publish ac charging event\n" + " charging wireless publish wireless charging event\n" + " charging none publish unplugged event\n" + " storage low publish COMMON_EVENT_DEVICE_STORAGE_LOW event\n" + " storage ok publish COMMON_EVENT_DEVICE_STORAGE_OKAY event\n"; +} + +void EventPublisher::PublishEvent(const std::vector &dumpOption, std::vector &dumpInfo) +{ + if (dumpOption[1] == NETWORK) { + PublishNetworkEvent(dumpOption, dumpInfo); + } else if (dumpOption[1] == CHARGING) { + PublishChargingEvent(dumpOption, dumpInfo); + } else if (dumpOption[1] == STORAGE) { + PublishStorageEvent(dumpOption, dumpInfo); + } else if (dumpOption[1] == HELP) { + dumpInfo.push_back(HELP_MSG); + } else { + dumpInfo.push_back(std::string("dump -E need right param.")); + dumpInfo.push_back(HELP_MSG); + } +} + +void EventPublisher::PublishNetworkEvent(const std::vector &dumpOption, std::vector &dumpInfo) +{ + EventFwk::Want want; + if (dumpOption[2] == EV_NETWORK_TYPE_WIFI) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); + dumpInfo.push_back(std::string("publishing COMMON_EVENT_WIFI_CONN_STATE")); + } else { + dumpInfo.push_back(std::string("dump need right param.")); + } + EventFwk::CommonEventData data; + data.SetWant(want); + bool isSuccess = EventFwk::CommonEventManager::PublishCommonEvent(data); + dumpInfo.push_back(std::string("publish result: " + std::to_string(isSuccess))); +} + +void EventPublisher::PublishChargingEvent(const std::vector &dumpOption, std::vector &dumpInfo) +{ + EventFwk::Want want; + EventFwk::CommonEventData data; + if (dumpOption[2] == EV_CHARGING_TYPE_AC) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + data.SetWant(want); + data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); + data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_AC))); + } else if (dumpOption[2] == EV_CHARGING_TYPE_USB) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + data.SetWant(want); + data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); + data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_USB))); + } else if (dumpOption[2] == EV_CHARGING_TYPE_WIRELESS) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + data.SetWant(want); + data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); + data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_WIRELESS))); + } else if (dumpOption[2] == EV_CHARGING_TYPE_NONE) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); + data.SetWant(want); + data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); + data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE))); + } else { + dumpInfo.push_back(std::string("dump need right param.")); + } + EventFwk::CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(false); + bool ret = EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo); + dumpInfo.push_back(std::string("publish charging event ret: ") + (ret ? "true" : "false")); +} + +void EventPublisher::PublishStorageEvent(const std::vector &dumpOption, std::vector &dumpInfo) +{ + EventFwk::Want want; + if (dumpOption[2] == EV_STORAGE_LOW) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW); + dumpInfo.push_back(std::string("publishing COMMON_EVENT_DEVICE_STORAGE_LOW")); + } else if (dumpOption[2] == EV_STORAGE_OKAY) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); + dumpInfo.push_back(std::string("publishing COMMON_EVENT_DEVICE_STORAGE_OKAY")); + } else { + dumpInfo.push_back(std::string("dump need right param.")); + } + EventFwk::CommonEventData data; + data.SetWant(want); + bool isSuccess = EventFwk::CommonEventManager::PublishCommonEvent(data); + dumpInfo.push_back(std::string("publish result: ") + std::to_string(isSuccess)); +} +} +} \ No newline at end of file diff --git a/utils/dump/src/main.cpp b/utils/dump/src/main.cpp new file mode 100644 index 0000000..430a0b4 --- /dev/null +++ b/utils/dump/src/main.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "workscheduler_shell_command.h" + +int main(int argc, char *argv[]) +{ + OHOS::WorkScheduler::WorkSchedulerShellCommand cmd(argc, argv); + std::cout << cmd.ExecCommand(); + return 0; +} \ No newline at end of file diff --git a/utils/dump/src/shell_command.cpp b/utils/dump/src/shell_command.cpp new file mode 100644 index 0000000..536f460 --- /dev/null +++ b/utils/dump/src/shell_command.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "shell_command.h" + +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +ShellCommand::ShellCommand(int argc, char *argv[], std::string name) +{ + argc_ = argc; + argv_ = argv; + name_ = name; + + if (argc < MIN_ARGUMENT_NUMBER) { + cmd_ = "help"; + return; + } + cmd_ = argv[1]; + for (int i = 2; i < argc; i++) { + argList_.push_back(argv[i]); + } +} + +ErrCode ShellCommand::OnCommand() +{ + int result = OHOS::ERR_OK; + + auto respond = commandMap_[cmd_]; + if (respond == nullptr) { + resultReceiver_.append(GetCommandErrorMsg()); + respond = commandMap_["help"]; + } + + if (init() == OHOS::ERR_OK) { + respond(); + } else { + result = OHOS::ERR_INVALID_VALUE; + } + + return result; +} + +std::string ShellCommand::ExecCommand() +{ + int result = CreateCommandMap(); + if (result != OHOS::ERR_OK) { + WS_HILOGE("failed to create command map."); + } + + result = CreateMessageMap(); + if (result != OHOS::ERR_OK) { + WS_HILOGE("failed to create message map."); + } + + result = OnCommand(); + if (result != OHOS::ERR_OK) { + WS_HILOGE("failed to execute your command."); + resultReceiver_ = "error: failed to execute your command.\n"; + } + + return resultReceiver_; +} + +std::string ShellCommand::GetCommandErrorMsg() const +{ + std::string commandErrorMsg = + name_ + ": '" + cmd_ + "' is not a valid " + name_ + " command. See '" + name_ + " help'.\n"; + return commandErrorMsg; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/utils/dump/src/workscheduler_shell_command.cpp b/utils/dump/src/workscheduler_shell_command.cpp new file mode 100644 index 0000000..0e84e16 --- /dev/null +++ b/utils/dump/src/workscheduler_shell_command.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "workscheduler_shell_command.h" + +#include + +#include + +#include "event_publisher.h" +#include "iservice_registry.h" +#include "singleton.h" + +namespace OHOS { +namespace WorkScheduler { +namespace { + auto& client_ = WorkSchedulerSrvClient::GetInstance(); + + static const struct option OPTIONS[] = { + {"help", no_argument, nullptr, 'h'}, + {"all", no_argument, nullptr, 'A'}, + }; + + static const std::string DUMP_HELP_MSG = + "usage: workscheduler dump []\n" + "options list:\n" + " -h help menu\n" + " -A All dump all infos\n" + " -A WorkQueue dump work queue infos\n" + " -A WorkPolicy dump work policy infos\n" + " -E help show publish common event help menu\n"; +} // namespace + +WorkSchedulerShellCommand::WorkSchedulerShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "workscheduler") +{} + +ErrCode WorkSchedulerShellCommand:: CreateCommandMap() +{ + commandMap_ = { + {"dump", std::bind(&WorkSchedulerShellCommand::RunAsDumpCommand, this)}, + }; + return ERR_OK; +} + +ErrCode WorkSchedulerShellCommand::CreateMessageMap() +{ + messageMap_ = {}; + return ERR_OK; +} + +ErrCode WorkSchedulerShellCommand::init() +{ + return ERR_OK; +} + +ErrCode WorkSchedulerShellCommand::RunAsDumpCommand() +{ + int ind = 0; + int option = getopt_long(argc_, argv_, "hAE", OPTIONS, &ind); + std::vector infos; + switch (option) { + case 'h': + resultReceiver_.append(DUMP_HELP_MSG); + break; + case 'A': + if (!client_.ShellDump(argList_, infos)) { + resultReceiver_.append("ErrNo: " + std::to_string(ERR_INVALID_VALUE) + "\n"); + return ERR_INVALID_VALUE; + } + break; + case 'E': + EventPublisher eventPublisher; + eventPublisher.PublishEvent(argList_, infos); + break; + default: + resultReceiver_.append("please add right options.\n"); + resultReceiver_.append(DUMP_HELP_MSG); + break; + } + for (auto info : infos) { + resultReceiver_.append(info); + resultReceiver_.append("\n"); + } + return ERR_OK; +} +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/utils/BUILD.gn b/utils/native/BUILD.gn similarity index 80% rename from utils/BUILD.gn rename to utils/native/BUILD.gn index 8cf59f6..529b57d 100644 --- a/utils/BUILD.gn +++ b/utils/native/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -14,18 +14,22 @@ import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") config("utils_config") { - include_dirs = [ "native/include" ] + include_dirs = [ "include" ] } ohos_source_set("workschedutils") { - sources = [] + sources = [ + "${worksched_utils_path}/src/work_sched_hilog.cpp" + ] public_configs = [ ":utils_config" ] deps = [] external_deps = [ + "battery_manager_native:batterysrv_client", "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", "utils_base:utils", ] diff --git a/utils/native/include/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h new file mode 100644 index 0000000..334f5ae --- /dev/null +++ b/utils/native/include/delayed_sp_singleton.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_UTILS_SP_SINGLETON_H +#define WORK_SCHED_UTILS_SP_SINGLETON_H + +#include +#include + +#include +#include + +namespace OHOS { +namespace WorkScheduler { +#define DECLARE_DELAYED_SP_SINGLETON(MyClass)\ +public:\ + ~MyClass();\ +private:\ + friend DelayedSpSingleton;\ + MyClass(); + +template +class DelayedSpSingleton : public NoCopyable { +public: + static sptr GetInstance(); + static void DestroyInstance(); + +private: + static sptr instance_; + static std::mutex mutex_; +}; + +template +sptr DelayedSpSingleton::instance_ = nullptr; + +template +std::mutex DelayedSpSingleton::mutex_; + +template +sptr DelayedSpSingleton::GetInstance() +{ + if (!instance_) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = new T(); + } + } + + return instance_; +} + +template +void DelayedSpSingleton::DestroyInstance() +{ + std::lock_guard lock(mutex_); + if (instance_) { + instance_.clear(); + instance_ = nullptr; + } +} +} // namespace WorkScheduler +} // namespace OHOS +#endif // WORK_SCHED_UTILS_SP_SINGLETON_H \ No newline at end of file diff --git a/utils/native/include/work_sched_common.h b/utils/native/include/work_sched_common.h new file mode 100644 index 0000000..06bceef --- /dev/null +++ b/utils/native/include/work_sched_common.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WORK_SCHED_UTILS_COMMON_H +#define WORK_SCHED_UTILS_COMMON_H + +#include +#include + +#include "work_sched_hilog.h" +#include "work_sched_errors.h" + +namespace OHOS { +namespace WorkScheduler { +#define TEST_LOG_FILE_PATH "/data/test_log_file" +#define RETURN_IF_WITH_RET(cond, retval) if (cond) {return (retval);} +#define RETURN_IF(cond) if (cond) {return;} + +#define RETURN_IF_WITH_LOG(cond, loginfo) \ + do { \ + if (cond) { \ + WS_HILOGE("%{public}s "#loginfo" ", __func__); \ + return; \ + } \ + } while(0) + +#define READ_PARCEL_NO_RET(parcel, type, out) \ + do { \ + if (!(parcel).Read##type(out)) { \ + WS_HILOGE("%{public}s read"#out" failed", __func__); \ + return; \ + } \ + } while (0) +} + +#define READ_PARCEL_WITHOUT_RET(parcel, type, out) \ + do { \ + if (!(parcel).Read##type(out)) { \ + WS_HILOGE("%{public}s read"#out" failed", __func__); \ + } \ + } while (0) +} + +#define WRITE_PARCEL_NO_RET(parcel, type, data) \ + do { \ + if (!(parcel).Write##type(data)) { \ + WS_HILOGE("%{public}s write "#data" failed", __func__); \ + return; \ + } \ + } while (0) + +#define READ_PARCEL_WITH_RET(parcel, type, out, retval) \ + do { \ + if (!(parcel).Read##type(out)) { \ + WS_HILOGE("%{public}s read "#out" failed", __func__); \ + return (retval); \ + } \ + } while (0) + +#define WRITE_PARCEL_WITHOUT_RET(parcel, type, data) \ + do { \ + if (!(parcel).Write##type(data)) { \ + WS_HILOGE("%{public}s write "#data" failed", __func__); \ + } \ + } while (0) + +#define WRITE_PARCEL_WITH_RET(parcel, type, data, retval) \ + do { \ + if (!(parcel).Write##type(data)) { \ + WS_HILOGE("%{public}s write "#data" failed", __func__); \ + return (retval); \ + } \ + } while (0) + +#define WRITE_TO_LOG_FILE(logstr) \ + do { \ + ofstream fout; \ + fout.open(TEST_LOG_FILE_PATH, ios::out); \ + fout< + #include "hilog/log.h" namespace OHOS { namespace WorkScheduler { -#define __FILENAME__ (__builtin_strchr(__FILE__, '/') ? __builtin_strchr(__FILE__, '/') + 1 : __FILE__) -#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__ -#ifdef WORKSCHED_HILOGF -#undef WORKSCHED_HILOGF +#ifndef WORKSCHEDULER_DOMAIN_ID +#define WORKSCHEDULER_DOMAIN_ID 0xD001900 #endif -#ifdef WORKSCHED_HILOGE -#undef WORKSCHED_HILOGE +#ifndef WORKSCHEDULER_MGR_LOG_TAG +#define WORKSCHEDULER_MGR_LOG_TAG "WORK_SCHEDULER" #endif -#ifdef WORKSCHED_HILOGW -#undef WORKSCHED_HILOGW -#endif +static constexpr OHOS::HiviewDFX::HiLogLabel WORKSCHEDULER_LABEL = {LOG_CORE, WORKSCHEDULER_DOMAIN_ID, WORKSCHEDULER_MGR_LOG_TAG}; -#ifdef WORKSCHED_HILOGI -#undef WORKSCHED_HILOGI -#endif +enum class WorkSchedLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; -#ifdef WORKSCHED_HILOGD -#undef WORKSCHED_HILOGD -#endif +class WorkSchedHilog { +public : + WorkSchedHilog() = delete; + ~WorkSchedHilog() = delete; -// param of log interface, such as WORKSCHED_HILOGF. -enum WorkSchedSubModule { - MODULE_INNERKIT = 0, - MODULE_SERVICE, - MODULE_JAVAKIT, - MODULE_JNI, - MODULE_COMMON, - MODULE_JS_NAPI, - WORKSCHED_MODULE_BUTT, -}; + static bool JudgeLevel(const WorkSchedLogLevel &level); -// 0xD001900: subsystem:resouceschedule module:workscheduler, 8 bits reserved. -static constexpr unsigned int BASE_WORKSCHEDULER_DOMAIN_ID = 0xD001900; - -enum WorkSchedDomainId { - WORKSCHED_INNERKIT_DOMAIN = BASE_WORKSCHEDULER_DOMAIN_ID + MODULE_INNERKIT, - WORKSCHED_SERVICE_DOMAIN, - WORKSCHED_JAVAKIT_DOMAIN, - WORKSCHED_JNI_DOMAIN, - COMMON_DOMAIN, - WORKSCHED_JS_NAPI, - WORKSCHED_BUTT, -}; + static void SetLogLevel(const WorkSchedLogLevel &level) + { + level_ = level; + } -static constexpr OHOS::HiviewDFX::HiLogLabel WORKSCHED_LABEL[WORKSCHED_MODULE_BUTT] = { - {LOG_CORE, WORKSCHED_INNERKIT_DOMAIN, "WorkSchedInnerKit"}, - {LOG_CORE, WORKSCHED_SERVICE_DOMAIN, "WorkSchedService"}, - {LOG_CORE, WORKSCHED_JAVAKIT_DOMAIN, "WorkSchedJavaKit"}, - {LOG_CORE, WORKSCHED_JNI_DOMAIN, "WorkSchedJni"}, - {LOG_CORE, COMMON_DOMAIN, "WorkSchedCommon"}, - {LOG_CORE, WORKSCHED_JS_NAPI, "WorkSchedJSNAPI"}, + static const WorkSchedLogLevel &GetLogLevel() + { + return level_; + } + + static std::string GetBriefFileName(const char *str); + +private: + static WorkSchedLogLevel level_; }; -// In order to improve performance, do not check the module range. -// Besides, make sure module is less than WORKSCHED_MODULE_BUTT. -#define WS_HILOGF(module, ...) (void)OHOS::HiviewDFX::HiLog::Fatal(WORKSCHED_LABEL[module], __FORMATED(__VA_ARGS__)) -#define WS_HILOGE(module, ...) (void)OHOS::HiviewDFX::HiLog::Error(WORKSCHED_LABEL[module], __FORMATED(__VA_ARGS__)) -#define WS_HILOGW(module, ...) (void)OHOS::HiviewDFX::HiLog::Warn(WORKSCHED_LABEL[module], __FORMATED(__VA_ARGS__)) -#define WS_HILOGI(module, ...) (void)OHOS::HiviewDFX::HiLog::Info(WORKSCHED_LABEL[module], __FORMATED(__VA_ARGS__)) -#define WS_HILOGD(module, ...) (void)OHOS::HiviewDFX::HiLog::Debug(WORKSCHED_LABEL[module], __FORMATED(__VA_ARGS__)) +#define WS_PRINT_LOG(LEVEL, Level, fmt, ...) \ + if (WorkScheduler::WorkSchedHilog::JudgeLevel(WorkScheduler::WorkSchedLogLevel::LEVEL)) \ + OHOS::HiviewDFX::HiLog::Level(WorkScheduler::WORKSCHEDULER_LABEL, \ + "[%{public}s(%{public}s):%{public}d] " fmt, \ + WorkScheduler::WorkSchedHilog::GetBriefFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + __LINE__, \ + ##__VA_ARGS__) + +#define WS_HILOGD(fmt, ...) WS_PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define WS_HILOGI(fmt, ...) WS_PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define WS_HILOGW(fmt, ...) WS_PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define WS_HILOGE(fmt, ...) WS_PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define WS_HILOGF(fmt, ...) WS_PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace WorkScheduler } // namespace OHOS - -#else - -#define WS_HILOGF(...) -#define WS_HILOGE(...) -#define WS_HILOGW(...) -#define WS_HILOGI(...) -#define WS_HILOGD(...) - -#endif // CONFIG_HILOG - #endif // WORK_SCHED_UTILS_HILOG_H \ No newline at end of file diff --git a/utils/native/src/work_sched_hilog.cpp b/utils/native/src/work_sched_hilog.cpp new file mode 100644 index 0000000..36a35eb --- /dev/null +++ b/utils/native/src/work_sched_hilog.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +WorkSchedLogLevel WorkSchedHilog::level_ = {WorkSchedLogLevel::DEBUG}; + +bool WorkSchedHilog::JudgeLevel(const WorkSchedLogLevel &level) +{ + const WorkSchedLogLevel &curLevel = WorkSchedHilog::GetLogLevel(); + if (level < curLevel) { + return false; + } + return true; +} + +std::string WorkSchedHilog::GetBriefFileName(const char *str) +{ + if (!str) { + return std::string(); + } + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + if (pos == std::string::npos) { + return std::string(); + } + return fullPath.substr(pos + 1); +} +} +} diff --git a/workscheduler.gni b/workscheduler.gni index d16adbd..7a671b1 100644 --- a/workscheduler.gni +++ b/workscheduler.gni @@ -21,12 +21,10 @@ worksched_service_path = "${worksched_root_path}/services" worksched_kits_path = "${worksched_root_path}/kits" -worksched_utils_path = "${worksched_root_path}/utils" +worksched_utils_path = "${worksched_root_path}/utils/native" worksched_interfaces_path = "${worksched_root_path}/interfaces" -worksched_native_innerkits_path = "${worksched_interfaces_path}/innerkits" - worksched_frameworks_path = "${worksched_root_path}/frameworks" system_type = "default" \ No newline at end of file -- Gitee From 48bf044ab7433fb9b82be6d3388b2c04603d08c7 Mon Sep 17 00:00:00 2001 From: chenming Date: Sun, 30 Jan 2022 15:18:43 +0800 Subject: [PATCH 02/29] add code style Signed-off-by: chenming --- interfaces/kits/js/napi/src/common.cpp | 29 +++++++++++-------- .../native/include/policy/memory_policy.h | 10 +++---- .../native/src/conditions/timer_listener.cpp | 2 +- services/native/src/policy/memory_policy.cpp | 10 ++----- 4 files changed, 24 insertions(+), 27 deletions(-) diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index cc73f0e..6dfb5ac 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace WorkScheduler { const int NAME_MAXIMUM_LIMIT = 128; const int RESULT_PARAMS_NUM = 2; +const int UNSET_PARAM = -1; +const int TRUE_PARAM = 1; +const int FALSE_PARAM = 0; napi_value Common::NapiGetNull(napi_env env) { @@ -34,27 +37,29 @@ WorkInfo Common::ParseWorkInfo(WorkContext &workContext) WorkInfo workInfo = WorkInfo(); workInfo.SetWorkId(workContext.workId); workInfo.SetElement(workContext.bundleName, workContext.abilityName); - if (workContext.networkType != -1) { + if (workContext.networkType != UNSET_PARAM) { workInfo.RequestNetworkType(WorkCondition::Network(workContext.networkType)); } - if (workContext.isCharging == 0) { + if (workContext.isCharging == FALSE_PARAM) { workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGER_UNPLUGGED); - } else if (workContext.isCharging == 1 && workContext.chargingType != -1) { + } else if (workContext.isCharging == TRUE_PARAM && workContext.chargingType != UNSET_PARAM) { workInfo.RequestChargerType(true, WorkCondition::Charger(workContext.chargingType)); - } else if (workContext.isCharging == 1 && workContext.chargingType == -1) { + } else if (workContext.isCharging == TRUE_PARAM && workContext.chargingType == UNSET_PARAM) { workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); } - if (workContext.batteryLevel != -1) { + if (workContext.batteryLevel != UNSET_PARAM) { workInfo.RequestBatteryLevel(workContext.batteryLevel); } - if (workContext.batteryStatus != -1) { + if (workContext.batteryStatus != UNSET_PARAM) { workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus(workContext.batteryStatus)); } - if (workContext.storageRequest != -1) { + if (workContext.storageRequest != UNSET_PARAM) { workInfo.RequestStorageLevel(WorkCondition::Storage(workContext.storageRequest)); } - if (workContext.repeatCycleTime != -1 && workContext.repeatCount != -1) { - workInfo.RequestRepeatCycle(workContext.repeatCycleTime, workContext.repeatCount); + if (workContext.isRepeat == TRUE_PARAM) { + if (workContext.repeatCycleTime != UNSET_PARAM && workContext.repeatCount != UNSET_PARAM) { + workInfo.RequestRepeatCycle(workContext.repeatCycleTime, workContext.repeatCount); + } } workInfo.RequestPersisted(workContext.isPersisted); return workInfo; @@ -81,7 +86,7 @@ void Common::GetWorkInfo(napi_env env, napi_value objValue, WorkContext &workCon int32_t Common::GetIntProperty(napi_env env, napi_value object, const std::string &propertyName) { - int32_t intValue = -1; + int32_t intValue = UNSET_PARAM; napi_value value = nullptr; napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); if (getNameStatus == napi_ok) { @@ -115,10 +120,10 @@ int32_t Common::GetBoolToIntProperty(napi_env env, napi_value object, const std: if (getNameStatus == napi_ok) { napi_status getIntStatus = napi_get_value_bool(env, value, &boolValue); if (getIntStatus == napi_ok) { - return boolValue ? 1 : 0; + return boolValue ? TRUE_PARAM : FALSE_PARAM; } } - return -1; + return UNSET_PARAM; } std::string Common::GetStringProperty(napi_env env, napi_value object, const std::string &propertyName) diff --git a/services/native/include/policy/memory_policy.h b/services/native/include/policy/memory_policy.h index 0b9c37a..d2ef316 100644 --- a/services/native/include/policy/memory_policy.h +++ b/services/native/include/policy/memory_policy.h @@ -28,13 +28,11 @@ public: int32_t Check(int32_t currentIsRunning) override; int32_t GetMaxRunningCountByMemory(); - const int32_t MEM_LEFT_CRUCIAL = 600 * 1024; - const int32_t MEM_LEFT_WARNING = 1 * 1024 * 1024; - const int32_t MEM_LEFT_LOW = 2 * 1024 * 1024; + const int32_t MEM_CRUCIAL = 1 * 1024 * 1024; + const int32_t MEM_LOW = 2 * 1024 * 1024; const int32_t COUNT_MEMORY_CRUCIAL = 0; - const int32_t COUNT_MEMORY_WARNING = 1; - const int32_t COUNT_MEMORY_LOW = 3; - const int32_t COUNT_MEMORY_NORMAL = 5; + const int32_t COUNT_MEMORY_LOW = 1; + const int32_t COUNT_MEMORY_NORMAL = 2; private: std::shared_ptr workPolicyManager_; }; diff --git a/services/native/src/conditions/timer_listener.cpp b/services/native/src/conditions/timer_listener.cpp index 1eebda9..6ebe630 100644 --- a/services/native/src/conditions/timer_listener.cpp +++ b/services/native/src/conditions/timer_listener.cpp @@ -45,7 +45,7 @@ bool TimerListener::Start() if (!handler_) { handler_ = make_shared(eventRunner_, workQueueManager_); } - handler_->SendEvent(InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), 30000); + handler_->SendEvent(InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), 600000); return true; } bool TimerListener::Stop() diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp index 2741dc9..429d1c3 100644 --- a/services/native/src/policy/memory_policy.cpp +++ b/services/native/src/policy/memory_policy.cpp @@ -55,16 +55,10 @@ int32_t MemoryPolicy::GetMaxRunningCountByMemory() int32_t mem_available = -1; GetMemAvailable(mem_available); WS_HILOGI("mem_available: %{public}d", mem_available); - if (mem_available > 0 && mem_available < MEM_LEFT_CRUCIAL) { - WS_HILOGI("mem_available < %{public}d", MEM_LEFT_CRUCIAL); + if (mem_available < MEM_CRUCIAL) { return COUNT_MEMORY_CRUCIAL; } - if (mem_available >= MEM_LEFT_CRUCIAL && mem_available < MEM_LEFT_WARNING) { - WS_HILOGI("%{public}d < mem_available < %{public}d", MEM_LEFT_CRUCIAL, MEM_LEFT_WARNING); - return COUNT_MEMORY_WARNING; - } - if (mem_available >= MEM_LEFT_WARNING && mem_available < MEM_LEFT_LOW) { - WS_HILOGI("%{public}d < mem_available < %{public}d", MEM_LEFT_WARNING, MEM_LEFT_LOW); + if (mem_available >= MEM_CRUCIAL && mem_available < MEM_LOW) { return COUNT_MEMORY_LOW; } WS_HILOGI("memory left normal"); -- Gitee From b169515c3389f5cd83785161341a5ee6d0094ccc Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 2 Feb 2022 14:21:44 +0800 Subject: [PATCH 03/29] add bugfix Signed-off-by: chenming --- bundle.json | 3 +- frameworks/BUILD.gn | 29 +-- frameworks/extension/BUILD.gn | 32 +-- .../src/work_scheduler_extension.cpp | 4 - frameworks/include/work_condition.h | 1 - frameworks/src/workscheduler_srv_client.cpp | 27 ++- interfaces/kits/js/BUILD.gn | 10 +- interfaces/kits/js/napi/include/common.h | 38 ++-- .../kits/js/napi/include/get_work_status.h | 2 +- .../js/napi/include/is_last_work_time_out.h | 4 +- .../kits/js/napi/include/obtain_all_works.h | 5 +- interfaces/kits/js/napi/include/start_work.h | 5 +- .../js/napi/include/stop_and_clear_works.h | 5 +- interfaces/kits/js/napi/include/stop_work.h | 5 +- .../kits/js/napi/include/workscheduler_napi.h | 11 +- interfaces/kits/js/napi/src/common.cpp | 198 ++++++++++++++---- .../kits/js/napi/src/get_work_status.cpp | 12 +- .../js/napi/src/is_last_work_time_out.cpp | 15 +- .../kits/js/napi/src/obtain_all_works.cpp | 10 +- interfaces/kits/js/napi/src/start_work.cpp | 29 +-- .../kits/js/napi/src/stop_and_clear_works.cpp | 8 +- interfaces/kits/js/napi/src/stop_work.cpp | 29 +-- .../kits/js/napi/src/workscheduler_napi.cpp | 122 ++++++----- interfaces/test/unittest/BUILD.gn | 26 +++ .../work_scheduler_jsunittest/config.json | 60 ++++++ .../work_scheduler_jsunit.test.js | 157 ++++++++++++++ services/BUILD.gn | 11 +- utils/native/BUILD.gn | 6 +- utils/native/include/delayed_sp_singleton.h | 7 +- utils/native/include/work_sched_common.h | 11 +- utils/native/include/work_sched_errors.h | 21 +- utils/native/include/work_sched_hilog.h | 11 +- 32 files changed, 623 insertions(+), 291 deletions(-) create mode 100644 interfaces/test/unittest/BUILD.gn create mode 100644 interfaces/test/unittest/work_scheduler_jsunittest/config.json create mode 100644 interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js diff --git a/bundle.json b/bundle.json index 7333464..6440399 100644 --- a/bundle.json +++ b/bundle.json @@ -47,7 +47,8 @@ "inner_kits": [], "test": [ "//foundation/resourceschedule/work_scheduler/frameworks/test:workschedinnerkits_test", - "//foundation/resourceschedule/work_scheduler/services/native/test:worksched_native_test" + "//foundation/resourceschedule/work_scheduler/services/native/test:worksched_native_test", + "//foundation/resourceschedule/work_scheduler/interfaces/test/unittest:js_unittest" ] } } diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 234f45f..cee4f35 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -17,7 +17,7 @@ config("worksched_private_config") { include_dirs = [ "${worksched_service_path}/zidl/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/", - "//foundation/ace/napi/native_engine" + "//foundation/ace/napi/native_engine", ] } @@ -29,12 +29,14 @@ ohos_shared_library("workschedclient") { sources = [ "${worksched_frameworks_path}/src/work_info.cpp", "${worksched_frameworks_path}/src/workscheduler_srv_client.cpp", + # "${worksched_frameworks_path}/src/work_scheduler_extension_context.cpp", # "${worksched_frameworks_path}/src/work_scheduler_extension.cpp", # "${worksched_frameworks_path}/src/js_work_scheduler_extension.cpp", # "${worksched_frameworks_path}/src/js_work_scheduler_extension_context.cpp", "${worksched_service_path}/zidl/src/work_conn_proxy.cpp", "${worksched_service_path}/zidl/src/work_sched_service_proxy.cpp", + # "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", # "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp" ] @@ -45,25 +47,26 @@ ohos_shared_library("workschedclient") { deps = [ "${worksched_utils_path}:workschedutils", - # "${worksched_frameworks_path}/extension:workschedextension", - "//third_party/jsoncpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/ace/napi:ace_napi", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native" + + # "${worksched_frameworks_path}/extension:workschedextension", + "//third_party/jsoncpp", ] external_deps = [ - "safwk:system_ability_fwk", - "ipc:ipc_core", - "samgr_standard:samgr_proxy", - "hiviewdfx_hilog_native:libhilog", - "appexecfwk_standard:appexecfwk_core", - "ability_runtime:app_manager", - "ability_runtime:want", "ability_runtime:ability_manager", + "ability_runtime:app_manager", "ability_runtime:runtime", - "napi:ace_napi" + "ability_runtime:want", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", ] part_name = "${worksched_native_part_name}" -} \ No newline at end of file +} diff --git a/frameworks/extension/BUILD.gn b/frameworks/extension/BUILD.gn index 0e05084..f397de6 100644 --- a/frameworks/extension/BUILD.gn +++ b/frameworks/extension/BUILD.gn @@ -17,7 +17,7 @@ config("worksched_private_config") { include_dirs = [ "${worksched_service_path}/zidl/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/", - "//foundation/ace/napi/native_engine" + "//foundation/ace/napi/native_engine", ] } @@ -27,13 +27,13 @@ config("worksched_public_config") { ohos_shared_library("workschedextension") { sources = [ - "src/work_scheduler_extension_context.cpp", - "src/work_scheduler_extension.cpp", + "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp", + "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", "src/js_work_scheduler_extension.cpp", "src/js_work_scheduler_extension_context.cpp", + "src/work_scheduler_extension.cpp", + "src/work_scheduler_extension_context.cpp", "src/work_scheduler_extension_module_loader.cpp", - "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", - "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp" ] configs = [ ":worksched_private_config" ] @@ -42,24 +42,24 @@ ohos_shared_library("workschedextension") { deps = [ "${worksched_utils_path}:workschedutils", - "//third_party/jsoncpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/ace/napi:ace_napi", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native" + "//third_party/jsoncpp", ] external_deps = [ - "safwk:system_ability_fwk", - "ipc:ipc_core", - "samgr_standard:samgr_proxy", - "hiviewdfx_hilog_native:libhilog", - "appexecfwk_standard:appexecfwk_core", - "ability_runtime:app_manager", - "ability_runtime:want", "ability_runtime:ability_manager", + "ability_runtime:app_manager", "ability_runtime:runtime", - "napi:ace_napi" + "ability_runtime:want", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", ] part_name = "${worksched_native_part_name}" -} \ No newline at end of file +} diff --git a/frameworks/extension/src/work_scheduler_extension.cpp b/frameworks/extension/src/work_scheduler_extension.cpp index 37925a2..998f30c 100644 --- a/frameworks/extension/src/work_scheduler_extension.cpp +++ b/frameworks/extension/src/work_scheduler_extension.cpp @@ -16,11 +16,7 @@ #include "work_scheduler_extension.h" #include "ability_loader.h" -#include "extension_base.cpp" -//#include "hilog_wrapper.h" -// #include "work_sched_hilog.h" #include "js_work_scheduler_extension.h" -//#include "static_subscriber_extension_context.h" namespace OHOS { namespace WorkScheduler { diff --git a/frameworks/include/work_condition.h b/frameworks/include/work_condition.h index 201be40..cef52c9 100644 --- a/frameworks/include/work_condition.h +++ b/frameworks/include/work_condition.h @@ -46,7 +46,6 @@ public: NETWORK_TYPE_BLUETOOTH, NETWORK_TYPE_WIFI_P2P, NETWORK_TYPE_ETHERNET, - NETWORK_TYPE_DISCONNECT, NETWORK_UNKNOWN }; enum Charger { diff --git a/frameworks/src/workscheduler_srv_client.cpp b/frameworks/src/workscheduler_srv_client.cpp index c35cc7c..ea66f81 100644 --- a/frameworks/src/workscheduler_srv_client.cpp +++ b/frameworks/src/workscheduler_srv_client.cpp @@ -45,25 +45,25 @@ ErrCode WorkSchedulerSrvClient::Connect() } sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sam == nullptr) { - WS_HILOGE("%{public}s failed to get registry!", __func__); - return E_GET_SYSTEM_ABILITY_MANAGER_FAILED_WORKSCHED; + WS_HILOGE("GetSystemAbilityManager failed!"); + return E_CLIENT_CONNECT_SERVICE_FAILED; } sptr remoteObject_ = sam->CheckSystemAbility(WORK_SCHEDULE_SERVICE_ID); if (remoteObject_ == nullptr) { WS_HILOGE("GetSystemAbility failed!"); - return E_GET_WORKSCHED_SERVICE_FALIED; + return E_CLIENT_CONNECT_SERVICE_FAILED; } deathRecipient_ = sptr(new WorkSchedulerDeathRecipient()); if (deathRecipient_ == nullptr) { - WS_HILOGE("%{public}s failed to create WorkScheduelrDeathRecipient!", __func__); - return ERR_NO_MEMORY; + WS_HILOGE("Failed to create WorkScheduelrDeathRecipient!"); + return E_CLIENT_CONNECT_SERVICE_FAILED; } if ((remoteObject_->IsProxyObject()) && (!remoteObject_->AddDeathRecipient(deathRecipient_))) { - WS_HILOGE("%{public}s Add death recipient to WorkSchedulerService failed!", __func__); - return E_ADD_WORK_SCHED_DEATH_RECIPIENT_FAILED; + WS_HILOGE("Add death recipient to WorkSchedulerService failed!"); + return E_CLIENT_CONNECT_SERVICE_FAILED; } iWorkSchedService_ = iface_cast(remoteObject_); - WS_HILOGD("%{public}s Connecting WorkSchedService success.", __func__); + WS_HILOGD("Connecting WorkSchedService success."); return ERR_OK; } @@ -122,9 +122,8 @@ bool WorkSchedulerSrvClient::StopAndCancelWork(WorkInfo& workInfo) bool WorkSchedulerSrvClient::StopAndClearWorks() { - WS_HILOGD("%{public}s.", __func__); if (Connect() != ERR_OK) { - WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); + WS_HILOGE("StopAndClearWorks connect service failed!"); return false; } return iWorkSchedService_->StopAndClearWorks(); @@ -132,7 +131,6 @@ bool WorkSchedulerSrvClient::StopAndClearWorks() ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) { - WS_HILOGD("%{public}s.", __func__); ErrCode errCode = Connect(); if (errCode != ERR_OK) { return errCode; @@ -143,7 +141,6 @@ ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list> &workInfos) { - WS_HILOGD("%{public}s.", __func__); ErrCode errCode = Connect(); if (errCode != ERR_OK) { return errCode; @@ -155,7 +152,9 @@ ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list &workInfo) { - WS_HILOGD("%{public}s.", __func__); + if (workId <= 0) { + return E_WORK_ID_INVALID; + } ErrCode code = Connect(); if (code != ERR_OK) { return code; @@ -163,7 +162,7 @@ ErrCode WorkSchedulerSrvClient::GetWorkStatus(int32_t workId, std::shared_ptrGetWorkStatus(uid, workId); if (workInfo == nullptr) { - return E_INNER_ERR; + return E_GET_WORK_STATUS_ERROR; } return ERR_OK; } diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 6ab8141..79af9ba 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -41,14 +41,14 @@ ohos_shared_library("workscheduler") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:libeventhandler", - "ipc:ipc_core", + "bundle_framework:appexecfwk_base", + "ces_standard:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "ces_standard:cesfwk_innerkits", - "napi:ace_napi" ] relative_install_dir = "module" diff --git a/interfaces/kits/js/napi/include/common.h b/interfaces/kits/js/napi/include/common.h index bf36dde..1960991 100644 --- a/interfaces/kits/js/napi/include/common.h +++ b/interfaces/kits/js/napi/include/common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -28,30 +28,10 @@ struct CallbackPromiseInfo { int errorCode = 0; }; -class WorkContext { -public: - int workId; - int32_t networkType; - bool isDeepIdle; - int32_t idleWaitTime; - int32_t isCharging; - int32_t chargingType; - int32_t batteryLevel; - int32_t batteryStatus; - int32_t storageRequest; - bool isRepeat; - bool isPersisted; - int32_t repeatCycleTime; - int32_t repeatCount; - std::string bundleName; - std::string abilityName; -}; - class Common { public: static napi_value NapiGetNull(napi_env env); - static WorkInfo ParseWorkInfo(WorkContext &workContext); - static void GetWorkInfo(napi_env env, napi_value objValue, WorkContext &workContext); + static bool GetWorkInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); static int32_t GetIntProperty(napi_env env, napi_value object, const std::string &propertyName); static bool GetBoolProperty(napi_env env, napi_value object, const std::string &propertyName); static int32_t GetBoolToIntProperty(napi_env env, napi_value object, const std::string &propertyName); @@ -62,9 +42,19 @@ public: const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); static napi_value GetNapiWorkInfo(napi_env env, std::shared_ptr &workInfo); static napi_value GetCallbackErrorValue(napi_env env, int errCode); - static void SetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result); + static void SetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, + const napi_value &result); static napi_value SetPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); - static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); + static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, + const napi_value &result); + +private: + static bool GetBaseWorkInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); + static bool GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); + static bool GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); + static bool GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); + static bool GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); + static bool GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &WorkInfo); }; } } diff --git a/interfaces/kits/js/napi/include/get_work_status.h b/interfaces/kits/js/napi/include/get_work_status.h index 5dec1f2..801265b 100644 --- a/interfaces/kits/js/napi/include/get_work_status.h +++ b/interfaces/kits/js/napi/include/get_work_status.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/kits/js/napi/include/is_last_work_time_out.h b/interfaces/kits/js/napi/include/is_last_work_time_out.h index 4613f74..3f856cc 100644 --- a/interfaces/kits/js/napi/include/is_last_work_time_out.h +++ b/interfaces/kits/js/napi/include/is_last_work_time_out.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,8 +16,6 @@ #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT -#include - #include "napi/native_api.h" namespace OHOS { diff --git a/interfaces/kits/js/napi/include/obtain_all_works.h b/interfaces/kits/js/napi/include/obtain_all_works.h index 428255d..7efd7ac 100644 --- a/interfaces/kits/js/napi/include/obtain_all_works.h +++ b/interfaces/kits/js/napi/include/obtain_all_works.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS -#include - #include "napi/native_api.h" namespace OHOS { diff --git a/interfaces/kits/js/napi/include/start_work.h b/interfaces/kits/js/napi/include/start_work.h index 1e59ba2..4b0cc6c 100644 --- a/interfaces/kits/js/napi/include/start_work.h +++ b/interfaces/kits/js/napi/include/start_work.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK -#include - #include "napi/native_api.h" namespace OHOS { diff --git a/interfaces/kits/js/napi/include/stop_and_clear_works.h b/interfaces/kits/js/napi/include/stop_and_clear_works.h index 1c7704b..4635729 100644 --- a/interfaces/kits/js/napi/include/stop_and_clear_works.h +++ b/interfaces/kits/js/napi/include/stop_and_clear_works.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_AND_CLEAR_WORKS #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_AND_CLEAR_WORKS -#include - #include "napi/native_api.h" #include "napi/native_node_api.h" diff --git a/interfaces/kits/js/napi/include/stop_work.h b/interfaces/kits/js/napi/include/stop_work.h index 881b9e4..d3bf174 100644 --- a/interfaces/kits/js/napi/include/stop_work.h +++ b/interfaces/kits/js/napi/include/stop_work.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK -#include - #include "napi/native_api.h" namespace OHOS { diff --git a/interfaces/kits/js/napi/include/workscheduler_napi.h b/interfaces/kits/js/napi/include/workscheduler_napi.h index a88c983..69d0794 100644 --- a/interfaces/kits/js/napi/include/workscheduler_napi.h +++ b/interfaces/kits/js/napi/include/workscheduler_napi.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORKSCHED_NAPI_H -#define WORKSCHED_NAPI_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHED_NAPI_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHED_NAPI_H #include "napi/native_api.h" #include "napi/native_node_api.h" @@ -53,6 +52,6 @@ napi_module _module = { .nm_priv = ((void *)0), .reserved = {0} }; -} -} +} // namespace WorkScheduler +} // namespace OHOS #endif \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index 6dfb5ac..1e57db6 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,16 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include - #include "common.h" + +#include "errors.h" #include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { const int NAME_MAXIMUM_LIMIT = 128; const int RESULT_PARAMS_NUM = 2; -const int UNSET_PARAM = -1; +const int UNSET_INT_PARAM = -1; +const std::string UNSET_STRING_PARAM = ""; const int TRUE_PARAM = 1; const int FALSE_PARAM = 0; @@ -32,61 +33,166 @@ napi_value Common::NapiGetNull(napi_env env) return result; } -WorkInfo Common::ParseWorkInfo(WorkContext &workContext) +bool Common::GetBaseWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(workContext.workId); - workInfo.SetElement(workContext.bundleName, workContext.abilityName); - if (workContext.networkType != UNSET_PARAM) { - workInfo.RequestNetworkType(WorkCondition::Network(workContext.networkType)); + // Get workid. + int workId = Common::GetIntProperty(env, objValue, "workId"); + if (workId == UNSET_INT_PARAM || workId < 0) { + WS_HILOGE("Work id is invalid, failed."); + return false; } - if (workContext.isCharging == FALSE_PARAM) { + + // Get bundleName and abilityName. + std::string bundleName = Common::GetStringProperty(env, objValue, "bundleName"); + std::string abilityName = Common::GetStringProperty(env, objValue, "abilityName"); + if (bundleName == UNSET_STRING_PARAM || abilityName == UNSET_STRING_PARAM) { + WS_HILOGE("BundleName or abilityName is invalid, failed."); + return false; + } + + workInfo.SetWorkId(workId); + workInfo.SetElement(bundleName, abilityName); + + // Get persist param. if not set, it will be used false. + workInfo.RequestPersisted(Common::GetBoolProperty(env, objValue, "isPersisted")); + return true; +} + +bool Common::GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { + bool hasCondition = false; + int32_t networkType = Common::GetIntProperty(env, objValue, "networkType"); + if (networkType == UNSET_INT_PARAM) { + WS_HILOGI("Unset networkType."); + } else if (networkType >= WorkCondition::Network::NETWORK_TYPE_ANY && + networkType <= WorkCondition::Network::NETWORK_TYPE_ETHERNET) { + workInfo.RequestNetworkType(WorkCondition::Network(networkType)); + hasCondition = true; + } else { + WS_HILOGI("NetworkType set is invalid, just ignore set."); + } + return hasCondition; +} + +bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { + bool hasCondition = false; + int32_t isCharging = Common::GetBoolToIntProperty(env, objValue, "isCharging"); + int32_t chargerType = Common::GetIntProperty(env, objValue, "chargerType"); + if (isCharging == UNSET_INT_PARAM) { + WS_HILOGI("Unset isCharging, ignore ChargerType set also."); + } else if (isCharging == FALSE_PARAM) { workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGER_UNPLUGGED); - } else if (workContext.isCharging == TRUE_PARAM && workContext.chargingType != UNSET_PARAM) { - workInfo.RequestChargerType(true, WorkCondition::Charger(workContext.chargingType)); - } else if (workContext.isCharging == TRUE_PARAM && workContext.chargingType == UNSET_PARAM) { - workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); + hasCondition = true; + } else { + if (chargerType == UNSET_INT_PARAM) { + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); + } else if (chargerType >= WorkCondition::Charger::CHARGER_PLUGGED_ANY && + chargerType <= WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS) { + workInfo.RequestChargerType(true, WorkCondition::Charger(chargerType)); + } else { + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); + WS_HILOGI("ChargeType info is invalid, just ignore set."); + } + hasCondition = true; } - if (workContext.batteryLevel != UNSET_PARAM) { - workInfo.RequestBatteryLevel(workContext.batteryLevel); + return hasCondition; +} + +bool Common::GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { + bool hasCondition = false; + // Get battery level info. + int32_t batteryLevel = Common::GetIntProperty(env, objValue, "batteryLevel"); + if (batteryLevel == UNSET_INT_PARAM) { + WS_HILOGI("Unset batteryLevel."); + } else if (batteryLevel >= 0 && batteryLevel <= 100) { + // batteryLevel only can be between 0 and 100. + workInfo.RequestBatteryLevel(batteryLevel); + hasCondition = true; + } else { + WS_HILOGI("BatteryLevel set is invalid, just ignore set."); } - if (workContext.batteryStatus != UNSET_PARAM) { - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus(workContext.batteryStatus)); + + // Get battery status info. + int32_t batteryStatus = Common::GetIntProperty(env, objValue, "batteryStatus"); + if (batteryStatus == UNSET_INT_PARAM) { + WS_HILOGI("Unset batteryStatus."); + } else if (batteryStatus >= WorkCondition::BatteryStatus::BATTERY_STATUS_LOW && + batteryStatus <= WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY) { + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus(batteryStatus)); + hasCondition = true; + } else { + WS_HILOGI("BatteryStatus set is invalid, just ignore set."); } - if (workContext.storageRequest != UNSET_PARAM) { - workInfo.RequestStorageLevel(WorkCondition::Storage(workContext.storageRequest)); + return hasCondition; +} + +bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { + bool hasCondition = false; + int32_t storageRequest = Common::GetIntProperty(env, objValue, "storageRequest"); + if (storageRequest == UNSET_INT_PARAM) { + WS_HILOGI("Unset StorageRequest."); + } else if (storageRequest >= WorkCondition::Storage::STORAGE_LEVEL_LOW + && storageRequest <= WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY) { + workInfo.RequestStorageLevel(WorkCondition::Storage(storageRequest)); + hasCondition = true; + } else { + WS_HILOGI("StorageRequest set is invalid, just ignore set."); } - if (workContext.isRepeat == TRUE_PARAM) { - if (workContext.repeatCycleTime != UNSET_PARAM && workContext.repeatCount != UNSET_PARAM) { - workInfo.RequestRepeatCycle(workContext.repeatCycleTime, workContext.repeatCount); + return hasCondition; +} + +bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { + bool hasCondition = false; + bool isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); + if (isRepeat) { + int32_t repeatCycleTime = Common::GetIntProperty(env, objValue, "repeatCycleTime"); + int32_t repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); + if (repeatCycleTime == UNSET_INT_PARAM || repeatCount == UNSET_INT_PARAM) { + WS_HILOGI("RepeatCycleTime or repeatCycleTime set is invalid, just ignore set."); + } else { + workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount); + hasCondition = true; } + } else { + WS_HILOGI("Not set isRepeat or set isRepeat false, ignore repeatCycleTime and repeatCount."); } - workInfo.RequestPersisted(workContext.isPersisted); - return workInfo; + return hasCondition; } -void Common::GetWorkInfo(napi_env env, napi_value objValue, WorkContext &workContext) +bool Common::GetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { - workContext.workId = Common::GetIntProperty(env, objValue, "workId"); - workContext.bundleName = Common::GetStringProperty(env, objValue, "bundleName"); - workContext.abilityName = Common::GetStringProperty(env, objValue, "abilityName"); - workContext.networkType = Common::GetIntProperty(env, objValue, "networkType"); - workContext.chargingType = Common::GetIntProperty(env, objValue, "chargerType"); - workContext.batteryLevel = Common::GetIntProperty(env, objValue, "batteryLevel"); - workContext.batteryStatus = Common::GetIntProperty(env, objValue, "batteryStatus"); - workContext.storageRequest = Common::GetIntProperty(env, objValue, "storageRequest"); - workContext.isCharging = Common::GetBoolToIntProperty(env, objValue, "isCharging"); - workContext.isPersisted = Common::GetBoolProperty(env, objValue, "isPersisted"); - workContext.isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); - workContext.repeatCycleTime = Common::GetIntProperty(env, objValue, "repeatCycleTime"); - workContext.repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); - workContext.isDeepIdle = Common::GetBoolProperty(env, objValue, "isDeepIdle"); - workContext.idleWaitTime = Common::GetIntProperty(env, objValue, "idleWaitTime"); + // Get base info. + if (!GetBaseWorkInfo(env, objValue, workInfo)) { + return false; + } + + // Get condition info. + bool hasConditions = false; + if (GetNetWorkInfo(env, objValue, workInfo)) { + hasConditions = true; + } + if (GetChargeInfo(env, objValue, workInfo)) { + hasConditions = true; + } + if (GetBatteryInfo(env, objValue, workInfo)) { + hasConditions = true; + } + if (GetStorageInfo(env, objValue, workInfo)) { + hasConditions = true; + } + if (GetRepeatInfo(env, objValue, workInfo)) { + hasConditions = true; + } + + if (!hasConditions) { + WS_HILOGE("Set none conditions, so fail to init WorkInfo."); + return false; + } + return true; } int32_t Common::GetIntProperty(napi_env env, napi_value object, const std::string &propertyName) { - int32_t intValue = UNSET_PARAM; + int32_t intValue = UNSET_INT_PARAM; napi_value value = nullptr; napi_status getNameStatus = napi_get_named_property(env, object, propertyName.c_str(), &value); if (getNameStatus == napi_ok) { @@ -123,7 +229,7 @@ int32_t Common::GetBoolToIntProperty(napi_env env, napi_value object, const std: return boolValue ? TRUE_PARAM : FALSE_PARAM; } } - return UNSET_PARAM; + return UNSET_INT_PARAM; } std::string Common::GetStringProperty(napi_env env, napi_value object, const std::string &propertyName) @@ -139,7 +245,7 @@ std::string Common::GetStringProperty(napi_env env, napi_value object, const std return std::string(chars, charLength); } } - return ""; + return UNSET_STRING_PARAM; } bool Common::MatchValueType(napi_env env, napi_value value, napi_valuetype targetType) @@ -266,4 +372,4 @@ void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInf } } } -} +} \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/get_work_status.cpp b/interfaces/kits/js/napi/src/get_work_status.cpp index 2b42af2..3ad4b59 100644 --- a/interfaces/kits/js/napi/src/get_work_status.cpp +++ b/interfaces/kits/js/napi/src/get_work_status.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,13 +13,13 @@ * limitations under the License. */ #include "get_work_status.h" + #include "common.h" -#include "work_sched_hilog.h" #include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { - static const int32_t WORK_ID_INDEX = 0; static const int32_t CALLBACK_INDEX = 1; static const int32_t GET_WORK_STATUS_MIN_PARAMS = 1; @@ -63,7 +63,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value GetWorkStatus(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("Get work status napi begin."); // Get params. GetWorkStatusParamsInfo params; @@ -90,7 +90,8 @@ napi_value GetWorkStatus(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncCallbackInfoGetWorkStatus *asynccallbackinfo = (AsyncCallbackInfoGetWorkStatus *)data; asynccallbackinfo->info.errorCode = - WorkSchedulerSrvClient::GetInstance().GetWorkStatus(asynccallbackinfo->workId, asynccallbackinfo->workInfo); + WorkSchedulerSrvClient::GetInstance().GetWorkStatus(asynccallbackinfo->workId, + asynccallbackinfo->workInfo); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoGetWorkStatus *asynccallbackinfo = (AsyncCallbackInfoGetWorkStatus *)data; @@ -111,6 +112,7 @@ napi_value GetWorkStatus(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + WS_HILOGD("Get work status napi end."); if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { diff --git a/interfaces/kits/js/napi/src/is_last_work_time_out.cpp b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp index c7aebf2..d9fa6ce 100644 --- a/interfaces/kits/js/napi/src/is_last_work_time_out.cpp +++ b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,13 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "is_last_work_time_out.h" + #include "common.h" -#include "work_sched_hilog.h" #include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { - static const int32_t WORK_ID_INDEX = 0; static const int32_t CALLBACK_INDEX = 1; static const int32_t IS_LAST_WORK_TIME_OUT_MIN_PARAMS = 1; @@ -62,7 +63,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value IsLastWorkTimeOut(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("IsLastWorkTimeOut napi begin."); // Get params. IsLastWorkTimeOutParamsInfo params; @@ -89,10 +90,11 @@ napi_value IsLastWorkTimeOut(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = (AsyncCallbackIsLastWorkTimeOut *)data; asynccallbackinfo->info.errorCode = - WorkSchedulerSrvClient::GetInstance().IsLastWorkTimeout(asynccallbackinfo->workId, asynccallbackinfo->result); + WorkSchedulerSrvClient::GetInstance().IsLastWorkTimeout(asynccallbackinfo->workId, + asynccallbackinfo->result); }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = (AsyncCallbackIsLastWorkTimeOut *)data; + AsyncCallbackIsLastWorkTimeOut *asynccallbackinfo = (AsyncCallbackIsLastWorkTimeOut *) data; if (asynccallbackinfo != nullptr) { napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { @@ -114,6 +116,7 @@ napi_value IsLastWorkTimeOut(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + WS_HILOGD("IsLastWorkTimeOut napi end."); if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { diff --git a/interfaces/kits/js/napi/src/obtain_all_works.cpp b/interfaces/kits/js/napi/src/obtain_all_works.cpp index a511185..efd2649 100644 --- a/interfaces/kits/js/napi/src/obtain_all_works.cpp +++ b/interfaces/kits/js/napi/src/obtain_all_works.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,13 +13,13 @@ * limitations under the License. */ #include "obtain_all_works.h" + +#include "common.h" #include "workscheduler_srv_client.h" #include "work_sched_hilog.h" -#include "common.h" namespace OHOS { namespace WorkScheduler { - static const int32_t CALLBACK_INDEX = 0; static const int32_t OBTAIN_ALL_WORKS_MIN_PARAMS = 0; static const int32_t OBTAIN_ALL_WORKS_MAX_PARAMS = 1; @@ -48,7 +48,8 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value ObtainAllWorks(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("ObtainAllWorks napi begin."); + // Get params. napi_ref callback = nullptr; if (ParseParameters(env, info, callback) == nullptr) { @@ -104,6 +105,7 @@ napi_value ObtainAllWorks(napi_env env, napi_callback_info info) &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + WS_HILOGD("ObtainAllWorks napi end."); if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { diff --git a/interfaces/kits/js/napi/src/start_work.cpp b/interfaces/kits/js/napi/src/start_work.cpp index eb7a761..365f286 100644 --- a/interfaces/kits/js/napi/src/start_work.cpp +++ b/interfaces/kits/js/napi/src/start_work.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ #include "start_work.h" -#include "work_sched_hilog.h" -#include "workscheduler_srv_client.h" + #include "common.h" +#include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { - static const int32_t WORK_INFO_INDEX = 0; static const int32_t START_WORK_PARAMS = 1; napi_value StartWork(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("Start work napi begin."); // Check params. size_t argc = START_WORK_PARAMS; @@ -33,19 +33,20 @@ napi_value StartWork(napi_env env, napi_callback_info info) napi_get_cb_info(env, info, &argc, argv, NULL, NULL); NAPI_ASSERT(env, argc == START_WORK_PARAMS, "parameter error!"); bool matchFlag = Common::MatchValueType(env, argv[WORK_INFO_INDEX], napi_object); - NAPI_ASSERT(env, matchFlag, "Type error, Should is object"); - - // Create work info. - auto workContext = (std::make_unique()).release(); - Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], *workContext); - WorkInfo workInfo = Common::ParseWorkInfo(*workContext); + NAPI_ASSERT(env, matchFlag, "Type error, it should be object"); - // Call service. - bool result = WorkSchedulerSrvClient::GetInstance().StartWork(workInfo); + // Get workInfo and call service. + WorkInfo workInfo = WorkInfo(); + bool result; + if (!Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], workInfo)) { + result = false; + } else { + result = WorkSchedulerSrvClient::GetInstance().StartWork(workInfo); + } napi_value napiValue = nullptr; NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + WS_HILOGD("Start work napi end."); return napiValue; - WS_HILOGD("%{public}s: return", __func__); } } } diff --git a/interfaces/kits/js/napi/src/stop_and_clear_works.cpp b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp index a0747d3..76637a7 100644 --- a/interfaces/kits/js/napi/src/stop_and_clear_works.cpp +++ b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,6 +13,7 @@ * limitations under the License. */ #include "stop_and_clear_works.h" + #include "workscheduler_srv_client.h" #include "work_sched_hilog.h" @@ -21,13 +22,12 @@ namespace WorkScheduler { napi_value StopAndClearWorks(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("StopAndClearWorks napi begin"); napi_value napiValue = nullptr; bool result = WorkSchedulerSrvClient::GetInstance().StopAndClearWorks(); NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); - WS_HILOGD("%{public}s: call result: %{public}s", __func__, result ? "true" : "false"); + WS_HILOGD("StopAndClearWorks napi end. result: %{public}s", result ? "true" : "false"); return napiValue; - WS_HILOGD("%{public}s: return", __func__); } } } diff --git a/interfaces/kits/js/napi/src/stop_work.cpp b/interfaces/kits/js/napi/src/stop_work.cpp index 32d092c..c478988 100644 --- a/interfaces/kits/js/napi/src/stop_work.cpp +++ b/interfaces/kits/js/napi/src/stop_work.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,9 +13,10 @@ * limitations under the License. */ #include "stop_work.h" + #include "common.h" -#include "work_sched_hilog.h" #include "workscheduler_srv_client.h" +#include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { @@ -25,7 +26,7 @@ static const int32_t STOP_WORK_PARAMS = 2; napi_value StopWork(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("Stop Work napi begin."); // Check params. size_t argc = STOP_WORK_PARAMS; @@ -38,23 +39,27 @@ napi_value StopWork(napi_env env, napi_callback_info info) NAPI_ASSERT(env, matchFlag, "Type error, Should is boolean"); // get params - auto workContext = (std::make_unique()).release(); - Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], *workContext); - WorkInfo workInfo = Common::ParseWorkInfo(*workContext); + WorkInfo workInfo = WorkInfo(); + bool getWorkRes = Common::GetWorkInfo(env, argv[WORK_INFO_INDEX], workInfo); bool needCancel = false; napi_get_value_bool(env, argv[NEED_CANCEL_INDEX], &needCancel); - // call service. - bool result = false; - if (needCancel) { - result = WorkSchedulerSrvClient::GetInstance().StopAndCancelWork(workInfo); + // Check workInfo and call service. + bool result; + if (!getWorkRes) { + WS_HILOGD("Work info create failed."); + result = false; } else { - result = WorkSchedulerSrvClient::GetInstance().StopWork(workInfo); + if (needCancel) { + result = WorkSchedulerSrvClient::GetInstance().StopAndCancelWork(workInfo); + } else { + result = WorkSchedulerSrvClient::GetInstance().StopWork(workInfo); + } } napi_value napiValue = nullptr; NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + WS_HILOGD("Stop Work napi end."); return napiValue; - WS_HILOGD("%{public}s: return", __func__); } } } \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/workscheduler_napi.cpp b/interfaces/kits/js/napi/src/workscheduler_napi.cpp index a251ac6..579612d 100644 --- a/interfaces/kits/js/napi/src/workscheduler_napi.cpp +++ b/interfaces/kits/js/napi/src/workscheduler_napi.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -38,7 +38,7 @@ napi_ref storageRequestConstructor_ = nullptr; napi_value Init(napi_env env, napi_value exports) { - WS_HILOGD("%{public}s: enter", __func__); + WS_HILOGD("Work scheduler napi init."); napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("startWork", StartWork), DECLARE_NAPI_FUNCTION("stopWork", StopWork), @@ -69,12 +69,18 @@ napi_value InitNetworkType(napi_env env, napi_value exports) napi_value network_type_ethernet; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ANY), &network_type_any); - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_MOBILE), &network_type_mobile); - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI), &network_type_wifi); - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_BLUETOOTH), &network_type_bluetooth); - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI_P2P), &network_type_wifi_p2p); - napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ETHERNET), &network_type_ethernet); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ANY), + &network_type_any); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_MOBILE), + &network_type_mobile); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI), + &network_type_wifi); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_BLUETOOTH), + &network_type_bluetooth); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_WIFI_P2P), + &network_type_wifi_p2p); + napi_create_uint32(env, static_cast(WorkCondition::Network::NETWORK_TYPE_ETHERNET), + &network_type_ethernet); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("NETWORK_TYPE_ANY", network_type_any), @@ -86,9 +92,11 @@ napi_value InitNetworkType(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &networkTypeConstructor_); - napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "NetworkType", NAPI_AUTO_LENGTH, EnumNetworkTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &networkTypeConstructor_); napi_set_named_property(env, exports, "NetworkType", result); return exports; @@ -96,20 +104,17 @@ napi_value InitNetworkType(napi_env env, napi_value exports) napi_value EnumNetworkTypeConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; - napi_value args[ARG_FIRST] = { 0 }; - napi_value jsthis = nullptr; + napi_value args[ARG_FIRST] = {0}; + napi_value res = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - - WS_HILOGD("EnumNetworkTypeConstructor %{public}d", status); + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); if (status != napi_ok) { return nullptr; } - WS_HILOGD("%{public}s: return", __func__); - return jsthis; + + return res; } napi_value InitChargingType(napi_env env, napi_value exports) @@ -120,10 +125,14 @@ napi_value InitChargingType(napi_env env, napi_value exports) napi_value charging_plugged_wireless; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY), &charging_plugged_any); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_AC), &charging_plugged_ac); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_USB), &charging_plugged_usb); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS), &charging_plugged_wireless); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY), + &charging_plugged_any); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_AC), + &charging_plugged_ac); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_USB), + &charging_plugged_usb); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS), + &charging_plugged_wireless); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("CHARGING_PLUGGED_ANY", charging_plugged_any), @@ -133,7 +142,8 @@ napi_value InitChargingType(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "ChargingType", NAPI_AUTO_LENGTH, EnumChargingTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "ChargingType", NAPI_AUTO_LENGTH, EnumChargingTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &chargingTypeConstructor_); napi_set_named_property(env, exports, "ChargingType", result); return exports; @@ -142,18 +152,16 @@ napi_value InitChargingType(napi_env env, napi_value exports) napi_value EnumChargingTypeConstructor(napi_env env, napi_callback_info info) { size_t argc = 0; - napi_value args[ARG_FIRST] = { 0 }; - napi_value jsthis = nullptr; + napi_value args[ARG_FIRST] = {0}; + napi_value res = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - - WS_HILOGD("EnumChargingTypeConstructor %{public}d", status); + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); if (status != napi_ok) { return nullptr; } - WS_HILOGD("%{public}s: return", __func__); - return jsthis; + + return res; } napi_value InitBatteryStatus(napi_env env, napi_value exports) @@ -163,9 +171,12 @@ napi_value InitBatteryStatus(napi_env env, napi_value exports) napi_value battery_status_low_or_okay; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW), &battery_status_low); - napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY), &battery_status_okay); - napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY), &battery_status_low_or_okay); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW), + &battery_status_low); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY), + &battery_status_okay); + napi_create_uint32(env, static_cast(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY), + &battery_status_low_or_okay); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("BATTERY_STATUS_LOW", battery_status_low), @@ -174,7 +185,8 @@ napi_value InitBatteryStatus(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "BatteryStatus", NAPI_AUTO_LENGTH, EnumBatteryStatusConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "BatteryStatus", NAPI_AUTO_LENGTH, EnumBatteryStatusConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &batteryStatusConstructor_); napi_set_named_property(env, exports, "BatteryStatus", result); return exports; @@ -182,20 +194,16 @@ napi_value InitBatteryStatus(napi_env env, napi_value exports) napi_value EnumBatteryStatusConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; - napi_value args[ARG_FIRST] = { 0 }; - napi_value jsthis = nullptr; + napi_value args[ARG_FIRST] = {0}; + napi_value res = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - - WS_HILOGD("EnumBatteryStatusConstructor %{public}d", status); + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); if (status != napi_ok) { return nullptr; } - WS_HILOGD("%{public}s: return", __func__); - return jsthis; + return res; } napi_value InitStorageRequest(napi_env env, napi_value exports) @@ -205,9 +213,12 @@ napi_value InitStorageRequest(napi_env env, napi_value exports) napi_value storage_level_low_or_okay; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW), &storage_level_low); - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_OKAY), &storage_level_okay); - napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY), &storage_level_low_or_okay); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW), + &storage_level_low); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_OKAY), + &storage_level_okay); + napi_create_uint32(env, static_cast(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY), + &storage_level_low_or_okay); napi_property_descriptor desc[] = { DECLARE_NAPI_STATIC_PROPERTY("STORAGE_LEVEL_LOW", storage_level_low), @@ -216,7 +227,8 @@ napi_value InitStorageRequest(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "StorageRequest", NAPI_AUTO_LENGTH, EnumStorageRequestConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_define_class(env, "StorageRequest", NAPI_AUTO_LENGTH, EnumStorageRequestConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); napi_create_reference(env, result, refCount, &storageRequestConstructor_); napi_set_named_property(env, exports, "StorageRequest", result); return exports; @@ -224,20 +236,17 @@ napi_value InitStorageRequest(napi_env env, napi_value exports) napi_value EnumStorageRequestConstructor(napi_env env, napi_callback_info info) { - WS_HILOGD("%{public}s: enter", __func__); size_t argc = 0; - napi_value args[ARG_FIRST] = { 0 }; - napi_value jsthis = nullptr; + napi_value args[ARG_FIRST] = {0}; + napi_value res = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); - - WS_HILOGD("EnumStorageRequestConstructor %{public}d", status); + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); if (status != napi_ok) { return nullptr; } - WS_HILOGD("%{public}s: return", __func__); - return jsthis; + + return res; } /* @@ -248,6 +257,5 @@ __attribute__((constructor)) void RegisterModule(void) napi_module_register(&_module); } EXTERN_C_END - -} -} \ No newline at end of file +} // namespace WorkScheduler +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn new file mode 100644 index 0000000..e46065e --- /dev/null +++ b/interfaces/test/unittest/BUILD.gn @@ -0,0 +1,26 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +module_output_path = "work_scheduler_jsunittest/interfaces" + +ohos_js_unittest("WorkSchedulerJsTest") { + module_out_path = module_output_path + hap_profile = "./work_scheduler_jsunittest/config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + +group("js_unittest") { + testonly = true + deps = [ ":WorkSchedulerJsTest" ] +} \ No newline at end of file diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/config.json b/interfaces/test/unittest/work_scheduler_jsunittest/config.json new file mode 100644 index 0000000..a7dc22c --- /dev/null +++ b/interfaces/test/unittest/work_scheduler_jsunittest/config.json @@ -0,0 +1,60 @@ +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} \ No newline at end of file diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js new file mode 100644 index 0000000..2380674 --- /dev/null +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import workScheduler from '@ohos.workScheduler' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("WorkSchedulerJsTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll caled') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll caled') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach caled') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach caled') + }) + + /* + * @tc.name: WorkSchedulerJsTest001 + * @tc.desc: test work scheduler work id < 0 + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest001", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest001---------------------------'); + let workInfo = { + workId: -1, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName" + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(false) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest002 + * @tc.desc: test work scheduler work id = 0 + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest002", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest002---------------------------'); + let workInfo = { + workId: 0, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(true) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest003 + * @tc.desc: test work scheduler without bundle name. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest003", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest003---------------------------'); + let workInfo = { + workId: 3, + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(false) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest004 + * @tc.desc: test work scheduler without ability name. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest004", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest004---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(false) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest005 + * @tc.desc: test work scheduler without conditions. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest005", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest005---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName" + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(false) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest006 + * @tc.desc: test work scheduler success. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest006", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest006---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(true) + done(); + }) +}) \ No newline at end of file diff --git a/services/BUILD.gn b/services/BUILD.gn index 309b78d..55f373b 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -39,12 +39,12 @@ ohos_shared_library("workschedservice") { "native/src/work_queue.cpp", "native/src/work_queue_event_handler.cpp", "native/src/work_queue_manager.cpp", + "native/src/work_scheduler_connection.cpp", "native/src/work_scheduler_service.cpp", "native/src/work_status.cpp", "zidl/src//work_conn_stub.cpp", "zidl/src/work_sched_service_stub.cpp", "zidl/src/work_scheduler_proxy.cpp", - "native/src/work_scheduler_connection.cpp" ] configs = [ ":worksched_private_config" ] @@ -60,18 +60,19 @@ ohos_shared_library("workschedservice") { external_deps = [ "ability_runtime:ability_manager", + "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", "battery_manager_native:batterysrv_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", - "ability_runtime:app_manager" + # "thermal_manager_native:thermalsrv_client", ] diff --git a/utils/native/BUILD.gn b/utils/native/BUILD.gn index 529b57d..028590c 100644 --- a/utils/native/BUILD.gn +++ b/utils/native/BUILD.gn @@ -18,18 +18,14 @@ config("utils_config") { } ohos_source_set("workschedutils") { - sources = [ - "${worksched_utils_path}/src/work_sched_hilog.cpp" - ] + sources = [ "${worksched_utils_path}/src/work_sched_hilog.cpp" ] public_configs = [ ":utils_config" ] deps = [] external_deps = [ - "battery_manager_native:batterysrv_client", "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", "utils_base:utils", ] diff --git a/utils/native/include/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h index 334f5ae..8fbeae9 100644 --- a/utils/native/include/delayed_sp_singleton.h +++ b/utils/native/include/delayed_sp_singleton.h @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_UTILS_SP_SINGLETON_H -#define WORK_SCHED_UTILS_SP_SINGLETON_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_SP_SINGLETON_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_SP_SINGLETON_H #include #include @@ -72,4 +71,4 @@ void DelayedSpSingleton::DestroyInstance() } } // namespace WorkScheduler } // namespace OHOS -#endif // WORK_SCHED_UTILS_SP_SINGLETON_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_SP_SINGLETON_H \ No newline at end of file diff --git a/utils/native/include/work_sched_common.h b/utils/native/include/work_sched_common.h index 06bceef..874eaf1 100644 --- a/utils/native/include/work_sched_common.h +++ b/utils/native/include/work_sched_common.h @@ -13,14 +13,15 @@ * limitations under the License. */ -#ifndef WORK_SCHED_UTILS_COMMON_H -#define WORK_SCHED_UTILS_COMMON_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_COMMON_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_COMMON_H -#include #include -#include "work_sched_hilog.h" +#include + #include "work_sched_errors.h" +#include "work_sched_hilog.h" namespace OHOS { namespace WorkScheduler { @@ -92,4 +93,4 @@ namespace WorkScheduler { fout.close(); \ } while (0) -#endif // WORK_SCHED_UTILS_COMMON_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_COMMON_H \ No newline at end of file diff --git a/utils/native/include/work_sched_errors.h b/utils/native/include/work_sched_errors.h index 4e2520a..d5f9ab8 100644 --- a/utils/native/include/work_sched_errors.h +++ b/utils/native/include/work_sched_errors.h @@ -12,16 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_UTILS_ERRORS_H -#define WORK_SCHED_UTILS_ERRORS_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_ERRORS_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_ERRORS_H #include namespace OHOS { namespace WorkScheduler { - -// WorkScheduler's module const defined. enum { WORKSCHED_MODULE_TYPE = 0x00, }; @@ -30,20 +27,16 @@ enum { constexpr ErrCode WORKSCHED_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_IAWARE, WORKSCHED_MODULE_TYPE); enum { - E_WRITE_PARCEL_ERROR = WORKSCHED_SERVICE_ERR_OFFSET + 1, - E_READ_PARCEL_ERROR, - E_GET_SYSTEM_ABILITY_MANAGER_FAILED_WORKSCHED, + E_WORK_ID_INVALID = WORKSCHED_SERVICE_ERR_OFFSET + 1, + E_CLIENT_CONNECT_SERVICE_FAILED, + E_GET_WORK_STATUS_ERROR, E_GET_WORKSCHED_SERVICE_FALIED, E_START_WORK_FAILED, E_STOP_WORK_FAILED, E_STOP_AND_CANCEL_WORK_FAILED, E_STOP_AND_CLEAR_WORKS_FAILED, - E_IS_LAST_WORK_TIMEOUT_FALSE, - E_ADD_WORK_SCHED_DEATH_RECIPIENT_FAILED, - E_INNER_ERR + E_IS_LAST_WORK_TIMEOUT_FALSE }; - } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_UTILS_ERRORS_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_ERRORS_H \ No newline at end of file diff --git a/utils/native/include/work_sched_hilog.h b/utils/native/include/work_sched_hilog.h index 1128c8e..9798886 100644 --- a/utils/native/include/work_sched_hilog.h +++ b/utils/native/include/work_sched_hilog.h @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_UTILS_HILOG_H -#define WORK_SCHED_UTILS_HILOG_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H #include @@ -22,7 +21,6 @@ namespace OHOS { namespace WorkScheduler { - #ifndef WORKSCHEDULER_DOMAIN_ID #define WORKSCHEDULER_DOMAIN_ID 0xD001900 #endif @@ -31,7 +29,8 @@ namespace WorkScheduler { #define WORKSCHEDULER_MGR_LOG_TAG "WORK_SCHEDULER" #endif -static constexpr OHOS::HiviewDFX::HiLogLabel WORKSCHEDULER_LABEL = {LOG_CORE, WORKSCHEDULER_DOMAIN_ID, WORKSCHEDULER_MGR_LOG_TAG}; +static constexpr OHOS::HiviewDFX::HiLogLabel WORKSCHEDULER_LABEL = {LOG_CORE, + WORKSCHEDULER_DOMAIN_ID, WORKSCHEDULER_MGR_LOG_TAG}; enum class WorkSchedLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; @@ -74,4 +73,4 @@ private: #define WS_HILOGF(fmt, ...) WS_PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace WorkScheduler } // namespace OHOS -#endif // WORK_SCHED_UTILS_HILOG_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H \ No newline at end of file -- Gitee From 1bf14b6a8e0c6dce14101e6c47c61d52c181dcb6 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 3 Feb 2022 17:48:38 +0800 Subject: [PATCH 04/29] add work_info tdd Signed-off-by: chenming --- bundle.json | 2 +- frameworks/BUILD.gn | 10 - frameworks/include/iwork_sched_service.h | 13 +- frameworks/include/work_condition.h | 42 ++- frameworks/include/work_info.h | 15 +- frameworks/include/workscheduler_srv_client.h | 12 +- frameworks/src/work_info.cpp | 55 ++-- frameworks/test/BUILD.gn | 20 -- frameworks/test/unittest/BUILD.gn | 30 +-- .../test/unittest/include/workinfo_test.h | 10 +- .../test/unittest/src/workinfo_test.cpp | 77 +++--- interfaces/kits/js/napi/src/common.cpp | 75 ++++-- .../kits/js/napi/src/workscheduler_napi.cpp | 8 +- .../work_scheduler_jsunit.test.js | 251 ++++++++++++++++++ services/BUILD.gn | 1 - .../include/conditions/power_listener.h | 55 ---- .../src/conditions/charger_listener.cpp | 8 +- .../native/src/conditions/power_listener.cpp | 93 ------- services/native/src/work_policy_manager.cpp | 6 +- services/native/src/work_queue.cpp | 1 - .../native/src/work_scheduler_service.cpp | 3 - services/native/src/work_status.cpp | 15 +- 22 files changed, 439 insertions(+), 363 deletions(-) delete mode 100644 frameworks/test/BUILD.gn delete mode 100644 services/native/include/conditions/power_listener.h delete mode 100644 services/native/src/conditions/power_listener.cpp diff --git a/bundle.json b/bundle.json index 6440399..7a311b5 100644 --- a/bundle.json +++ b/bundle.json @@ -46,7 +46,7 @@ ], "inner_kits": [], "test": [ - "//foundation/resourceschedule/work_scheduler/frameworks/test:workschedinnerkits_test", + "//foundation/resourceschedule/work_scheduler/frameworks/test/unittest:workinfotest", "//foundation/resourceschedule/work_scheduler/services/native/test:worksched_native_test", "//foundation/resourceschedule/work_scheduler/interfaces/test/unittest:js_unittest" ] diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index cee4f35..8b6d90f 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -29,16 +29,8 @@ ohos_shared_library("workschedclient") { sources = [ "${worksched_frameworks_path}/src/work_info.cpp", "${worksched_frameworks_path}/src/workscheduler_srv_client.cpp", - - # "${worksched_frameworks_path}/src/work_scheduler_extension_context.cpp", - # "${worksched_frameworks_path}/src/work_scheduler_extension.cpp", - # "${worksched_frameworks_path}/src/js_work_scheduler_extension.cpp", - # "${worksched_frameworks_path}/src/js_work_scheduler_extension_context.cpp", "${worksched_service_path}/zidl/src/work_conn_proxy.cpp", "${worksched_service_path}/zidl/src/work_sched_service_proxy.cpp", - - # "${worksched_service_path}/zidl/src/work_scheduler_stub_imp.cpp", - # "${worksched_service_path}/zidl/src/work_scheduler_stub.cpp" ] configs = [ ":worksched_private_config" ] @@ -50,8 +42,6 @@ ohos_shared_library("workschedclient") { "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/ace/napi:ace_napi", - - # "${worksched_frameworks_path}/extension:workschedextension", "//third_party/jsoncpp", ] diff --git a/frameworks/include/iwork_sched_service.h b/frameworks/include/iwork_sched_service.h index 8e8fa7c..34855fa 100644 --- a/frameworks/include/iwork_sched_service.h +++ b/frameworks/include/iwork_sched_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IWORK_SCHED_SERVICE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IWORK_SCHED_SERVICE_H -#ifndef WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H -#define WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H +#include +#include #include #include -#include -#include #include "work_info.h" @@ -51,5 +51,4 @@ public: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKSCHED_ZIDL_IWORK_SCHED_SERVICE_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IWORK_SCHED_SERVICE_H \ No newline at end of file diff --git a/frameworks/include/work_condition.h b/frameworks/include/work_condition.h index cef52c9..8f549d4 100644 --- a/frameworks/include/work_condition.h +++ b/frameworks/include/work_condition.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_CONDITION_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_CONDITION_H -#ifndef WORKSCHED_INNERKITS_WORK_CONDITION_H -#define WORKSCHED_INNERKITS_WORK_CONDITION_H - -#include -#include #include namespace OHOS { @@ -25,20 +22,17 @@ namespace WorkScheduler { class WorkCondition { public: virtual ~WorkCondition() = default; + enum Type { - WORK_ID = 0, - BUNDLE_NAME, - ABILITY_NAME, - NETWORK, + NETWORK = 0, CHARGER, - POWER, BATTERY_STATUS, BATTERY_LEVEL, STORAGE, TIMER, // uint32_t intervalTime, int32_t cycle, bool repeat - TIMER_ROUND, // int32_t passedRound UNKNOWN, }; + enum Network { NETWORK_TYPE_ANY = 0, NETWORK_TYPE_MOBILE, @@ -48,25 +42,23 @@ public: NETWORK_TYPE_ETHERNET, NETWORK_UNKNOWN }; + enum Charger { - CHARGER_PLUGGED_ANY = 0, - CHARGER_PLUGGED_AC, - CHARGER_PLUGGED_USB, - CHARGER_PLUGGED_WIRELESS, - CHARGER_UNPLUGGED, - CHARGER_UNKNOWN, - }; - enum Power { - POWER_UNKNOWN = 30, - POWER_CONNECTED, - POWER_DISCONNECTED + CHARGING_PLUGGED_ANY = 0, + CHARGING_PLUGGED_AC, + CHARGING_PLUGGED_USB, + CHARGING_PLUGGED_WIRELESS, + CHARGING_UNPLUGGED, + CHARGING_UNKNOWN, }; + enum BatteryStatus { BATTERY_STATUS_LOW = 0, BATTERY_STATUS_OKAY, BATTERY_STATUS_LOW_OR_OKAY, BATTERY_UNKNOWN }; + enum Storage { STORAGE_LEVEL_LOW = 0, STORAGE_LEVEL_OKAY, @@ -82,9 +74,7 @@ struct Condition { uint32_t uintVal; time_t timeVal; bool boolVal; - std::string strVal; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKSCHED_INNERKITS_WORK_CONDITION_H +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_CONDITION_H diff --git a/frameworks/include/work_info.h b/frameworks/include/work_info.h index 3cfb34e..f3645dd 100644 --- a/frameworks/include/work_info.h +++ b/frameworks/include/work_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,16 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_INFO_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_INFO_H -#ifndef WORKSCHED_INNERKITS_WORK_INFO_H -#define WORKSCHED_INNERKITS_WORK_INFO_H - -#include #include #include #include -#include +#include + #include "json/json.h" +#include #include "work_condition.h" @@ -70,5 +70,4 @@ private: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKSCHED_INNERKITS_WORK_INFO_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_INFO_H \ No newline at end of file diff --git a/frameworks/include/workscheduler_srv_client.h b/frameworks/include/workscheduler_srv_client.h index 57975d4..1a896e3 100644 --- a/frameworks/include/workscheduler_srv_client.h +++ b/frameworks/include/workscheduler_srv_client.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORKSCHEDDULER_SRV_CLIENT_H -#define WORKSCHEDDULER_SRV_CLIENT_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H #include + #include #include "iwork_sched_service.h" @@ -25,7 +25,6 @@ namespace OHOS { namespace WorkScheduler { class WorkSchedulerSrvClient final : public DelayedRefSingleton { DECLARE_DELAYED_REF_SINGLETON(WorkSchedulerSrvClient) - public: DISALLOW_COPY_AND_MOVE(WorkSchedulerSrvClient); @@ -54,8 +53,7 @@ private: void ResetProxy(const wptr& remote); std::mutex mutex_; }; - } } -#endif // WORKSCHEDDULER_SRV_CLIENT_H +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H diff --git a/frameworks/src/work_info.cpp b/frameworks/src/work_info.cpp index ee821a2..956b9c4 100644 --- a/frameworks/src/work_info.cpp +++ b/frameworks/src/work_info.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,29 +12,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_info.h" #include "work_sched_common.h" -using namespace std; - namespace OHOS { namespace WorkScheduler { -WorkInfo::WorkInfo() -{ -} +WorkInfo::WorkInfo() {} -WorkInfo::~WorkInfo() -{ -} +WorkInfo::~WorkInfo() {} void WorkInfo::SetWorkId(int32_t workId) { workId_ = workId; } -void WorkInfo::SetElement(string bundleName, string abilityName) +void WorkInfo::SetElement(std::string bundleName, std::string abilityName) { bundleName_ = bundleName; abilityName_ = abilityName; @@ -47,14 +40,14 @@ void WorkInfo::RequestPersisted(bool persisted) void WorkInfo::RequestNetworkType(WorkCondition::Network condition) { - shared_ptr networkCondition = make_shared(); + std::shared_ptr networkCondition = std::make_shared(); networkCondition->enumVal = static_cast(condition); conditionMap_.emplace(WorkCondition::Type::NETWORK, networkCondition); } void WorkInfo::RequestChargerType(bool isCharging, WorkCondition::Charger condition) { - shared_ptr chargerCondition = make_shared(); + std::shared_ptr chargerCondition = std::make_shared(); chargerCondition->boolVal = isCharging; chargerCondition->enumVal = static_cast(condition); conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); @@ -62,28 +55,28 @@ void WorkInfo::RequestChargerType(bool isCharging, WorkCondition::Charger condit void WorkInfo::RequestBatteryLevel(int32_t battLevel) { - shared_ptr batteryLevelCondition = make_shared(); + std::shared_ptr batteryLevelCondition = std::make_shared(); batteryLevelCondition->intVal = battLevel; conditionMap_.emplace(WorkCondition::Type::BATTERY_LEVEL, batteryLevelCondition); } void WorkInfo::RequestBatteryStatus(WorkCondition::BatteryStatus condition) { - shared_ptr batteryCondition = make_shared(); + std::shared_ptr batteryCondition = std::make_shared(); batteryCondition->enumVal = static_cast(condition); conditionMap_.emplace(WorkCondition::Type::BATTERY_STATUS, batteryCondition); } void WorkInfo::RequestStorageLevel(WorkCondition::Storage condition) { - shared_ptr storageCondition = make_shared(); + std::shared_ptr storageCondition = std::make_shared(); storageCondition->enumVal = static_cast(condition); conditionMap_.emplace(WorkCondition::Type::STORAGE, storageCondition); } void WorkInfo::RequestRepeatCycle(uint32_t timeInterval, uint32_t cycle) { - shared_ptr repeatCycle = make_shared(); + std::shared_ptr repeatCycle = std::make_shared(); repeatCycle->uintVal = timeInterval; repeatCycle->intVal = cycle; repeatCycle->boolVal = false; @@ -92,7 +85,7 @@ void WorkInfo::RequestRepeatCycle(uint32_t timeInterval, uint32_t cycle) void WorkInfo::RequestRepeatCycle(uint32_t timeInterval) { - shared_ptr repeatCycle = make_shared(); + std::shared_ptr repeatCycle = std::make_shared(); repeatCycle->uintVal = timeInterval; repeatCycle->boolVal = true; conditionMap_.emplace(WorkCondition::Type::TIMER, repeatCycle); @@ -103,12 +96,12 @@ int32_t WorkInfo::GetWorkId() return workId_; } -string WorkInfo::GetBundleName() +std::string WorkInfo::GetBundleName() { return bundleName_; } -string WorkInfo::GetAbilityName() +std::string WorkInfo::GetAbilityName() { return abilityName_; } @@ -135,7 +128,7 @@ WorkCondition::Charger WorkInfo::GetChargerType() WorkCondition::Charger charger = WorkCondition::Charger(enumVal); return WorkCondition::Charger(charger); } - return WorkCondition::Charger::CHARGER_UNKNOWN; + return WorkCondition::Charger::CHARGING_UNKNOWN; } int32_t WorkInfo::GetBatteryLevel() @@ -143,7 +136,7 @@ int32_t WorkInfo::GetBatteryLevel() if (conditionMap_.count(WorkCondition::Type::BATTERY_LEVEL) > 0) { return conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal; } - return 0; + return -1; } WorkCondition::BatteryStatus WorkInfo::GetBatteryStatus() @@ -182,9 +175,9 @@ uint32_t WorkInfo::GetTimeInterval() return -1; } -shared_ptr>> WorkInfo::GetConditionMap() +std::shared_ptr>> WorkInfo::GetConditionMap() { - return make_shared>>(conditionMap_); + return std::make_shared>>(conditionMap_); } bool WorkInfo::Marshalling(Parcel &parcel) const @@ -240,10 +233,10 @@ WorkInfo *WorkInfo::Unmarshalling(Parcel &parcel) read->abilityName_ = parcel.ReadString(); read->persisted_ = parcel.ReadBool(); size_t mapsize = parcel.ReadUint32(); - read->conditionMap_ = map>(); + read->conditionMap_ = std::map>(); for (size_t i = 0; i < mapsize; i++) { int32_t key = parcel.ReadInt32(); - auto condition = make_shared(); + auto condition = std::make_shared(); switch (key) { case WorkCondition::Type::NETWORK: case WorkCondition::Type::BATTERY_STATUS: @@ -276,7 +269,7 @@ WorkInfo *WorkInfo::Unmarshalling(Parcel &parcel) return read; } -string WorkInfo::ParseToJsonStr() +std::string WorkInfo::ParseToJsonStr() { Json::Value root; root["workId"] = workId_; @@ -320,10 +313,10 @@ string WorkInfo::ParseToJsonStr() } root["conditions"] = conditions; Json::StreamWriterBuilder writerBuilder; - ostringstream os; - unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + std::ostringstream os; + std::unique_ptr jsonWriter(writerBuilder.newStreamWriter()); jsonWriter->write(root, &os); - string result = os.str(); + std::string result = os.str(); return result; } @@ -367,7 +360,7 @@ bool WorkInfo::ParseFromJson(const Json::Value value) return true; } -void WorkInfo::Dump(string &result) +void WorkInfo::Dump(std::string &result) { result.append(ParseToJsonStr()); } diff --git a/frameworks/test/BUILD.gn b/frameworks/test/BUILD.gn deleted file mode 100644 index 22f96a8..0000000 --- a/frameworks/test/BUILD.gn +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") - -group("workschedinnerkits_test") { - testonly = true - deps = [ "unittest:unittest" ] -} diff --git a/frameworks/test/unittest/BUILD.gn b/frameworks/test/unittest/BUILD.gn index 40ec80c..cc79dca 100644 --- a/frameworks/test/unittest/BUILD.gn +++ b/frameworks/test/unittest/BUILD.gn @@ -14,17 +14,19 @@ import("//build/test.gni") import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") -module_output_path = "${worksched_native_part_name}/worksched_native" +module_output_path = "work_scheduler/work_info_unittest" +ohos_systemtest("WorkSchedulerWorkInfoTest") { + module_out_path = module_output_path + + sources = [ "src/workinfo_test.cpp" ] -config("module_private_config") { - visibility = [ ":*" ] include_dirs = [ "include" ] -} -ohos_unittest("test_workinfo") { - module_out_path = module_output_path - sources = [ "src/workinfo_test.cpp" ] - configs = [ ":module_private_config" ] + cflags = [] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } deps = [ "${worksched_frameworks_path}:workschedclient", @@ -32,15 +34,11 @@ ohos_unittest("test_workinfo") { "//third_party/jsoncpp", ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - ] + external_deps = [ "utils_base:utils" ] } -group("unittest") { +group("workinfotest") { testonly = true - deps = [ ":test_workinfo" ] + + deps = [ ":WorkSchedulerWorkInfoTest" ] } diff --git a/frameworks/test/unittest/include/workinfo_test.h b/frameworks/test/unittest/include/workinfo_test.h index 2178214..f5dc71f 100644 --- a/frameworks/test/unittest/include/workinfo_test.h +++ b/frameworks/test/unittest/include/workinfo_test.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORKINFO_TEST_H -#define WORKINFO_TEST_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H #include @@ -29,5 +28,4 @@ public: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKINFO_TEST_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H \ No newline at end of file diff --git a/frameworks/test/unittest/src/workinfo_test.cpp b/frameworks/test/unittest/src/workinfo_test.cpp index a7b3ee6..8646a35 100644 --- a/frameworks/test/unittest/src/workinfo_test.cpp +++ b/frameworks/test/unittest/src/workinfo_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,16 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "workinfo_test.h" #include "work_info.h" -using namespace testing::ext; -using namespace OHOS::WorkScheduler; -using namespace OHOS; using namespace std; +using namespace testing::ext; +namespace OHOS { +namespace WorkScheduler { void WorkInfoTest::SetUpTestCase(void) { } @@ -43,7 +42,7 @@ void WorkInfoTest::TearDown() * @tc.desc Set WorkId to WorkInfo * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest001, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest001, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); workInfo.SetWorkId(1); @@ -55,7 +54,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest001, TestSize.Level0) * @tc.desc Set bundleName and abilityName to WorkInfo * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest002, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest002, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); workInfo.SetElement("bundle_name", "ability_name"); @@ -68,7 +67,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest002, TestSize.Level0) * @tc.desc Set workInfo persisted * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest003, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest003, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); workInfo.RequestPersisted(true); @@ -82,11 +81,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest003, TestSize.Level0) * @tc.desc Set workInfo charger condition charging * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest004, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest004, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); - EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGER_CHARGING); + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGING_PLUGGED_ANY); } /** @@ -94,11 +93,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest004, TestSize.Level0) * @tc.desc Set workInfo charger condiiton discharging * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest005, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest005, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_DISCHARGING); - EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGER_DISCHARGING); + workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGING_UNPLUGGED); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGING_UNPLUGGED); } /** @@ -106,11 +105,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest005, TestSize.Level0) * @tc.desc Set workInfo battery condition battery changed * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest006, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest006, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_CHANGED); - EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_CHANGED); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY); } /** @@ -118,11 +117,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest006, TestSize.Level0) * @tc.desc Set workInfo battery condition battery low * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest007, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest007, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); - EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_LOW); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_STATUS_LOW); } /** @@ -130,23 +129,23 @@ HWTEST_F (WorkInfoTest, WorkInfoTest007, TestSize.Level0) * @tc.desc Set workInfo battery condition battery okey * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest008, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest008, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_OKEY); - EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_OKEY); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_STATUS_OKAY); } /** * @tc.name WorkInfoTest009 - * @tc.desc Set workInfo storage condition storage full + * @tc.desc Set workInfo storage condition storage change * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest009, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest009, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); - EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_FULL); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY); } /** @@ -154,11 +153,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest009, TestSize.Level0) * @tc.desc Set workInfo storage condition storage low * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest010, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest010, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); - EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LOW); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_LOW); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_LOW); } /** @@ -166,11 +165,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest010, TestSize.Level0) * @tc.desc Set workInfo storage condition storage ok * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest011, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest011, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); - EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_OK); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_OKAY); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_OKAY); } /** @@ -178,11 +177,11 @@ HWTEST_F (WorkInfoTest, WorkInfoTest011, TestSize.Level0) * @tc.desc Set workInfo network condition * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest012, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest012, Function | MediumTest | Level0) { WorkInfo workInfo = WorkInfo(); - workInfo.RequestNetworkType(WorkCondition::NetWork::WIFI_CONNECTED); - EXPECT_EQ(workInfo.GetNetworkType(), WorkCondition::NetWork::WIFI_CONNECTED); + workInfo.RequestNetworkType(WorkCondition::Network::NETWORK_TYPE_ANY); + EXPECT_EQ(workInfo.GetNetworkType(), WorkCondition::Network::NETWORK_TYPE_ANY); } /** @@ -190,7 +189,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest012, TestSize.Level0) * @tc.desc Set workInfo repeat time condition repeat count 3 * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest013, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest013, Function | MediumTest | Level0) { uint32_t timeInterval = 120; WorkInfo workInfo = WorkInfo(); @@ -204,11 +203,13 @@ HWTEST_F (WorkInfoTest, WorkInfoTest013, TestSize.Level0) * @tc.desc Set workInfo repeat time condition repeat * @tc.type FUNC */ -HWTEST_F (WorkInfoTest, WorkInfoTest014, TestSize.Level0) +HWTEST_F (WorkInfoTest, WorkInfoTest014, Function | MediumTest | Level0) { uint32_t timeInterval = 120; WorkInfo workInfo = WorkInfo(); workInfo.RequestRepeatCycle(timeInterval); EXPECT_EQ(workInfo.GetTimeInterval(), timeInterval); EXPECT_EQ(workInfo.IsRepeat(), true); +} +} } \ No newline at end of file diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index 1e57db6..274e8d1 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -80,16 +80,16 @@ bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo if (isCharging == UNSET_INT_PARAM) { WS_HILOGI("Unset isCharging, ignore ChargerType set also."); } else if (isCharging == FALSE_PARAM) { - workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGER_UNPLUGGED); + workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGING_UNPLUGGED); hasCondition = true; } else { if (chargerType == UNSET_INT_PARAM) { - workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); - } else if (chargerType >= WorkCondition::Charger::CHARGER_PLUGGED_ANY && - chargerType <= WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS) { + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY); + } else if (chargerType >= WorkCondition::Charger::CHARGING_PLUGGED_ANY && + chargerType <= WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS) { workInfo.RequestChargerType(true, WorkCondition::Charger(chargerType)); } else { - workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGER_PLUGGED_ANY); + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY); WS_HILOGI("ChargeType info is invalid, just ignore set."); } hasCondition = true; @@ -289,33 +289,60 @@ napi_value Common::GetNapiWorkInfo(napi_env env, std::shared_ptr &work } napi_value napiWork = nullptr; napi_create_object(env, &napiWork); + + // Set base info. napi_value napiWorkId = nullptr; napi_value napiBundleName = nullptr; napi_value napiAbilityName = nullptr; - napi_value napiNetworkType = nullptr; - napi_value napiChargingType = nullptr; - napi_value napiBatteryLevel = nullptr; - napi_value napiBatteryStatus = nullptr; - napi_value napiStorageRequest = nullptr; - napi_value napiIsPersisted = nullptr; napi_create_int32(env, workInfo->GetWorkId(), &napiWorkId); - napi_create_string_utf8(env, workInfo->GetBundleName().c_str(), workInfo->GetBundleName().length(), &napiBundleName); - napi_create_string_utf8(env, workInfo->GetAbilityName().c_str(), workInfo->GetAbilityName().length(), &napiAbilityName); - napi_create_int32(env, static_cast(workInfo->GetNetworkType()), &napiNetworkType); - napi_create_int32(env, static_cast(workInfo->GetChargerType()), &napiChargingType); - napi_create_int32(env, workInfo->GetBatteryLevel(), &napiBatteryLevel); - napi_create_int32(env, static_cast(workInfo->GetBatteryStatus()), &napiBatteryStatus); - napi_create_int32(env, static_cast(workInfo->GetStorageLevel()), &napiStorageRequest); - napi_get_boolean(env, workInfo->IsPersisted(), &napiIsPersisted); + napi_create_string_utf8(env, workInfo->GetBundleName().c_str(), workInfo->GetBundleName().length(), + &napiBundleName); + napi_create_string_utf8(env, workInfo->GetAbilityName().c_str(), workInfo->GetAbilityName().length(), + &napiAbilityName); napi_set_named_property(env, napiWork, "workId", napiWorkId); napi_set_named_property(env, napiWork, "bundleName", napiBundleName); napi_set_named_property(env, napiWork, "abilityName", napiAbilityName); - napi_set_named_property(env, napiWork, "networkType", napiNetworkType); - napi_set_named_property(env, napiWork, "chargingType", napiChargingType); - napi_set_named_property(env, napiWork, "batteryLevel", napiBatteryLevel); - napi_set_named_property(env, napiWork, "batteryStatus", napiBatteryStatus); - napi_set_named_property(env, napiWork, "storageRequest", napiStorageRequest); + + // Set isPersisted. + napi_value napiIsPersisted = nullptr; + napi_get_boolean(env, workInfo->IsPersisted(), &napiIsPersisted); napi_set_named_property(env, napiWork, "isPersisted", napiIsPersisted); + + // Set net info. + if (workInfo->GetNetworkType() != WorkCondition::Network::NETWORK_UNKNOWN) { + napi_value napiNetworkType = nullptr; + napi_create_int32(env, static_cast(workInfo->GetNetworkType()), &napiNetworkType); + napi_set_named_property(env, napiWork, "networkType", napiNetworkType); + } + + // Set charge info. + if (workInfo->GetChargerType() != WorkCondition::Charger::CHARGING_UNKNOWN) { + napi_value napiChargingType = nullptr; + napi_create_int32(env, static_cast(workInfo->GetChargerType()), &napiChargingType); + napi_set_named_property(env, napiWork, "chargingType", napiChargingType); + } + + // Set batteryLevel info. + if (workInfo->GetBatteryLevel() >= 0) { + napi_value napiBatteryLevel = nullptr; + napi_create_int32(env, workInfo->GetBatteryLevel(), &napiBatteryLevel); + napi_set_named_property(env, napiWork, "batteryLevel", napiBatteryLevel); + } + + // Set batteryStatus info. + if (workInfo->GetBatteryStatus() != WorkCondition::BatteryStatus::BATTERY_UNKNOWN) { + napi_value napiBatteryStatus = nullptr; + napi_create_int32(env, static_cast(workInfo->GetBatteryStatus()), &napiBatteryStatus); + napi_set_named_property(env, napiWork, "batteryStatus", napiBatteryStatus); + } + + // Set storage info. + if (workInfo->GetStorageLevel() != WorkCondition::Storage::STORAGE_UNKNOWN) { + napi_value napiStorageRequest = nullptr; + napi_create_int32(env, static_cast(workInfo->GetStorageLevel()), &napiStorageRequest); + napi_set_named_property(env, napiWork, "storageRequest", napiStorageRequest); + } + return napiWork; } diff --git a/interfaces/kits/js/napi/src/workscheduler_napi.cpp b/interfaces/kits/js/napi/src/workscheduler_napi.cpp index 579612d..e826bc9 100644 --- a/interfaces/kits/js/napi/src/workscheduler_napi.cpp +++ b/interfaces/kits/js/napi/src/workscheduler_napi.cpp @@ -125,13 +125,13 @@ napi_value InitChargingType(napi_env env, napi_value exports) napi_value charging_plugged_wireless; int32_t refCount = 1; - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY), + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY), &charging_plugged_any); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_AC), + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_AC), &charging_plugged_ac); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_USB), + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_USB), &charging_plugged_usb); - napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS), + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS), &charging_plugged_wireless); napi_property_descriptor desc[] = { diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js index 2380674..05fd840 100644 --- a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -154,4 +154,255 @@ describe("WorkSchedulerJsTest", function () { expect(res).assertEqual(true) done(); }) + + /* + * @tc.name: WorkSchedulerJsTest007 + * @tc.desc: test stopWork. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest007", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest007---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + if (res == true) { + var stopRes = workScheduler.stopWork(workInfo, false); + expect(stopRes).assertEqual(true) + } else { + expect(false).assertEqual(true) + } + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest008 + * @tc.desc: test stopWork. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest008", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest008---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + if (res == true) { + var stopRes = workScheduler.stopWork(workInfo, false); + expect(stopRes).assertEqual(true) + } else { + expect(false).assertEqual(true) + } + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest009 + * @tc.desc: test getWorkStatus callback. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest009", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest009---------------------------'); + let workInfo = { + workId: 3, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + if (res == false) { + expect(false).assertEqual(true) + done(); + } + workScheduler.getWorkStatus(3, (err, res) => { + if (err) { + expect(false).assertEqual(true) + } else { + for (let item in res) { + console.info('WORK_SCHEDULER getWorkStatuscallback success,' + item + ' is:' + res[item]); + } + expect(true).assertEqual(true) + } + }); + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: WorkSchedulerJsTest010 + * @tc.desc: test getWorkStatus promise. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest010", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest010---------------------------'); + let workInfo = { + workId: 10, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY, + batteryLevel: 15 + } + var res = workScheduler.startWork(workInfo); + if (res == false) { + expect(false).assertEqual(true) + done(); + } + + workScheduler.getWorkStatus(10).then((res) => { + for (let item in res) { + console.info('WORK_SCHEDULER getWorkStatuscallback success,' + item + ' is:' + res[item]); + } + expect(true).assertEqual(true) + }).catch((err) => { + expect(false).assertEqual(true) + }) + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: WorkSchedulerJsTest011 + * @tc.desc: test obtainAllWorks callback. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest011", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest011---------------------------'); + let workInfo = { + workId: 11, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + if (res == false) { + expect(false).assertEqual(true) + done(); + } + + workScheduler.obtainAllWorks((err, res) =>{ + if (err) { + expect(false).assertEqual(true) + } else { + console.info('WORK_SCHEDULER obtainAllWorks callback success, data is:' + JSON.stringify(res)); + expect(true).assertEqual(true) + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: WorkSchedulerJsTest012 + * @tc.desc: test obtainAllWorks promise. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest012", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest012---------------------------'); + let workInfo = { + workId: 12, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY, + batteryLevel: 15 + } + var res = workScheduler.startWork(workInfo); + if (res == false) { + expect(false).assertEqual(true) + done(); + } + + workScheduler.obtainAllWorks().then((res) => { + console.info('WORK_SCHEDULER obtainAllWorks promise success, data is:' + JSON.stringify(res)); + expect(true).assertEqual(true) + }).catch((err) => { + console.info('workschedulerLog obtainAllWorks promise failed, because:' + err.data); + expect(false).assertEqual(true) + }) + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: WorkSchedulerJsTest013 + * @tc.desc: test stopAndClearWorks. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest013", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest013---------------------------'); + let workInfo = { + workId: 13, + bundleName: "com.mytest.bundleName", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + if (res == true) { + var stopRes = workScheduler.stopAndClearWorks(); + expect(stopRes).assertEqual(true) + } else { + expect(false).assertEqual(true) + } + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest014 + * @tc.desc: test isLastWorkTimeOut callback. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest014", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest014---------------------------'); + workScheduler.isLastWorkTimeOut(14, (err, res) =>{ + if (err) { + expect(false).assertEqual(true) + } else { + console.info('WORK_SCHEDULER isLastWorkTimeOut callback success, data is:' + res); + expect(true).assertEqual(true) + } + }); + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: WorkSchedulerJsTest015 + * @tc.desc: test isLastWorkTimeOut promise. + * @tc.type: FUNC + * @tc.require: AR000GH86K AR000GH86N AR000GH86L + */ + it("WorkSchedulerJsTest015", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest015---------------------------'); + workScheduler.isLastWorkTimeOut(15) + .then(res => { + console.info('WORK_SCHEDULER isLastWorkTimeOut promise success, data is:' + res); + expect(true).assertEqual(true) + }) + .catch(err => { + expect(false).assertEqual(true) + }); + setTimeout(()=>{ + done(); + }, 500); + }) }) \ No newline at end of file diff --git a/services/BUILD.gn b/services/BUILD.gn index 55f373b..e92aa3e 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -27,7 +27,6 @@ ohos_shared_library("workschedservice") { "native/src/conditions/battery_status_listener.cpp", "native/src/conditions/charger_listener.cpp", "native/src/conditions/network_listener.cpp", - "native/src/conditions/power_listener.cpp", "native/src/conditions/storage_listener.cpp", "native/src/conditions/timer_listener.cpp", "native/src/policy/app_removed_listener.cpp", diff --git a/services/native/include/conditions/power_listener.h b/services/native/include/conditions/power_listener.h deleted file mode 100644 index 1421ad1..0000000 --- a/services/native/include/conditions/power_listener.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H - -#include - -#include "icondition_listener.h" -#include "common_event_subscriber.h" -#include "work_queue_manager.h" - -namespace OHOS { -using namespace EventFwk; -namespace WorkScheduler { -class WorkQueueManager; -class PowerListener; -class PowerEventSubscriber : public CommonEventSubscriber { -public: - PowerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, PowerListener &listener); - ~PowerEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; -private: - PowerListener &listener_; -}; -class PowerListener : public IConditionListener { -public: - PowerListener(std::shared_ptr workQueueManager); - ~PowerListener(); - - void OnConditionChanged(WorkCondition::Type conditionType, - std::shared_ptr conditionVal) override; - bool Start() override; - bool Stop() override; - -private: - std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_POWER_LISTENER_H \ No newline at end of file diff --git a/services/native/src/conditions/charger_listener.cpp b/services/native/src/conditions/charger_listener.cpp index 86d05d2..cab3f47 100644 --- a/services/native/src/conditions/charger_listener.cpp +++ b/services/native/src/conditions/charger_listener.cpp @@ -42,17 +42,17 @@ void ChargerEventSubscriber::OnReceiveEvent(const CommonEventData &data) case static_cast(BatteryPluggedType::PLUGGED_TYPE_AC): WS_HILOGI("Condition changed: CHARGER_PLUGGED_AC"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGER_PLUGGED_AC, 0, 0, string())); + make_shared(WorkCondition::CHARGING_PLUGGED_AC, 0, 0, string())); break; case static_cast(BatteryPluggedType::PLUGGED_TYPE_USB): WS_HILOGI("Condition changed: CHARGER_PLUGGED_USB"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGER_PLUGGED_USB, 0, 0, string())); + make_shared(WorkCondition::CHARGING_PLUGGED_USB, 0, 0, string())); break; case static_cast(BatteryPluggedType::PLUGGED_TYPE_WIRELESS): WS_HILOGI("Condition changed: CHARGER_WIRELESS"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGER_PLUGGED_WIRELESS, 0, 0, string())); + make_shared(WorkCondition::CHARGING_PLUGGED_WIRELESS, 0, 0, string())); break; default: break; @@ -67,7 +67,7 @@ void ChargerEventSubscriber::OnReceiveEvent(const CommonEventData &data) case static_cast(BatteryPluggedType::PLUGGED_TYPE_BUTT): WS_HILOGI("Condition changed: CHARGER_PLUGGED_UNPLUGGED"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGER_UNPLUGGED, 0, 0, string())); + make_shared(WorkCondition::CHARGING_UNPLUGGED, 0, 0, string())); break; default: break; diff --git a/services/native/src/conditions/power_listener.cpp b/services/native/src/conditions/power_listener.cpp deleted file mode 100644 index 39a14e6..0000000 --- a/services/native/src/conditions/power_listener.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "conditions/power_listener.h" -#include "common_event_support.h" -#include "common_event_manager.h" -#include "matching_skills.h" -#include "want.h" - -using namespace std; - -namespace OHOS { -namespace WorkScheduler { -PowerEventSubscriber::PowerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, PowerListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} - -void PowerEventSubscriber::OnReceiveEvent(const CommonEventData &data) -{ - const string action = data.GetWant().GetAction(); - WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - - if (action == CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { - WS_HILOGI("Condition changed: POWER_CONNECTED"); - listener_.OnConditionChanged(WorkCondition::Type::POWER, - make_shared(WorkCondition::POWER_CONNECTED, 0, 0, string())); - } else if (action == CommonEventSupport::COMMON_EVENT_CHARGING) { - WS_HILOGI("Condition changed: POWER_DISCONNECTED"); - listener_.OnConditionChanged(WorkCondition::Type::POWER, - make_shared(WorkCondition::POWER_DISCONNECTED, 0, 0, string())); - } else { - WS_HILOGI("OnReceiveEvent action is invalid"); - } -} - -shared_ptr CreatePowerEventSubscriber(PowerListener &listener) -{ - WS_HILOGI("%{public}s", __func__); - MatchingSkills skill = MatchingSkills(); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); - CommonEventSubscribeInfo info(skill); - return make_shared(info, listener); -} - -PowerListener::PowerListener(shared_ptr workQueueManager) -{ - workQueueManager_ = workQueueManager; -} - -PowerListener::~PowerListener() -{ - this->Stop(); -} - -bool PowerListener::Start() -{ - WS_HILOGI("PowerListener start"); - this->commonEventSubscriber = CreatePowerEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); -} - -bool PowerListener::Stop() -{ - WS_HILOGI("PowerListener stop"); - if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); - if (result) { - this->commonEventSubscriber = nullptr; - } - return result; - } - return true; -} - -void PowerListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) -{ - workQueueManager_->OnConditionChanged(conditionType, conditionVal); -} -} // namespace WorkScheduler -} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index cbf250e..5d8c0f4 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -140,10 +140,12 @@ bool WorkPolicyManager::StopAndClearWorks(int32_t uid) bool WorkPolicyManager::IsLastWorkTimeout(int32_t workId, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); string workIdStr = WorkStatus::MakeWorkId(workId, uid); if (uidQueueMap_.count(uid) > 0) { - return uidQueueMap_.at(uid)->Find(workIdStr)->IsLastWorkTimeout(); + shared_ptr workStatus = uidQueueMap_.at(uid)->Find(workIdStr); + if (workStatus != nullptr) { + return workStatus->IsLastWorkTimeout(); + } } return false; } diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index aae288b..1871b87 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -28,7 +28,6 @@ vector> WorkQueue::OnConditionChanged(WorkCondition::Type switch (type) { case WorkCondition::Type::NETWORK: case WorkCondition::Type::CHARGER: - case WorkCondition::Type::POWER: case WorkCondition::Type::BATTERY_STATUS: case WorkCondition::Type::STORAGE: { value->enumVal = conditionVal->intVal; diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 72bb5cb..e7585d8 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -34,7 +34,6 @@ #include "bundle_mgr_proxy.h" #include "conditions/network_listener.h" -#include "conditions/power_listener.h" #include "conditions/charger_listener.h" #include "conditions/battery_status_listener.h" #include "conditions/battery_level_listener.h" @@ -169,14 +168,12 @@ bool WorkSchedulerService::WorkQueueManagerInit() } auto networkListener = make_shared(workQueueManager_); - auto powerListener = make_shared(workQueueManager_); auto chargerListener = make_shared(workQueueManager_); auto batteryStatusListener = make_shared(workQueueManager_); auto batteryLevelListener = make_shared(workQueueManager_); auto storageListener = make_shared(workQueueManager_); auto timerListener = make_shared(workQueueManager_); bool ret = workQueueManager_->AddListener(WorkCondition::Type::NETWORK, networkListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::POWER, powerListener); ret = ret && workQueueManager_->AddListener(WorkCondition::Type::CHARGER, chargerListener); ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_STATUS, batteryStatusListener); ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_LEVEL, batteryLevelListener); diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index c59463c..8cd9f13 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -57,19 +57,19 @@ WorkStatus::WorkStatus(WorkInfo &workInfo, int32_t uid) switch(pluggedType) { case BatteryPluggedType::PLUGGED_TYPE_NONE: chargerCondition->boolVal = false; - chargerCondition->enumVal = WorkCondition::Charger::CHARGER_UNPLUGGED; + chargerCondition->enumVal = WorkCondition::Charger::CHARGING_UNPLUGGED; break; case BatteryPluggedType::PLUGGED_TYPE_AC: chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_AC; + chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_AC; break; case BatteryPluggedType::PLUGGED_TYPE_USB: chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_USB; + chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_USB; break; case BatteryPluggedType::PLUGGED_TYPE_WIRELESS: chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGER_PLUGGED_WIRELESS; + chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS; break; default: break; @@ -153,11 +153,11 @@ bool WorkStatus::IsReady() auto conditionCurrent = conditionMap_.at(it.first); if (conditionSet->boolVal) { if (conditionCurrent->enumVal != conditionSet->enumVal - && conditionSet->enumVal != static_cast(WorkCondition::Charger::CHARGER_PLUGGED_ANY)) { + && conditionSet->enumVal != static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY)) { return false; } } else { - if (conditionCurrent->enumVal != static_cast(WorkCondition::Charger::CHARGER_UNPLUGGED)) { + if (conditionCurrent->enumVal != static_cast(WorkCondition::Charger::CHARGING_UNPLUGGED)) { return false; } } @@ -205,6 +205,9 @@ bool WorkStatus::IsLastWorkTimeout() bool WorkStatus::IsRepeating() { + if (workInfo_->GetConditionMap()->count(WorkCondition::Type::TIMER) <= 0) { + return false; + } if (workInfo_->GetConditionMap()->at(WorkCondition::Type::TIMER)->boolVal) { return true; } else { -- Gitee From 0476178c830531fb0650ef9c9ec1966cb0a4d2c6 Mon Sep 17 00:00:00 2001 From: chenming Date: Fri, 4 Feb 2022 09:23:41 +0800 Subject: [PATCH 05/29] add condition bugfix Signed-off-by: chenming --- .../conditions/battery_level_listener.h | 21 +++--- .../conditions/battery_status_listener.h | 22 +++--- .../include/conditions/charger_listener.h | 21 +++--- .../conditions/common_event_detector.h | 30 -------- .../include/conditions/network_listener.h | 21 +++--- .../include/conditions/storage_listener.h | 21 +++--- .../include/conditions/timer_listener.h | 15 ++-- services/native/include/detector_value.h | 12 ++- services/native/include/icondition_listener.h | 12 ++- .../src/conditions/battery_level_listener.cpp | 50 ++++++------- .../conditions/battery_status_listener.cpp | 53 ++++++------- .../src/conditions/charger_listener.cpp | 74 ++++++++++--------- .../src/conditions/network_listener.cpp | 44 +++++------ .../src/conditions/storage_listener.cpp | 53 ++++++------- .../native/src/conditions/timer_listener.cpp | 14 ++-- 15 files changed, 209 insertions(+), 254 deletions(-) delete mode 100644 services/native/include/conditions/common_event_detector.h diff --git a/services/native/include/conditions/battery_level_listener.h b/services/native/include/conditions/battery_level_listener.h index aca84de..4c202f2 100644 --- a/services/native/include/conditions/battery_level_listener.h +++ b/services/native/include/conditions/battery_level_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,25 +13,25 @@ * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_LEVEL_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_LEVEL_LISTENER_H #include -#include "icondition_listener.h" #include "common_event_subscriber.h" +#include "icondition_listener.h" #include "work_queue_manager.h" namespace OHOS { -using namespace EventFwk; namespace WorkScheduler { class WorkQueueManager; class BatteryLevelListener; -class BatteryLevelEventSubscriber : public CommonEventSubscriber { +class BatteryLevelEventSubscriber : public EventFwk::CommonEventSubscriber { public: - BatteryLevelEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryLevelListener &listener); + BatteryLevelEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryLevelListener &listener); ~BatteryLevelEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; private: BatteryLevelListener &listener_; }; @@ -46,9 +46,8 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; + std::shared_ptr commonEventSubscriber = nullptr; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_BATTERY_LEVEL_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_LEVEL_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/battery_status_listener.h b/services/native/include/conditions/battery_status_listener.h index 5fed547..b7c3de0 100644 --- a/services/native/include/conditions/battery_status_listener.h +++ b/services/native/include/conditions/battery_status_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,26 +12,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_STATUS_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_STATUS_LISTENER_H #include -#include "icondition_listener.h" #include "common_event_subscriber.h" +#include "icondition_listener.h" #include "work_queue_manager.h" namespace OHOS { -using namespace EventFwk; namespace WorkScheduler { class WorkQueueManager; class BatteryStatusListener; -class BatteryStatusEventSubscriber : public CommonEventSubscriber { +class BatteryStatusEventSubscriber : public EventFwk::CommonEventSubscriber { public: - BatteryStatusEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryStatusListener &listener); + BatteryStatusEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryStatusListener &listener); ~BatteryStatusEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; private: BatteryStatusListener &listener_; }; @@ -46,9 +45,8 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; + std::shared_ptr commonEventSubscriber = nullptr; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_BATTERY_STATUS_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_STATUS_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/charger_listener.h b/services/native/include/conditions/charger_listener.h index 43a0e1d..3fde124 100644 --- a/services/native/include/conditions/charger_listener.h +++ b/services/native/include/conditions/charger_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,26 +12,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_CHARGER_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_CHARGER_LISTENER_H #include -#include "icondition_listener.h" #include "common_event_subscriber.h" +#include "icondition_listener.h" #include "work_queue_manager.h" namespace OHOS { -using namespace EventFwk; namespace WorkScheduler { class WorkQueueManager; class ChargerListener; -class ChargerEventSubscriber : public CommonEventSubscriber { +class ChargerEventSubscriber : public EventFwk::CommonEventSubscriber { public: - ChargerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, ChargerListener &listener); + ChargerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + ChargerListener &listener); ~ChargerEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; private: ChargerListener &listener_; }; @@ -46,8 +45,8 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; + std::shared_ptr commonEventSubscriber = nullptr; }; } // namespace WorkScheduler } // namespace OHOS -#endif // WORK_SCHED_SERVICES_CONDITIONS_CHARGER_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_CHARGER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/common_event_detector.h b/services/native/include/conditions/common_event_detector.h deleted file mode 100644 index c8b69c7..0000000 --- a/services/native/include/conditions/common_event_detector.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H -#define WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H - -namespace OHOS { -namespace WorkScheduler { -class CommonEventDetector { -// 从BMS中获取应用数据 -// 判断应用是否有权限进行注册 -// 注册静态广播回调 -// 从静态广播回调应用 -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_COMMON_EVENT_DETECTOR_H \ No newline at end of file diff --git a/services/native/include/conditions/network_listener.h b/services/native/include/conditions/network_listener.h index 72659e5..56f4589 100644 --- a/services/native/include/conditions/network_listener.h +++ b/services/native/include/conditions/network_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,25 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_NETWORK_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_NETWORK_LISTENER_H #include -#include "icondition_listener.h" #include "common_event_subscriber.h" +#include "icondition_listener.h" #include "work_queue_manager.h" namespace OHOS { -using namespace EventFwk; namespace WorkScheduler { class NetworkListener; -class NetworkEventSubscriber : public CommonEventSubscriber { +class NetworkEventSubscriber : public EventFwk::CommonEventSubscriber { public: - NetworkEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener); + NetworkEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener); ~NetworkEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; private: NetworkListener &listener_; }; @@ -44,9 +42,8 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; + std::shared_ptr commonEventSubscriber = nullptr; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_NETWORK_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_NETWORK_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/storage_listener.h b/services/native/include/conditions/storage_listener.h index 30ff76a..508ac58 100644 --- a/services/native/include/conditions/storage_listener.h +++ b/services/native/include/conditions/storage_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,26 +12,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_STORAGE_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_STORAGE_LISTENER_H #include -#include "icondition_listener.h" #include "common_event_subscriber.h" +#include "icondition_listener.h" #include "work_queue_manager.h" namespace OHOS { -using namespace EventFwk; namespace WorkScheduler { class WorkQueueManager; class StorageListener; -class StorageEventSubscriber : public CommonEventSubscriber { +class StorageEventSubscriber : public EventFwk::CommonEventSubscriber { public: - StorageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener); + StorageEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener); ~StorageEventSubscriber() override = default; - void OnReceiveEvent(const CommonEventData &data) override; + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; private: StorageListener &listener_; }; @@ -46,9 +44,8 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr commonEventSubscriber = nullptr; + std::shared_ptr commonEventSubscriber = nullptr; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_STORAGE_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_STORAGE_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/timer_listener.h b/services/native/include/conditions/timer_listener.h index 6b9abf6..d8f5c6a 100644 --- a/services/native/include/conditions/timer_listener.h +++ b/services/native/include/conditions/timer_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,20 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H -#define WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_TIMER_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_TIMER_LISTENER_H #include #include #include "icondition_listener.h" -#include "work_queue_manager.h" #include "work_queue_event_handler.h" +#include "work_queue_manager.h" #include "work_scheduler_service.h" namespace OHOS { -using namespace AppExecFwk; namespace WorkScheduler { class TimerListener : public IConditionListener { public: @@ -37,11 +35,10 @@ public: bool Stop() override; private: std::shared_ptr workQueueManager_; - std::shared_ptr eventRunner_; + std::shared_ptr eventRunner_; std::shared_ptr handler_; const std::string TIMER_LISTENER = "TimerListener"; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITIONS_TIMER_LISTENER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_TIMER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/detector_value.h b/services/native/include/detector_value.h index defcc28..84d90bf 100644 --- a/services/native/include/detector_value.h +++ b/services/native/include/detector_value.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_CONDITION_VALUE_H -#define WORK_SCHED_SERVICES_CONDITION_VALUE_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_H #include #include @@ -27,9 +26,8 @@ struct DetectorValue { bool boolVal; std::string strVal; DetectorValue(int32_t intVal, time_t timeVal, bool boolVal, const std::string &strVal) - : intVal(intVal), timeVal(timeVal), boolVal(boolVal) {} + : intVal(intVal), timeVal(timeVal), boolVal(boolVal), strVal(strVal) {} }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_CONDITION_VALUE_H +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_H diff --git a/services/native/include/icondition_listener.h b/services/native/include/icondition_listener.h index d6d824b..100d3b6 100644 --- a/services/native/include/icondition_listener.h +++ b/services/native/include/icondition_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,14 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_ICONDITION_LISTENER_H -#define WORK_SCHED_SERVICES_ICONDITION_LISTENER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_H #include -#include "work_condition.h" #include "detector_value.h" +#include "work_condition.h" namespace OHOS { namespace WorkScheduler { @@ -33,5 +32,4 @@ public: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_ICONDITION_DETECTOR_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_H \ No newline at end of file diff --git a/services/native/src/conditions/battery_level_listener.cpp b/services/native/src/conditions/battery_level_listener.cpp index bfbf109..7c92a81 100644 --- a/services/native/src/conditions/battery_level_listener.cpp +++ b/services/native/src/conditions/battery_level_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,50 +12,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/battery_level_listener.h" #include -#include "common_event_support.h" + +#include "battery_info.h" #include "common_event_manager.h" +#include "common_event_support.h" #include "matching_skills.h" #include "want.h" -#include "battery_info.h" - -using namespace std; namespace OHOS { namespace WorkScheduler { -BatteryLevelEventSubscriber::BatteryLevelEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryLevelListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} +BatteryLevelEventSubscriber::BatteryLevelEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryLevelListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} -void BatteryLevelEventSubscriber::OnReceiveEvent(const CommonEventData &data) +void BatteryLevelEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) { - const string action = data.GetWant().GetAction(); - WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + const std::string action = data.GetWant().GetAction(); - if (action == CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED) { - WS_HILOGI("Condition changed: BATTERY_CHANGED"); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED) { if (data.GetCode() == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_CAPACITY) { int battCap = atoi(data.GetData().c_str()); listener_.OnConditionChanged(WorkCondition::Type::BATTERY_LEVEL, - make_shared(battCap, 0, 0, string())); + std::make_shared(battCap, 0, 0, std::string())); } } else { WS_HILOGI("OnReceiveEvent action is invalid"); } } -shared_ptr CreateBatteryEventSubscriber(BatteryLevelListener &listener) +std::shared_ptr CreateBatteryEventSubscriber(BatteryLevelListener &listener) { - WS_HILOGI("%{public}s", __func__); - MatchingSkills skill = MatchingSkills(); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED); - CommonEventSubscribeInfo info(skill); - return make_shared(info, listener); + EventFwk::MatchingSkills skill = EventFwk::MatchingSkills(); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED); + EventFwk::CommonEventSubscribeInfo info(skill); + return std::make_shared(info, listener); } -BatteryLevelListener::BatteryLevelListener(shared_ptr workQueueManager) +BatteryLevelListener::BatteryLevelListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; } @@ -69,14 +65,14 @@ bool BatteryLevelListener::Start() { WS_HILOGI("BatteryLevelListener Start"); this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); } bool BatteryLevelListener::Stop() { WS_HILOGI("BatteryLevelListener Stop"); if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); if (result) { this->commonEventSubscriber = nullptr; } @@ -86,9 +82,13 @@ bool BatteryLevelListener::Stop() } void BatteryLevelListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) + std::shared_ptr conditionVal) { - workQueueManager_->OnConditionChanged(conditionType, conditionVal); + if (workQueueManager_ != nullptr) { + workQueueManager_->OnConditionChanged(conditionType, conditionVal); + } else { + WS_HILOGD("workQueueManager_ is nullptr."); + } } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/battery_status_listener.cpp b/services/native/src/conditions/battery_status_listener.cpp index 0051d90..e1e9921 100644 --- a/services/native/src/conditions/battery_status_listener.cpp +++ b/services/native/src/conditions/battery_status_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,52 +12,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/battery_status_listener.h" #include -#include "common_event_support.h" + +#include "battery_info.h" #include "common_event_manager.h" +#include "common_event_support.h" #include "matching_skills.h" #include "want.h" -#include "battery_info.h" - -using namespace std; namespace OHOS { namespace WorkScheduler { -BatteryStatusEventSubscriber::BatteryStatusEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, BatteryStatusListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} +BatteryStatusEventSubscriber::BatteryStatusEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryStatusListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} -void BatteryStatusEventSubscriber::OnReceiveEvent(const CommonEventData &data) +void BatteryStatusEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) { - const string action = data.GetWant().GetAction(); + const std::string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_BATTERY_LOW) { + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_LOW) { WS_HILOGI("Condition changed: BATTERY_STATUS_LOW"); listener_.OnConditionChanged(WorkCondition::Type::BATTERY_STATUS, - make_shared(WorkCondition::BATTERY_STATUS_LOW, 0, 0, string())); - } else if (action == CommonEventSupport::COMMON_EVENT_BATTERY_OKAY) { + std::make_shared(WorkCondition::BATTERY_STATUS_LOW, 0, 0, std::string())); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY) { WS_HILOGI("Condition changed: BATTERY_STATUS_OKAY"); listener_.OnConditionChanged(WorkCondition::Type::BATTERY_STATUS, - make_shared(WorkCondition::BATTERY_STATUS_OKAY, 0, 0, string())); + std::make_shared(WorkCondition::BATTERY_STATUS_OKAY, 0, 0, std::string())); } else { WS_HILOGI("OnReceiveEvent action is invalid"); } } -shared_ptr CreateBatteryEventSubscriber(BatteryStatusListener &listener) +std::shared_ptr CreateBatteryEventSubscriber(BatteryStatusListener &listener) { - WS_HILOGI("%{public}s", __func__); - MatchingSkills skill = MatchingSkills(); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_LOW); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); - CommonEventSubscribeInfo info(skill); - return make_shared(info, listener); + EventFwk::MatchingSkills skill = EventFwk::MatchingSkills(); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_LOW); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + EventFwk::CommonEventSubscribeInfo info(skill); + return std::make_shared(info, listener); } -BatteryStatusListener::BatteryStatusListener(shared_ptr workQueueManager) +BatteryStatusListener::BatteryStatusListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; } @@ -71,14 +68,14 @@ bool BatteryStatusListener::Start() { WS_HILOGI("BatteryStatusListener Start"); this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); } bool BatteryStatusListener::Stop() { WS_HILOGI("BatteryStatusListener Stop"); if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); if (result) { this->commonEventSubscriber = nullptr; } @@ -88,9 +85,13 @@ bool BatteryStatusListener::Stop() } void BatteryStatusListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) + std::shared_ptr conditionVal) { - workQueueManager_->OnConditionChanged(conditionType, conditionVal); + if (workQueueManager_ != nullptr) { + workQueueManager_->OnConditionChanged(conditionType, conditionVal); + } else { + WS_HILOGD("workQueueManager_ is nullptr."); + } } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/charger_listener.cpp b/services/native/src/conditions/charger_listener.cpp index cab3f47..59fe70b 100644 --- a/services/native/src/conditions/charger_listener.cpp +++ b/services/native/src/conditions/charger_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,62 +12,61 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/charger_listener.h" -#include "common_event_support.h" +#include "battery_info.h" #include "common_event_manager.h" +#include "common_event_support.h" #include "matching_skills.h" #include "want.h" -#include "battery_info.h" - -using namespace std; -using namespace OHOS::PowerMgr; namespace OHOS { namespace WorkScheduler { -ChargerEventSubscriber::ChargerEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, ChargerListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} +ChargerEventSubscriber::ChargerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + ChargerListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} -void ChargerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +void ChargerEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) { - const string action = data.GetWant().GetAction(); + const std::string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { int code = data.GetCode(); - if (code == BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { int type = atoi(data.GetData().c_str()); switch(type) { - case static_cast(BatteryPluggedType::PLUGGED_TYPE_AC): + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_AC): WS_HILOGI("Condition changed: CHARGER_PLUGGED_AC"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGING_PLUGGED_AC, 0, 0, string())); + std::make_shared(WorkCondition::CHARGING_PLUGGED_AC, + 0, 0, std::string())); break; - case static_cast(BatteryPluggedType::PLUGGED_TYPE_USB): + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_USB): WS_HILOGI("Condition changed: CHARGER_PLUGGED_USB"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGING_PLUGGED_USB, 0, 0, string())); + std::make_shared(WorkCondition::CHARGING_PLUGGED_USB, + 0, 0, std::string())); break; - case static_cast(BatteryPluggedType::PLUGGED_TYPE_WIRELESS): + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_WIRELESS): WS_HILOGI("Condition changed: CHARGER_WIRELESS"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGING_PLUGGED_WIRELESS, 0, 0, string())); + std::make_shared(WorkCondition::CHARGING_PLUGGED_WIRELESS, + 0, 0, std::string())); break; default: break; } } - } else if (action == CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) { + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) { int code = data.GetCode(); - if (code == BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { int type = atoi(data.GetData().c_str()); switch(type) { - case static_cast(BatteryPluggedType::PLUGGED_TYPE_NONE): - case static_cast(BatteryPluggedType::PLUGGED_TYPE_BUTT): + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE): + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_BUTT): WS_HILOGI("Condition changed: CHARGER_PLUGGED_UNPLUGGED"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, - make_shared(WorkCondition::CHARGING_UNPLUGGED, 0, 0, string())); + std::make_shared(WorkCondition::CHARGING_UNPLUGGED, 0, 0, std::string())); break; default: break; @@ -76,17 +75,16 @@ void ChargerEventSubscriber::OnReceiveEvent(const CommonEventData &data) } } -shared_ptr CreateChargerEventSubscriber(ChargerListener &listener) +std::shared_ptr CreateChargerEventSubscriber(ChargerListener &listener) { - WS_HILOGI("%{public}s", __func__); - MatchingSkills skills = MatchingSkills(); - skills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); - skills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); - CommonEventSubscribeInfo info(skills); - return make_shared(info, listener); + EventFwk::MatchingSkills skills = EventFwk::MatchingSkills(); + skills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + skills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); + EventFwk::CommonEventSubscribeInfo info(skills); + return std::make_shared(info, listener); } -ChargerListener::ChargerListener(shared_ptr workQueueManager) +ChargerListener::ChargerListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; } @@ -100,14 +98,14 @@ bool ChargerListener::Start() { WS_HILOGI("ChargerListener start"); this->commonEventSubscriber = CreateChargerEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); } bool ChargerListener::Stop() { WS_HILOGI("ChargerListener stop"); if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); if (result) { this->commonEventSubscriber = nullptr; } @@ -117,9 +115,13 @@ bool ChargerListener::Stop() } void ChargerListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) + std::shared_ptr conditionVal) { - workQueueManager_->OnConditionChanged(conditionType, conditionVal); + if (workQueueManager_ != nullptr) { + workQueueManager_->OnConditionChanged(conditionType, conditionVal); + } else { + WS_HILOGD("workQueueManager_ is nullptr."); + } } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/network_listener.cpp b/services/native/src/conditions/network_listener.cpp index b990063..3510417 100644 --- a/services/native/src/conditions/network_listener.cpp +++ b/services/native/src/conditions/network_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,46 +12,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/network_listener.h" -#include "common_event_support.h" #include "common_event_manager.h" +#include "common_event_support.h" #include "matching_skills.h" #include "want.h" -using namespace std; -using namespace OHOS::EventFwk; - namespace OHOS { namespace WorkScheduler { -NetworkEventSubscriber::NetworkEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} +NetworkEventSubscriber::NetworkEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + NetworkListener &listener) : CommonEventSubscriber(subscribeInfo), listener_(listener) {} -void NetworkEventSubscriber::OnReceiveEvent(const CommonEventData &data) +void NetworkEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) { - const string action = data.GetWant().GetAction(); + const std::string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE) { + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE) { WS_HILOGI("Condition changed: WIFI_CONN_STATE"); listener_.OnConditionChanged(WorkCondition::Type::NETWORK, - make_shared(WorkCondition::NETWORK_TYPE_WIFI, 0, 0, string())); + std::make_shared(WorkCondition::NETWORK_TYPE_WIFI, 0, 0, std::string())); } else { WS_HILOGI("OnReceiveEvent action is invalid"); } } -shared_ptr CreateNetworkEventSubscriber(NetworkListener &listener) +std::shared_ptr CreateNetworkEventSubscriber(NetworkListener &listener) { WS_HILOGI("%{public}s", __func__); - MatchingSkills skill = MatchingSkills(); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); - CommonEventSubscribeInfo info(skill); - return make_shared(info, listener); + EventFwk::MatchingSkills skill = EventFwk::MatchingSkills(); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); + EventFwk::CommonEventSubscribeInfo info(skill); + return std::make_shared(info, listener); } -NetworkListener::NetworkListener(shared_ptr workQueueManager) +NetworkListener::NetworkListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; } @@ -65,14 +61,14 @@ bool NetworkListener::Start() { WS_HILOGI("NetworkListener start"); this->commonEventSubscriber = CreateNetworkEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); } bool NetworkListener::Stop() { WS_HILOGI("NetworkListener stop"); if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); if (result) { this->commonEventSubscriber = nullptr; } @@ -82,9 +78,13 @@ bool NetworkListener::Stop() } void NetworkListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) + std::shared_ptr conditionVal) { - workQueueManager_->OnConditionChanged(conditionType, conditionVal); + if (workQueueManager_ != nullptr) { + workQueueManager_->OnConditionChanged(conditionType, conditionVal); + } else { + WS_HILOGD("workQueueManager_ is nullptr."); + } } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/storage_listener.cpp b/services/native/src/conditions/storage_listener.cpp index f821c86..166db42 100644 --- a/services/native/src/conditions/storage_listener.cpp +++ b/services/native/src/conditions/storage_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,49 +12,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/storage_listener.h" -#include "common_event_support.h" + #include "common_event_manager.h" +#include "common_event_support.h" #include "matching_skills.h" #include "want.h" -using namespace std; - namespace OHOS { namespace WorkScheduler { -StorageEventSubscriber::StorageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} +StorageEventSubscriber::StorageEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + StorageListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} -void StorageEventSubscriber::OnReceiveEvent(const CommonEventData &data) +void StorageEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) { - const string action = data.GetWant().GetAction(); + const std::string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW) { + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW) { WS_HILOGI("Condition changed: STORAGE_LOW"); listener_.OnConditionChanged(WorkCondition::Type::STORAGE, - make_shared(WorkCondition::STORAGE_LEVEL_LOW, 0, 0, string())); - } else if (action == CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK) { + std::make_shared(WorkCondition::STORAGE_LEVEL_LOW, 0, 0, std::string())); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK) { WS_HILOGI("Condition changed: STORAGE_OK"); listener_.OnConditionChanged(WorkCondition::Type::STORAGE, - make_shared(WorkCondition::STORAGE_LEVEL_OKAY, 0, 0, string())); + std::make_shared(WorkCondition::STORAGE_LEVEL_OKAY, 0, 0, std::string())); } else { WS_HILOGI("OnReceiveEvent action is invalid"); } } -shared_ptr CreateStorageEventSubscriber(StorageListener &listener) +std::shared_ptr CreateStorageEventSubscriber(StorageListener &listener) { - WS_HILOGI("%{public}s", __func__); - MatchingSkills skill = MatchingSkills(); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_FULL); - CommonEventSubscribeInfo info(skill); - return make_shared(info, listener); + EventFwk::MatchingSkills skill = EventFwk::MatchingSkills(); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); + skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_FULL); + EventFwk::CommonEventSubscribeInfo info(skill); + return std::make_shared(info, listener); } -StorageListener::StorageListener(shared_ptr workQueueManager) +StorageListener::StorageListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; } @@ -68,14 +65,14 @@ bool StorageListener::Start() { WS_HILOGI("StorageListener start"); this->commonEventSubscriber = CreateStorageEventSubscriber(*this); - return CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); } bool StorageListener::Stop() { WS_HILOGI("StorageListener stop"); if (this->commonEventSubscriber != nullptr) { - bool result = CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); if (result) { this->commonEventSubscriber = nullptr; } @@ -85,9 +82,13 @@ bool StorageListener::Stop() } void StorageListener::OnConditionChanged(WorkCondition::Type conditionType, - shared_ptr conditionVal) + std::shared_ptr conditionVal) { - workQueueManager_->OnConditionChanged(conditionType, conditionVal); + if (workQueueManager_ != nullptr) { + workQueueManager_->OnConditionChanged(conditionType, conditionVal); + } else { + WS_HILOGD("workQueueManager_ is nullptr."); + } } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/conditions/timer_listener.cpp b/services/native/src/conditions/timer_listener.cpp index 6ebe630..cd38ee7 100644 --- a/services/native/src/conditions/timer_listener.cpp +++ b/services/native/src/conditions/timer_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,16 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "conditions/timer_listener.h" #include "work_queue_event_handler.h" -using namespace std; -using namespace OHOS::AppExecFwk; - namespace OHOS { namespace WorkScheduler { +const int TIME_CYCLE = 10 * 60 * 60; // 10min TimerListener::TimerListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; @@ -36,18 +33,19 @@ void TimerListener::OnConditionChanged(WorkCondition::Type conditionType, bool TimerListener::Start() { if (!eventRunner_) { - eventRunner_ = EventRunner::Create(TIMER_LISTENER); + eventRunner_ = AppExecFwk::EventRunner::Create(TIMER_LISTENER); if (eventRunner_ == nullptr) { WS_HILOGD("Init failed due to create EventHandler"); return false; } } if (!handler_) { - handler_ = make_shared(eventRunner_, workQueueManager_); + handler_ = std::make_shared(eventRunner_, workQueueManager_); } - handler_->SendEvent(InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), 600000); + handler_->SendEvent(AppExecFwk::InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), TIME_CYCLE); return true; } + bool TimerListener::Stop() { if (handler_ != nullptr) { -- Gitee From df83f790255b513023590af6de7a66b090d927b4 Mon Sep 17 00:00:00 2001 From: chenming Date: Sat, 5 Feb 2022 22:11:01 +0800 Subject: [PATCH 06/29] add account id check Signed-off-by: chenming --- frameworks/BUILD.gn | 9 +- frameworks/include/workscheduler_srv_client.h | 3 +- frameworks/src/workscheduler_srv_client.cpp | 17 ++- .../work_scheduler_jsunit.test.js | 24 ++-- services/BUILD.gn | 3 +- .../native/include/work_scheduler_service.h | 40 +++--- services/native/src/work_policy_manager.cpp | 3 +- .../native/src/work_scheduler_service.cpp | 130 ++++++++++++------ .../zidl/include/work_sched_service_proxy.h | 10 +- .../zidl/include/work_sched_service_stub.h | 10 +- .../zidl/src/work_sched_service_proxy.cpp | 7 +- services/zidl/src/work_sched_service_stub.cpp | 25 +--- 12 files changed, 153 insertions(+), 128 deletions(-) diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 8b6d90f..69bd246 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -14,11 +14,7 @@ import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") config("worksched_private_config") { - include_dirs = [ - "${worksched_service_path}/zidl/include", - "//foundation/aafwk/standard/frameworks/kits/ability/native/src/", - "//foundation/ace/napi/native_engine", - ] + include_dirs = [ "${worksched_service_path}/zidl/include" ] } config("worksched_public_config") { @@ -39,9 +35,6 @@ ohos_shared_library("workschedclient") { deps = [ "${worksched_utils_path}:workschedutils", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/ace/napi:ace_napi", "//third_party/jsoncpp", ] diff --git a/frameworks/include/workscheduler_srv_client.h b/frameworks/include/workscheduler_srv_client.h index 1a896e3..3f7b127 100644 --- a/frameworks/include/workscheduler_srv_client.h +++ b/frameworks/include/workscheduler_srv_client.h @@ -55,5 +55,4 @@ private: }; } } -#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H - +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H \ No newline at end of file diff --git a/frameworks/src/workscheduler_srv_client.cpp b/frameworks/src/workscheduler_srv_client.cpp index ea66f81..f03184d 100644 --- a/frameworks/src/workscheduler_srv_client.cpp +++ b/frameworks/src/workscheduler_srv_client.cpp @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "workscheduler_srv_client.h" #include @@ -27,6 +26,7 @@ namespace OHOS { namespace WorkScheduler { WorkSchedulerSrvClient::WorkSchedulerSrvClient() {} + WorkSchedulerSrvClient::~WorkSchedulerSrvClient() { if (iWorkSchedService_ != nullptr) { @@ -92,7 +92,7 @@ void WorkSchedulerSrvClient::WorkSchedulerDeathRecipient::OnRemoteDied(const wpt bool WorkSchedulerSrvClient::StartWork(WorkInfo& workInfo) { - WS_HILOGD("%{public}s.", __func__); + WS_HILOGD("StartWork"); if (Connect() != ERR_OK) { WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); return false; @@ -102,7 +102,7 @@ bool WorkSchedulerSrvClient::StartWork(WorkInfo& workInfo) bool WorkSchedulerSrvClient::StopWork(WorkInfo& workInfo) { - WS_HILOGD("%{public}s.", __func__); + WS_HILOGD("StopWork"); if (Connect() != ERR_OK) { WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); return false; @@ -112,7 +112,7 @@ bool WorkSchedulerSrvClient::StopWork(WorkInfo& workInfo) bool WorkSchedulerSrvClient::StopAndCancelWork(WorkInfo& workInfo) { - WS_HILOGD("%{public}s.", __func__); + WS_HILOGD("StopAndCancelWork"); if (Connect() != ERR_OK) { WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); return false; @@ -122,6 +122,7 @@ bool WorkSchedulerSrvClient::StopAndCancelWork(WorkInfo& workInfo) bool WorkSchedulerSrvClient::StopAndClearWorks() { + WS_HILOGD("StopAndClearWorks"); if (Connect() != ERR_OK) { WS_HILOGE("StopAndClearWorks connect service failed!"); return false; @@ -131,6 +132,7 @@ bool WorkSchedulerSrvClient::StopAndClearWorks() ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) { + WS_HILOGD("IsLastWorkTimeout"); ErrCode errCode = Connect(); if (errCode != ERR_OK) { return errCode; @@ -141,6 +143,7 @@ ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list> &workInfos) { + WS_HILOGD("ObtainAllWorks"); ErrCode errCode = Connect(); if (errCode != ERR_OK) { return errCode; @@ -152,6 +155,7 @@ ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list &workInfo) { + WS_HILOGD("GetWorkStatus"); if (workId <= 0) { return E_WORK_ID_INVALID; } @@ -167,9 +171,10 @@ ErrCode WorkSchedulerSrvClient::GetWorkStatus(int32_t workId, std::shared_ptr &dumpOption, std::vector &dumpInfo) +bool WorkSchedulerSrvClient::ShellDump(const std::vector &dumpOption, + std::vector &dumpInfo) { - WS_HILOGD("%{public}s", __func__); + WS_HILOGD("ShellDump"); if (Connect() != ERR_OK) { WS_HILOGE("%{public}s Connect() failed, errno: %{public}d", __func__, Connect()); dumpInfo.push_back("Connect() failed, errno:" + std::to_string(Connect())); diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js index 05fd840..ec477a7 100644 --- a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -55,7 +55,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest001---------------------------'); let workInfo = { workId: -1, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName" } var res = workScheduler.startWork(workInfo); @@ -73,7 +73,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest002---------------------------'); let workInfo = { workId: 0, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -110,7 +110,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest004---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } var res = workScheduler.startWork(workInfo); @@ -128,7 +128,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest005---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName" } var res = workScheduler.startWork(workInfo); @@ -146,7 +146,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest006---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -165,7 +165,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest007---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -189,7 +189,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest008---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -213,7 +213,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest009---------------------------'); let workInfo = { workId: 3, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -247,7 +247,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest010---------------------------'); let workInfo = { workId: 10, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY, batteryLevel: 15 @@ -282,7 +282,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest011---------------------------'); let workInfo = { workId: 11, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -316,7 +316,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest012---------------------------'); let workInfo = { workId: 12, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY, batteryLevel: 15 @@ -350,7 +350,7 @@ describe("WorkSchedulerJsTest", function () { console.info('----------------------WorkSchedulerJsTest013---------------------------'); let workInfo = { workId: 13, - bundleName: "com.mytest.bundleName", + bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } diff --git a/services/BUILD.gn b/services/BUILD.gn index e92aa3e..acd93d4 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -71,7 +71,8 @@ ohos_shared_library("workschedservice") { "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", - + "os_account_standard:libaccountkits", + "os_account_standard:os_account_innerkits", # "thermal_manager_native:thermalsrv_client", ] diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 197d12a..349560d 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,24 +13,25 @@ * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_WORK_SCHEDULER_SERVICES_H -#define WORK_SCHED_SERVICES_WORK_SCHEDULER_SERVICES_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H -#include -#include -#include -#include -#include #include #include +#include +#include +#include + +#include +#include #include "ability_manager_interface.h" #include "delayed_sp_singleton.h" -#include "work_sched_service_stub.h" -#include "work_policy_manager.h" #include "work_info.h" -#include "work_status.h" +#include "work_policy_manager.h" #include "work_queue_manager.h" +#include "work_sched_service_stub.h" +#include "work_status.h" #include "work_event_handler.h" namespace OHOS { @@ -73,23 +74,26 @@ private: const char* PERSISTED_FILE_PATH = "/data/workscheduler/persisted"; const char* PERSISTED_PATH = "/data/workscheduler/"; const char* PERSISTED_FILE = "persisted"; - bool Init(); - bool WorkQueueManagerInit(); - bool WorkPolicyManagerInit(); + std::shared_ptr workQueueManager_; std::shared_ptr workPolicyManager_; std::map> persistedMap_; bool ready_ {false}; + std::shared_ptr handler_; + std::shared_ptr eventRunner_; + + bool Init(); + void WorkQueueManagerInit(); + bool WorkPolicyManagerInit(); void RefreshPersistedWorks(); std::list> ReadPersistedWorks(); void InitPersistedWork(WorkInfo& workInfo); - std::shared_ptr handler_; - std::shared_ptr eventRunner_; void DumpAllInfo(std::vector &dumpInfo); void DumpWorkQueueInfo(std::vector &dumpInfo); void DumpWorkPolicyInfo(std::vector &dumpInfo); + bool CheckWorkInfo(WorkInfo &workInfo, int32_t &uid); + int GetCurrentAccountId(); }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_WORK_SCHEDULER_SERVICES_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICES_H \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 5d8c0f4..5fa29be 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -39,7 +39,7 @@ WorkPolicyManager::WorkPolicyManager(const wptr& wss) : ws bool WorkPolicyManager::Init() { - WS_HILOGI("WorkPolicyManager::%{public}s come in", __func__); + WS_HILOGI("WorkPolicyManager::Init"); workConnManager_ = make_shared(); auto wmsptr = wss_.promote(); if (wmsptr == nullptr) { @@ -51,7 +51,6 @@ bool WorkPolicyManager::Init() WS_HILOGE("WorkPolicyManager::%{public}s failed due to handler_ is nullptr", __func__); return false; } - WS_HILOGD("WorkPolicyManager::%{public}s success", __func__); return true; } diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index e7585d8..5c6b7b6 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,37 +12,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_scheduler_service.h" -#include -#include -#include -#include -#include -#include #include #include + +#include +#include #include +#include +#include +#include #include #include -#include -#include -#include +#include +#include #include -#include "json/json.h" -#include "bundle_mgr_proxy.h" +#include -#include "conditions/network_listener.h" -#include "conditions/charger_listener.h" -#include "conditions/battery_status_listener.h" +#include "bundle_mgr_proxy.h" #include "conditions/battery_level_listener.h" +#include "conditions/battery_status_listener.h" +#include "conditions/charger_listener.h" +#include "conditions/network_listener.h" #include "conditions/storage_listener.h" #include "conditions/timer_listener.h" -#include "policy/thermal_policy.h" +#include "json/json.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" #include "policy/memory_policy.h" -#include "work_sched_common.h" +#include "policy/thermal_policy.h" #include "work_scheduler_connection.h" +#include "work_sched_common.h" using namespace std; using namespace OHOS::AppExecFwk; @@ -92,7 +93,6 @@ void WorkSchedulerService::OnStart() list> WorkSchedulerService::ReadPersistedWorks() { - WS_HILOGD("WorkSchedulerService::%{public}s enter", __func__); list> workInfos; ifstream fin; fin.open(PERSISTED_FILE_PATH, ios::in); @@ -135,10 +135,6 @@ void WorkSchedulerService::OnStop() bool WorkSchedulerService::Init() { WS_HILOGE("WorkSchedulerService::Init() come in"); - if (!WorkQueueManagerInit()) { - WS_HILOGE("init failed due to work queue manager init."); - return false; - } if (!eventRunner_) { eventRunner_ = AppExecFwk::EventRunner::Create(WORKSCHEDULER_SERVICE_NAME); } @@ -146,11 +142,8 @@ bool WorkSchedulerService::Init() WS_HILOGE("Init failed due to create EventRunner"); return false; } - if (!handler_) { - handler_ = std::make_shared(eventRunner_, wss); - WS_HILOGD("handler make shared."); - } - + handler_ = std::make_shared(eventRunner_, wss); + WorkQueueManagerInit(); if (!WorkPolicyManagerInit()) { WS_HILOGE("init failed due to work policy manager init."); return false; @@ -160,9 +153,9 @@ bool WorkSchedulerService::Init() return true; } -bool WorkSchedulerService::WorkQueueManagerInit() +void WorkSchedulerService::WorkQueueManagerInit() { - WS_HILOGE("WorkQueueManagerInit come in"); + WS_HILOGD("WorkQueueManagerInit come in"); if (workQueueManager_ == nullptr) { workQueueManager_ = make_shared(wss); } @@ -173,15 +166,13 @@ bool WorkSchedulerService::WorkQueueManagerInit() auto batteryLevelListener = make_shared(workQueueManager_); auto storageListener = make_shared(workQueueManager_); auto timerListener = make_shared(workQueueManager_); - bool ret = workQueueManager_->AddListener(WorkCondition::Type::NETWORK, networkListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::CHARGER, chargerListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_STATUS, batteryStatusListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::BATTERY_LEVEL, batteryLevelListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::STORAGE, storageListener); - ret = ret && workQueueManager_->AddListener(WorkCondition::Type::TIMER, timerListener); - - WS_HILOGI("work queue manager init success: %{public}s", to_string(ret).c_str()); - return ret; + + workQueueManager_->AddListener(WorkCondition::Type::NETWORK, networkListener); + workQueueManager_->AddListener(WorkCondition::Type::CHARGER, chargerListener); + workQueueManager_->AddListener(WorkCondition::Type::BATTERY_STATUS, batteryStatusListener); + workQueueManager_->AddListener(WorkCondition::Type::BATTERY_LEVEL, batteryLevelListener); + workQueueManager_->AddListener(WorkCondition::Type::STORAGE, storageListener); + workQueueManager_->AddListener(WorkCondition::Type::TIMER, timerListener); } bool WorkSchedulerService::WorkPolicyManagerInit() @@ -203,11 +194,64 @@ bool WorkSchedulerService::WorkPolicyManagerInit() return true; } +int WorkSchedulerService::GetCurrentAccountId() +{ + std::vector osAccountInfos; + ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + if (ret != ERR_OK) { + WS_HILOGE("QueryAllCreatedOsAccounts failed."); + return 0; + } + + if (osAccountInfos.empty()) { + WS_HILOGE("osAccountInfos is empty, no accounts."); + return 0; + } + + for (const auto& account : osAccountInfos) { + if (account.GetIsActived()) { + return account.GetLocalId(); + } + } + WS_HILOGE("GetCurrentAccountId failed, no Actived now."); + return -1; +} + +bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) { + std::string bundleName = workInfo.GetBundleName(); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + WS_HILOGE("fail to get system ability mgr."); + return false; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + WS_HILOGE("fail to get bundle manager proxy."); + return false; + } + sptr bundleMgr = iface_cast(remoteObject); + BundleInfo bundleInfo; + int currentAccountId = GetCurrentAccountId(); + WS_HILOGD("currentAccountId : %{public}d.", currentAccountId); + if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), BundleFlag::GET_BUNDLE_WITH_ABILITIES, + bundleInfo, currentAccountId)) { + shared_ptr workStatus = make_shared(workInfo, bundleInfo.uid); + WS_HILOGD("bundleUid : %{public}d , uid : %{public}d.", bundleInfo.uid, uid); + return bundleInfo.uid == uid; + } + WS_HILOGD("Get bundle info failed."); + return false; +} + bool WorkSchedulerService::StartWork(WorkInfo& workInfo) { int32_t uid = IPCSkeleton::GetCallingUid(); - WS_HILOGD("WorkSchedulerService::%{public}s workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", - __func__, workInfo.GetBundleName().c_str(), workInfo.GetAbilityName().c_str(), workInfo.GetWorkId(), uid); + if (!CheckWorkInfo(workInfo, uid)) { + return false; + } + WS_HILOGD("WorkSchedulerService::StartWork workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", + workInfo.GetBundleName().c_str(), workInfo.GetAbilityName().c_str(), workInfo.GetWorkId(), uid); shared_ptr workStatus = make_shared(workInfo, uid); if (workInfo.IsPersisted()) { persistedMap_.emplace(workStatus->workId_, make_shared(workInfo)); @@ -238,7 +282,9 @@ void WorkSchedulerService::InitPersistedWork(WorkInfo& workInfo) } sptr bundleMgr = iface_cast(remoteObject); BundleInfo bundleInfo; - if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { + int currentAccountId = GetCurrentAccountId(); + if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), + BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, currentAccountId)) { shared_ptr workStatus = make_shared(workInfo, bundleInfo.uid); if (workPolicyManager_->AddWork(workStatus, bundleInfo.uid)) { workQueueManager_->AddWork(workStatus); diff --git a/services/zidl/include/work_sched_service_proxy.h b/services/zidl/include/work_sched_service_proxy.h index e5fe6bf..c9b72be 100644 --- a/services/zidl/include/work_sched_service_proxy.h +++ b/services/zidl/include/work_sched_service_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H -#define WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICE_PROXY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICE_PROXY_H #include #include @@ -44,5 +43,4 @@ private: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKSCHED_ZIDL_WORK_SCHED_SERVICE_PROXY_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICE_PROXY_H \ No newline at end of file diff --git a/services/zidl/include/work_sched_service_stub.h b/services/zidl/include/work_sched_service_stub.h index 611fc41..ed35e2b 100644 --- a/services/zidl/include/work_sched_service_stub.h +++ b/services/zidl/include/work_sched_service_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H -#define WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICE_STUB_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICE_STUB_H #include #include @@ -44,5 +43,4 @@ private: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORKSCHED_ZIDL_WORK_SCHEDULER_SERVICE_STUB_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICE_STUB_H \ No newline at end of file diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index 88d6d14..9169f2f 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_sched_service_proxy.h" #include @@ -42,7 +41,8 @@ bool WorkSchedServiceProxy::StartWork(WorkInfo& workInfo) int ret = remote->SendRequest(static_cast(IWorkSchedService::START_WORK), data, reply, option); if (ret != ERR_OK) { - WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, error code: %{public}d", __func__, ret); + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, error code: %{public}d", + __func__, ret); return false; } bool result = false; @@ -244,7 +244,6 @@ bool WorkSchedServiceProxy::ShellDump(const std::vector &dumpOption WS_HILOGE("[ShellDump] fail: read dumpInfo failed."); return false; } - WS_HILOGE("success."); return true; } } // namespace WorkScheduler diff --git a/services/zidl/src/work_sched_service_stub.cpp b/services/zidl/src/work_sched_service_stub.cpp index 47c0116..2a425aa 100644 --- a/services/zidl/src/work_sched_service_stub.cpp +++ b/services/zidl/src/work_sched_service_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_sched_service_stub.h" #include @@ -25,7 +24,7 @@ namespace WorkScheduler { int WorkSchedServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WS_HILOGD("BUGOAWF WorkSchedServiceStub::OnRemoteRequest, cmd = %{public}u, flags = %{public}d", code, option.GetFlags()); + WS_HILOGD("WorkSchedServiceStub::OnRemoteRequest, cmd = %{public}u, flags = %{public}d", code, option.GetFlags()); std::u16string descriptor = WorkSchedServiceStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -34,48 +33,39 @@ int WorkSchedServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me } switch (code) { case static_cast(IWorkSchedService::START_WORK): { - WS_HILOGI("call StartWorkStub"); int32_t ret = StartWorkStub(data); reply.WriteBool(ret == ERR_OK); return ret; } case static_cast(IWorkSchedService::STOP_WORK): { - WS_HILOGI("call StopWorkStub"); int32_t ret = StopWorkStub(data); reply.WriteBool(ret == ERR_OK); return ret; } case static_cast(IWorkSchedService::STOP_AND_CANCEL_WORK): { - WS_HILOGI("call StopAndCancelWorkStub"); int32_t ret = StopAndCancelWorkStub(data); reply.WriteBool(ret == ERR_OK); return ret; } case static_cast(IWorkSchedService::STOP_AND_CLEAR_WORKS): { - WS_HILOGI("call StopAndClearWorksStub"); int32_t ret = StopAndClearWorksStub(data); WS_HILOGD("%{public}s ret is ERR_OK ? %{public}s", __func__, (ret == ERR_OK) ? "true" : "false"); - bool wret = reply.WriteBool(ret == ERR_OK); - WS_HILOGD("%{public}s wret is: %{public}s", __func__, wret ? "true" : "false"); + reply.WriteBool(ret == ERR_OK); return ret; } case static_cast(IWorkSchedService::IS_LAST_WORK_TIMEOUT): { - WS_HILOGI("call IsLastWorkTimeoutStub"); int32_t ret = IsLastWorkTimeoutStub(data); reply.WriteBool(ret == ERR_OK); return ret; } case static_cast(IWorkSchedService::OBTAIN_ALL_WORKS): { - WS_HILOGI("BUGOAWF call ObtainAllWorksStub"); std::list> workInfos = ObtainAllWorksStub(data); size_t worksize = workInfos.size(); WS_HILOGD("BUFOAWF OBTAIN_ALL_WORKS worksize returns %{public}d", worksize); reply.WriteInt32(worksize); - WS_HILOGD("WP reply write worksize: %{public}d", worksize); for (auto workInfo : workInfos) { reply.WriteParcelable(&*workInfo); // workInfo->Marshalling(reply); - WS_HILOGD("WP reply write workInfo, ID: %{public}d", workInfo->GetWorkId()); } return ERR_OK; } @@ -105,7 +95,6 @@ int32_t WorkSchedServiceStub::StartWorkStub(MessageParcel& data) WS_HILOGE("StartWork failed"); return E_START_WORK_FAILED; } - WS_HILOGE("call StartWork success"); return ERR_OK; } @@ -131,12 +120,10 @@ int32_t WorkSchedServiceStub::StopAndCancelWorkStub(MessageParcel& data) int32_t WorkSchedServiceStub::StopAndClearWorksStub(MessageParcel& data) { - WS_HILOGD("WSSS %{public}s come in", __func__); if (!StopAndClearWorks()) { - WS_HILOGD("WSSS %{public}s return E_STOP_AND_CLEAR_WORKS_FAILED", __func__); + WS_HILOGE("StopAndClearWorks failed"); return E_STOP_AND_CLEAR_WORKS_FAILED; } - WS_HILOGD("WSSS %{public}s return ERR_OK and come out", __func__); return ERR_OK; } @@ -151,18 +138,14 @@ int32_t WorkSchedServiceStub::IsLastWorkTimeoutStub(MessageParcel& data) std::list> WorkSchedServiceStub::ObtainAllWorksStub(MessageParcel& data) { - WS_HILOGD("WorkSchedServiceStub %{public}s enter", __func__); int32_t pid = 0, uid = 0; READ_PARCEL_WITHOUT_RET(data, Int32, uid); READ_PARCEL_WITHOUT_RET(data, Int32, pid); - WS_HILOGD("WorkSchedServiceStub %{public}s: uid: %{public}d, pid: %{public}d", __func__, uid, pid); - WS_HILOGD("WorkSchedServiceStub %{public}s return", __func__); return ObtainAllWorks(uid, pid); } std::shared_ptr WorkSchedServiceStub::GetWorkStatusStub(MessageParcel& data) { - WS_HILOGD("WorkSchedServiceStub %{public}s enter", __func__); int32_t uid; int32_t workId; READ_PARCEL_WITHOUT_RET(data, Int32, uid); -- Gitee From 01cb4a2cd468743e17bdb590b267dfca275ef0a8 Mon Sep 17 00:00:00 2001 From: chenming Date: Sat, 5 Feb 2022 23:21:12 +0800 Subject: [PATCH 07/29] fix accountid bugfix Signed-off-by: chenming --- services/BUILD.gn | 3 +- .../native/include/work_scheduler_service.h | 1 - .../native/src/work_scheduler_service.cpp | 30 ++--------- utils/native/BUILD.gn | 11 +++- utils/native/include/work_sched_utils.h | 33 ++++++++++++ utils/native/src/work_sched_hilog.cpp | 2 +- utils/native/src/work_sched_utils.cpp | 50 +++++++++++++++++++ 7 files changed, 97 insertions(+), 33 deletions(-) create mode 100644 utils/native/include/work_sched_utils.h create mode 100644 utils/native/src/work_sched_utils.cpp diff --git a/services/BUILD.gn b/services/BUILD.gn index acd93d4..e92aa3e 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -71,8 +71,7 @@ ohos_shared_library("workschedservice") { "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", - "os_account_standard:libaccountkits", - "os_account_standard:os_account_innerkits", + # "thermal_manager_native:thermalsrv_client", ] diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 349560d..2e09ad1 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -92,7 +92,6 @@ private: void DumpWorkQueueInfo(std::vector &dumpInfo); void DumpWorkPolicyInfo(std::vector &dumpInfo); bool CheckWorkInfo(WorkInfo &workInfo, int32_t &uid); - int GetCurrentAccountId(); }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 5c6b7b6..809bc04 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -38,12 +38,11 @@ #include "conditions/storage_listener.h" #include "conditions/timer_listener.h" #include "json/json.h" -#include "ohos_account_kits.h" -#include "os_account_manager.h" #include "policy/memory_policy.h" #include "policy/thermal_policy.h" #include "work_scheduler_connection.h" #include "work_sched_common.h" +#include "work_sched_utils.h" using namespace std; using namespace OHOS::AppExecFwk; @@ -194,29 +193,6 @@ bool WorkSchedulerService::WorkPolicyManagerInit() return true; } -int WorkSchedulerService::GetCurrentAccountId() -{ - std::vector osAccountInfos; - ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); - if (ret != ERR_OK) { - WS_HILOGE("QueryAllCreatedOsAccounts failed."); - return 0; - } - - if (osAccountInfos.empty()) { - WS_HILOGE("osAccountInfos is empty, no accounts."); - return 0; - } - - for (const auto& account : osAccountInfos) { - if (account.GetIsActived()) { - return account.GetLocalId(); - } - } - WS_HILOGE("GetCurrentAccountId failed, no Actived now."); - return -1; -} - bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) { std::string bundleName = workInfo.GetBundleName(); sptr systemAbilityManager = @@ -232,7 +208,7 @@ bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) { } sptr bundleMgr = iface_cast(remoteObject); BundleInfo bundleInfo; - int currentAccountId = GetCurrentAccountId(); + int currentAccountId = WorkSchedUtils::GetCurrentAccountId(); WS_HILOGD("currentAccountId : %{public}d.", currentAccountId); if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, currentAccountId)) { @@ -282,7 +258,7 @@ void WorkSchedulerService::InitPersistedWork(WorkInfo& workInfo) } sptr bundleMgr = iface_cast(remoteObject); BundleInfo bundleInfo; - int currentAccountId = GetCurrentAccountId(); + int currentAccountId = WorkSchedUtils::GetCurrentAccountId(); if (bundleMgr->GetBundleInfo(workInfo.GetBundleName(), BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, currentAccountId)) { shared_ptr workStatus = make_shared(workInfo, bundleInfo.uid); diff --git a/utils/native/BUILD.gn b/utils/native/BUILD.gn index 028590c..aba267f 100644 --- a/utils/native/BUILD.gn +++ b/utils/native/BUILD.gn @@ -18,14 +18,21 @@ config("utils_config") { } ohos_source_set("workschedutils") { - sources = [ "${worksched_utils_path}/src/work_sched_hilog.cpp" ] + sources = [ + "${worksched_utils_path}/src/work_sched_hilog.cpp", + "${worksched_utils_path}/src/work_sched_utils.cpp", + ] public_configs = [ ":utils_config" ] - deps = [] + deps = [ "//third_party/jsoncpp" ] external_deps = [ + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "os_account_standard:libaccountkits", + "os_account_standard:os_account_innerkits", "utils_base:utils", ] diff --git a/utils/native/include/work_sched_utils.h b/utils/native/include/work_sched_utils.h new file mode 100644 index 0000000..a6d828e --- /dev/null +++ b/utils/native/include/work_sched_utils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_UTILS_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_UTILS_H + +#include + +#include "hilog/log.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedUtils { +public : + WorkSchedUtils() = delete; + ~WorkSchedUtils() = delete; + + static int GetCurrentAccountId(); +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_UTILS_H \ No newline at end of file diff --git a/utils/native/src/work_sched_hilog.cpp b/utils/native/src/work_sched_hilog.cpp index 36a35eb..f62058d 100644 --- a/utils/native/src/work_sched_hilog.cpp +++ b/utils/native/src/work_sched_hilog.cpp @@ -41,4 +41,4 @@ std::string WorkSchedHilog::GetBriefFileName(const char *str) return fullPath.substr(pos + 1); } } -} +} \ No newline at end of file diff --git a/utils/native/src/work_sched_utils.cpp b/utils/native/src/work_sched_utils.cpp new file mode 100644 index 0000000..aff7028 --- /dev/null +++ b/utils/native/src/work_sched_utils.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "work_sched_utils.h" + +#include +#include + +#include "errors.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" +#include "work_sched_hilog.h" + +namespace OHOS { +namespace WorkScheduler { +int WorkSchedUtils::GetCurrentAccountId() +{ + std::vector osAccountInfos; + ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + if (ret != ERR_OK) { + WS_HILOGE("QueryAllCreatedOsAccounts failed."); + return 0; + } + + if (osAccountInfos.empty()) { + WS_HILOGE("osAccountInfos is empty, no accounts."); + return 0; + } + + for (const auto& account : osAccountInfos) { + if (account.GetIsActived()) { + return account.GetLocalId(); + } + } + WS_HILOGE("GetCurrentAccountId failed, no Actived now."); + return -1; +} +} +} \ No newline at end of file -- Gitee From f90d737767a89a651f7c3cf029c312b7890de13b Mon Sep 17 00:00:00 2001 From: chenming Date: Sun, 6 Feb 2022 12:45:25 +0800 Subject: [PATCH 08/29] add lock Signed-off-by: chenming --- .../{ => conditions}/icondition_listener.h | 0 .../include/{ => policy}/ipolicy_filter.h | 0 .../native/include/policy/memory_policy.h | 2 +- services/native/include/work_policy_manager.h | 45 ++++++------ services/native/include/work_queue.h | 10 +-- services/native/include/work_queue_manager.h | 13 ++-- .../native/include/work_scheduler_service.h | 2 + services/native/include/work_status.h | 1 - .../src/conditions/network_listener.cpp | 1 - services/native/src/policy/memory_policy.cpp | 2 +- services/native/src/work_policy_manager.cpp | 73 +++++++++++++------ services/native/src/work_queue.cpp | 7 +- services/native/src/work_queue_manager.cpp | 15 ++-- .../native/src/work_scheduler_service.cpp | 14 ++-- 14 files changed, 109 insertions(+), 76 deletions(-) rename services/native/include/{ => conditions}/icondition_listener.h (100%) rename services/native/include/{ => policy}/ipolicy_filter.h (100%) diff --git a/services/native/include/icondition_listener.h b/services/native/include/conditions/icondition_listener.h similarity index 100% rename from services/native/include/icondition_listener.h rename to services/native/include/conditions/icondition_listener.h diff --git a/services/native/include/ipolicy_filter.h b/services/native/include/policy/ipolicy_filter.h similarity index 100% rename from services/native/include/ipolicy_filter.h rename to services/native/include/policy/ipolicy_filter.h diff --git a/services/native/include/policy/memory_policy.h b/services/native/include/policy/memory_policy.h index d2ef316..6ae2090 100644 --- a/services/native/include/policy/memory_policy.h +++ b/services/native/include/policy/memory_policy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index a85530e..7eb9640 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,24 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_POLICY_MANAGER_H -#define WORK_SCHED_SERVICES_POLICY_MANAGER_H - -#include -#include +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICES_POLICY_MANAGER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICES_POLICY_MANAGER_H #include +#include #include +#include #include "policy_type.h" -#include "work_queue.h" -#include "work_info.h" -#include "work_status.h" -#include "work_sched_common.h" +#include "policy/ipolicy_filter.h" #include "work_conn_manager.h" +#include "work_info.h" +#include "work_queue.h" #include "work_scheduler_service.h" -#include "ipolicy_filter.h" - +#include "work_sched_common.h" +#include "work_status.h" namespace OHOS { namespace WorkScheduler { @@ -38,7 +35,7 @@ class WorkEventHandler; class WorkPolicyManager { public: - const size_t MAX_WORK_COUNT_PER_UID = 200; + const size_t MAX_WORK_COUNT_PER_UID = 10; explicit WorkPolicyManager(const wptr& wss); ~WorkPolicyManager() = default; bool Init(); @@ -62,20 +59,24 @@ public: void SendRetrigger(int64_t delayTime); private: - const wptr wss_; - std::shared_ptr workConnManager_; - std::map> uidQueueMap_; - std::shared_ptr conditionReadyQueue_; - std::list> policyFilters_; - int32_t runningWorkCount = 0; int32_t GetMaxRunningCount(); int32_t GetRunningCount(); void RemoveByBundle(std::string bundle); + void DumpConditionReadyQueue(std::string& result); + void DumpUidQueueMap(std::string& result); + + const wptr wss_; + std::shared_ptr workConnManager_; std::shared_ptr handler_; - std::mutex mutex_; + std::mutex uidMapMutex_; + std::map> uidQueueMap_; + + std::mutex conditionReadyMutex_; + std::shared_ptr conditionReadyQueue_; + std::list> policyFilters_; }; } } // namespace OHOS -#endif // WORK_SCHED_SERVICES_POLICY_MANAGER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICES_POLICY_MANAGER_H \ No newline at end of file diff --git a/services/native/include/work_queue.h b/services/native/include/work_queue.h index 58351a9..f98e800 100644 --- a/services/native/include/work_queue.h +++ b/services/native/include/work_queue.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_WORK_QUEUE_H -#define WORK_SCHED_SERVICES_WORK_QUEUE_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_H #include #include @@ -53,5 +52,4 @@ public: }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_WORK_QUEUE_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_H \ No newline at end of file diff --git a/services/native/include/work_queue_manager.h b/services/native/include/work_queue_manager.h index bb96dba..d9ba84d 100644 --- a/services/native/include/work_queue_manager.h +++ b/services/native/include/work_queue_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H -#define WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_MANAGER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_MANAGER_H #include #include @@ -24,7 +24,7 @@ #include "work_queue.h" #include "work_status.h" #include "work_sched_common.h" -#include "icondition_listener.h" +#include "conditions/icondition_listener.h" #include "work_scheduler_service.h" namespace OHOS { @@ -45,12 +45,13 @@ public: std::shared_ptr conditionVal); bool StopAndClearWorks(std::list> workList); void Dump(std::string& result); + private: + std::mutex mutex_; const wptr wss_; std::map> queueMap_; std::map> listenerMap_; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_WORK_QUEUE_MANAGER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_MANAGER_H \ No newline at end of file diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 2e09ad1..6eb2f1f 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -77,6 +78,7 @@ private: std::shared_ptr workQueueManager_; std::shared_ptr workPolicyManager_; + std::mutex mutex_; std::map> persistedMap_; bool ready_ {false}; std::shared_ptr handler_; diff --git a/services/native/include/work_status.h b/services/native/include/work_status.h index 0831675..7103ad9 100644 --- a/services/native/include/work_status.h +++ b/services/native/include/work_status.h @@ -30,7 +30,6 @@ public: enum Status { WAIT_CONDITION = 0, CONDITION_READY, - POLICY_PENDING, RUNNING, REMOVED }; diff --git a/services/native/src/conditions/network_listener.cpp b/services/native/src/conditions/network_listener.cpp index 3510417..401a070 100644 --- a/services/native/src/conditions/network_listener.cpp +++ b/services/native/src/conditions/network_listener.cpp @@ -40,7 +40,6 @@ void NetworkEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &dat std::shared_ptr CreateNetworkEventSubscriber(NetworkListener &listener) { - WS_HILOGI("%{public}s", __func__); EventFwk::MatchingSkills skill = EventFwk::MatchingSkills(); skill.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); EventFwk::CommonEventSubscribeInfo info(skill); diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp index 429d1c3..01cdb94 100644 --- a/services/native/src/policy/memory_policy.cpp +++ b/services/native/src/policy/memory_policy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 5fa29be..e9a2212 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -34,6 +34,7 @@ const int64_t delayTime = 10000; } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) { + std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_ = std::make_shared(); } @@ -61,29 +62,30 @@ void WorkPolicyManager::AddPolicyFilter(shared_ptr filter) bool WorkPolicyManager::AddWork(shared_ptr workStatus, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s workStatus ID: %{public}s, uid: %{public}d", - __func__, workStatus->workId_.c_str(), uid); + WS_HILOGI("WorkPolicyManager::AddWork"); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { - WS_HILOGD("uidQueue(%{public}d) exists", uid); - if (!uidQueueMap_.at(uid)->Contains(make_shared(workStatus->workId_)) - && uidQueueMap_.at(uid)->GetSize() >= MAX_WORK_COUNT_PER_UID) { + if (uidQueueMap_.at(uid)->Contains(make_shared(workStatus->workId_))) { + WS_HILOGE("Workid has been added, should remove first."); + return false; + } else if (uidQueueMap_.at(uid)->GetSize() > MAX_WORK_COUNT_PER_UID) { WS_HILOGE("each uid only can be added %{public}d works", MAX_WORK_COUNT_PER_UID); return false; } - WS_HILOGI("push workStatus ID: %{public}s to uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); uidQueueMap_.at(uid)->Push(workStatus); } else { WS_HILOGD("uidQueue(%{public}d) not exists, create", uid); uidQueueMap_.emplace(uid, make_shared()); - WS_HILOGI("push workStatus ID: %{public}s to uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); uidQueueMap_.at(uid)->Push(workStatus); } + WS_HILOGI("push workStatus ID: %{public}s to uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); return true; } bool WorkPolicyManager::RemoveWork(shared_ptr workStatus, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::RemoveWork"); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { WS_HILOGD("Remove workStatus ID: %{public}s form uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); return uidQueueMap_.at(uid)->Remove(workStatus); @@ -93,7 +95,8 @@ bool WorkPolicyManager::RemoveWork(shared_ptr workStatus, int32_t ui shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::FindWorkStatus"); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { return uidQueueMap_.at(uid)->Find(WorkStatus::MakeWorkId(workInfo.GetWorkId(), uid)); } @@ -102,7 +105,8 @@ shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int bool WorkPolicyManager::StopWork(shared_ptr workStatus, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::StopWork"); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0 && uidQueueMap_.at(uid)->StopWork(workStatus)) { workConnManager_->StopWork(workStatus); } @@ -112,7 +116,8 @@ bool WorkPolicyManager::StopWork(shared_ptr workStatus, int32_t uid) bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::CancelWork"); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { bool ret = uidQueueMap_.at(uid)->Remove(workStatus); return ret; @@ -122,7 +127,8 @@ bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t ui bool WorkPolicyManager::StopAndClearWorks(int32_t uid) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::StopAndClearWorks"); + std::lock_guard lock(uidMapMutex_); bool result = true; if (uidQueueMap_.count(uid) > 0) { auto queue = uidQueueMap_.at(uid); @@ -139,6 +145,7 @@ bool WorkPolicyManager::StopAndClearWorks(int32_t uid) bool WorkPolicyManager::IsLastWorkTimeout(int32_t workId, int32_t uid) { + std::lock_guard lock(uidMapMutex_); string workIdStr = WorkStatus::MakeWorkId(workId, uid); if (uidQueueMap_.count(uid) > 0) { shared_ptr workStatus = uidQueueMap_.at(uid)->Find(workIdStr); @@ -152,16 +159,16 @@ bool WorkPolicyManager::IsLastWorkTimeout(int32_t workId, int32_t uid) void WorkPolicyManager::OnConditionReady(shared_ptr>> workStatusVector) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); - for (auto it : *workStatusVector) { - it->MarkStatus(WorkStatus::Status::POLICY_PENDING); + if (workStatusVector == nullptr) { + return; } + std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->Push(workStatusVector); CheckWorkToRun(); } int32_t WorkPolicyManager::GetMaxRunningCount() { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); int32_t currentMaxRunning = IPolicyFilter::MAX_RUNNING_COUNT; for (auto policyFilter : policyFilters_) { if (!policyFilter->Check(currentRunningCount)) { @@ -173,7 +180,8 @@ int32_t WorkPolicyManager::GetMaxRunningCount() int32_t WorkPolicyManager::GetRunningCount() { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("WorkPolicyManager::GetRunningCount"); + std::lock_guard lock(uidMapMutex_); int32_t count = 0; auto it = uidQueueMap_.begin(); while(it != uidQueueMap_.end()) { @@ -212,6 +220,7 @@ void WorkPolicyManager::RemoveByBundle(string bundle) } sptr bundleMgr = iface_cast(remoteObject); BundleInfo bundleInfo; + std::lock_guard lock(uidMapMutex_); if (bundleMgr->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { auto ws = wss_.promote(); for (auto it : uidQueueMap_.at(bundleInfo.uid)->GetWorkList()) { @@ -223,12 +232,11 @@ void WorkPolicyManager::RemoveByBundle(string bundle) void WorkPolicyManager::CheckWorkToRun() { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->RemoveUnReady(); for (auto it : uidQueueMap_) { it.second->RemoveUnReady(); } - std::lock_guard lock(mutex_); - // auto handler = handler_.lock(); if (handler_ == nullptr) { WS_HILOGE("handler lock() returns nullptr"); return; @@ -265,6 +273,7 @@ void WorkPolicyManager::SendRetrigger(int64_t delaytime) { list> WorkPolicyManager::ObtainAllWorks(int32_t &uid) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + std::lock_guard lock(uidMapMutex_); list> allWorks; if (uidQueueMap_.count(uid) > 0) { auto queue = uidQueueMap_.at(uid); @@ -279,6 +288,7 @@ list> WorkPolicyManager::ObtainAllWorks(int32_t &uid) shared_ptr WorkPolicyManager::GetWorkStatus(int32_t &uid, int32_t &workId) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { auto queue = uidQueueMap_.at(uid); auto workStatus = queue->Find(string("u") + to_string(uid) + "_" + to_string(workId)); @@ -290,6 +300,7 @@ shared_ptr WorkPolicyManager::GetWorkStatus(int32_t &uid, int32_t &wor list> WorkPolicyManager::GetAllWorkStatus(int32_t &uid) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + std::lock_guard lock(uidMapMutex_); list> allWorks; if (uidQueueMap_.count(uid) > 0) { allWorks = uidQueueMap_.at(uid)->GetWorkList(); @@ -297,17 +308,33 @@ list> WorkPolicyManager::GetAllWorkStatus(int32_t &u return allWorks; } -void WorkPolicyManager::Dump(string& result) +void WorkPolicyManager::DumpConditionReadyQueue(string& result) { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); - result.append("1. workPolicyManager conditionReadyQueue:\n"); + std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->Dump(result); - result.append("\n"); - result.append("2. workPolicyManager uidQueueMap:\n"); +} + +void WorkPolicyManager::DumpUidQueueMap(string& result) +{ + std::lock_guard lock(uidMapMutex_); for (auto it : uidQueueMap_) { result.append("uid: " + std::to_string(it.first) + ":\n"); it.second->Dump(result); } } + +void WorkPolicyManager::Dump(string& result) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + result.append("1. workPolicyManager conditionReadyQueue:\n"); + DumpConditionReadyQueue(result); + result.append("\n"); + + result.append("2. workPolicyManager uidQueueMap:\n"); + DumpUidQueueMap(result); + + result.append("3. GetMaxRunningCount:"); + result.append(to_string(GetMaxRunningCount())); +} } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index 1871b87..8730367 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_queue.h" + #include "work_condition.h" #include "work_sched_common.h" @@ -114,11 +114,10 @@ shared_ptr WorkQueue::Find(string workId) shared_ptr WorkQueue::GetWorkToRunByPriority() { workList_.sort(WorkComp()); - // shared_ptr workStatus = workList_.front(); auto work = workList_.begin(); shared_ptr workStatus = nullptr; while (work != workList_.end()) { - if ((*work)->GetStatus() == WorkStatus::POLICY_PENDING) { + if ((*work)->GetStatus() == WorkStatus::CONDITION_READY) { workStatus = *work; break; } diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index 3ce4597..1fc2cb3 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "work_queue_manager.h" using namespace std; @@ -30,6 +29,7 @@ bool WorkQueueManager::Init() bool WorkQueueManager::AddListener(WorkCondition::Type type, shared_ptr listener) { + std::lock_guard lock(mutex_); if (listenerMap_.count(type) > 0) { return false; } @@ -40,6 +40,7 @@ bool WorkQueueManager::AddListener(WorkCondition::Type type, shared_ptr workStatus) { WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + std::lock_guard lock(mutex_); auto map = workStatus->workInfo_->GetConditionMap(); for (auto it : *map) { if (queueMap_.count(it.first) == 0) { @@ -53,6 +54,7 @@ bool WorkQueueManager::AddWork(shared_ptr workStatus) bool WorkQueueManager::RemoveWork(shared_ptr workStatus) { + std::lock_guard lock(mutex_); WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); auto map = workStatus->workInfo_->GetConditionMap(); for (auto it : *map) { @@ -68,6 +70,7 @@ bool WorkQueueManager::RemoveWork(shared_ptr workStatus) bool WorkQueueManager::StopWork(shared_ptr workStatus) { + std::lock_guard lock(mutex_); WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); bool ret = false; for (auto it : queueMap_) { @@ -78,6 +81,7 @@ bool WorkQueueManager::StopWork(shared_ptr workStatus) bool WorkQueueManager::CancelWork(shared_ptr workStatus) { + std::lock_guard lock(mutex_); WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); bool ret = false; for (auto it : queueMap_) { @@ -92,6 +96,7 @@ bool WorkQueueManager::CancelWork(shared_ptr workStatus) void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, shared_ptr conditionVal) { + std::lock_guard lock(mutex_); if (queueMap_.count(conditionType) > 0) { shared_ptr workQueue = queueMap_.at(conditionType); auto readyWorkVector = workQueue->OnConditionChanged(conditionType, conditionVal); @@ -120,9 +125,9 @@ bool WorkQueueManager::StopAndClearWorks(list> workList) void WorkQueueManager::Dump(string& result) { - string conditionType[] = {"workId", "bundle_name", "ability_name", - "network", "charging", "power", "battery_status", "battery_level", - "storage", "timer", "timer_round", "unknown"}; + std::lock_guard lock(mutex_); + string conditionType[] = {"network", "charger", "battery_status", "battery_level", + "storage", "timer", "unknown"}; int size = sizeof(conditionType); for (auto it : queueMap_) { int type = it.first; diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 809bc04..385e428 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -229,13 +229,15 @@ bool WorkSchedulerService::StartWork(WorkInfo& workInfo) WS_HILOGD("WorkSchedulerService::StartWork workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", workInfo.GetBundleName().c_str(), workInfo.GetAbilityName().c_str(), workInfo.GetWorkId(), uid); shared_ptr workStatus = make_shared(workInfo, uid); - if (workInfo.IsPersisted()) { - persistedMap_.emplace(workStatus->workId_, make_shared(workInfo)); - RefreshPersistedWorks(); - } bool ret = false; if (workPolicyManager_->AddWork(workStatus, uid)) { - ret = workQueueManager_->AddWork(workStatus); + workQueueManager_->AddWork(workStatus); + if (workInfo.IsPersisted()) { + std::lock_guard lock(mutex_); + persistedMap_.emplace(workStatus->workId_, make_shared(workInfo)); + RefreshPersistedWorks(); + } + ret = true; } else { WS_HILOGE("WorkPolicyManager->AddWork return false"); } @@ -287,6 +289,7 @@ bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) if (workStatus != nullptr && workPolicyManager_->StopWork(workStatus, uid) && workQueueManager_->StopWork(workStatus)) { if (workInfo.IsPersisted()) { + std::lock_guard lock(mutex_); persistedMap_.erase(workStatus->workId_); RefreshPersistedWorks(); } @@ -391,7 +394,6 @@ void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) void WorkSchedulerService::RefreshPersistedWorks() { - WS_HILOGD("%{public}s come in", __func__); Json::Value root; for (auto &it : persistedMap_) { auto workInfo = it.second; -- Gitee From b06d7026823cf387e155f4eb2ea301706f1aa4a3 Mon Sep 17 00:00:00 2001 From: chenming Date: Mon, 7 Feb 2022 00:38:26 +0800 Subject: [PATCH 09/29] add thermal policy Signed-off-by: chenming --- services/BUILD.gn | 3 +- .../native/include/policy/ipolicy_filter.h | 14 +++-- .../native/include/policy/memory_policy.h | 19 ++++--- .../native/include/policy/thermal_policy.h | 19 +++---- services/native/src/policy/memory_policy.cpp | 29 +++++------ services/native/src/policy/thermal_policy.cpp | 51 ++++++------------- services/native/src/work_policy_manager.cpp | 5 +- 7 files changed, 56 insertions(+), 84 deletions(-) diff --git a/services/BUILD.gn b/services/BUILD.gn index e92aa3e..4933727 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -70,9 +70,8 @@ ohos_shared_library("workschedservice") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", + "thermal_manager_native:thermalsrv_client", "utils_base:utils", - - # "thermal_manager_native:thermalsrv_client", ] part_name = "${worksched_native_part_name}" diff --git a/services/native/include/policy/ipolicy_filter.h b/services/native/include/policy/ipolicy_filter.h index 220b7f0..54e5d86 100644 --- a/services/native/include/policy/ipolicy_filter.h +++ b/services/native/include/policy/ipolicy_filter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef WORK_SCHED_SERVICES_IPOLICY_FILTER_H -#define WORK_SCHED_SERVICES_IPOLICY_FILTER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_FILTER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_FILTER_H #include @@ -23,11 +22,10 @@ namespace WorkScheduler { class IPolicyFilter { public: virtual ~IPolicyFilter() = default; - virtual int32_t Check(int32_t currentIsRunning); + virtual int32_t getPolicyMaxRunning(); static const int32_t CANNOT_RUNNING_MORE = -1; - static const int32_t MAX_RUNNING_COUNT = 5; + static const int32_t MAX_RUNNING_COUNT = 3; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_IPOLICY_FILTER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_FILTER_H \ No newline at end of file diff --git a/services/native/include/policy/memory_policy.h b/services/native/include/policy/memory_policy.h index 6ae2090..b1084b8 100644 --- a/services/native/include/policy/memory_policy.h +++ b/services/native/include/policy/memory_policy.h @@ -12,11 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H -#define WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_MEMORY_POLICY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_MEMORY_POLICY_H -#include "ipolicy_filter.h" #include + +#include "ipolicy_filter.h" #include "work_policy_manager.h" namespace OHOS { @@ -25,18 +26,16 @@ class MemoryPolicy : public IPolicyFilter { public: MemoryPolicy(std::shared_ptr workPolicyManager); ~MemoryPolicy(); - int32_t Check(int32_t currentIsRunning) override; - int32_t GetMaxRunningCountByMemory(); + int32_t getPolicyMaxRunning() override; const int32_t MEM_CRUCIAL = 1 * 1024 * 1024; const int32_t MEM_LOW = 2 * 1024 * 1024; - const int32_t COUNT_MEMORY_CRUCIAL = 0; - const int32_t COUNT_MEMORY_LOW = 1; - const int32_t COUNT_MEMORY_NORMAL = 2; + const int32_t COUNT_MEMORY_CRUCIAL = 1; + const int32_t COUNT_MEMORY_LOW = 2; + const int32_t COUNT_MEMORY_NORMAL = 3; private: std::shared_ptr workPolicyManager_; }; } } - -#endif // WORK_SCHED_SERVICES_POLICY_MEMORY_POLICY_FILTER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_MEMORY_POLICY_H \ No newline at end of file diff --git a/services/native/include/policy/thermal_policy.h b/services/native/include/policy/thermal_policy.h index 29dd2e3..2c6ee2e 100644 --- a/services/native/include/policy/thermal_policy.h +++ b/services/native/include/policy/thermal_policy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,11 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H -#define WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_H #include "ipolicy_filter.h" - #include "work_policy_manager.h" namespace OHOS { @@ -25,15 +24,13 @@ class ThermalPolicy : public IPolicyFilter { public: ThermalPolicy(std::shared_ptr workPolicyManager); ~ThermalPolicy(); - int32_t Check(int32_t currentIsRunning) override; + int32_t getPolicyMaxRunning() override; private: std::shared_ptr workPolicyManager_; - // const int32_t MAX_RUNNING_COUNT_COOL = MAX_RUNNING_COUNT; - // const int32_t MAX_RUNNING_COUNT_HOT = 3; - // const int32_t MAX_RUNNING_COUNT_OVERHEATED = 1; - // int32_t current_max_running_count = MAX_RUNNING_COUNT_COOL; + const int32_t COUNT_THERMAL_CRUCIAL = 0; + const int32_t COUNT_THERMAL_LOW = 1; + const int32_t COUNT_THERMAL_NORMAL = 3; }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_POLICY_THERMAL_POLICY_FILTER_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_H \ No newline at end of file diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp index 01cdb94..72d30a6 100644 --- a/services/native/src/policy/memory_policy.cpp +++ b/services/native/src/policy/memory_policy.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ #include "policy/memory_policy.h" + #include using namespace std; @@ -27,11 +28,13 @@ MemoryPolicy::~MemoryPolicy() { } -void GetMemAvailable(int32_t mem_available) { +int32_t GetMemAvailable() { + int32_t memAvailable; FILE *fp; fp = fopen("/proc/meminfo", "r"); if (fp == NULL) { - mem_available = IPolicyFilter::CANNOT_RUNNING_MORE; + WS_HILOGE("GetMemAvailable file open failed."); + memAvailable = IPolicyFilter::CANNOT_RUNNING_MORE; } char buf[128]; int buff_len = 128; @@ -42,33 +45,27 @@ void GetMemAvailable(int32_t mem_available) { sscanf(buf, "%s%d", name, &value); string sname = name; if (sname.find(mem_name) != string::npos) { - mem_available = value; + memAvailable = value; break; } } fclose(fp); + fp = nullptr; + return memAvailable; } -int32_t MemoryPolicy::GetMaxRunningCountByMemory() +int32_t MemoryPolicy::getPolicyMaxRunning() { - WS_HILOGI("MemoryPolicy::%{public}s", __func__); - int32_t mem_available = -1; - GetMemAvailable(mem_available); - WS_HILOGI("mem_available: %{public}d", mem_available); - if (mem_available < MEM_CRUCIAL) { + int32_t memAvailable = GetMemAvailable(); + WS_HILOGI("mem_available: %{public}d", memAvailable); + if (memAvailable <= MEM_CRUCIAL) { return COUNT_MEMORY_CRUCIAL; } - if (mem_available >= MEM_CRUCIAL && mem_available < MEM_LOW) { + if (memAvailable <= MEM_LOW && memAvailable > MEM_CRUCIAL) { return COUNT_MEMORY_LOW; } WS_HILOGI("memory left normal"); return COUNT_MEMORY_NORMAL; } -int32_t MemoryPolicy::Check(int32_t currentIsRunning) -{ - WS_HILOGI("MemoryPolicy::%{public}s(%{public}d)", __func__, currentIsRunning); - int32_t maxRunning = GetMaxRunningCountByMemory(); - return maxRunning > currentIsRunning ? maxRunning : CANNOT_RUNNING_MORE; -} } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/policy/thermal_policy.cpp b/services/native/src/policy/thermal_policy.cpp index de8053b..3413ebd 100644 --- a/services/native/src/policy/thermal_policy.cpp +++ b/services/native/src/policy/thermal_policy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,10 +14,10 @@ */ #include "policy/thermal_policy.h" -// #include "thermal_mgr_client.h" +#include "thermal_mgr_client.h" using namespace std; -// using namespace OHOS::PowerMgr; +using namespace OHOS::PowerMgr; namespace OHOS { namespace WorkScheduler { @@ -25,44 +25,25 @@ ThermalPolicy::ThermalPolicy(shared_ptr workPolicyManager) { workPolicyManager_ = workPolicyManager; } + ThermalPolicy::~ThermalPolicy() { } -int32_t ThermalPolicy::Check(int32_t currentIsRunning) + +int32_t ThermalPolicy::getPolicyMaxRunning() { - WS_HILOGI("ThermalPolicy::%{public}s", __func__); - /* auto& thermalMgrClient = ThermalMgrClient::GetInstance(); ThermalLevel thermalLevel = thermalMgrClient.GetThermalLevel(); - switch (thermalLevel) { - case ThermalLevel::COOL: - { - WS_HILOGI("ThermalLevel COOL | WARM"); - current_max_running_count = MAX_RUNNING_COUNT_COOL; - break; - } - case ThermalLevel::WARM: - case ThermalLevel::WARNING: - case ThermalLevel::HOT: - { - WS_HILOGI("ThermalLevel WARNING | HOT"); - current_max_running_count = MAX_RUNNING_COUNT_HOT; - break; - } - case ThermalLevel::OVERHEATED: - case ThermalLevel::EMERGENCY: - { - WS_HILOGI("ThermalLevel OVERHEATED | EMERGENCY"); - current_max_running_count = MAX_RUNNING_COUNT_OVERHEATED; - break; - } - default: - { - break; - } - } */ - // return current_max_running_count > currentIsRunning ? current_max_running_count : CANNOT_RUNNING_MORE; - return 5; + int32_t res; + if (thermalLevel >= ThermalLevel::WARM) { + res = COUNT_THERMAL_CRUCIAL; + } else if (thermalLevel < ThermalLevel::WARM && thermalLevel >= ThermalLevel::NORMAL) { + res = COUNT_THERMAL_LOW; + } else { + res = COUNT_THERMAL_NORMAL; + } + WS_HILOGI("ThermalLevel:%{public}d, PolicyRes:%{public}d", thermalLevel, res); + return res; } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index e9a2212..6bb6778 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -171,8 +171,9 @@ int32_t WorkPolicyManager::GetMaxRunningCount() { int32_t currentMaxRunning = IPolicyFilter::MAX_RUNNING_COUNT; for (auto policyFilter : policyFilters_) { - if (!policyFilter->Check(currentRunningCount)) { - break; + int32_t policyMaxRunning = policyFilter->getPolicyMaxRunning(); + if (policyMaxRunning < currentMaxRunning) { + currentMaxRunning = policyMaxRunning; } } return currentMaxRunning; -- Gitee From bd0c71910988a62d24398ff93fc9e9c47cae180f Mon Sep 17 00:00:00 2001 From: chenming Date: Mon, 7 Feb 2022 22:00:55 +0800 Subject: [PATCH 10/29] Add work scheduler stop bugfix Signed-off-by: chenming --- bundle.json | 1 - services/native/include/work_policy_manager.h | 4 +- services/native/include/work_queue.h | 2 +- services/native/include/work_queue_manager.h | 1 - .../native/include/work_scheduler_service.h | 1 + services/native/src/work_policy_manager.cpp | 48 +- services/native/src/work_queue.cpp | 27 +- services/native/src/work_queue_manager.cpp | 26 +- .../native/src/work_scheduler_service.cpp | 69 ++- services/native/test/BUILD.gn | 20 - services/native/test/unittest/BUILD.gn | 55 -- .../unittest/include/workscheduler_test.h | 33 -- .../test/unittest/src/workscheduler_test.cpp | 482 ------------------ .../zidl/include/work_scheduler_stub_imp.h | 1 - .../zidl/src/work_sched_service_proxy.cpp | 2 +- services/zidl/src/work_sched_service_stub.cpp | 1 - 16 files changed, 102 insertions(+), 671 deletions(-) delete mode 100644 services/native/test/BUILD.gn delete mode 100644 services/native/test/unittest/BUILD.gn delete mode 100644 services/native/test/unittest/include/workscheduler_test.h delete mode 100644 services/native/test/unittest/src/workscheduler_test.cpp diff --git a/bundle.json b/bundle.json index 7a311b5..75fd9b8 100644 --- a/bundle.json +++ b/bundle.json @@ -47,7 +47,6 @@ "inner_kits": [], "test": [ "//foundation/resourceschedule/work_scheduler/frameworks/test/unittest:workinfotest", - "//foundation/resourceschedule/work_scheduler/services/native/test:worksched_native_test", "//foundation/resourceschedule/work_scheduler/interfaces/test/unittest:js_unittest" ] } diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index 7eb9640..23025f8 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -43,7 +43,7 @@ public: void AddPolicyFilter(std::shared_ptr filter); bool AddWork(std::shared_ptr workStatus, int32_t uid); bool RemoveWork(std::shared_ptr workStatus, int32_t uid); - bool StopWork(std::shared_ptr workStatus, int32_t uid); + bool StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel); bool CancelWork(std::shared_ptr workStatus, int32_t uid); bool StopAndClearWorks(int32_t uid); bool IsLastWorkTimeout(int32_t workId, int32_t uid); @@ -64,6 +64,8 @@ private: void RemoveByBundle(std::string bundle); void DumpConditionReadyQueue(std::string& result); void DumpUidQueueMap(std::string& result); + void removeFromUidQueue(std::shared_ptr workStatus, int32_t uid); + void removeFromReadyQueue(std::shared_ptr workStatus); const wptr wss_; std::shared_ptr workConnManager_; diff --git a/services/native/include/work_queue.h b/services/native/include/work_queue.h index f98e800..86395bf 100644 --- a/services/native/include/work_queue.h +++ b/services/native/include/work_queue.h @@ -36,13 +36,13 @@ public: bool Contains(std::shared_ptr workId); std::shared_ptr Find(std::string workId); size_t GetSize(); - bool StopWork(std::shared_ptr workStatus); bool CancelWork(std::shared_ptr workStatus); std::list> GetWorkList(); void RemoveUnReady(); int32_t GetRunningCount(); void GetWorkIdStr(std::string& result); void Dump(std::string& result); + void ClearAll(); private: std::list> workList_; }; diff --git a/services/native/include/work_queue_manager.h b/services/native/include/work_queue_manager.h index d9ba84d..8e82051 100644 --- a/services/native/include/work_queue_manager.h +++ b/services/native/include/work_queue_manager.h @@ -38,7 +38,6 @@ public: bool AddListener(WorkCondition::Type type, std::shared_ptr listener); bool AddWork(std::shared_ptr workStatus); bool RemoveWork(std::shared_ptr workStatus); - bool StopWork(std::shared_ptr workStatus); bool CancelWork(std::shared_ptr workStatus); void OnConditionChanged(WorkCondition::Type conditionType, diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 6eb2f1f..6b499fd 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -94,6 +94,7 @@ private: void DumpWorkQueueInfo(std::vector &dumpInfo); void DumpWorkPolicyInfo(std::vector &dumpInfo); bool CheckWorkInfo(WorkInfo &workInfo, int32_t &uid); + bool StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel); }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 6bb6778..3508488 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -103,13 +103,33 @@ shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int return nullptr; } -bool WorkPolicyManager::StopWork(shared_ptr workStatus, int32_t uid) -{ - WS_HILOGI("WorkPolicyManager::StopWork"); +void WorkPolicyManager::removeFromUidQueue(std::shared_ptr workStatus, int32_t uid) { std::lock_guard lock(uidMapMutex_); - if (uidQueueMap_.count(uid) > 0 && uidQueueMap_.at(uid)->StopWork(workStatus)) { + if (uidQueueMap_.count(uid) > 0) { + uidQueueMap_.at(uid)->CancelWork(workStatus); + } +} + +void WorkPolicyManager::removeFromReadyQueue(std::shared_ptr workStatus) { + std::lock_guard lock(conditionReadyMutex_); + conditionReadyQueue_->RemoveUnReady(); +} + +bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel) { + WS_HILOGI("WorkPolicyManager::StopWork"); + if (workStatus->IsRunning()) { workConnManager_->StopWork(workStatus); } + if (workStatus->IsRepeating() || workStatus->persisted_) { + workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } else { + workStatus->MarkStatus(WorkStatus::Status::REMOVED); + } + if (needCancel) { + removeFromUidQueue(workStatus, uid); + removeFromReadyQueue(workStatus); + } + CheckWorkToRun(); return true; } @@ -129,18 +149,18 @@ bool WorkPolicyManager::StopAndClearWorks(int32_t uid) { WS_HILOGI("WorkPolicyManager::StopAndClearWorks"); std::lock_guard lock(uidMapMutex_); - bool result = true; if (uidQueueMap_.count(uid) > 0) { auto queue = uidQueueMap_.at(uid); for (auto it : queue->GetWorkList()) { - bool ret = StopWork(it, uid); - ret = ret & CancelWork(it, uid); - if (!ret) { - result = false; - } + workConnManager_->StopWork(it); + it->MarkStatus(WorkStatus::Status::REMOVED); + removeFromReadyQueue(it); } + queue->ClearAll(); + uidQueueMap_.erase(uid); } - return result; + CheckWorkToRun(); + return true; } bool WorkPolicyManager::IsLastWorkTimeout(int32_t workId, int32_t uid) @@ -232,12 +252,9 @@ void WorkPolicyManager::RemoveByBundle(string bundle) void WorkPolicyManager::CheckWorkToRun() { - WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + WS_HILOGI("CheckWorkToRun"); std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->RemoveUnReady(); - for (auto it : uidQueueMap_) { - it.second->RemoveUnReady(); - } if (handler_ == nullptr) { WS_HILOGE("handler lock() returns nullptr"); return; @@ -262,7 +279,6 @@ void WorkPolicyManager::CheckWorkToRun() void WorkPolicyManager::SendRetrigger(int64_t delaytime) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); - // auto handler = handler_.lock(); if (handler_ == nullptr) { return; } diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index 8730367..1575aac 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -126,23 +126,6 @@ shared_ptr WorkQueue::GetWorkToRunByPriority() return workStatus; } -bool WorkQueue::StopWork(shared_ptr workStatus) -{ - bool ret = false; - for (auto work : workList_) { - if (work->workId_ == workStatus->workId_) { - if (workStatus->IsRepeating()) { - workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); - } else { - workStatus->MarkStatus(WorkStatus::Status::REMOVED); - } - ret = true; - } - } - RemoveUnReady(); - return ret; -} - bool WorkQueue::CancelWork(shared_ptr workStatus) { workList_.remove(workStatus); @@ -156,9 +139,9 @@ list> WorkQueue::GetWorkList() void WorkQueue::RemoveUnReady() { - workList_.remove_if([](shared_ptr value){ - return (value->GetStatus() == WorkStatus::Status::WAIT_CONDITION) - || (value->GetStatus() == WorkStatus::Status::REMOVED);}); + workList_.remove_if([](shared_ptr value) { + return (value->GetStatus() != WorkStatus::Status::CONDITION_READY); + }); } int32_t WorkQueue::GetRunningCount() @@ -185,6 +168,10 @@ void WorkQueue::Dump(string& result) } } +void WorkQueue::ClearAll() { + workList_.clear(); +} + bool WorkComp::operator () (const shared_ptr w1, const shared_ptr w2) { return w1->priority_ >= w2->priority_; diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index 1fc2cb3..73472d2 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -68,29 +68,17 @@ bool WorkQueueManager::RemoveWork(shared_ptr workStatus) return true; } -bool WorkQueueManager::StopWork(shared_ptr workStatus) -{ - std::lock_guard lock(mutex_); - WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); - bool ret = false; - for (auto it : queueMap_) { - ret = ret || it.second->StopWork(workStatus); - } - return ret; -} - bool WorkQueueManager::CancelWork(shared_ptr workStatus) { std::lock_guard lock(mutex_); WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); - bool ret = false; for (auto it : queueMap_) { - ret = it.second->CancelWork(workStatus); - if (ret) { - RemoveWork(workStatus); + it.second->CancelWork(workStatus); + if (queueMap_.count(it.first) == 0) { + listenerMap_.at(it.first)->Stop(); } } - return ret; + return true; } void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, @@ -114,11 +102,7 @@ void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, bool WorkQueueManager::StopAndClearWorks(list> workList) { for (auto &it : workList) { - if (StopWork(it) && CancelWork(it)) { - continue; - } else { - return false; - } + CancelWork(it); } return true; } diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 385e428..5dd35a1 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -275,35 +275,70 @@ bool WorkSchedulerService::StopWork(WorkInfo& workInfo) { int32_t uid = IPCSkeleton::GetCallingUid(); shared_ptr workStatus = workPolicyManager_->FindWorkStatus(workInfo, uid); - if (workStatus != nullptr && workPolicyManager_->StopWork(workStatus, uid) - && workQueueManager_->StopWork(workStatus)) { - return true; + if (workStatus == nullptr) { + WS_HILOGD("StopWorkInner, workStatus is nullptr"); + return false; } - return false; + return StopWorkInner(workStatus, uid, false); } bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) { int32_t uid = IPCSkeleton::GetCallingUid(); shared_ptr workStatus = workPolicyManager_->FindWorkStatus(workInfo, uid); - if (workStatus != nullptr && workPolicyManager_->StopWork(workStatus, uid) - && workQueueManager_->StopWork(workStatus)) { - if (workInfo.IsPersisted()) { - std::lock_guard lock(mutex_); - persistedMap_.erase(workStatus->workId_); - RefreshPersistedWorks(); - } - return workQueueManager_->CancelWork(workStatus) - && workPolicyManager_->CancelWork(workStatus, uid); + if (workStatus == nullptr) { + WS_HILOGD("StopWorkInner, workStatus is nullptr"); + return false; + } + StopWorkInner(workStatus, uid, true); + if (workStatus->persisted_) { + std::lock_guard lock(mutex_); + persistedMap_.erase(workStatus->workId_); + RefreshPersistedWorks(); + } + return true; +} + +bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel) +{ + workPolicyManager_->StopWork(workStatus, uid, needCancel); + if (needCancel) { + workQueueManager_->CancelWork(workStatus); } return true; } +bool IsInList(list &list, std::string myWork) { + for (auto work : list) { + if (work.compare(myWork) == 0) { + return true; + } + } + return false; +} + bool WorkSchedulerService::StopAndClearWorks() { int32_t uid = IPCSkeleton::GetCallingUid(); - return workQueueManager_->StopAndClearWorks(workPolicyManager_->GetAllWorkStatus(uid)) + list> allWorks = workPolicyManager_->GetAllWorkStatus(uid); + list workIdList; + for (auto work : allWorks) { + workIdList.push_back(work->workId_); + } + bool ret = workQueueManager_->StopAndClearWorks(allWorks) && workPolicyManager_->StopAndClearWorks(uid); + + if (ret) { + std::lock_guard lock(mutex_); + for (auto workId : workIdList) { + if (persistedMap_.count(workId) != 0) { + persistedMap_.erase(workId); + WS_HILOGD("chenmingid %{public}s", workId.c_str()); + } + } + RefreshPersistedWorks(); + } + return ret; } bool WorkSchedulerService::IsLastWorkTimeout(int32_t workId) @@ -352,7 +387,7 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector connection(new (std::nothrow) WorkSchedulerConnection()); - abilityMgr_->ConnectAbility(want, connection, nullptr); + abilityMgr_->ConnectAbility(want, connection, nullptr, 100); return true; } else if (dumpOption[1] == WORK_QUEUE_INFO) { DumpWorkQueueInfo(dumpInfo); @@ -437,7 +472,7 @@ int32_t WorkSchedulerService::CreateNodeDir(std::string dir) return flag; } } else { - WS_HILOGE("%{public}s: This directory already exists.", __func__); + WS_HILOGD("%{public}s: This directory already exists.", __func__); } return ERR_OK; } @@ -452,7 +487,7 @@ int32_t WorkSchedulerService::CreateNodeFile(std::string filePath) return fd; } } else { - WS_HILOGE("%{public}s: the file already exists.", __func__); + WS_HILOGD("%{public}s: the file already exists.", __func__); } return ERR_OK; } diff --git a/services/native/test/BUILD.gn b/services/native/test/BUILD.gn deleted file mode 100644 index 3b7a21e..0000000 --- a/services/native/test/BUILD.gn +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") - -group("worksched_native_test") { - testonly = true - deps = [ "unittest:unittest_service" ] -} diff --git a/services/native/test/unittest/BUILD.gn b/services/native/test/unittest/BUILD.gn deleted file mode 100644 index 083a5c6..0000000 --- a/services/native/test/unittest/BUILD.gn +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") - -module_output_path = "${worksched_native_part_name}/worksched_native" - -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "include", - "${worksched_service_path}/zidl/include", - ] -} - -ohos_unittest("test_workscheduler") { - module_out_path = module_output_path - sources = [ "src/workscheduler_test.cpp" ] - configs = [ ":module_private_config" ] - deps = [ - "${worksched_frameworks_path}:workschedclient", - "${worksched_service_path}:workschedservice", - "${worksched_utils_path}:workschedutils", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", - "//third_party/jsoncpp", - ] - - external_deps = [ - "ces_standard:cesfwk_innerkits", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - ] - - subsystem_name = "resourceschedule" - part_name = "${worksched_native_part_name}" -} - -group("unittest_service") { - testonly = true - deps = [ ":test_workscheduler" ] -} diff --git a/services/native/test/unittest/include/workscheduler_test.h b/services/native/test/unittest/include/workscheduler_test.h deleted file mode 100644 index 73fdd2b..0000000 --- a/services/native/test/unittest/include/workscheduler_test.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORKINFO_TEST_H -#define WORKINFO_TEST_H - -#include - -namespace OHOS { -namespace WorkScheduler { -class WorkSchedulerTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORKINFO_TEST_H \ No newline at end of file diff --git a/services/native/test/unittest/src/workscheduler_test.cpp b/services/native/test/unittest/src/workscheduler_test.cpp deleted file mode 100644 index 5b869b1..0000000 --- a/services/native/test/unittest/src/workscheduler_test.cpp +++ /dev/null @@ -1,482 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "workscheduler_test.h" - -#include -#include -#include -#include -#include - -#include "want.h" -#include "common_event_support.h" -#include "common_event_manager.h" -#include "iwork_sched_service.h" -#include "work_scheduler_service.h" -#include "workscheduler_srv_client.h" -using namespace testing::ext; -using namespace OHOS::WorkScheduler; -using namespace OHOS::AAFwk; -using namespace OHOS::EventFwk; -using namespace OHOS; -using namespace std; - -void WorkSchedulerTest::SetUpTestCase(void) -{ -} - -void WorkSchedulerTest::TearDownTestCase(void) -{ -} - -void WorkSchedulerTest::SetUp() -{ -} - -void WorkSchedulerTest::TearDown() -{ -} - -/** - * @tc.name WorkSchedulerTest001 - * @tc.desc WorkScheduler start & stopAndCancel work info with CHARGER_CHARGING - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest001, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST001 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST001 come out"); -} - -/** - * @tc.name WorkSchedulerTest002 - * @tc.desc WorkScheduler start & stopAndCancel work info with CHARGER_DISCHARGING - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest002, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST002 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestChargerType(WorkCondition::Charger::CHARGER_DISCHARGING); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST002 come out"); -} - -/** - * @tc.name WorkSchedulerTest003 - * @tc.desc WorkScheduler start & stop work info with BATTERY_CHANGED - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest003, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST003 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_CHANGED); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST003 come out"); -} - -/** - * @tc.name WorkSchedulerTest004 - * @tc.desc WorkScheduler start & stop work info with BATTERY_LOW - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest004, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST004 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST004 come out"); -} - -/** - * @tc.name WorkSchedulerTest005 - * @tc.desc WorkScheduler start & stop work info with BATTERY_OKEY - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest005, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST005 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_OKEY); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST005 come out"); -} - -/** - * @tc.name WorkSchedulerTest006 - * @tc.desc WorkScheduler start & stop work info with STORAGE_FULL - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest006, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST006 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST006 come out"); -} - -/** - * @tc.name WorkSchedulerTest007 - * @tc.desc WorkScheduler start & stop work info with STORAGE_LOW - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest007, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST007 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST007 come out"); -} - -/** - * @tc.name WorkSchedulerTest008 - * @tc.desc WorkScheduler start & stop work info with STORAGE_OK - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchdulerTest008, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST008 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - bool stopRet = wsc.StopAndCancelWork(workInfo); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST008 come out"); -} - -/** - * @tc.name WorkSchedulerTest009 - * @tc.desc Test WorkSchedulerService#ObtainAllWorks() when app has 1 work in queue - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest009, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST009 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 1); - bool stopRet = wsc.StopAndClearWorks(); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST009 come out"); -} - -/** - * @tc.name WorkSchedulerTest010 - * @tc.desc Test WorkSchedulerService#ObtainAllWorks() when app has 3 works in queue - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest010, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST010 come in"); - WorkInfo workInfo1 = WorkInfo(); - workInfo1.SetWorkId(1); - workInfo1.SetElement("com.test.bundlename", "abilityname"); - workInfo1.RequestStorageLevel(WorkCondition::Storage::STORAGE_FULL); - WorkInfo workInfo2 = WorkInfo(); - workInfo2.SetWorkId(2); - workInfo2.SetElement("com.test.bundlename", "abilityname"); - workInfo2.RequestStorageLevel(WorkCondition::Storage::STORAGE_LOW); - WorkInfo workInfo3 = WorkInfo(); - workInfo3.SetWorkId(3); - workInfo3.SetElement("com.test.bundlename", "abilityname"); - workInfo3.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet1 = wsc.StartWork(workInfo1); - EXPECT_TRUE(startRet1); - bool startRet2 = wsc.StartWork(workInfo2); - EXPECT_TRUE(startRet2); - bool startRet3 = wsc.StartWork(workInfo3); - EXPECT_TRUE(startRet3); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 3); - bool stopRet = wsc.StopAndClearWorks(); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST010 come out"); -} - -/** - * @tc.name WorkSchedulerTest011 - * @tc.desc Test WorkSchedulerService#StopWork - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest011, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST011 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_OK); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - shared_ptr want = make_shared(); - want->SetAction(CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); - shared_ptr event = make_shared(*want); - auto publishResult = CommonEventManager::PublishCommonEvent(*event); - EXPECT_TRUE(publishResult); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 1); - bool stopRet = wsc.StopWork(workInfo); - EXPECT_TRUE(stopRet); - bool ret = wsc.StopAndClearWorks(); - EXPECT_TRUE(ret); - WS_HILOGD(MODULE_SERVICE, "TEST011 come out"); -} - -/** - * @tc.name WorkSchedulerTest012 - * @tc.desc Test WorkSchedulerService#ObtainAllWorks will get the same workInfo - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest012, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST012 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 1); - auto work = list.back(); - EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); - EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); - EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); - bool stopRet = wsc.StopWork(workInfo); - EXPECT_TRUE(stopRet); - bool ret = wsc.StopAndClearWorks(); - EXPECT_TRUE(ret); - WS_HILOGD(MODULE_SERVICE, "TEST012 come out"); -} - -/** - * @tc.name WorkSchedulerTest013 - * @tc.desc Test WorkSchedulerService#ObtainAllWorks will get the same workInfo - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest013, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST013 come in"); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(1); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 1); - auto work = list.back(); - EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); - EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); - EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); - EXPECT_EQ(work->GetBatteryStatus(), workInfo.GetBatteryStatus()); - WS_HILOGD(MODULE_SERVICE, "TEST013 BF call StopWork"); - bool stopRet = wsc.StopWork(workInfo); - WS_HILOGD(MODULE_SERVICE, "TEST013 AF call StopWork returns: %{public}s", stopRet ? "true" : "false"); - EXPECT_TRUE(stopRet); - WS_HILOGD(MODULE_SERVICE, "TEST013 BF call StopAndClearWorks"); - bool ret = wsc.StopAndClearWorks(); - WS_HILOGD(MODULE_SERVICE, "TEST013 AF call StopAndClearWorks returns: %{public}s", ret ? "true" : "false"); - EXPECT_TRUE(ret); - WS_HILOGD(MODULE_SERVICE, "TEST013 come out"); -} - -/** - * @tc.name WorkSchedulerTest014 - * @tc.desc Test WorkSchedulerService#RequestPersisted true to set persisted work - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest014, TestSize.Level0) -{ - WS_HILOGD(MODULE_SERVICE, "TEST014 come in"); - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - int32_t workId = wsc.ObtainAllWorks().size() + 1; - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(workId); - workInfo.SetElement("com.test.bundlename", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); - workInfo.RequestPersisted(true); - bool startRet = wsc.StartWork(workInfo); - EXPECT_TRUE(startRet); - auto list = wsc.ObtainAllWorks(); - EXPECT_TRUE(list.size() == 1); - auto work = list.back(); - EXPECT_EQ(work->GetWorkId(), workInfo.GetWorkId()); - EXPECT_EQ(work->GetBundleName(), workInfo.GetBundleName()); - EXPECT_EQ(work->GetAbilityName(), workInfo.GetAbilityName()); - EXPECT_EQ(work->GetBatteryStatus(), workInfo.GetBatteryStatus()); - bool stopRet = wsc.StopWork(workInfo); - EXPECT_TRUE(stopRet); - bool ret = wsc.StopAndClearWorks(); - EXPECT_TRUE(ret); - WS_HILOGD(MODULE_SERVICE, "TEST014 come out"); -} - -/** - * @tc.name WorkSchedulerTest015 - * @tc.desc Test WorkSchedulerService - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest015, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "WorkSchedulerTest015 enter"; - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - int32_t workId = wsc.ObtainAllWorks().size() + 1; - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(workId); - workInfo.SetElement("ohos.samples.flashlight", "abilityname"); - workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_LOW); - workInfo.RequestPersisted(true); - bool startRet = wsc.StartWork(workInfo); - WS_HILOGD(MODULE_SERVICE, "TEST015 StartWork result: %{public}s", startRet ? "TRUE" : "FALSE"); - EXPECT_TRUE(startRet); - auto list = wsc.ObtainAllWorks(); - WS_HILOGD(MODULE_SERVICE, "TEST015 obtain all works size: %{public}d", list.size()); - EXPECT_TRUE(list.size() > 0); - bool stopRet = wsc.StopWork(workInfo); - EXPECT_TRUE(stopRet); - bool ret = wsc.StopAndClearWorks(); - EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "WorkSchedulerTest015 return"; -} - -/** - * @tc.name WorkSchedulerTest016 - * @tc.desc Test WorkSchedulerService - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest016, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "WorkSchedulerTest016 enter"; - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - WorkInfo workInfo_0 = WorkInfo(); - workInfo_0.SetWorkId(0); - workInfo_0.SetElement("ohos.samples.demo", "abilityName0"); - workInfo_0.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); - WorkInfo workInfo_1 = WorkInfo(); - workInfo_1.SetWorkId(1); - workInfo_1.SetElement("ohos.samples.demo", "abilityName1"); - workInfo_1.RequestChargerType(WorkCondition::Charger::CHARGER_CHARGING); - bool startRet0 = wsc.StartWork(workInfo_0); - EXPECT_TRUE(startRet0); - bool startRet1 = wsc.StartWork(workInfo_1); - EXPECT_TRUE(startRet1); - shared_ptr want = make_shared(); - want->SetAction(CommonEventSupport::COMMON_EVENT_CHARGING); - shared_ptr event = make_shared(*want); - auto publishResult = CommonEventManager::PublishCommonEvent(*event); - EXPECT_TRUE(publishResult); - GTEST_LOG_(INFO) << "Send COMMON_EVENT_CHARGING already"; - GTEST_LOG_(INFO) << "sleep 6 sec..."; - sleep(6); - GTEST_LOG_(INFO) << "workInfo_0 call stop work"; - bool stopRet0 = wsc.StopWork(workInfo_0); - EXPECT_TRUE(stopRet0); - GTEST_LOG_(INFO) << "sleep 10 sec..."; - sleep(10); - GTEST_LOG_(INFO) << "workInfo_1 call stop work"; - bool stopRet1 = wsc.StopWork(workInfo_1); - EXPECT_TRUE(stopRet1); - sleep(4); - bool ret = wsc.StopAndClearWorks(); - EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "WorkSchedulerTest016 return"; -} - -/** - * @tc.name WorkSchedulerTest017 - * @tc.desc Test WorkSchedulerService - * @tc.type FUNC - */ -HWTEST_F (WorkSchedulerTest, WorkSchedulerTest017, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "WorkSchedulerTest017 enter"; - auto& wsc = WorkSchedulerSrvClient::GetInstance(); - WorkInfo workInfo = WorkInfo(); - workInfo.SetWorkId(0); - workInfo.SetElement("com.samples.demo", "abilityName"); - workInfo.RequestRepeatCycle(600); - bool ret = wsc.StartWork(workInfo); - EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "sleep 70s..."; - sleep(70); - wsc.StopAndCancelWork(workInfo); - GTEST_LOG_(INFO) << "Stop and clear workInfo"; - EXPECT_TRUE(ret); - sleep(25); - GTEST_LOG_(INFO) << "WorkSchedulerTest017 END"; -} \ No newline at end of file diff --git a/services/zidl/include/work_scheduler_stub_imp.h b/services/zidl/include/work_scheduler_stub_imp.h index 9e32e07..e226155 100644 --- a/services/zidl/include/work_scheduler_stub_imp.h +++ b/services/zidl/include/work_scheduler_stub_imp.h @@ -23,7 +23,6 @@ namespace OHOS { namespace WorkScheduler { -// using AbilityRuntime::JsWorkSchedulerExtension; class WorkSchedulerStubImp : public WorkSchedulerStub { public: explicit WorkSchedulerStubImp(const std::shared_ptr& extension) diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index 9169f2f..a0b3f30 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -47,7 +47,7 @@ bool WorkSchedServiceProxy::StartWork(WorkInfo& workInfo) } bool result = false; READ_PARCEL_WITH_RET(reply, Bool, result, false); - WS_HILOGE("after result : %{public}s ", std::to_string(result).c_str()); + WS_HILOGD("after result : %{public}s ", std::to_string(result).c_str()); return result; } diff --git a/services/zidl/src/work_sched_service_stub.cpp b/services/zidl/src/work_sched_service_stub.cpp index 2a425aa..6c8de28 100644 --- a/services/zidl/src/work_sched_service_stub.cpp +++ b/services/zidl/src/work_sched_service_stub.cpp @@ -65,7 +65,6 @@ int WorkSchedServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me reply.WriteInt32(worksize); for (auto workInfo : workInfos) { reply.WriteParcelable(&*workInfo); - // workInfo->Marshalling(reply); } return ERR_OK; } -- Gitee From 4067894189b1280f5c7f8623a3400dd39ee0c128 Mon Sep 17 00:00:00 2001 From: chenming Date: Mon, 7 Feb 2022 23:09:45 +0800 Subject: [PATCH 11/29] get status bugfix Signed-off-by: chenming --- services/zidl/src/work_sched_service_proxy.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index a0b3f30..cc97389 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -213,6 +213,9 @@ std::shared_ptr WorkSchedServiceProxy::GetWorkStatus(int32_t &uid, int } WorkInfo *workInfo; workInfo = reply.ReadParcelable(); + if (workInfo == nullptr) { + return nullptr; + } return std::make_shared(*workInfo); } -- Gitee From c528b5402960408b3ed355537f8e7488ede304fa Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 00:19:11 +0800 Subject: [PATCH 12/29] add tdd bugfix Signed-off-by: chenming --- .../work_scheduler_jsunit.test.js | 14 +++++++------- services/native/src/work_policy_manager.cpp | 4 +++- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js index ec477a7..8d7d581 100644 --- a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -109,7 +109,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest004", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest004---------------------------'); let workInfo = { - workId: 3, + workId: 4, bundleName: "com.example.myapplication", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY } @@ -127,7 +127,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest005", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest005---------------------------'); let workInfo = { - workId: 3, + workId: 5, bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName" } @@ -145,7 +145,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest006", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest006---------------------------'); let workInfo = { - workId: 3, + workId: 6, bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY @@ -164,7 +164,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest007", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest007---------------------------'); let workInfo = { - workId: 3, + workId: 7, bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY @@ -188,7 +188,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest008", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest008---------------------------'); let workInfo = { - workId: 3, + workId: 8, bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY @@ -212,7 +212,7 @@ describe("WorkSchedulerJsTest", function () { it("WorkSchedulerJsTest009", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest009---------------------------'); let workInfo = { - workId: 3, + workId: 9, bundleName: "com.example.myapplication", abilityName: "com.mytest.abilityName", storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY @@ -222,7 +222,7 @@ describe("WorkSchedulerJsTest", function () { expect(false).assertEqual(true) done(); } - workScheduler.getWorkStatus(3, (err, res) => { + workScheduler.getWorkStatus(9, (err, res) => { if (err) { expect(false).assertEqual(true) } else { diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 3508488..23df32f 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -309,7 +309,9 @@ shared_ptr WorkPolicyManager::GetWorkStatus(int32_t &uid, int32_t &wor if (uidQueueMap_.count(uid) > 0) { auto queue = uidQueueMap_.at(uid); auto workStatus = queue->Find(string("u") + to_string(uid) + "_" + to_string(workId)); - return workStatus->workInfo_; + if (workStatus != nullptr) { + return workStatus->workInfo_; + } } return nullptr; } -- Gitee From 4b62a3369b712cec5ba74541ded87e06faf46ace Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 15:28:56 +0800 Subject: [PATCH 13/29] codestyle fixed Signed-off-by: chenming --- frameworks/include/work_info.h | 2 +- frameworks/src/work_info.cpp | 5 +-- interfaces/kits/js/napi/src/common.cpp | 23 +++++++++----- .../kits/js/napi/src/stop_and_clear_works.cpp | 1 - .../js/napi/work_scheduler_extension/BUILD.gn | 3 +- .../include/work_scheduler_connection.h | 4 +-- services/native/include/work_status.h | 1 + services/native/src/policy/memory_policy.cpp | 8 ++--- services/native/src/work_conn_manager.cpp | 3 +- services/native/src/work_policy_manager.cpp | 31 ++++++++++++------- services/native/src/work_queue.cpp | 3 +- .../native/src/work_scheduler_service.cpp | 10 +++--- services/native/src/work_status.cpp | 23 ++++++++------ .../zidl/src/work_sched_service_proxy.cpp | 4 +-- services/zidl/src/work_scheduler_stub_imp.cpp | 4 --- .../dump/src/workscheduler_shell_command.cpp | 2 +- utils/native/include/delayed_sp_singleton.h | 10 +++--- 17 files changed, 76 insertions(+), 61 deletions(-) diff --git a/frameworks/include/work_info.h b/frameworks/include/work_info.h index f3645dd..b18f0bf 100644 --- a/frameworks/include/work_info.h +++ b/frameworks/include/work_info.h @@ -20,8 +20,8 @@ #include #include -#include "json/json.h" #include +#include "json/json.h" #include "work_condition.h" diff --git a/frameworks/src/work_info.cpp b/frameworks/src/work_info.cpp index 956b9c4..e279e3a 100644 --- a/frameworks/src/work_info.cpp +++ b/frameworks/src/work_info.cpp @@ -98,7 +98,7 @@ int32_t WorkInfo::GetWorkId() std::string WorkInfo::GetBundleName() { - return bundleName_; + return bundleName_; } std::string WorkInfo::GetAbilityName() @@ -337,7 +337,8 @@ bool WorkInfo::ParseFromJson(const Json::Value value) this->RequestNetworkType(WorkCondition::Network(conditions["network"].asInt())); } if (conditions.isMember("isCharging") && conditions.isMember("chargerType")) { - this->RequestChargerType(conditions["isCharging"].asBool(), WorkCondition::Charger(conditions["chargerType"].asInt())); + this->RequestChargerType(conditions["isCharging"].asBool(), + WorkCondition::Charger(conditions["chargerType"].asInt())); } if (conditions.isMember("batteryLevel")) { this->RequestBatteryLevel(conditions["batteryLevel"].asInt()); diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index 274e8d1..f81ea53 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -25,6 +25,8 @@ const int UNSET_INT_PARAM = -1; const std::string UNSET_STRING_PARAM = ""; const int TRUE_PARAM = 1; const int FALSE_PARAM = 0; +const int BATTERY_LEVEL_MIN = 0; +const int BATTERY_LEVEL_MAX = 100; napi_value Common::NapiGetNull(napi_env env) { @@ -58,7 +60,8 @@ bool Common::GetBaseWorkInfo(napi_env env, napi_value objValue, WorkInfo &workIn return true; } -bool Common::GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { +bool Common::GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ bool hasCondition = false; int32_t networkType = Common::GetIntProperty(env, objValue, "networkType"); if (networkType == UNSET_INT_PARAM) { @@ -73,7 +76,8 @@ bool Common::GetNetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInf return hasCondition; } -bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { +bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ bool hasCondition = false; int32_t isCharging = Common::GetBoolToIntProperty(env, objValue, "isCharging"); int32_t chargerType = Common::GetIntProperty(env, objValue, "chargerType"); @@ -97,14 +101,14 @@ bool Common::GetChargeInfo(napi_env env, napi_value objValue, WorkInfo &workInfo return hasCondition; } -bool Common::GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { +bool Common::GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ bool hasCondition = false; // Get battery level info. int32_t batteryLevel = Common::GetIntProperty(env, objValue, "batteryLevel"); if (batteryLevel == UNSET_INT_PARAM) { WS_HILOGI("Unset batteryLevel."); - } else if (batteryLevel >= 0 && batteryLevel <= 100) { - // batteryLevel only can be between 0 and 100. + } else if (batteryLevel >= BATTERY_LEVEL_MIN && batteryLevel <= BATTERY_LEVEL_MAX) { workInfo.RequestBatteryLevel(batteryLevel); hasCondition = true; } else { @@ -125,7 +129,8 @@ bool Common::GetBatteryInfo(napi_env env, napi_value objValue, WorkInfo &workInf return hasCondition; } -bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { +bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ bool hasCondition = false; int32_t storageRequest = Common::GetIntProperty(env, objValue, "storageRequest"); if (storageRequest == UNSET_INT_PARAM) { @@ -140,7 +145,8 @@ bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInf return hasCondition; } -bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { +bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ bool hasCondition = false; bool isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); if (isRepeat) { @@ -371,7 +377,8 @@ void Common::SetCallback( napi_value results[RESULT_PARAMS_NUM] = {nullptr}; results[0] = GetCallbackErrorValue(env, errorCode); results[1] = result; - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, RESULT_PARAMS_NUM, &results[0], &resultout)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, + RESULT_PARAMS_NUM, &results[0], &resultout)); } napi_value Common::SetPromise( diff --git a/interfaces/kits/js/napi/src/stop_and_clear_works.cpp b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp index 76637a7..d206a2b 100644 --- a/interfaces/kits/js/napi/src/stop_and_clear_works.cpp +++ b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace WorkScheduler { - napi_value StopAndClearWorks(napi_env env, napi_callback_info info) { WS_HILOGD("StopAndClearWorks napi begin"); diff --git a/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn index 7222e02..adc23e7 100644 --- a/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn +++ b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn @@ -15,7 +15,6 @@ import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") - ts2abc_gen_abc("gen_work_scheduler_extension_abc") { src_js = rebase_path("work_scheduler_extension.js") dst_file = rebase_path(target_out_dir + "/work_scheduler_extension.abc") @@ -48,5 +47,5 @@ ohos_shared_library("workschedulerextension_napi") { relative_install_dir = "module" part_name = "${worksched_native_part_name}" - subsystem_name = "resourceschedule" + subsystem_name = "resourceschedule" } diff --git a/services/native/include/work_scheduler_connection.h b/services/native/include/work_scheduler_connection.h index b9aa3cc..457aa01 100644 --- a/services/native/include/work_scheduler_connection.h +++ b/services/native/include/work_scheduler_connection.h @@ -30,6 +30,6 @@ public: private: sptr proxy_ = nullptr; }; -} // namespace -} // namespace OHOS +} // namespace +} // namespace OHOS #endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H diff --git a/services/native/include/work_status.h b/services/native/include/work_status.h index 7103ad9..6fe25a2 100644 --- a/services/native/include/work_status.h +++ b/services/native/include/work_status.h @@ -49,6 +49,7 @@ public: bool IsReady(); bool IsRunning(); + bool IsRemoved(); bool IsRepeating(); bool IsLastWorkTimeout(); void OnConditionChanged(WorkCondition::Type &type, std::shared_ptr value); diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp index 72d30a6..fb36a9e 100644 --- a/services/native/src/policy/memory_policy.cpp +++ b/services/native/src/policy/memory_policy.cpp @@ -28,10 +28,10 @@ MemoryPolicy::~MemoryPolicy() { } -int32_t GetMemAvailable() { +int32_t GetMemAvailable() +{ int32_t memAvailable; - FILE *fp; - fp = fopen("/proc/meminfo", "r"); + FILE *fp = fopen("/proc/meminfo", "r"); if (fp == NULL) { WS_HILOGE("GetMemAvailable file open failed."); memAvailable = IPolicyFilter::CANNOT_RUNNING_MORE; @@ -41,7 +41,7 @@ int32_t GetMemAvailable() { const char mem_name[] = "MemAvailable"; char name[20]; int32_t value = -1; - while (NULL != fgets(buf, buff_len, fp)) { + while (fgets(buf, buff_len, fp) != NULL) { sscanf(buf, "%s%d", name, &value); string sname = name; if (sname.find(mem_name) != string::npos) { diff --git a/services/native/src/work_conn_manager.cpp b/services/native/src/work_conn_manager.cpp index 44c1f5c..57fb7ab 100644 --- a/services/native/src/work_conn_manager.cpp +++ b/services/native/src/work_conn_manager.cpp @@ -56,7 +56,8 @@ void WorkConnManager::StopWork(shared_ptr workStatus) } auto workConn = connMap_.at(workStatus->workId_); WS_HILOGD("work stop: %{public}s/%{public}s id: %{public}s", - workStatus->workInfo_->GetBundleName().c_str(), workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); + workStatus->workInfo_->GetBundleName().c_str(), + workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); workConn->OnWorkStop(workStatus->workInfo_); connMap_.erase(workStatus->workId_); } diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 23df32f..1d13e84 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -103,35 +103,44 @@ shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int return nullptr; } -void WorkPolicyManager::removeFromUidQueue(std::shared_ptr workStatus, int32_t uid) { +void WorkPolicyManager::removeFromUidQueue(std::shared_ptr workStatus, int32_t uid) +{ std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { uidQueueMap_.at(uid)->CancelWork(workStatus); } } -void WorkPolicyManager::removeFromReadyQueue(std::shared_ptr workStatus) { +void WorkPolicyManager::removeFromReadyQueue(std::shared_ptr workStatus) +{ std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->RemoveUnReady(); } -bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel) { +bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel) +{ WS_HILOGI("WorkPolicyManager::StopWork"); + bool hasCanceled = false; if (workStatus->IsRunning()) { workConnManager_->StopWork(workStatus); + if (!workStatus->IsRepeating()) { + workStatus->MarkStatus(WorkStatus::Status::REMOVED); + removeFromUidQueue(workStatus, uid); + removeFromReadyQueue(workStatus); + hasCanceled = true; + } else { + workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } } - if (workStatus->IsRepeating() || workStatus->persisted_) { - workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); - } else { - workStatus->MarkStatus(WorkStatus::Status::REMOVED); - } - if (needCancel) { + + if (!hasCanceled && needCancel) { removeFromUidQueue(workStatus, uid); removeFromReadyQueue(workStatus); + hasCanceled = true; } CheckWorkToRun(); - return true; + return hasCanceled; } bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t uid) @@ -205,7 +214,7 @@ int32_t WorkPolicyManager::GetRunningCount() std::lock_guard lock(uidMapMutex_); int32_t count = 0; auto it = uidQueueMap_.begin(); - while(it != uidQueueMap_.end()) { + while (it != uidQueueMap_.end()) { count += it->second->GetRunningCount(); it++; } diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index 1575aac..e7c9ede 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -168,7 +168,8 @@ void WorkQueue::Dump(string& result) } } -void WorkQueue::ClearAll() { +void WorkQueue::ClearAll() +{ workList_.clear(); } diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 5dd35a1..98504c5 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -14,6 +14,8 @@ */ #include "work_scheduler_service.h" +#include +#include #include #include @@ -23,8 +25,6 @@ #include #include #include -#include -#include #include #include #include @@ -193,7 +193,8 @@ bool WorkSchedulerService::WorkPolicyManagerInit() return true; } -bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) { +bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) +{ std::string bundleName = workInfo.GetBundleName(); sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); @@ -301,8 +302,7 @@ bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel) { - workPolicyManager_->StopWork(workStatus, uid, needCancel); - if (needCancel) { + if (workPolicyManager_->StopWork(workStatus, uid, needCancel)) { workQueueManager_->CancelWork(workStatus); } return true; diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index 8cd9f13..67aa1c3 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -83,9 +83,7 @@ WorkStatus::WorkStatus(WorkInfo &workInfo, int32_t uid) this->currentStatus_ = WAIT_CONDITION; } -WorkStatus::~WorkStatus() -{ -} +WorkStatus::~WorkStatus() {} void WorkStatus::OnConditionChanged(WorkCondition::Type &type, shared_ptr value) { @@ -152,12 +150,14 @@ bool WorkStatus::IsReady() auto conditionSet = workConditionMap->at(it.first); auto conditionCurrent = conditionMap_.at(it.first); if (conditionSet->boolVal) { - if (conditionCurrent->enumVal != conditionSet->enumVal - && conditionSet->enumVal != static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY)) { + if (conditionCurrent->enumVal != conditionSet->enumVal && + conditionSet->enumVal != + static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY)) { return false; } } else { - if (conditionCurrent->enumVal != static_cast(WorkCondition::Charger::CHARGING_UNPLUGGED)) { + if (conditionCurrent->enumVal != + static_cast(WorkCondition::Charger::CHARGING_UNPLUGGED)) { return false; } } @@ -172,10 +172,8 @@ bool WorkStatus::IsReady() case WorkCondition::Type::TIMER: { bool repeat = workConditionMap->at(WorkCondition::Type::TIMER)->boolVal; int32_t cycleLeft = workConditionMap->at(WorkCondition::Type::TIMER)->intVal; - if (!repeat) { - if (cycleLeft == 0) { - return false; - } + if (!repeat && cycleLeft == 0) { + return false; } uint32_t intervalTime = workConditionMap->at(WorkCondition::Type::TIMER)->uintVal; if (baseTime_ + static_cast(intervalTime) >= getCurrentTime()) { @@ -198,6 +196,11 @@ bool WorkStatus::IsRunning() return currentStatus_ == RUNNING; } +bool WorkStatus::IsRemoved() +{ + return currentStatus_ == REMOVED; +} + bool WorkStatus::IsLastWorkTimeout() { return lastTimeout_; diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index cc97389..19a272b 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -93,7 +93,6 @@ bool WorkSchedServiceProxy::StopAndCancelWork(WorkInfo& workInfo) WRITE_PARCEL_WITH_RET(data, Parcelable, &workInfo, false); int ret = remote->SendRequest(static_cast(IWorkSchedService::STOP_AND_CANCEL_WORK), data, reply, option); - if (ret != ERR_OK) { WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); return false; @@ -211,8 +210,7 @@ std::shared_ptr WorkSchedServiceProxy::GetWorkStatus(int32_t &uid, int WS_HILOGE("%{pulbic}s SendRequest is failed, err code: %{public}d", __func__, ret); return nullptr; } - WorkInfo *workInfo; - workInfo = reply.ReadParcelable(); + WorkInfo *workInfo = reply.ReadParcelable(); if (workInfo == nullptr) { return nullptr; } diff --git a/services/zidl/src/work_scheduler_stub_imp.cpp b/services/zidl/src/work_scheduler_stub_imp.cpp index 8b90255..b7470be 100644 --- a/services/zidl/src/work_scheduler_stub_imp.cpp +++ b/services/zidl/src/work_scheduler_stub_imp.cpp @@ -26,10 +26,8 @@ void WorkSchedulerStubImp::OnWorkStart() if (extension != nullptr) { extension->OnWorkStart(); WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); - // return 0; } WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); - // return -1; } void WorkSchedulerStubImp::OnWorkStop() @@ -39,10 +37,8 @@ void WorkSchedulerStubImp::OnWorkStop() if (extension != nullptr) { extension->OnWorkStop(); WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); - // return 0; } WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); - // return -1; } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/utils/dump/src/workscheduler_shell_command.cpp b/utils/dump/src/workscheduler_shell_command.cpp index 0e84e16..c46159a 100644 --- a/utils/dump/src/workscheduler_shell_command.cpp +++ b/utils/dump/src/workscheduler_shell_command.cpp @@ -46,7 +46,7 @@ namespace { WorkSchedulerShellCommand::WorkSchedulerShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "workscheduler") {} -ErrCode WorkSchedulerShellCommand:: CreateCommandMap() +ErrCode WorkSchedulerShellCommand::CreateCommandMap() { commandMap_ = { {"dump", std::bind(&WorkSchedulerShellCommand::RunAsDumpCommand, this)}, diff --git a/utils/native/include/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h index 8fbeae9..17a8088 100644 --- a/utils/native/include/delayed_sp_singleton.h +++ b/utils/native/include/delayed_sp_singleton.h @@ -23,11 +23,11 @@ namespace OHOS { namespace WorkScheduler { -#define DECLARE_DELAYED_SP_SINGLETON(MyClass)\ -public:\ - ~MyClass();\ -private:\ - friend DelayedSpSingleton;\ +#define DECLARE_DELAYED_SP_SINGLETON(MyClass) \ +public: \ + ~MyClass(); \ +private: \ + friend DelayedSpSingleton; \ MyClass(); template -- Gitee From 10448561b085d3b0d53754e1b8923717a886b56b Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 16:31:07 +0800 Subject: [PATCH 14/29] code style fix Signed-off-by: chenming --- .../src/js_work_scheduler_extension.cpp | 4 --- .../js_work_scheduler_extension_context.cpp | 8 ++---- frameworks/src/workscheduler_srv_client.cpp | 3 ++- services/native/include/detector_value.h | 2 +- .../include/work_scheduler_connection.h | 2 +- .../native/include/work_scheduler_service.h | 9 ++++--- .../src/conditions/charger_listener.cpp | 4 +-- .../src/policy/app_removed_listener.cpp | 2 +- services/native/src/work_event_handler.cpp | 3 ++- services/native/src/work_policy_manager.cpp | 15 ++++++----- .../native/src/work_queue_event_handler.cpp | 6 +++-- services/native/src/work_status.cpp | 26 +++++++++++-------- .../zidl/src/work_sched_service_proxy.cpp | 3 +-- services/zidl/src/work_scheduler_proxy.cpp | 18 ------------- 14 files changed, 46 insertions(+), 59 deletions(-) diff --git a/frameworks/extension/src/js_work_scheduler_extension.cpp b/frameworks/extension/src/js_work_scheduler_extension.cpp index a6cfd7a..41fd04c 100644 --- a/frameworks/extension/src/js_work_scheduler_extension.cpp +++ b/frameworks/extension/src/js_work_scheduler_extension.cpp @@ -117,10 +117,6 @@ void JsWorkSchedulerExtension::OnWorkStart() { WorkSchedulerExtension::OnWorkStart(); WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); - // if (data == nullptr) { - // //HILOG_ERROR("%{public}s common event data == nullptr", __func__); - // return; - // } AbilityRuntime::HandleScope handleScope(jsRuntime_); NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); diff --git a/frameworks/extension/src/js_work_scheduler_extension_context.cpp b/frameworks/extension/src/js_work_scheduler_extension_context.cpp index 695e91a..b62b0c3 100644 --- a/frameworks/extension/src/js_work_scheduler_extension_context.cpp +++ b/frameworks/extension/src/js_work_scheduler_extension_context.cpp @@ -15,8 +15,6 @@ #include "js_work_scheduler_extension_context.h" -//#include "hilog_wrapper.h" - #include "js_extension_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" @@ -33,7 +31,6 @@ public: static void Finalizer(NativeEngine* engine, void* data, void* hint) { - //HILOG_INFO("JsStaticSubscriberExtensionContext::Finalizer is called"); std::unique_ptr( static_cast(data)); } @@ -45,7 +42,6 @@ private: NativeValue* CreateJsWorkSchedulerExtensionContext(NativeEngine& engine, std::shared_ptr context) { - //HILOG_INFO("CreateJsStaticSubscriberExtensionContext begin"); NativeValue *objValue = AbilityRuntime::CreateJsExtensionContext(engine, context); NativeObject *object = AbilityRuntime::ConvertNativeValueTo(objValue); @@ -54,5 +50,5 @@ NativeValue* CreateJsWorkSchedulerExtensionContext(NativeEngine& engine, object->SetNativePointer(jsContext.release(), JsWorkSchedulerExtensionContext::Finalizer, nullptr); return objValue; } -} // namespace WorkScheduler -} // namespace OHOS +} // namespace WorkScheduler +} // namespace OHOS diff --git a/frameworks/src/workscheduler_srv_client.cpp b/frameworks/src/workscheduler_srv_client.cpp index f03184d..43ab5c5 100644 --- a/frameworks/src/workscheduler_srv_client.cpp +++ b/frameworks/src/workscheduler_srv_client.cpp @@ -154,7 +154,8 @@ ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list &workInfo) { +ErrCode WorkSchedulerSrvClient::GetWorkStatus(int32_t workId, std::shared_ptr &workInfo) +{ WS_HILOGD("GetWorkStatus"); if (workId <= 0) { return E_WORK_ID_INVALID; diff --git a/services/native/include/detector_value.h b/services/native/include/detector_value.h index 84d90bf..e774c27 100644 --- a/services/native/include/detector_value.h +++ b/services/native/include/detector_value.h @@ -30,4 +30,4 @@ struct DetectorValue { }; } // namespace WorkScheduler } // namespace OHOS -#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_H +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_H \ No newline at end of file diff --git a/services/native/include/work_scheduler_connection.h b/services/native/include/work_scheduler_connection.h index 457aa01..8fd97a8 100644 --- a/services/native/include/work_scheduler_connection.h +++ b/services/native/include/work_scheduler_connection.h @@ -32,4 +32,4 @@ private: }; } // namespace } // namespace OHOS -#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H +#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 6b499fd..80c825d 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -59,15 +59,18 @@ public: void OnConditionReady(std::shared_ptr>> workStatusVector); - std::shared_ptr GetHandler() { + std::shared_ptr GetHandler() + { return handler_; } - std::shared_ptr GetWorkQueueManager() { + std::shared_ptr GetWorkQueueManager() + { return workQueueManager_; } - std::shared_ptr GetWorkPolicyManager() { + std::shared_ptr GetWorkPolicyManager() + { return workPolicyManager_; } diff --git a/services/native/src/conditions/charger_listener.cpp b/services/native/src/conditions/charger_listener.cpp index 59fe70b..6f3f4c0 100644 --- a/services/native/src/conditions/charger_listener.cpp +++ b/services/native/src/conditions/charger_listener.cpp @@ -34,7 +34,7 @@ void ChargerEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &dat int code = data.GetCode(); if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { int type = atoi(data.GetData().c_str()); - switch(type) { + switch (type) { case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_AC): WS_HILOGI("Condition changed: CHARGER_PLUGGED_AC"); listener_.OnConditionChanged(WorkCondition::Type::CHARGER, @@ -61,7 +61,7 @@ void ChargerEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &dat int code = data.GetCode(); if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { int type = atoi(data.GetData().c_str()); - switch(type) { + switch (type) { case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE): case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_BUTT): WS_HILOGI("Condition changed: CHARGER_PLUGGED_UNPLUGGED"); diff --git a/services/native/src/policy/app_removed_listener.cpp b/services/native/src/policy/app_removed_listener.cpp index f4cdf2a..aa97266 100644 --- a/services/native/src/policy/app_removed_listener.cpp +++ b/services/native/src/policy/app_removed_listener.cpp @@ -25,7 +25,7 @@ using namespace std; namespace OHOS { namespace WorkScheduler { AppRemovedSubscriber::AppRemovedSubscriber(const CommonEventSubscribeInfo &subscribeInfo, AppRemovedListener &listener) - : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + : CommonEventSubscriber(subscribeInfo), listener_(listener) {} void AppRemovedSubscriber::OnReceiveEvent(const CommonEventData &data) { diff --git a/services/native/src/work_event_handler.cpp b/services/native/src/work_event_handler.cpp index 9403c27..53edc75 100644 --- a/services/native/src/work_event_handler.cpp +++ b/services/native/src/work_event_handler.cpp @@ -44,8 +44,9 @@ void WorkEventHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer& wssptr->GetWorkPolicyManager()->CheckWorkToRun(); break; } + default: + return; } } - } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 1d13e84..cae96c4 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -30,7 +30,9 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace WorkScheduler { namespace { -const int64_t delayTime = 10000; +const int64_t DELAY_TIME_LONG = 10000; +const int64_t DELAY_TIME_SHORT = 1000; + } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) { @@ -278,21 +280,22 @@ void WorkPolicyManager::CheckWorkToRun() if (GetRunningCount() < GetMaxRunningCount()) { WS_HILOGD("running count < max running count"); workConnManager_->StartWork(topWork); - SendRetrigger(1000); + SendRetrigger(DELAY_TIME_SHORT); } else { - WS_HILOGD("trigger delay: %{public}lld", delayTime); - SendRetrigger(delayTime); + WS_HILOGD("trigger delay: %{public}lld", DELAY_TIME_LONG); + SendRetrigger(DELAY_TIME_LONG); } WS_HILOGD("WorkPolicyManager::%{public}s out", __func__); } -void WorkPolicyManager::SendRetrigger(int64_t delaytime) { +void WorkPolicyManager::SendRetrigger(int64_t delaytime) +{ WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); if (handler_ == nullptr) { return; } WS_HILOGD("WorkPolicyManager::%{public}s ,delay = %{public}lld", __func__, - delayTime); + delaytime); handler_->SendEvent(InnerEvent::Get(WorkEventHandler::RETRIGGER_MSG, 0), delaytime); } diff --git a/services/native/src/work_queue_event_handler.cpp b/services/native/src/work_queue_event_handler.cpp index 7efd6ad..a646dbd 100644 --- a/services/native/src/work_queue_event_handler.cpp +++ b/services/native/src/work_queue_event_handler.cpp @@ -21,6 +21,8 @@ using namespace std; namespace OHOS { namespace WorkScheduler { +const int TIMER_TICK_DELAY = 600000; + WorkQueueEventHandler::WorkQueueEventHandler(const shared_ptr& runner, shared_ptr manager) : AppExecFwk::EventHandler(runner) { @@ -31,10 +33,10 @@ WorkQueueEventHandler::WorkQueueEventHandler(const shared_ptrGetInnerEventId()); - switch(event->GetInnerEventId()) { + switch (event->GetInnerEventId()) { case TIMER_TICK: { manager_->OnConditionChanged(WorkCondition::Type::TIMER, make_shared(0, 0, 0, string())); - SendEvent(AppExecFwk::InnerEvent::Get(TIMER_TICK, 0), 600000); + SendEvent(AppExecFwk::InnerEvent::Get(TIMER_TICK, 0), TIMER_TICK_DELAY); break; } } diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index 67aa1c3..a502b14 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -127,10 +127,7 @@ void WorkStatus::MarkStatus(Status status) } } -void WorkStatus::MarkRound() -{ - -} +void WorkStatus::MarkRound() {} bool WorkStatus::IsReady() { @@ -164,7 +161,8 @@ bool WorkStatus::IsReady() break; } case WorkCondition::Type::BATTERY_LEVEL: { - if (workConditionMap->at(it.first)->intVal > PowerMgr::BatterySrvClient::GetInstance().GetCapacity()) { + if (workConditionMap->at(it.first)->intVal > + PowerMgr::BatterySrvClient::GetInstance().GetCapacity()) { return false; } break; @@ -232,20 +230,26 @@ void WorkStatus::Dump(string& result) result.append(string("\"isPersisted\":") + to_string(persisted_) + ",\n"); result.append(string("\"conditionMap\":{\n")); if (conditionMap_.count(WorkCondition::Type::NETWORK) > 0) { - result.append(string("\"networkType\":") + to_string(conditionMap_.at(WorkCondition::Type::NETWORK)->enumVal) + ",\n"); + result.append(string("\"networkType\":") + + to_string(conditionMap_.at(WorkCondition::Type::NETWORK)->enumVal) + ",\n"); } if (conditionMap_.count(WorkCondition::Type::CHARGER) > 0) { - result.append(string("\"isCharging\":") + (conditionMap_.at(WorkCondition::Type::CHARGER)->boolVal ? "true" : "false") + ",\n"); - result.append(string("\"chargerType\":") + to_string(conditionMap_.at(WorkCondition::Type::CHARGER)->enumVal) + ",\n"); + result.append(string("\"isCharging\":") + + (conditionMap_.at(WorkCondition::Type::CHARGER)->boolVal ? "true" : "false") + ",\n"); + result.append(string("\"chargerType\":") + + to_string(conditionMap_.at(WorkCondition::Type::CHARGER)->enumVal) + ",\n"); } if (conditionMap_.count(WorkCondition::Type::BATTERY_LEVEL) > 0) { - result.append(string("\"batteryLevel\":") + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal) + ",\n"); + result.append(string("\"batteryLevel\":") + + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal) + ",\n"); } if (conditionMap_.count(WorkCondition::Type::BATTERY_STATUS) > 0) { - result.append(string("\"batteryStatus\":") + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_STATUS)->enumVal) + ",\n"); + result.append(string("\"batteryStatus\":") + + to_string(conditionMap_.at(WorkCondition::Type::BATTERY_STATUS)->enumVal) + ",\n"); } if (conditionMap_.count(WorkCondition::Type::STORAGE) > 0) { - result.append(string("\"storageLevel\":") + to_string(conditionMap_.at(WorkCondition::Type::STORAGE)->enumVal) + ",\n"); + result.append(string("\"storageLevel\":") + + to_string(conditionMap_.at(WorkCondition::Type::STORAGE)->enumVal) + ",\n"); } result.append("},\n\"workInfo\":\n"); workInfo_->Dump(result); diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index 19a272b..a7e9e3d 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -181,8 +181,7 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 READ_PARCEL_WITHOUT_RET(reply, Int32, worksize); WS_HILOGD("BUGOAWF WSSP ObtainAllWorks worksize from read parcel is: %{public}d", worksize); for (int32_t i = 0; i < worksize; i++) { - WorkInfo *workInfo; - workInfo = reply.ReadParcelable(); + WorkInfo *workInfo = reply.ReadParcelable(); WS_HILOGD("WP read from parcel, workInfo ID: %{public}d", workInfo->GetWorkId()); workInfos.emplace_back(std::make_shared(*workInfo)); } diff --git a/services/zidl/src/work_scheduler_proxy.cpp b/services/zidl/src/work_scheduler_proxy.cpp index df25de5..580ddb5 100644 --- a/services/zidl/src/work_scheduler_proxy.cpp +++ b/services/zidl/src/work_scheduler_proxy.cpp @@ -23,16 +23,7 @@ void WorkSchedulerProxy::OnWorkStart() MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - // data.WriteParcelable(inData); - Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); - - // ErrCode ec = reply.ReadInt32(); - // if (FAILED(ec)) { - // return ec; - // } - - // return ERR_OK; } void WorkSchedulerProxy::OnWorkStop() @@ -41,16 +32,7 @@ void WorkSchedulerProxy::OnWorkStop() MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - // data.WriteParcelable(inData); - Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); - - // ErrCode ec = reply.ReadInt32(); - // if (FAILED(ec)) { - // return ec; - // } - - // return ERR_OK; } } // namespace WorkScheduler } // namespace OHOS -- Gitee From 8fab43d3b952cb2ac5b655a99d587132223db80b Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 20:16:32 +0800 Subject: [PATCH 15/29] fix Signed-off-by: chenming --- interfaces/test/unittest/BUILD.gn | 2 +- services/native/src/work_scheduler_service.cpp | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index e46065e..470a8ed 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") -module_output_path = "work_scheduler_jsunittest/interfaces" +module_output_path = "work_scheduler/interfaces" ohos_js_unittest("WorkSchedulerJsTest") { module_out_path = module_output_path diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 98504c5..055f4b4 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -368,8 +368,7 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemAbilityManager == nullptr) { -- Gitee From 4d68a77074f4c5aa4bac1dd5f69b245e612abbb1 Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 20:51:24 +0800 Subject: [PATCH 16/29] init persist when boot Signed-off-by: chenming --- services/native/include/work_event_handler.h | 1 + services/native/include/work_scheduler_service.h | 1 + services/native/src/work_event_handler.cpp | 4 ++++ services/native/src/work_policy_manager.cpp | 4 ++-- services/native/src/work_queue_event_handler.cpp | 2 +- services/native/src/work_scheduler_service.cpp | 13 ++++++++++--- 6 files changed, 19 insertions(+), 6 deletions(-) diff --git a/services/native/include/work_event_handler.h b/services/native/include/work_event_handler.h index a9739db..f130d32 100644 --- a/services/native/include/work_event_handler.h +++ b/services/native/include/work_event_handler.h @@ -28,6 +28,7 @@ class WorkEventHandler : public AppExecFwk::EventHandler { public: enum { RETRIGGER_MSG = 0, + INIT_PERSISTED_MSG, }; WorkEventHandler(const std::shared_ptr& runner, const wptr& service); diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 80c825d..f9899a2 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -53,6 +53,7 @@ public: std::list> ObtainAllWorks(int32_t &uid, int32_t &pid) override; std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workId) override; bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; + void InitPersisted(); int32_t CreateNodeDir(std::string dir); int32_t CreateNodeFile(std::string filePath); diff --git a/services/native/src/work_event_handler.cpp b/services/native/src/work_event_handler.cpp index 53edc75..c116a88 100644 --- a/services/native/src/work_event_handler.cpp +++ b/services/native/src/work_event_handler.cpp @@ -44,6 +44,10 @@ void WorkEventHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer& wssptr->GetWorkPolicyManager()->CheckWorkToRun(); break; } + case INIT_PERSISTED_MSG: { + wssptr->InitPersisted(); + break; + } default: return; } diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index cae96c4..1b2ea23 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -30,8 +30,8 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace WorkScheduler { namespace { -const int64_t DELAY_TIME_LONG = 10000; -const int64_t DELAY_TIME_SHORT = 1000; +static const int64_t DELAY_TIME_LONG = 10000; +static const int64_t DELAY_TIME_SHORT = 1000; } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) diff --git a/services/native/src/work_queue_event_handler.cpp b/services/native/src/work_queue_event_handler.cpp index a646dbd..2a60e8b 100644 --- a/services/native/src/work_queue_event_handler.cpp +++ b/services/native/src/work_queue_event_handler.cpp @@ -21,7 +21,7 @@ using namespace std; namespace OHOS { namespace WorkScheduler { -const int TIMER_TICK_DELAY = 600000; +static const int TIMER_TICK_DELAY = 600000; WorkQueueEventHandler::WorkQueueEventHandler(const shared_ptr& runner, shared_ptr manager) : AppExecFwk::EventHandler(runner) diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 055f4b4..ba36117 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -81,13 +81,20 @@ void WorkSchedulerService::OnStart() return; } + GetHandler()->SendEvent(InnerEvent::Get(WorkEventHandler::INIT_PERSISTED_MSG, 0), 15000); + + ready_ = true; + WS_HILOGE("OnStart and add system ability success."); +} + +void WorkSchedulerService::InitPersisted() +{ + WS_HILOGE("WorkSchedulerService::InitPersisted"); list> persistedWorks = ReadPersistedWorks(); for (auto it : persistedWorks) { + WS_HILOGE("%{public}s get persisted work, id: %{public}d", __func__, it->GetWorkId()); InitPersistedWork(*it); } - - ready_ = true; - WS_HILOGE("OnStart and add system ability success."); } list> WorkSchedulerService::ReadPersistedWorks() -- Gitee From 18245cc39b0307a858d2c791e2de5ade629351c1 Mon Sep 17 00:00:00 2001 From: chenming Date: Tue, 8 Feb 2022 21:24:29 +0800 Subject: [PATCH 17/29] code style Signed-off-by: chenming --- .../test/unittest/src/workinfo_test.cpp | 26 +++++++++---------- .../kits/js/napi/src/get_work_status.cpp | 2 +- services/native/include/ipolicy_listener.h | 3 +-- services/native/include/work_event_handler.h | 3 --- .../include/work_scheduler_connection.h | 2 +- .../src/conditions/battery_level_listener.cpp | 2 -- .../conditions/battery_status_listener.cpp | 2 -- services/native/src/work_queue.cpp | 3 ++- .../native/src/work_queue_event_handler.cpp | 3 +++ services/native/src/work_queue_manager.cpp | 2 +- services/native/src/work_status.cpp | 2 +- utils/dump/src/event_publisher.cpp | 24 +++++++++-------- 12 files changed, 36 insertions(+), 38 deletions(-) diff --git a/frameworks/test/unittest/src/workinfo_test.cpp b/frameworks/test/unittest/src/workinfo_test.cpp index 8646a35..9af3ce0 100644 --- a/frameworks/test/unittest/src/workinfo_test.cpp +++ b/frameworks/test/unittest/src/workinfo_test.cpp @@ -1,16 +1,16 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ #include "workinfo_test.h" diff --git a/interfaces/kits/js/napi/src/get_work_status.cpp b/interfaces/kits/js/napi/src/get_work_status.cpp index 3ad4b59..599ad9a 100644 --- a/interfaces/kits/js/napi/src/get_work_status.cpp +++ b/interfaces/kits/js/napi/src/get_work_status.cpp @@ -28,7 +28,7 @@ static const int32_t GET_WORK_STATUS_MAX_PARAMS = 2; struct GetWorkStatusParamsInfo { int32_t workId; napi_ref callback = nullptr; -}; +}; struct AsyncCallbackInfoGetWorkStatus { napi_env env = nullptr; diff --git a/services/native/include/ipolicy_listener.h b/services/native/include/ipolicy_listener.h index ef90be7..cf362ed 100644 --- a/services/native/include/ipolicy_listener.h +++ b/services/native/include/ipolicy_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H #define WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H diff --git a/services/native/include/work_event_handler.h b/services/native/include/work_event_handler.h index f130d32..b8e5191 100644 --- a/services/native/include/work_event_handler.h +++ b/services/native/include/work_event_handler.h @@ -21,7 +21,6 @@ #include #include "work_scheduler_service.h" - namespace OHOS { namespace WorkScheduler { class WorkEventHandler : public AppExecFwk::EventHandler { @@ -37,9 +36,7 @@ public: private: wptr service_; - }; } // namespace WorkScheduler } // namespace OHOS - #endif // WORK_SCHED_SERVICES_WORK_EVENT_HANDLER_H \ No newline at end of file diff --git a/services/native/include/work_scheduler_connection.h b/services/native/include/work_scheduler_connection.h index 8fd97a8..e4e6627 100644 --- a/services/native/include/work_scheduler_connection.h +++ b/services/native/include/work_scheduler_connection.h @@ -30,6 +30,6 @@ public: private: sptr proxy_ = nullptr; }; -} // namespace +} // namespace } // namespace OHOS #endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_STATIC_SUBSCRIBER_CONNECTION_H diff --git a/services/native/src/conditions/battery_level_listener.cpp b/services/native/src/conditions/battery_level_listener.cpp index 7c92a81..b553136 100644 --- a/services/native/src/conditions/battery_level_listener.cpp +++ b/services/native/src/conditions/battery_level_listener.cpp @@ -14,8 +14,6 @@ */ #include "conditions/battery_level_listener.h" -#include - #include "battery_info.h" #include "common_event_manager.h" #include "common_event_support.h" diff --git a/services/native/src/conditions/battery_status_listener.cpp b/services/native/src/conditions/battery_status_listener.cpp index e1e9921..c35a7a8 100644 --- a/services/native/src/conditions/battery_status_listener.cpp +++ b/services/native/src/conditions/battery_status_listener.cpp @@ -14,8 +14,6 @@ */ #include "conditions/battery_status_listener.h" -#include - #include "battery_info.h" #include "common_event_manager.h" #include "common_event_support.h" diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index e7c9ede..a1460c2 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -155,7 +155,8 @@ int32_t WorkQueue::GetRunningCount() return count; } -void WorkQueue::GetWorkIdStr(string& result) { +void WorkQueue::GetWorkIdStr(string& result) +{ for (auto it : workList_) { result.append(it->workId_ + ", "); } diff --git a/services/native/src/work_queue_event_handler.cpp b/services/native/src/work_queue_event_handler.cpp index 2a60e8b..25cf784 100644 --- a/services/native/src/work_queue_event_handler.cpp +++ b/services/native/src/work_queue_event_handler.cpp @@ -39,6 +39,9 @@ void WorkQueueEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::Inne SendEvent(AppExecFwk::InnerEvent::Get(TIMER_TICK, 0), TIMER_TICK_DELAY); break; } + default: { + return; + } } } } // namespace WorkScheduler diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index 73472d2..a86a97f 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -32,7 +32,7 @@ bool WorkQueueManager::AddListener(WorkCondition::Type type, shared_ptr lock(mutex_); if (listenerMap_.count(type) > 0) { return false; - } + } listenerMap_.emplace(type, listener); return true; } diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index a502b14..9d283a6 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -54,7 +54,7 @@ WorkStatus::WorkStatus(WorkInfo &workInfo, int32_t uid) shared_ptr chargerCondition = make_shared(); chargerCondition->enumVal = -1; BatteryPluggedType pluggedType = BatterySrvClient::GetInstance().GetPluggedType(); - switch(pluggedType) { + switch (pluggedType) { case BatteryPluggedType::PLUGGED_TYPE_NONE: chargerCondition->boolVal = false; chargerCondition->enumVal = WorkCondition::Charger::CHARGING_UNPLUGGED; diff --git a/utils/dump/src/event_publisher.cpp b/utils/dump/src/event_publisher.cpp index 1fc0405..40d1b07 100644 --- a/utils/dump/src/event_publisher.cpp +++ b/utils/dump/src/event_publisher.cpp @@ -28,6 +28,8 @@ namespace OHOS { namespace WorkScheduler { namespace { + static const int TYPE_PARAM = 1; + static const int DETAIL_PARAM = 2; static const std::string NETWORK = "network"; static const std::string EV_NETWORK_TYPE_WIFI = "wifi"; static const std::string CHARGING = "charging"; @@ -54,13 +56,13 @@ namespace { void EventPublisher::PublishEvent(const std::vector &dumpOption, std::vector &dumpInfo) { - if (dumpOption[1] == NETWORK) { + if (dumpOption[TYPE_PARAM] == NETWORK) { PublishNetworkEvent(dumpOption, dumpInfo); - } else if (dumpOption[1] == CHARGING) { + } else if (dumpOption[TYPE_PARAM] == CHARGING) { PublishChargingEvent(dumpOption, dumpInfo); - } else if (dumpOption[1] == STORAGE) { + } else if (dumpOption[TYPE_PARAM] == STORAGE) { PublishStorageEvent(dumpOption, dumpInfo); - } else if (dumpOption[1] == HELP) { + } else if (dumpOption[TYPE_PARAM] == HELP) { dumpInfo.push_back(HELP_MSG); } else { dumpInfo.push_back(std::string("dump -E need right param.")); @@ -71,7 +73,7 @@ void EventPublisher::PublishEvent(const std::vector &dumpOption, st void EventPublisher::PublishNetworkEvent(const std::vector &dumpOption, std::vector &dumpInfo) { EventFwk::Want want; - if (dumpOption[2] == EV_NETWORK_TYPE_WIFI) { + if (dumpOption[DETAIL_PARAM] == EV_NETWORK_TYPE_WIFI) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE); dumpInfo.push_back(std::string("publishing COMMON_EVENT_WIFI_CONN_STATE")); } else { @@ -87,22 +89,22 @@ void EventPublisher::PublishChargingEvent(const std::vector &dumpOp { EventFwk::Want want; EventFwk::CommonEventData data; - if (dumpOption[2] == EV_CHARGING_TYPE_AC) { + if (dumpOption[DETAIL_PARAM] == EV_CHARGING_TYPE_AC) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); data.SetWant(want); data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_AC))); - } else if (dumpOption[2] == EV_CHARGING_TYPE_USB) { + } else if (dumpOption[DETAIL_PARAM] == EV_CHARGING_TYPE_USB) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); data.SetWant(want); data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_USB))); - } else if (dumpOption[2] == EV_CHARGING_TYPE_WIRELESS) { + } else if (dumpOption[DETAIL_PARAM] == EV_CHARGING_TYPE_WIRELESS) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); data.SetWant(want); data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); data.SetData(std::to_string(static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_WIRELESS))); - } else if (dumpOption[2] == EV_CHARGING_TYPE_NONE) { + } else if (dumpOption[DETAIL_PARAM] == EV_CHARGING_TYPE_NONE) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); data.SetWant(want); data.SetCode(PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE); @@ -119,10 +121,10 @@ void EventPublisher::PublishChargingEvent(const std::vector &dumpOp void EventPublisher::PublishStorageEvent(const std::vector &dumpOption, std::vector &dumpInfo) { EventFwk::Want want; - if (dumpOption[2] == EV_STORAGE_LOW) { + if (dumpOption[DETAIL_PARAM] == EV_STORAGE_LOW) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW); dumpInfo.push_back(std::string("publishing COMMON_EVENT_DEVICE_STORAGE_LOW")); - } else if (dumpOption[2] == EV_STORAGE_OKAY) { + } else if (dumpOption[DETAIL_PARAM] == EV_STORAGE_OKAY) { want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_OK); dumpInfo.push_back(std::string("publishing COMMON_EVENT_DEVICE_STORAGE_OKAY")); } else { -- Gitee From 2b2c3507f794b39dffec99005c67ea451a88805b Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 9 Feb 2022 11:54:41 +0800 Subject: [PATCH 18/29] add remove listener Signed-off-by: chenming --- services/native/include/work_policy_manager.h | 6 ++- .../native/include/work_scheduler_service.h | 3 +- .../src/policy/app_removed_listener.cpp | 10 ++--- services/native/src/work_policy_manager.cpp | 37 +++++-------------- .../native/src/work_scheduler_service.cpp | 12 ++++-- 5 files changed, 29 insertions(+), 39 deletions(-) diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index 23025f8..40823af 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -20,6 +20,7 @@ #include #include "policy_type.h" +#include "policy/app_removed_listener.h" #include "policy/ipolicy_filter.h" #include "work_conn_manager.h" #include "work_info.h" @@ -32,7 +33,7 @@ namespace OHOS { namespace WorkScheduler { class WorkSchedulerService; class WorkEventHandler; - +class AppRemovedListener; class WorkPolicyManager { public: const size_t MAX_WORK_COUNT_PER_UID = 10; @@ -57,11 +58,11 @@ public: int32_t currentRunningCount = 0; void CheckWorkToRun(); void SendRetrigger(int64_t delayTime); + void AddAppRemoveListener(std::shared_ptr listener); private: int32_t GetMaxRunningCount(); int32_t GetRunningCount(); - void RemoveByBundle(std::string bundle); void DumpConditionReadyQueue(std::string& result); void DumpUidQueueMap(std::string& result); void removeFromUidQueue(std::shared_ptr workStatus, int32_t uid); @@ -77,6 +78,7 @@ private: std::mutex conditionReadyMutex_; std::shared_ptr conditionReadyQueue_; std::list> policyFilters_; + std::shared_ptr appRemovedListener_; }; } } // namespace OHOS diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index f9899a2..1dea823 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -28,6 +28,7 @@ #include "ability_manager_interface.h" #include "delayed_sp_singleton.h" +#include "policy/app_removed_listener.h" #include "work_info.h" #include "work_policy_manager.h" #include "work_queue_manager.h" @@ -54,7 +55,7 @@ public: std::shared_ptr GetWorkStatus(int32_t &uid, int32_t &workId) override; bool ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; void InitPersisted(); - + bool StopAndClearWorksByUid(int32_t uid); int32_t CreateNodeDir(std::string dir); int32_t CreateNodeFile(std::string filePath); diff --git a/services/native/src/policy/app_removed_listener.cpp b/services/native/src/policy/app_removed_listener.cpp index aa97266..bd52322 100644 --- a/services/native/src/policy/app_removed_listener.cpp +++ b/services/native/src/policy/app_removed_listener.cpp @@ -24,6 +24,7 @@ using namespace std; namespace OHOS { namespace WorkScheduler { +static const std::string UID_PARAM = "uid"; AppRemovedSubscriber::AppRemovedSubscriber(const CommonEventSubscribeInfo &subscribeInfo, AppRemovedListener &listener) : CommonEventSubscriber(subscribeInfo), listener_(listener) {} @@ -31,11 +32,11 @@ void AppRemovedSubscriber::OnReceiveEvent(const CommonEventData &data) { const string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED - || action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) { - WS_HILOGI("Policy changed: APP_REMOVED"); + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { string bundle = data.GetWant().GetBundle(); - auto detectorVal = make_shared(PolicyType::APP_REMOVED, 0, 0, bundle); + int32_t uid = data.GetWant().GetIntParam(UID_PARAM, -1); + WS_HILOGI("bundleName: %{public}s , uid: %{public}d", bundle.c_str(), uid); + auto detectorVal = make_shared(uid, 0, 0, bundle); listener_.OnPolicyChanged(PolicyType::APP_REMOVED, detectorVal); } } @@ -44,7 +45,6 @@ shared_ptr CreateAppRemovedSubscriber(AppRemovedListener { MatchingSkills skill = MatchingSkills(); skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); - skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); CommonEventSubscribeInfo info(skill); return make_shared(info, listener); } diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 1b2ea23..09de46f 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -20,7 +20,7 @@ #include #include #include -#include "bundle_mgr_proxy.h" + #include "work_scheduler_service.h" #include "work_event_handler.h" @@ -32,7 +32,6 @@ namespace WorkScheduler { namespace { static const int64_t DELAY_TIME_LONG = 10000; static const int64_t DELAY_TIME_SHORT = 1000; - } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) { @@ -62,6 +61,12 @@ void WorkPolicyManager::AddPolicyFilter(shared_ptr filter) policyFilters_.emplace_back(filter); } +void WorkPolicyManager::AddAppRemoveListener(shared_ptr listener) +{ + appRemovedListener_ = listener; + appRemovedListener_->Start(); +} + bool WorkPolicyManager::AddWork(shared_ptr workStatus, int32_t uid) { WS_HILOGI("WorkPolicyManager::AddWork"); @@ -228,7 +233,8 @@ void WorkPolicyManager::OnPolicyChanged(PolicyType policyType, shared_ptrRemoveByBundle(detectorVal->strVal); + auto ws = wss_.promote(); + ws->StopAndClearWorksByUid(detectorVal->intVal); break; } default: {} @@ -236,31 +242,6 @@ void WorkPolicyManager::OnPolicyChanged(PolicyType policyType, shared_ptr systemAbilityManager = - SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!systemAbilityManager) { - WS_HILOGE("fail to get system ability mgr."); - return; - } - sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (!remoteObject) { - WS_HILOGE("fail to get bundle manager proxy."); - return; - } - sptr bundleMgr = iface_cast(remoteObject); - BundleInfo bundleInfo; - std::lock_guard lock(uidMapMutex_); - if (bundleMgr->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { - auto ws = wss_.promote(); - for (auto it : uidQueueMap_.at(bundleInfo.uid)->GetWorkList()) { - ws->StopAndCancelWork(*(it->workInfo_)); - } - } -} - void WorkPolicyManager::CheckWorkToRun() { WS_HILOGI("CheckWorkToRun"); diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index ba36117..b442465 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -196,6 +196,9 @@ bool WorkSchedulerService::WorkPolicyManagerInit() auto memoryFilter = make_shared(workPolicyManager_); workPolicyManager_->AddPolicyFilter(thermalFilter); workPolicyManager_->AddPolicyFilter(memoryFilter); + + auto appRemoveListener = make_shared(workPolicyManager_); + workPolicyManager_->AddAppRemoveListener(appRemoveListener); WS_HILOGI("work policy manager init success."); return true; } @@ -324,9 +327,13 @@ bool IsInList(list &list, std::string myWork) { return false; } -bool WorkSchedulerService::StopAndClearWorks() +bool WorkSchedulerService::StopAndClearWorks() { + return StopAndClearWorksByUid(IPCSkeleton::GetCallingUid()); +} + +bool WorkSchedulerService::StopAndClearWorksByUid(int32_t uid) { - int32_t uid = IPCSkeleton::GetCallingUid(); + WS_HILOGD("StopAndClearWorksByUid:%{public}d", uid); list> allWorks = workPolicyManager_->GetAllWorkStatus(uid); list workIdList; for (auto work : allWorks) { @@ -340,7 +347,6 @@ bool WorkSchedulerService::StopAndClearWorks() for (auto workId : workIdList) { if (persistedMap_.count(workId) != 0) { persistedMap_.erase(workId); - WS_HILOGD("chenmingid %{public}s", workId.c_str()); } } RefreshPersistedWorks(); -- Gitee From 25d25ab343fe9bf1b0b00901f77f1d1179ccd5c6 Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 9 Feb 2022 12:07:05 +0800 Subject: [PATCH 19/29] code style Signed-off-by: chenming --- .../extension/include/iwork_scheduler.h | 3 --- .../src/js_work_scheduler_extension.cpp | 10 ------- .../src/work_scheduler_extension.cpp | 7 +---- ...work_scheduler_extension_module_loader.cpp | 3 ++- .../test/unittest/include/workinfo_test.h | 26 +++++++++---------- .../js/napi/src/is_last_work_time_out.cpp | 2 +- services/native/include/detector_value.h | 2 +- .../native/src/work_scheduler_service.cpp | 6 +++-- .../zidl/src/work_sched_service_proxy.cpp | 3 --- utils/dump/src/event_publisher.cpp | 3 ++- utils/native/include/work_sched_common.h | 2 +- utils/native/include/work_sched_hilog.h | 2 +- utils/native/include/work_sched_utils.h | 2 +- 13 files changed, 27 insertions(+), 44 deletions(-) diff --git a/frameworks/extension/include/iwork_scheduler.h b/frameworks/extension/include/iwork_scheduler.h index 812c8c1..22b1c9a 100644 --- a/frameworks/extension/include/iwork_scheduler.h +++ b/frameworks/extension/include/iwork_scheduler.h @@ -21,13 +21,10 @@ namespace OHOS { namespace WorkScheduler { - class IWorkScheduler : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.WorkScheduler.IWorkScheduler"); - virtual void OnWorkStart() = 0; - virtual void OnWorkStop() = 0; }; } // namespace WorkScheduler diff --git a/frameworks/extension/src/js_work_scheduler_extension.cpp b/frameworks/extension/src/js_work_scheduler_extension.cpp index 41fd04c..cf2b686 100644 --- a/frameworks/extension/src/js_work_scheduler_extension.cpp +++ b/frameworks/extension/src/js_work_scheduler_extension.cpp @@ -122,16 +122,6 @@ void JsWorkSchedulerExtension::OnWorkStart() NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); NativeValue* jCommonEventData = nativeEngine.CreateObject(); - // NativeObject* commonEventData = AbilityRuntime::ConvertNativeValueTo(jCommonEventData); - // Want want = data->GetWant(); - // commonEventData->SetProperty("event", nativeEngine.CreateString(want.GetAction().c_str(), want.GetAction().size())); - // commonEventData->SetProperty("bundleName", nativeEngine.CreateString(want.GetBundle().c_str(), - // want.GetBundle().size())); - // commonEventData->SetProperty("code", nativeEngine.CreateNumber(data->GetCode())); - // commonEventData->SetProperty("data", nativeEngine.CreateString(data->GetData().c_str(), data->GetData().size())); - // napi_value napiParams = AppExecFwk::WrapWantParams(reinterpret_cast(&nativeEngine), want.GetParams()); - // NativeValue* nativeParams = reinterpret_cast(napiParams); - // commonEventData->SetProperty("parameters", nativeParams); NativeValue* argv[] = {jCommonEventData}; if (!jsObj_) { diff --git a/frameworks/extension/src/work_scheduler_extension.cpp b/frameworks/extension/src/work_scheduler_extension.cpp index 998f30c..c5f20b8 100644 --- a/frameworks/extension/src/work_scheduler_extension.cpp +++ b/frameworks/extension/src/work_scheduler_extension.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,6 @@ WorkSchedulerExtension* WorkSchedulerExtension::Create(const std::unique_ptrGetLanguage()) { case AbilityRuntime::Runtime::Language::JS: return JsWorkSchedulerExtension::Create(runtime); @@ -39,7 +38,6 @@ void WorkSchedulerExtension::Init(const std::shared_ptr& handler, const sptr& token) { - // WS_HILOGI(MODULE_SERVICE, "WorkSchedulerExtension begin init"); ExtensionBase::Init(record, application, handler, token); } @@ -52,18 +50,15 @@ std::shared_ptr WorkSchedulerExtension::CreateAnd std::shared_ptr context = ExtensionBase::CreateAndInitContext(record, application, handler, token); if (record == nullptr) { - // WS_HILOGI(MODULE_SERVICE, "WorkSchedulerExtension CreateAndInitContext record is nullptr"); return context; } return context; } void WorkSchedulerExtension::OnWorkStart() { - } void WorkSchedulerExtension::OnWorkStop() { - } } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/extension/src/work_scheduler_extension_module_loader.cpp b/frameworks/extension/src/work_scheduler_extension_module_loader.cpp index 851a20b..e94d430 100644 --- a/frameworks/extension/src/work_scheduler_extension_module_loader.cpp +++ b/frameworks/extension/src/work_scheduler_extension_module_loader.cpp @@ -21,7 +21,8 @@ namespace OHOS::WorkScheduler { WorkSchedulerExtensionModuleLoader::WorkSchedulerExtensionModuleLoader() = default; WorkSchedulerExtensionModuleLoader::~WorkSchedulerExtensionModuleLoader() = default; -AbilityRuntime::Extension *WorkSchedulerExtensionModuleLoader::Create(const std::unique_ptr& runtime) const +AbilityRuntime::Extension *WorkSchedulerExtensionModuleLoader::Create( + const std::unique_ptr& runtime) const { return WorkSchedulerExtension::Create(runtime); } diff --git a/frameworks/test/unittest/include/workinfo_test.h b/frameworks/test/unittest/include/workinfo_test.h index f5dc71f..b37c3f4 100644 --- a/frameworks/test/unittest/include/workinfo_test.h +++ b/frameworks/test/unittest/include/workinfo_test.h @@ -1,16 +1,16 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ #ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H #define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H diff --git a/interfaces/kits/js/napi/src/is_last_work_time_out.cpp b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp index d9fa6ce..d7578cf 100644 --- a/interfaces/kits/js/napi/src/is_last_work_time_out.cpp +++ b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp @@ -28,7 +28,7 @@ static const int32_t IS_LAST_WORK_TIME_OUT_MAX_PARAMS = 2; struct IsLastWorkTimeOutParamsInfo { int32_t workId; napi_ref callback = nullptr; -}; +}; struct AsyncCallbackIsLastWorkTimeOut { napi_env env = nullptr; diff --git a/services/native/include/detector_value.h b/services/native/include/detector_value.h index e774c27..94243a3 100644 --- a/services/native/include/detector_value.h +++ b/services/native/include/detector_value.h @@ -25,7 +25,7 @@ struct DetectorValue { time_t timeVal; bool boolVal; std::string strVal; - DetectorValue(int32_t intVal, time_t timeVal, bool boolVal, const std::string &strVal) + DetectorValue(int32_t intVal, time_t timeVal, bool boolVal, const std::string &strVal) : intVal(intVal), timeVal(timeVal), boolVal(boolVal), strVal(strVal) {} }; } // namespace WorkScheduler diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index b442465..e4c09b7 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -318,7 +318,8 @@ bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, return true; } -bool IsInList(list &list, std::string myWork) { +bool IsInList(list &list, std::string myWork) +{ for (auto work : list) { if (work.compare(myWork) == 0) { return true; @@ -327,7 +328,8 @@ bool IsInList(list &list, std::string myWork) { return false; } -bool WorkSchedulerService::StopAndClearWorks() { +bool WorkSchedulerService::StopAndClearWorks() +{ return StopAndClearWorksByUid(IPCSkeleton::GetCallingUid()); } diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index a7e9e3d..bb2ae81 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -169,8 +169,6 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 WRITE_PARCEL_WITHOUT_RET(data, Int32, uid); WRITE_PARCEL_WITHOUT_RET(data, Int32, pid); - WS_HILOGD("BUGOAWF static_cast to int OBTAIN_ALL_WORKS: %{public}d", static_cast(IWorkSchedService::OBTAIN_ALL_WORKS)); - WS_HILOGD("BUGOAWF SendRequest code: %{public}d, uint: %{public}u", static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), static_cast(IWorkSchedService::OBTAIN_ALL_WORKS)); int ret = remote->SendRequest(static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), data, reply, option); if (ret != ERR_OK) { WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); @@ -186,7 +184,6 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 workInfos.emplace_back(std::make_shared(*workInfo)); } WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s return list size: %{public}d", __func__, workInfos.size()); - WS_HILOGD("BUGOAWF WSSP function %{public}s invoked END.", __func__); return workInfos; } diff --git a/utils/dump/src/event_publisher.cpp b/utils/dump/src/event_publisher.cpp index 40d1b07..cc62f41 100644 --- a/utils/dump/src/event_publisher.cpp +++ b/utils/dump/src/event_publisher.cpp @@ -85,7 +85,8 @@ void EventPublisher::PublishNetworkEvent(const std::vector &dumpOpt dumpInfo.push_back(std::string("publish result: " + std::to_string(isSuccess))); } -void EventPublisher::PublishChargingEvent(const std::vector &dumpOption, std::vector &dumpInfo) +void EventPublisher::PublishChargingEvent(const std::vector &dumpOption, + std::vector &dumpInfo) { EventFwk::Want want; EventFwk::CommonEventData data; diff --git a/utils/native/include/work_sched_common.h b/utils/native/include/work_sched_common.h index 874eaf1..dcb2be2 100644 --- a/utils/native/include/work_sched_common.h +++ b/utils/native/include/work_sched_common.h @@ -35,7 +35,7 @@ namespace WorkScheduler { WS_HILOGE("%{public}s "#loginfo" ", __func__); \ return; \ } \ - } while(0) + } while (0) #define READ_PARCEL_NO_RET(parcel, type, out) \ do { \ diff --git a/utils/native/include/work_sched_hilog.h b/utils/native/include/work_sched_hilog.h index 9798886..58415e2 100644 --- a/utils/native/include/work_sched_hilog.h +++ b/utils/native/include/work_sched_hilog.h @@ -35,7 +35,7 @@ static constexpr OHOS::HiviewDFX::HiLogLabel WORKSCHEDULER_LABEL = {LOG_CORE, enum class WorkSchedLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; class WorkSchedHilog { -public : +public: WorkSchedHilog() = delete; ~WorkSchedHilog() = delete; diff --git a/utils/native/include/work_sched_utils.h b/utils/native/include/work_sched_utils.h index a6d828e..7ea8a2f 100644 --- a/utils/native/include/work_sched_utils.h +++ b/utils/native/include/work_sched_utils.h @@ -22,7 +22,7 @@ namespace OHOS { namespace WorkScheduler { class WorkSchedUtils { -public : +public: WorkSchedUtils() = delete; ~WorkSchedUtils() = delete; -- Gitee From 431e0adada71c34bed2540fe1ca270232c9ad215 Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 9 Feb 2022 16:35:28 +0800 Subject: [PATCH 20/29] fix cycle bugfix Signed-off-by: chenming --- interfaces/kits/js/napi/include/common.h | 2 ++ interfaces/kits/js/napi/src/common.cpp | 35 ++++++++++++++----- .../kits/js/napi/src/workscheduler_napi.cpp | 1 - .../native/src/work_scheduler_service.cpp | 3 +- .../zidl/src/work_sched_service_proxy.cpp | 3 +- 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/interfaces/kits/js/napi/include/common.h b/interfaces/kits/js/napi/include/common.h index 1960991..338cb20 100644 --- a/interfaces/kits/js/napi/include/common.h +++ b/interfaces/kits/js/napi/include/common.h @@ -21,6 +21,8 @@ namespace OHOS { namespace WorkScheduler { +static const int MIN_REPEAT_INTERVAL = 1200 * 1000; + struct CallbackPromiseInfo { napi_ref callback = nullptr; napi_deferred deferred = nullptr; diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index f81ea53..e666f8d 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -147,21 +147,38 @@ bool Common::GetStorageInfo(napi_env env, napi_value objValue, WorkInfo &workInf bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) { - bool hasCondition = false; + int32_t repeatCycleTime = Common::GetIntProperty(env, objValue, "repeatCycleTime"); + if (repeatCycleTime == UNSET_INT_PARAM) { + WS_HILOGI("RepeatCycleTime not set, just ignore other repeat set."); + return false; + } + if (repeatCycleTime < MIN_REPEAT_INTERVAL) { + WS_HILOGI("RepeatCycleTime set must not be less than %{public}d.", MIN_REPEAT_INTERVAL); + return false; + } + bool isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); + int32_t repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); + if (!isRepeat && repeatCount == UNSET_INT_PARAM) { + WS_HILOGI("Not set isRepeat or repeatCount, ignore."); + return false; + } if (isRepeat) { - int32_t repeatCycleTime = Common::GetIntProperty(env, objValue, "repeatCycleTime"); - int32_t repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); - if (repeatCycleTime == UNSET_INT_PARAM || repeatCount == UNSET_INT_PARAM) { - WS_HILOGI("RepeatCycleTime or repeatCycleTime set is invalid, just ignore set."); - } else { + if (repeatCount > 0) { + WS_HILOGI("RepeatCount has been set , ignore isRepeat."); workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount); - hasCondition = true; + } else { + workInfo.RequestRepeatCycle(repeatCycleTime); } + return true; } else { - WS_HILOGI("Not set isRepeat or set isRepeat false, ignore repeatCycleTime and repeatCount."); + if (repeatCount < 0) { + WS_HILOGI("RepeatCount is invalid, ignore."); + return false; + } + workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount); + return true; } - return hasCondition; } bool Common::GetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) diff --git a/interfaces/kits/js/napi/src/workscheduler_napi.cpp b/interfaces/kits/js/napi/src/workscheduler_napi.cpp index e826bc9..6a2dde6 100644 --- a/interfaces/kits/js/napi/src/workscheduler_napi.cpp +++ b/interfaces/kits/js/napi/src/workscheduler_napi.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace WorkScheduler { - EXTERN_C_START static const uint8_t ARG_FIRST = 1; diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index e4c09b7..0954f21 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -343,7 +343,6 @@ bool WorkSchedulerService::StopAndClearWorksByUid(int32_t uid) } bool ret = workQueueManager_->StopAndClearWorks(allWorks) && workPolicyManager_->StopAndClearWorks(uid); - if (ret) { std::lock_guard lock(mutex_); for (auto workId : workIdList) { @@ -399,7 +398,7 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector connection(new (std::nothrow) WorkSchedulerConnection()); abilityMgr_->ConnectAbility(want, connection, nullptr, 100); return true; diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index bb2ae81..f36a5a8 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -171,7 +171,8 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 int ret = remote->SendRequest(static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), data, reply, option); if (ret != ERR_OK) { - WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); + WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", + __func__, ret); return workInfos; } -- Gitee From ae53c4a3615816eb9398b0c7cc29a9fd1e4a7b87 Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 9 Feb 2022 19:07:59 +0800 Subject: [PATCH 21/29] add timer Signed-off-by: chenming --- .../src/policy/app_removed_listener.cpp | 4 +- services/native/src/work_queue.cpp | 1 - services/native/src/work_status.cpp | 154 +++++++++--------- .../zidl/src/work_sched_service_proxy.cpp | 4 +- 4 files changed, 78 insertions(+), 85 deletions(-) diff --git a/services/native/src/policy/app_removed_listener.cpp b/services/native/src/policy/app_removed_listener.cpp index bd52322..f2aa114 100644 --- a/services/native/src/policy/app_removed_listener.cpp +++ b/services/native/src/policy/app_removed_listener.cpp @@ -32,7 +32,8 @@ void AppRemovedSubscriber::OnReceiveEvent(const CommonEventData &data) { const string action = data.GetWant().GetAction(); WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + if ((action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) + || (action == CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED)) { string bundle = data.GetWant().GetBundle(); int32_t uid = data.GetWant().GetIntParam(UID_PARAM, -1); WS_HILOGI("bundleName: %{public}s , uid: %{public}d", bundle.c_str(), uid); @@ -45,6 +46,7 @@ shared_ptr CreateAppRemovedSubscriber(AppRemovedListener { MatchingSkills skill = MatchingSkills(); skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + skill.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); CommonEventSubscribeInfo info(skill); return make_shared(info, listener); } diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index a1460c2..47dfca9 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -38,7 +38,6 @@ vector> WorkQueue::OnConditionChanged(WorkCondition::Type break; } case WorkCondition::Type::TIMER: { - value->longVal = conditionVal->timeVal; break; } default: {} diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index 9d283a6..97248ad 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -23,6 +23,8 @@ using namespace OHOS::PowerMgr; namespace OHOS { namespace WorkScheduler { +static final int ONE_SECOND = 1000; + time_t getCurrentTime() { time_t result; @@ -39,45 +41,41 @@ WorkStatus::WorkStatus(WorkInfo &workInfo, int32_t uid) this->baseTime_ = getCurrentTime(); if (workInfo.GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { auto workTimerCondition = workInfo.GetConditionMap()->at(WorkCondition::Type::TIMER); - if (workTimerCondition->boolVal) { - shared_ptr timeCondition = make_shared(); - timeCondition->uintVal = workTimerCondition->uintVal; - if (workTimerCondition->boolVal) { - timeCondition->intVal = 1; - } else { - timeCondition->intVal = workTimerCondition->intVal; - } - conditionMap_.emplace(WorkCondition::Type::TIMER, timeCondition); - } - } - if (workInfo.GetConditionMap()->count(WorkCondition::Type::CHARGER) > 0) { - shared_ptr chargerCondition = make_shared(); - chargerCondition->enumVal = -1; - BatteryPluggedType pluggedType = BatterySrvClient::GetInstance().GetPluggedType(); - switch (pluggedType) { - case BatteryPluggedType::PLUGGED_TYPE_NONE: - chargerCondition->boolVal = false; - chargerCondition->enumVal = WorkCondition::Charger::CHARGING_UNPLUGGED; - break; - case BatteryPluggedType::PLUGGED_TYPE_AC: - chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_AC; - break; - case BatteryPluggedType::PLUGGED_TYPE_USB: - chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_USB; - break; - case BatteryPluggedType::PLUGGED_TYPE_WIRELESS: - chargerCondition->boolVal = true; - chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS; - break; - default: - break; - } - if (chargerCondition->enumVal != -1) { - conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); + shared_ptr timeCondition = make_shared(); + timeCondition->uintVal = workTimerCondition->uintVal; + if (!workTimerCondition->boolVal) { + timeCondition->intVal = workTimerCondition->intVal; } + conditionMap_.emplace(WorkCondition::Type::TIMER, timeCondition); } + // if (workInfo.GetConditionMap()->count(WorkCondition::Type::CHARGER) > 0) { + // shared_ptr chargerCondition = make_shared(); + // chargerCondition->enumVal = -1; + // BatteryPluggedType pluggedType = BatterySrvClient::GetInstance().GetPluggedType(); + // switch (pluggedType) { + // case BatteryPluggedType::PLUGGED_TYPE_NONE: + // chargerCondition->boolVal = false; + // chargerCondition->enumVal = WorkCondition::Charger::CHARGING_UNPLUGGED; + // break; + // case BatteryPluggedType::PLUGGED_TYPE_AC: + // chargerCondition->boolVal = true; + // chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_AC; + // break; + // case BatteryPluggedType::PLUGGED_TYPE_USB: + // chargerCondition->boolVal = true; + // chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_USB; + // break; + // case BatteryPluggedType::PLUGGED_TYPE_WIRELESS: + // chargerCondition->boolVal = true; + // chargerCondition->enumVal = WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS; + // break; + // default: + // break; + // } + // if (chargerCondition->enumVal != -1) { + // conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); + // } + // } this->persisted_ = workInfo.IsPersisted(); this->priority_ = DEFAULT_PRIORITY; this->currentStatus_ = WAIT_CONDITION; @@ -132,58 +130,52 @@ void WorkStatus::MarkRound() {} bool WorkStatus::IsReady() { auto workConditionMap = workInfo_->GetConditionMap(); + if (conditionMap_.count(it.first) <= 0 || workConditionMap == nullptr) { + return false; + } for (auto it : *workConditionMap) { - if (conditionMap_.count(it.first) > 0) { - switch (it.first) { - case WorkCondition::Type::NETWORK: - case WorkCondition::Type::BATTERY_STATUS: - case WorkCondition::Type::STORAGE: { - if (workConditionMap->at(it.first)->enumVal != conditionMap_.at(it.first)->enumVal) { - return false; - } - break; - } - case WorkCondition::Type::CHARGER: { - auto conditionSet = workConditionMap->at(it.first); - auto conditionCurrent = conditionMap_.at(it.first); - if (conditionSet->boolVal) { - if (conditionCurrent->enumVal != conditionSet->enumVal && - conditionSet->enumVal != - static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY)) { - return false; - } - } else { - if (conditionCurrent->enumVal != - static_cast(WorkCondition::Charger::CHARGING_UNPLUGGED)) { - return false; - } - } - break; + switch (it.first) { + case WorkCondition::Type::NETWORK: + case WorkCondition::Type::BATTERY_STATUS: + case WorkCondition::Type::STORAGE: { + if (workConditionMap->at(it.first)->enumVal != conditionMap_.at(it.first)->enumVal) { + return false; } - case WorkCondition::Type::BATTERY_LEVEL: { - if (workConditionMap->at(it.first)->intVal > - PowerMgr::BatterySrvClient::GetInstance().GetCapacity()) { - return false; - } - break; - } - case WorkCondition::Type::TIMER: { - bool repeat = workConditionMap->at(WorkCondition::Type::TIMER)->boolVal; - int32_t cycleLeft = workConditionMap->at(WorkCondition::Type::TIMER)->intVal; - if (!repeat && cycleLeft == 0) { + break; + } + case WorkCondition::Type::CHARGER: { + auto conditionSet = workConditionMap->at(it.first); + auto conditionCurrent = conditionMap_.at(it.first); + if (conditionSet->boolVal) { + if (conditionCurrent->enumVal != conditionSet->enumVal && + conditionSet->enumVal != + static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY)) { return false; } - uint32_t intervalTime = workConditionMap->at(WorkCondition::Type::TIMER)->uintVal; - if (baseTime_ + static_cast(intervalTime) >= getCurrentTime()) { + } else { + if (conditionCurrent->enumVal != + static_cast(WorkCondition::Charger::CHARGING_UNPLUGGED)) { return false; } - break; } - default: - break; + break; } - } else { - return false; + case WorkCondition::Type::BATTERY_LEVEL: { + if (workConditionMap->at(it.first)->intVal > + PowerMgr::BatterySrvClient::GetInstance().GetCapacity()) { + return false; + } + break; + } + case WorkCondition::Type::TIMER: { + uint32_t intervalTime = workConditionMap->at(WorkCondition::Type::TIMER)->uintVal; + if ((getCurrentTime() - baseTime_) * ONE_SECOND < static_cast(intervalTime)) { + return false; + } + break; + } + default: + break; } } return true; diff --git a/services/zidl/src/work_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp index f36a5a8..a2936e0 100644 --- a/services/zidl/src/work_sched_service_proxy.cpp +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -171,7 +171,7 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 int ret = remote->SendRequest(static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), data, reply, option); if (ret != ERR_OK) { - WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", + WS_HILOGE("WorkSchedServiceProxy::%{public}s SendRequest is failed, err code: %{public}d", __func__, ret); return workInfos; } @@ -184,7 +184,7 @@ std::list> WorkSchedServiceProxy::ObtainAllWorks(int32 WS_HILOGD("WP read from parcel, workInfo ID: %{public}d", workInfo->GetWorkId()); workInfos.emplace_back(std::make_shared(*workInfo)); } - WS_HILOGE("BUGOAWF WorkSchedServiceProxy::%{public}s return list size: %{public}d", __func__, workInfos.size()); + WS_HILOGD("WorkSchedServiceProxy::%{public}s return list size: %{public}d", __func__, workInfos.size()); return workInfos; } -- Gitee From 86b6b406a02a909abda7d2afb1d1fcdbb4b60620 Mon Sep 17 00:00:00 2001 From: chenming Date: Wed, 9 Feb 2022 23:45:23 +0800 Subject: [PATCH 22/29] add work ready Signed-off-by: chenming --- services/native/include/ipolicy_listener.h | 6 +- services/native/include/policy_type.h | 16 +--- services/native/include/work_conn_manager.h | 2 +- services/native/include/work_policy_manager.h | 11 ++- services/native/include/work_queue_manager.h | 2 + .../native/include/work_scheduler_service.h | 2 + services/native/include/work_status.h | 6 ++ services/native/src/work_conn_manager.cpp | 31 ++++++-- services/native/src/work_policy_manager.cpp | 60 +++++++++++---- services/native/src/work_queue.cpp | 4 + services/native/src/work_queue_manager.cpp | 28 ++++--- .../native/src/work_scheduler_service.cpp | 24 +++++- services/native/src/work_status.cpp | 75 ++++++++++++++----- utils/native/include/work_sched_utils.h | 3 + utils/native/src/work_sched_utils.cpp | 10 +++ 15 files changed, 213 insertions(+), 67 deletions(-) diff --git a/services/native/include/ipolicy_listener.h b/services/native/include/ipolicy_listener.h index cf362ed..ebe6e8e 100644 --- a/services/native/include/ipolicy_listener.h +++ b/services/native/include/ipolicy_listener.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H -#define WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_DETECTOR_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_DETECTOR_H #include @@ -32,4 +32,4 @@ public: } // namesapce WorkScheduler } // namespace OHOS -#endif // WORK_SCHED_SERVICES_IPOLICY_DETECTOR_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_DETECTOR_H \ No newline at end of file diff --git a/services/native/include/policy_type.h b/services/native/include/policy_type.h index 629b7b6..f7e852b 100644 --- a/services/native/include/policy_type.h +++ b/services/native/include/policy_type.h @@ -13,22 +13,14 @@ * limitations under the License. */ -#ifndef WORK_SCHED_SERVICES_POLICY_TYPE_H -#define WORK_SCHED_SERVICES_POLICY_TYPE_H +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_POLICY_TYPE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_POLICY_TYPE_H namespace OHOS { namespace WorkScheduler { enum PolicyType { - IDLE = 0, - TIMER, - APP_REMOVED -}; - -enum IdleStatus { - IDLE_START = 0, - IDLE_STOP + APP_REMOVED = 0 }; } // namespace WorkScheduler } // namespace OHOS - -#endif // WORK_SCHED_SERVICES_POLICY_TYPE_H \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_POLICY_TYPE_H \ No newline at end of file diff --git a/services/native/include/work_conn_manager.h b/services/native/include/work_conn_manager.h index d3f7a50..0b66db6 100644 --- a/services/native/include/work_conn_manager.h +++ b/services/native/include/work_conn_manager.h @@ -33,7 +33,7 @@ public: }; class WorkConnManager { public: - void StartWork(std::shared_ptr workStatus); + bool StartWork(std::shared_ptr workStatus); void StopWork(std::shared_ptr workStatus); private: std::map> connMap_; diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index 40823af..fb24e03 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -65,8 +65,14 @@ private: int32_t GetRunningCount(); void DumpConditionReadyQueue(std::string& result); void DumpUidQueueMap(std::string& result); - void removeFromUidQueue(std::shared_ptr workStatus, int32_t uid); - void removeFromReadyQueue(std::shared_ptr workStatus); + void RemoveFromUidQueue(std::shared_ptr workStatus, int32_t uid); + void RemoveFromReadyQueue(std::shared_ptr workStatus); + void AddToReadyQueue(std::shared_ptr>> workStatusVector); + void RealStartWork(std::shared_ptr workStatus); + void AddToRunningQueue(std::shared_ptr workStatus); + void RemoveConditionUnReady(); + std::shared_ptr GetWorkToRun(); + void RemoveAllUnReady(); const wptr wss_; std::shared_ptr workConnManager_; @@ -77,6 +83,7 @@ private: std::mutex conditionReadyMutex_; std::shared_ptr conditionReadyQueue_; + std::list> policyFilters_; std::shared_ptr appRemovedListener_; }; diff --git a/services/native/include/work_queue_manager.h b/services/native/include/work_queue_manager.h index 8e82051..5ddf23c 100644 --- a/services/native/include/work_queue_manager.h +++ b/services/native/include/work_queue_manager.h @@ -46,6 +46,8 @@ public: void Dump(std::string& result); private: + std::vector> GetReayQueue(WorkCondition::Type conditionType, + std::shared_ptr conditionVal); std::mutex mutex_; const wptr wss_; std::map> queueMap_; diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 1dea823..419f784 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -58,6 +58,7 @@ public: bool StopAndClearWorksByUid(int32_t uid); int32_t CreateNodeDir(std::string dir); int32_t CreateNodeFile(std::string filePath); + void UpdateWorkBeforeRealStart(std::shared_ptr work); void OnConditionReady(std::shared_ptr>> workStatusVector); @@ -88,6 +89,7 @@ private: bool ready_ {false}; std::shared_ptr handler_; std::shared_ptr eventRunner_; + bool checkBundle_; bool Init(); void WorkQueueManagerInit(); diff --git a/services/native/include/work_status.h b/services/native/include/work_status.h index 6fe25a2..1dbf63c 100644 --- a/services/native/include/work_status.h +++ b/services/native/include/work_status.h @@ -42,12 +42,15 @@ public: std::string workId_; std::string bundleName_; std::string abilityName_; + int32_t uid_; + int userId_; bool persisted_; int32_t priority_; std::map> conditionMap_; std::shared_ptr workInfo_; bool IsReady(); + bool IsReadyStatus(); bool IsRunning(); bool IsRemoved(); bool IsRepeating(); @@ -57,11 +60,14 @@ public: void MarkStatus(Status status); Status GetStatus(); void Dump(std::string& result); + void UpdateTimerIfNeed(); + bool NeedRemove(); private: Status currentStatus_; time_t baseTime_; bool lastTimeout_ {false}; void MarkTimeout(); + bool IsSameUser(); }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/src/work_conn_manager.cpp b/services/native/src/work_conn_manager.cpp index 57fb7ab..e4473d1 100644 --- a/services/native/src/work_conn_manager.cpp +++ b/services/native/src/work_conn_manager.cpp @@ -37,14 +37,35 @@ void WorkConnection::OnWorkStop(shared_ptr workInfo) workInfo->GetBundleName().c_str(), workInfo->GetAbilityName().c_str(), workInfo->GetWorkId()); } -void WorkConnManager::StartWork(shared_ptr workStatus) +bool WorkConnManager::StartWork(shared_ptr workStatus) { WS_HILOGD("StartWork, id: %{public}s, bundleName: %{public}s, abilityName: %{public}s", workStatus->workId_.c_str(), workStatus->bundleName_.c_str(), workStatus->abilityName_.c_str()); - auto workConn = make_shared(); - connMap_.emplace(workStatus->workId_, workConn); - workConn->OnWorkStart(workStatus->workInfo_); - workStatus->MarkStatus(WorkStatus::Status::RUNNING); + // auto workConn = make_shared(); + // connMap_.emplace(workStatus->workId_, workConn); + // workConn->OnWorkStart(workStatus->workInfo_); + // workStatus->MarkStatus(WorkStatus::Status::RUNNING); + + // Want want; + // want.SetElementName(workStatus->bundleName_, workStatus->abilityName_); + // sptr systemAbilityManager = + // SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + // if (systemAbilityManager == nullptr) { + // return false; + // } + // sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + // if (remoteObject == nullptr) { + // WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); + // return false; + // } + // sptr abilityMgr_ = iface_cast(remoteObject); + // if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { + // WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); + // return false; + // } + // sptr connection(new (std::nothrow) WorkSchedulerConnection()); + // abilityMgr_->ConnectAbility(want, connection, nullptr, workStatus->userId_); + return true; } void WorkConnManager::StopWork(shared_ptr workStatus) diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 09de46f..945b8d5 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -30,8 +30,8 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace WorkScheduler { namespace { -static const int64_t DELAY_TIME_LONG = 10000; -static const int64_t DELAY_TIME_SHORT = 1000; +static const int64_t DELAY_TIME_LONG = 30000; +static const int64_t DELAY_TIME_SHORT = 5000; } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) { @@ -110,7 +110,7 @@ shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int return nullptr; } -void WorkPolicyManager::removeFromUidQueue(std::shared_ptr workStatus, int32_t uid) +void WorkPolicyManager::RemoveFromUidQueue(std::shared_ptr workStatus, int32_t uid) { std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { @@ -118,7 +118,7 @@ void WorkPolicyManager::removeFromUidQueue(std::shared_ptr workStatu } } -void WorkPolicyManager::removeFromReadyQueue(std::shared_ptr workStatus) +void WorkPolicyManager::RemoveFromReadyQueue(std::shared_ptr workStatus) { std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->RemoveUnReady(); @@ -132,8 +132,8 @@ bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t workConnManager_->StopWork(workStatus); if (!workStatus->IsRepeating()) { workStatus->MarkStatus(WorkStatus::Status::REMOVED); - removeFromUidQueue(workStatus, uid); - removeFromReadyQueue(workStatus); + RemoveFromUidQueue(workStatus, uid); + RemoveFromReadyQueue(workStatus); hasCanceled = true; } else { workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); @@ -141,8 +141,8 @@ bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t } if (!hasCanceled && needCancel) { - removeFromUidQueue(workStatus, uid); - removeFromReadyQueue(workStatus); + RemoveFromUidQueue(workStatus, uid); + RemoveFromReadyQueue(workStatus); hasCanceled = true; } @@ -170,7 +170,7 @@ bool WorkPolicyManager::StopAndClearWorks(int32_t uid) for (auto it : queue->GetWorkList()) { workConnManager_->StopWork(it); it->MarkStatus(WorkStatus::Status::REMOVED); - removeFromReadyQueue(it); + RemoveFromReadyQueue(it); } queue->ClearAll(); uidQueueMap_.erase(uid); @@ -198,9 +198,14 @@ void WorkPolicyManager::OnConditionReady(shared_ptr>> workStatusVector) +{ std::lock_guard lock(conditionReadyMutex_); conditionReadyQueue_->Push(workStatusVector); - CheckWorkToRun(); } int32_t WorkPolicyManager::GetMaxRunningCount() @@ -245,22 +250,20 @@ void WorkPolicyManager::OnPolicyChanged(PolicyType policyType, shared_ptr lock(conditionReadyMutex_); - conditionReadyQueue_->RemoveUnReady(); + RemoveAllUnReady(); if (handler_ == nullptr) { WS_HILOGE("handler lock() returns nullptr"); return; } handler_->RemoveEvent(WorkEventHandler::RETRIGGER_MSG); - auto topWork = conditionReadyQueue_->GetWorkToRunByPriority(); + shared_ptr topWork = GetWorkToRun(); if (topWork == nullptr) { WS_HILOGD("no condition ready work not running, return."); return; } - WS_HILOGD("topWork ID: %{public}s", topWork->workId_.c_str()); if (GetRunningCount() < GetMaxRunningCount()) { WS_HILOGD("running count < max running count"); - workConnManager_->StartWork(topWork); + RealStartWork(topWork); SendRetrigger(DELAY_TIME_SHORT); } else { WS_HILOGD("trigger delay: %{public}lld", DELAY_TIME_LONG); @@ -269,6 +272,33 @@ void WorkPolicyManager::CheckWorkToRun() WS_HILOGD("WorkPolicyManager::%{public}s out", __func__); } +void WorkPolicyManager::RemoveAllUnReady() +{ + std::lock_guard lock(conditionReadyMutex_); + conditionReadyQueue_->RemoveUnReady(); +} + +std::shared_ptr WorkPolicyManager::GetWorkToRun() +{ + std::lock_guard lock(conditionReadyMutex_); + shared_ptr topWork = conditionReadyQueue_->GetWorkToRunByPriority(); + return topWork; +} + +void WorkPolicyManager::RealStartWork(std::shared_ptr topWork) +{ + WS_HILOGD("RealStartWork topWork ID: %{public}s", topWork->workId_.c_str()); + auto wmsptr = wss_.promote(); + if (wmsptr == nullptr) { + WS_HILOGE("Workscheduler service is null"); + return; + } + topWork->MarkStatus(WorkStatus::Status::RUNNING); + wmsptr->UpdateWorkBeforeRealStart(topWork); + RemoveFromReadyQueue(topWork); + workConnManager_->StartWork(topWork); +} + void WorkPolicyManager::SendRetrigger(int64_t delaytime) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); diff --git a/services/native/src/work_queue.cpp b/services/native/src/work_queue.cpp index 47dfca9..0ee6a52 100644 --- a/services/native/src/work_queue.cpp +++ b/services/native/src/work_queue.cpp @@ -47,6 +47,10 @@ vector> WorkQueue::OnConditionChanged(WorkCondition::Type it->OnConditionChanged(type, value); if (it->IsReady()) { result.emplace_back(it); + } else { + if (it->IsReadyStatus()) { + it->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } } } return result; diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index a86a97f..720b487 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -81,22 +81,30 @@ bool WorkQueueManager::CancelWork(shared_ptr workStatus) return true; } -void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, +vector> WorkQueueManager::GetReayQueue(WorkCondition::Type conditionType, shared_ptr conditionVal) { + vector> result; std::lock_guard lock(mutex_); if (queueMap_.count(conditionType) > 0) { shared_ptr workQueue = queueMap_.at(conditionType); - auto readyWorkVector = workQueue->OnConditionChanged(conditionType, conditionVal); - if (readyWorkVector.size() == 0) { - return; - } - for (auto it : readyWorkVector) { - it->MarkStatus(WorkStatus::Status::CONDITION_READY); - } - auto ws = wss_.promote(); - ws->OnConditionReady(make_shared>>(readyWorkVector)); + result = workQueue->OnConditionChanged(conditionType, conditionVal); + } + return result; +} + +void WorkQueueManager::OnConditionChanged(WorkCondition::Type conditionType, + shared_ptr conditionVal) +{ + vector> readyWorkVector = GetReayQueue(conditionType, conditionVal); + if (readyWorkVector.size() == 0) { + return; + } + for (auto it : readyWorkVector) { + it->MarkStatus(WorkStatus::Status::CONDITION_READY); } + auto ws = wss_.promote(); + ws->OnConditionReady(make_shared>>(readyWorkVector)); } bool WorkQueueManager::StopAndClearWorks(list> workList) diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 0954f21..4e8620f 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -57,6 +57,7 @@ static const string ALL_INFO = "All"; static const string WORK_QUEUE_INFO = "WorkQueue"; static const string WORK_POLICY_INFO = "WorkPolicy"; static const string EXTENSION = "Extension"; +static const string CHECK_BUNDLE = "CheckBundle"; } WorkSchedulerService::WorkSchedulerService() : SystemAbility(WORK_SCHEDULE_SERVICE_ID, true) {} @@ -82,7 +83,7 @@ void WorkSchedulerService::OnStart() } GetHandler()->SendEvent(InnerEvent::Get(WorkEventHandler::INIT_PERSISTED_MSG, 0), 15000); - + checkBundle_ = true; ready_ = true; WS_HILOGE("OnStart and add system ability success."); } @@ -234,7 +235,7 @@ bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) bool WorkSchedulerService::StartWork(WorkInfo& workInfo) { int32_t uid = IPCSkeleton::GetCallingUid(); - if (!CheckWorkInfo(workInfo, uid)) { + if (checkBundle_ && !CheckWorkInfo(workInfo, uid)) { return false; } WS_HILOGD("WorkSchedulerService::StartWork workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", @@ -380,6 +381,12 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector &dumpInfo) } } +void WorkSchedulerService::UpdateWorkBeforeRealStart(std::shared_ptr work) +{ + if (work == nullptr) { + return; + } + work->UpdateTimerIfNeed(); + if (work->NeedRemove()) { + workQueueManager_->RemoveWork(work); + } +} + void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) { + string info = "Need check bundle:" + std::to_string(checkBundle_); + dumpInfo.push_back(info); DumpWorkQueueInfo(dumpInfo); DumpWorkPolicyInfo(dumpInfo); } diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index 97248ad..0e3fece 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -17,13 +17,14 @@ #include "battery_srv_client.h" #include "work_sched_common.h" +#include "work_sched_utils.h" using namespace std; using namespace OHOS::PowerMgr; namespace OHOS { namespace WorkScheduler { -static final int ONE_SECOND = 1000; +static const int ONE_SECOND = 1000; time_t getCurrentTime() { @@ -39,6 +40,8 @@ WorkStatus::WorkStatus(WorkInfo &workInfo, int32_t uid) this->bundleName_ = workInfo.GetBundleName(); this->abilityName_ = workInfo.GetAbilityName(); this->baseTime_ = getCurrentTime(); + this->uid_ = uid; + this->userId_ = WorkSchedUtils::GetUserIdByUid(uid); if (workInfo.GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { auto workTimerCondition = workInfo.GetConditionMap()->at(WorkCondition::Type::TIMER); shared_ptr timeCondition = make_shared(); @@ -110,30 +113,54 @@ void WorkStatus::MarkTimeout() void WorkStatus::MarkStatus(Status status) { currentStatus_ = status; - WS_HILOGD("WorkStatus::%{public}s, ID: %{public}s mark status to: %{public}d", __func__, workId_.c_str(), status); - if (status == Status::RUNNING) { - if (workInfo_->GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { - auto workTimerCondition = workInfo_->GetConditionMap()->at(WorkCondition::Type::TIMER); - if (workTimerCondition->boolVal) { - if (workTimerCondition->boolVal) { - workTimerCondition->intVal = 1; - } else { - workTimerCondition->intVal--; - } - } +} + +void WorkStatus::MarkRound() {} + +void WorkStatus::UpdateTimerIfNeed() +{ + if (conditionMap_.count(WorkCondition::Type::TIMER) > 0) { + baseTime_ = getCurrentTime(); + if (conditionMap_.at(WorkCondition::Type::TIMER)->boolVal) { + return; } + int cycleLeft = conditionMap_.at(WorkCondition::Type::TIMER)->intVal; + conditionMap_.at(WorkCondition::Type::TIMER)->intVal = cycleLeft - 1; } } -void WorkStatus::MarkRound() {} +bool WorkStatus::NeedRemove() { + if (conditionMap_.count(WorkCondition::Type::TIMER) <= 0) { + return true; + } + if (conditionMap_.at(WorkCondition::Type::TIMER)->boolVal) { + return false; + } + if (conditionMap_.at(WorkCondition::Type::TIMER)->intVal <= 0) { + return true; + } + return false; +} + +bool WorkStatus::IsSameUser() { + + if (WorkSchedUtils::GetCurrentAccountId() != userId_) { + return false; + } + return true; +} bool WorkStatus::IsReady() { - auto workConditionMap = workInfo_->GetConditionMap(); - if (conditionMap_.count(it.first) <= 0 || workConditionMap == nullptr) { + if (!IsSameUser()) { + WS_HILOGD("Not same user. WorkId:%{public}s", workId_.c_str()); return false; } + auto workConditionMap = workInfo_->GetConditionMap(); for (auto it : *workConditionMap) { + if (conditionMap_.count(it.first) <= 0 || workConditionMap == nullptr) { + return false; + } switch (it.first) { case WorkCondition::Type::NETWORK: case WorkCondition::Type::BATTERY_STATUS: @@ -186,6 +213,11 @@ bool WorkStatus::IsRunning() return currentStatus_ == RUNNING; } +bool WorkStatus::IsReadyStatus() +{ + return currentStatus_ == CONDITION_READY; +} + bool WorkStatus::IsRemoved() { return currentStatus_ == REMOVED; @@ -218,8 +250,7 @@ void WorkStatus::Dump(string& result) result.append("{\n"); result.append(string("\"workId\":") + workId_ + ",\n"); result.append(string("\"bundleName\":") + bundleName_ + ",\n"); - result.append(string("\"priority\":") + to_string(priority_) + ",\n"); - result.append(string("\"isPersisted\":") + to_string(persisted_) + ",\n"); + result.append(string("\"status\":") + to_string(currentStatus_) + ",\n"); result.append(string("\"conditionMap\":{\n")); if (conditionMap_.count(WorkCondition::Type::NETWORK) > 0) { result.append(string("\"networkType\":") + @@ -243,9 +274,19 @@ void WorkStatus::Dump(string& result) result.append(string("\"storageLevel\":") + to_string(conditionMap_.at(WorkCondition::Type::STORAGE)->enumVal) + ",\n"); } + if (conditionMap_.count(WorkCondition::Type::TIMER) > 0) { + result.append(string("\"baseTime\":") + to_string(baseTime_) + ",\n"); + if (conditionMap_.at(WorkCondition::Type::TIMER)->boolVal) { + result.append(string("\"isRepeat\": true,\n")); + } else { + result.append(string("\"cycleLeft\":") + + to_string(conditionMap_.at(WorkCondition::Type::TIMER)->intVal) + ",\n"); + } + } result.append("},\n\"workInfo\":\n"); workInfo_->Dump(result); result.append("}\n"); + result.append("\n"); WS_HILOGD("%s", result.c_str()); } } // namespace WorkScheduler diff --git a/utils/native/include/work_sched_utils.h b/utils/native/include/work_sched_utils.h index 7ea8a2f..68cc1df 100644 --- a/utils/native/include/work_sched_utils.h +++ b/utils/native/include/work_sched_utils.h @@ -27,6 +27,9 @@ public: ~WorkSchedUtils() = delete; static int GetCurrentAccountId(); + static int32_t GetUserIdByUid(int32_t uid); + + static const int INVALID_DATA = -1; }; } // namespace WorkScheduler } // namespace OHOS diff --git a/utils/native/src/work_sched_utils.cpp b/utils/native/src/work_sched_utils.cpp index aff7028..214beac 100644 --- a/utils/native/src/work_sched_utils.cpp +++ b/utils/native/src/work_sched_utils.cpp @@ -46,5 +46,15 @@ int WorkSchedUtils::GetCurrentAccountId() WS_HILOGE("GetCurrentAccountId failed, no Actived now."); return -1; } + +int32_t WorkSchedUtils::GetUserIdByUid(int32_t uid) +{ + if (uid <= INVALID_DATA) { + WS_HILOGE("uid is illegal: %{public}d", uid); + return INVALID_DATA; + } + const int BASE_USER_RANGE = 200000; + return uid / BASE_USER_RANGE; +} } } \ No newline at end of file -- Gitee From f64e4e74e9ea5bafe445663fcf692ae2a3a4cf53 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 10 Feb 2022 17:20:39 +0800 Subject: [PATCH 23/29] add connect Signed-off-by: chenming --- frameworks/BUILD.gn | 1 - frameworks/include/iwork_conn.h | 40 --------- services/BUILD.gn | 3 +- services/native/include/work_conn_manager.h | 11 +-- .../include/work_scheduler_connection.h | 1 + services/native/src/work_conn_manager.cpp | 89 ++++++++++--------- .../native/src/work_scheduler_connection.cpp | 14 ++- services/zidl/include/work_conn_proxy.h | 40 --------- services/zidl/include/work_conn_stub.h | 39 -------- services/zidl/src/work_conn_proxy.cpp | 72 --------------- services/zidl/src/work_conn_stub.cpp | 61 ------------- 11 files changed, 61 insertions(+), 310 deletions(-) delete mode 100644 frameworks/include/iwork_conn.h delete mode 100644 services/zidl/include/work_conn_proxy.h delete mode 100644 services/zidl/include/work_conn_stub.h delete mode 100644 services/zidl/src/work_conn_proxy.cpp delete mode 100644 services/zidl/src/work_conn_stub.cpp diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 69bd246..ec6624e 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -25,7 +25,6 @@ ohos_shared_library("workschedclient") { sources = [ "${worksched_frameworks_path}/src/work_info.cpp", "${worksched_frameworks_path}/src/workscheduler_srv_client.cpp", - "${worksched_service_path}/zidl/src/work_conn_proxy.cpp", "${worksched_service_path}/zidl/src/work_sched_service_proxy.cpp", ] diff --git a/frameworks/include/iwork_conn.h b/frameworks/include/iwork_conn.h deleted file mode 100644 index b6a7ed0..0000000 --- a/frameworks/include/iwork_conn.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORKSCHED_ZIDL_IWORK_CONN_H -#define WORKSCHED_ZIDL_IWORK_CONN_H - -#include -#include -#include - -#include "work_info.h" - -namespace OHOS { -namespace WorkScheduler { -class IWorkConn : public IRemoteBroker { -public: - enum { - ON_WORK_START = 0, - ON_WORK_STOP, - }; - virtual void OnWorkStart(WorkInfo& workInfo) = 0; - virtual void OnWorkStop(WorkInfo& workInfo) = 0; - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.workscheduler.iworkconn"); -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORKSCHED_ZIDL_IWORK_CONN_H \ No newline at end of file diff --git a/services/BUILD.gn b/services/BUILD.gn index 4933727..ac1af1b 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -41,7 +41,6 @@ ohos_shared_library("workschedservice") { "native/src/work_scheduler_connection.cpp", "native/src/work_scheduler_service.cpp", "native/src/work_status.cpp", - "zidl/src//work_conn_stub.cpp", "zidl/src/work_sched_service_stub.cpp", "zidl/src/work_scheduler_proxy.cpp", ] diff --git a/services/native/include/work_conn_manager.h b/services/native/include/work_conn_manager.h index 0b66db6..5d7d743 100644 --- a/services/native/include/work_conn_manager.h +++ b/services/native/include/work_conn_manager.h @@ -21,23 +21,18 @@ #include #include "work_status.h" -#include "work_conn_proxy.h" +#include "errors.h" namespace OHOS { using namespace Utils; namespace WorkScheduler { -class WorkConnection { -public: - void OnWorkStart(std::shared_ptr workInfo); - void OnWorkStop(std::shared_ptr workInfo); -}; class WorkConnManager { public: bool StartWork(std::shared_ptr workStatus); void StopWork(std::shared_ptr workStatus); private: - std::map> connMap_; - std::unique_ptr timer_; + std::mutex connMapMutex_; + //std::map> connMap_; }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/include/work_scheduler_connection.h b/services/native/include/work_scheduler_connection.h index e4e6627..bd0f8e3 100644 --- a/services/native/include/work_scheduler_connection.h +++ b/services/native/include/work_scheduler_connection.h @@ -23,6 +23,7 @@ namespace OHOS { namespace WorkScheduler { class WorkSchedulerConnection : public AAFwk::AbilityConnectionStub { public: + void StopWork(); void OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; diff --git a/services/native/src/work_conn_manager.cpp b/services/native/src/work_conn_manager.cpp index e4473d1..f405b66 100644 --- a/services/native/src/work_conn_manager.cpp +++ b/services/native/src/work_conn_manager.cpp @@ -18,25 +18,19 @@ #include #include "ability_manager_client.h" #include "work_sched_common.h" +#include +#include +#include +#include +#include + +#include "work_scheduler_connection.h" using namespace std; using namespace OHOS::AAFwk; namespace OHOS { namespace WorkScheduler { -void WorkConnection::OnWorkStart(shared_ptr workInfo) -{ - WS_HILOGD("OnWorkStart, %{public}s/%{public}s : %{public}d", - workInfo->GetBundleName().c_str(), workInfo->GetAbilityName().c_str(), workInfo->GetWorkId()); - // AbilityManagerClient::GetInstance()->ConnectAbility(); -} - -void WorkConnection::OnWorkStop(shared_ptr workInfo) -{ - WS_HILOGD("OnWorkStop, %{public}s/%{public}s : %{public}d", - workInfo->GetBundleName().c_str(), workInfo->GetAbilityName().c_str(), workInfo->GetWorkId()); -} - bool WorkConnManager::StartWork(shared_ptr workStatus) { WS_HILOGD("StartWork, id: %{public}s, bundleName: %{public}s, abilityName: %{public}s", @@ -46,41 +40,50 @@ bool WorkConnManager::StartWork(shared_ptr workStatus) // workConn->OnWorkStart(workStatus->workInfo_); // workStatus->MarkStatus(WorkStatus::Status::RUNNING); - // Want want; - // want.SetElementName(workStatus->bundleName_, workStatus->abilityName_); - // sptr systemAbilityManager = - // SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - // if (systemAbilityManager == nullptr) { - // return false; - // } - // sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); - // if (remoteObject == nullptr) { - // WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); - // return false; - // } - // sptr abilityMgr_ = iface_cast(remoteObject); - // if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { - // WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); - // return false; - // } - // sptr connection(new (std::nothrow) WorkSchedulerConnection()); - // abilityMgr_->ConnectAbility(want, connection, nullptr, workStatus->userId_); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); + return false; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to ams service."); + return false; + } + sptr abilityMgr_ = iface_cast(remoteObject); + if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { + WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); + return false; + } + + WS_HILOGI("Begin to connect bundle:%{public}s, abilityName:%{public}s, userId:%{public}d", + workStatus->bundleName_.c_str(), workStatus->abilityName_.c_str(), workStatus->userId_); + sptr connection(new (std::nothrow) WorkSchedulerConnection()); + Want want; + want.SetElementName(workStatus->bundleName_, workStatus->abilityName_); + int ret = abilityMgr_->ConnectAbility(want, connection, nullptr, workStatus->userId_); + if (ret != ERR_OK) { + WS_HILOGE("connect failed"); + return false; + } + // connection->StartWork(); return true; } void WorkConnManager::StopWork(shared_ptr workStatus) { - WS_HILOGI("StopWork come in, workStatus ID: %{public}s", workStatus->workId_.c_str()); - if (connMap_.count(workStatus->workId_) == 0) { - WS_HILOGD("work id(%{public}s) is not key in connMap_", workStatus->workId_.c_str()); - return; - } - auto workConn = connMap_.at(workStatus->workId_); - WS_HILOGD("work stop: %{public}s/%{public}s id: %{public}s", - workStatus->workInfo_->GetBundleName().c_str(), - workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); - workConn->OnWorkStop(workStatus->workInfo_); - connMap_.erase(workStatus->workId_); + // WS_HILOGI("StopWork come in, workStatus ID: %{public}s", workStatus->workId_.c_str()); + // if (connMap_.count(workStatus->workId_) == 0) { + // WS_HILOGD("work id(%{public}s) is not key in connMap_", workStatus->workId_.c_str()); + // return; + // } + // auto workConn = connMap_.at(workStatus->workId_); + // WS_HILOGD("work stop: %{public}s/%{public}s id: %{public}s", + // workStatus->workInfo_->GetBundleName().c_str(), + // workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); + // workConn->OnWorkStop(workStatus->workInfo_); + // connMap_.erase(workStatus->workId_); } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_scheduler_connection.cpp b/services/native/src/work_scheduler_connection.cpp index 4126284..2f740a3 100644 --- a/services/native/src/work_scheduler_connection.cpp +++ b/services/native/src/work_scheduler_connection.cpp @@ -19,19 +19,25 @@ namespace OHOS { namespace WorkScheduler { +void WorkSchedulerConnection::StopWork() { + if (proxy_ == nullptr) { + WS_HILOGE("proxy is null"); + return; + } + proxy_->OnWorkStop(); +} + void WorkSchedulerConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - WS_HILOGI("WorkSchedulerExtension enter"); proxy_ = (new (std::nothrow) WorkSchedulerProxy(remoteObject)); proxy_->OnWorkStart(); - WS_HILOGI("WorkSchedulerExtension end"); + WS_HILOGI("OnAbilityConnectDone"); } void WorkSchedulerConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - WS_HILOGI("WorkSchedulerExtension enter"); - WS_HILOGI("WorkSchedulerExtension end"); + WS_HILOGI("OnAbilityDisconnectDone"); } } // namespace WorkScheduler } // namespace OHOS diff --git a/services/zidl/include/work_conn_proxy.h b/services/zidl/include/work_conn_proxy.h deleted file mode 100644 index 5cd2eab..0000000 --- a/services/zidl/include/work_conn_proxy.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORKSCHED_ZIDL_WORK_CONN_PROXY_H -#define WORKSCHED_ZIDL_WORK_CONN_PROXY_H - -#include -#include - -#include "iwork_conn.h" - -namespace OHOS { -namespace WorkScheduler { -class WorkConnProxy : public IRemoteProxy { -public: - explicit WorkConnProxy(const sptr& impl) : IRemoteProxy(impl) {} - ~WorkConnProxy() = default; - DISALLOW_COPY_AND_MOVE(WorkConnProxy); - - virtual void OnWorkStart(WorkInfo& workInfo); - virtual void OnWorkStop(WorkInfo& workInfo); -private: - static inline BrokerDelegator delegator_; -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORKSCHED_ZIDL_WORK_CONN_PROXY_H \ No newline at end of file diff --git a/services/zidl/include/work_conn_stub.h b/services/zidl/include/work_conn_stub.h deleted file mode 100644 index 4a1947e..0000000 --- a/services/zidl/include/work_conn_stub.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WORKSCHED_ZIDL_WORK_CONN_STUB_H -#define WORKSCHED_ZIDL_WORK_CONN_STUB_H - -#include -#include - -#include "iwork_conn.h" - -namespace OHOS { -namespace WorkScheduler { -class WorkConnStub : public IRemoteStub { -public: - WorkConnStub() = default; - virtual ~WorkConnStub() = default; - int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - DISALLOW_COPY_AND_MOVE(WorkConnStub); - - int32_t OnWorkStartStub(MessageParcel& data); - int32_t OnWorkStopStub(MessageParcel& data); -}; -} // namespace WorkScheduler -} // namespace OHOS - -#endif // WORKSCHED_ZIDL_WORK_CONN_STUB_H \ No newline at end of file diff --git a/services/zidl/src/work_conn_proxy.cpp b/services/zidl/src/work_conn_proxy.cpp deleted file mode 100644 index f2882d9..0000000 --- a/services/zidl/src/work_conn_proxy.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "work_conn_proxy.h" - -#include -#include -#include - -#include "work_sched_common.h" - -namespace OHOS { -namespace WorkScheduler { -void WorkConnProxy::OnWorkStart(WorkInfo& workInfo) -{ - sptr remote = Remote(); - RETURN_IF(remote == nullptr); - - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!data.WriteInterfaceToken(WorkConnProxy::GetDescriptor())) { - WS_HILOGE("WorkConnProxy::%{public}s write descriptor failed!", __func__); - return; - } - - WRITE_PARCEL_WITHOUT_RET(data, Parcelable, &workInfo); - - int ret = remote->SendRequest(static_cast(IWorkConn::ON_WORK_START), data, reply, option); - if (ret != ERR_OK) { - WS_HILOGE("WorkConnProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret); - return; - } -} - -void WorkConnProxy::OnWorkStop(WorkInfo& workInfo) -{ - sptr remote = Remote(); - RETURN_IF(remote == nullptr); - - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!data.WriteInterfaceToken(WorkConnProxy::GetDescriptor())) { - WS_HILOGE("WorkConnProxy::%{public}s write descriptor failed!", __func__); - return; - } - - WRITE_PARCEL_WITHOUT_RET(data, Parcelable, &workInfo); - - int ret = remote->SendRequest(static_cast(IWorkConn::ON_WORK_STOP), data, reply, option); - if (ret != ERR_OK) { - WS_HILOGE("WorkConnProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret); - return; - } -} -} // namespace WorkScheduler -} // namespace OHOS \ No newline at end of file diff --git a/services/zidl/src/work_conn_stub.cpp b/services/zidl/src/work_conn_stub.cpp deleted file mode 100644 index 0c57ac4..0000000 --- a/services/zidl/src/work_conn_stub.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "work_conn_stub.h" - -#include - -#include "work_sched_common.h" - -using namespace std; - -namespace OHOS { -namespace WorkScheduler { -int WorkConnStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - WS_HILOGD("WorkConnStub::OnRemoteRequest, cmd = %u, flags = %d", code, option.GetFlags()); - u16string descriptor = WorkConnStub::GetDescriptor(); - u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - WS_HILOGE("WorkConnStub::OnRemoteRequest failed, descriptor is not matched!"); - return E_GET_WORKSCHED_SERVICE_FALIED; - } - - switch (code) { - case static_cast(IWorkConn::ON_WORK_START): { - return OnWorkStartStub(data); - } - case static_cast(IWorkConn::ON_WORK_STOP): { - return OnWorkStopStub(data); - } - default: { - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - } - - return ERR_OK; -} - -int32_t WorkConnStub::OnWorkStartStub(MessageParcel& data) -{ - return ERR_OK; -} - -int32_t WorkConnStub::OnWorkStopStub(MessageParcel& data) -{ - return ERR_OK; -} -} // namespace WorkScheduler -} // namespace OHOS \ No newline at end of file -- Gitee From 6c0e422ef93ae1f10c6227c13e8694f4fa358ec8 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 10 Feb 2022 19:52:33 +0800 Subject: [PATCH 24/29] add onWorkStop callback Signed-off-by: chenming --- .../src/js_work_scheduler_extension.cpp | 28 +++++++ services/native/include/work_conn_manager.h | 11 ++- services/native/src/work_conn_manager.cpp | 78 ++++++++++++++----- services/native/src/work_policy_manager.cpp | 8 +- services/native/src/work_status.cpp | 4 + services/zidl/src/work_scheduler_proxy.cpp | 2 +- 6 files changed, 105 insertions(+), 26 deletions(-) diff --git a/frameworks/extension/src/js_work_scheduler_extension.cpp b/frameworks/extension/src/js_work_scheduler_extension.cpp index cf2b686..da856b1 100644 --- a/frameworks/extension/src/js_work_scheduler_extension.cpp +++ b/frameworks/extension/src/js_work_scheduler_extension.cpp @@ -147,6 +147,34 @@ void JsWorkSchedulerExtension::OnWorkStart() void JsWorkSchedulerExtension::OnWorkStop() { + WorkSchedulerExtension::OnWorkStop(); + WS_HILOGI("WorkSchedulerExtension %{public}s begin.", __func__); + + AbilityRuntime::HandleScope handleScope(jsRuntime_); + NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* jCommonEventData = nativeEngine.CreateObject(); + + NativeValue* argv[] = {jCommonEventData}; + if (!jsObj_) { + WS_HILOGI("WorkSchedulerExtension Not found js"); + return; + } + + NativeValue* value = jsObj_->Get(); + NativeObject* obj = AbilityRuntime::ConvertNativeValueTo(value); + if (obj == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get object"); + return; + } + + NativeValue* method = obj->GetProperty("onWorkStop"); + if (method == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get onCommonEventTriggered from object"); + return; + } + nativeEngine.CallFunction(value, method, argv, 1); + WS_HILOGI("WorkSchedulerExtension %{public}s end.", __func__); } void JsWorkSchedulerExtension::GetSrcPath(std::string &srcPath) diff --git a/services/native/include/work_conn_manager.h b/services/native/include/work_conn_manager.h index 5d7d743..82427fe 100644 --- a/services/native/include/work_conn_manager.h +++ b/services/native/include/work_conn_manager.h @@ -20,6 +20,7 @@ #include #include +#include "work_scheduler_connection.h" #include "work_status.h" #include "errors.h" @@ -29,12 +30,16 @@ namespace WorkScheduler { class WorkConnManager { public: bool StartWork(std::shared_ptr workStatus); - void StopWork(std::shared_ptr workStatus); + bool StopWork(std::shared_ptr workStatus); private: + void RemoveConnInfo(std::string &workId); + void AddConnInfo(std::string &workId, sptr &connection); + sptr GetConnInfo(std::string &workId); + bool DisConnect(sptr connect); std::mutex connMapMutex_; - //std::map> connMap_; + std::map> connMap_; + std::map eventIdMap_; }; } // namespace WorkScheduler } // namespace OHOS - #endif // WORK_SCHED_SERVICES_WORK_CONN_MANAGER_H \ No newline at end of file diff --git a/services/native/src/work_conn_manager.cpp b/services/native/src/work_conn_manager.cpp index f405b66..529efb3 100644 --- a/services/native/src/work_conn_manager.cpp +++ b/services/native/src/work_conn_manager.cpp @@ -24,22 +24,35 @@ #include #include -#include "work_scheduler_connection.h" - using namespace std; using namespace OHOS::AAFwk; namespace OHOS { namespace WorkScheduler { +void WorkConnManager::AddConnInfo(string &workId, sptr &connection) +{ + std::lock_guard lock(connMapMutex_); + connMap_.emplace(workId, connection); +} + +void WorkConnManager::RemoveConnInfo(string &workId) +{ + std::lock_guard lock(connMapMutex_); + connMap_.erase(workId); +} + +sptr WorkConnManager::GetConnInfo(string &workId) { + std::lock_guard lock(connMapMutex_); + if (connMap_.count(workId) >= 0) { + return connMap_.at(workId); + } + return nullptr; +} + bool WorkConnManager::StartWork(shared_ptr workStatus) { WS_HILOGD("StartWork, id: %{public}s, bundleName: %{public}s, abilityName: %{public}s", workStatus->workId_.c_str(), workStatus->bundleName_.c_str(), workStatus->abilityName_.c_str()); - // auto workConn = make_shared(); - // connMap_.emplace(workStatus->workId_, workConn); - // workConn->OnWorkStart(workStatus->workInfo_); - // workStatus->MarkStatus(WorkStatus::Status::RUNNING); - sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemAbilityManager == nullptr) { @@ -67,23 +80,48 @@ bool WorkConnManager::StartWork(shared_ptr workStatus) WS_HILOGE("connect failed"); return false; } - // connection->StartWork(); + AddConnInfo(workStatus->workId_, connection); return true; } -void WorkConnManager::StopWork(shared_ptr workStatus) +bool WorkConnManager::DisConnect(sptr connect) { - // WS_HILOGI("StopWork come in, workStatus ID: %{public}s", workStatus->workId_.c_str()); - // if (connMap_.count(workStatus->workId_) == 0) { - // WS_HILOGD("work id(%{public}s) is not key in connMap_", workStatus->workId_.c_str()); - // return; - // } - // auto workConn = connMap_.at(workStatus->workId_); - // WS_HILOGD("work stop: %{public}s/%{public}s id: %{public}s", - // workStatus->workInfo_->GetBundleName().c_str(), - // workStatus->workInfo_->GetAbilityName().c_str(), workStatus->workId_.c_str()); - // workConn->OnWorkStop(workStatus->workInfo_); - // connMap_.erase(workStatus->workId_); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); + return false; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + WS_HILOGI("WorkSchedulerExtension Failed to ams service."); + return false; + } + sptr abilityMgr_ = iface_cast(remoteObject); + if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { + WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); + return false; + } + int ret = abilityMgr_->DisconnectAbility(connect); + if (ret != ERR_OK) { + WS_HILOGE("disconnect failed"); + return false; + } + return true; +} + +bool WorkConnManager::StopWork(shared_ptr workStatus) +{ + bool ret = false; + sptr conn = GetConnInfo(workStatus->workId_); + if (conn != nullptr) { + conn->StopWork(); + } else { + WS_HILOGD("connection is null"); + } + ret = DisConnect(conn); + RemoveConnInfo(workStatus->workId_); + return ret; } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 945b8d5..7bc4f5f 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -92,12 +92,16 @@ bool WorkPolicyManager::AddWork(shared_ptr workStatus, int32_t uid) bool WorkPolicyManager::RemoveWork(shared_ptr workStatus, int32_t uid) { WS_HILOGI("WorkPolicyManager::RemoveWork"); + bool ret = false; std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { WS_HILOGD("Remove workStatus ID: %{public}s form uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); - return uidQueueMap_.at(uid)->Remove(workStatus); + ret = uidQueueMap_.at(uid)->Remove(workStatus); + if (uidQueueMap_.count(uid) == 0) { + uidQueueMap_.erase(uid); + } } - return false; + return ret; } shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int32_t uid) diff --git a/services/native/src/work_status.cpp b/services/native/src/work_status.cpp index 0e3fece..ce08625 100644 --- a/services/native/src/work_status.cpp +++ b/services/native/src/work_status.cpp @@ -156,6 +156,10 @@ bool WorkStatus::IsReady() WS_HILOGD("Not same user. WorkId:%{public}s", workId_.c_str()); return false; } + if (IsRunning()) { + WS_HILOGD("Work is running"); + return false; + } auto workConditionMap = workInfo_->GetConditionMap(); for (auto it : *workConditionMap) { if (conditionMap_.count(it.first) <= 0 || workConditionMap == nullptr) { diff --git a/services/zidl/src/work_scheduler_proxy.cpp b/services/zidl/src/work_scheduler_proxy.cpp index 580ddb5..e15fc46 100644 --- a/services/zidl/src/work_scheduler_proxy.cpp +++ b/services/zidl/src/work_scheduler_proxy.cpp @@ -32,7 +32,7 @@ void WorkSchedulerProxy::OnWorkStop() MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); + Remote()->SendRequest(COMMAND_ON_WORK_STOP, data, reply, option); } } // namespace WorkScheduler } // namespace OHOS -- Gitee From 80256db9c29bed056f106c53206db8fffcf0adf8 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 10 Feb 2022 20:38:28 +0800 Subject: [PATCH 25/29] add workstop callback bugfix Signed-off-by: chenming --- services/native/src/work_policy_manager.cpp | 8 +++++++- services/zidl/src/work_scheduler_stub_imp.cpp | 2 -- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 7bc4f5f..6938d47 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -97,7 +97,7 @@ bool WorkPolicyManager::RemoveWork(shared_ptr workStatus, int32_t ui if (uidQueueMap_.count(uid) > 0) { WS_HILOGD("Remove workStatus ID: %{public}s form uidQueue(%{public}d)", workStatus->workId_.c_str(), uid); ret = uidQueueMap_.at(uid)->Remove(workStatus); - if (uidQueueMap_.count(uid) == 0) { + if (uidQueueMap_.count(uid) <= 0) { uidQueueMap_.erase(uid); } } @@ -119,6 +119,9 @@ void WorkPolicyManager::RemoveFromUidQueue(std::shared_ptr workStatu std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { uidQueueMap_.at(uid)->CancelWork(workStatus); + if (uidQueueMap_.at(uid)->GetSize() <= 0) { + uidQueueMap_.erase(uid); + } } } @@ -160,6 +163,9 @@ bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t ui std::lock_guard lock(uidMapMutex_); if (uidQueueMap_.count(uid) > 0) { bool ret = uidQueueMap_.at(uid)->Remove(workStatus); + if (uidQueueMap_.at(uid)->GetSize() <= 0) { + uidQueueMap_.erase(uid); + } return ret; } return true; diff --git a/services/zidl/src/work_scheduler_stub_imp.cpp b/services/zidl/src/work_scheduler_stub_imp.cpp index b7470be..898fb42 100644 --- a/services/zidl/src/work_scheduler_stub_imp.cpp +++ b/services/zidl/src/work_scheduler_stub_imp.cpp @@ -27,7 +27,6 @@ void WorkSchedulerStubImp::OnWorkStart() extension->OnWorkStart(); WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); } - WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); } void WorkSchedulerStubImp::OnWorkStop() @@ -38,7 +37,6 @@ void WorkSchedulerStubImp::OnWorkStop() extension->OnWorkStop(); WS_HILOGI("WorkSchedulerExtension %{public}s end successfully.", __func__); } - WS_HILOGI("WorkSchedulerExtension %{public}s end failed.", __func__); } } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file -- Gitee From 7402fb8f56d97e224a2d9a935fb816df9be80e66 Mon Sep 17 00:00:00 2001 From: chenming Date: Thu, 10 Feb 2022 23:14:33 +0800 Subject: [PATCH 26/29] add callback Signed-off-by: chenming --- services/BUILD.gn | 1 + services/native/include/watchdog.h | 39 ++++++++++++ services/native/include/work_policy_manager.h | 12 ++++ .../native/include/work_scheduler_service.h | 2 +- services/native/src/watchdog.cpp | 59 +++++++++++++++++++ services/native/src/work_policy_manager.cpp | 50 +++++++++++++++- .../native/src/work_scheduler_service.cpp | 5 ++ utils/native/include/work_sched_utils.h | 1 - 8 files changed, 164 insertions(+), 5 deletions(-) create mode 100644 services/native/include/watchdog.h create mode 100644 services/native/src/watchdog.cpp diff --git a/services/BUILD.gn b/services/BUILD.gn index ac1af1b..01b7e50 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -35,6 +35,7 @@ ohos_shared_library("workschedservice") { "native/src/work_conn_manager.cpp", "native/src/work_event_handler.cpp", "native/src/work_policy_manager.cpp", + "native/src/watchdog.cpp", "native/src/work_queue.cpp", "native/src/work_queue_event_handler.cpp", "native/src/work_queue_manager.cpp", diff --git a/services/native/include/watchdog.h b/services/native/include/watchdog.h new file mode 100644 index 0000000..c6badc0 --- /dev/null +++ b/services/native/include/watchdog.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WATCHDOG_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WATCHDOG_H + +#include +#include +#include + +namespace OHOS { +namespace WorkScheduler { +class WorkPolicyManager; +class Watchdog : public AppExecFwk::EventHandler { +public: + Watchdog(const std::shared_ptr& service); + ~Watchdog() override = default; + bool AddWatchdog(const int32_t watchdogId, int32_t interval); + void RemoveWatchdog(int32_t watchdogId); + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) override; + +private: + std::shared_ptr service_; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WATCHDOG_H \ No newline at end of file diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index fb24e03..9884ea0 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -34,6 +34,7 @@ namespace WorkScheduler { class WorkSchedulerService; class WorkEventHandler; class AppRemovedListener; +class Watchdog; class WorkPolicyManager { public: const size_t MAX_WORK_COUNT_PER_UID = 10; @@ -59,6 +60,7 @@ public: void CheckWorkToRun(); void SendRetrigger(int64_t delayTime); void AddAppRemoveListener(std::shared_ptr listener); + void WatchdogTimeOut(int32_t watchdogId); private: int32_t GetMaxRunningCount(); @@ -73,6 +75,9 @@ private: void RemoveConditionUnReady(); std::shared_ptr GetWorkToRun(); void RemoveAllUnReady(); + int32_t NewWatchDogId(); + void AddWatchdogForWork(std::shared_ptr workStatus); + std::shared_ptr GetWorkFromWatchdog(int32_t id); const wptr wss_; std::shared_ptr workConnManager_; @@ -86,6 +91,13 @@ private: std::list> policyFilters_; std::shared_ptr appRemovedListener_; + + std::shared_ptr watchdog_; + + std::mutex watchdogIdMapMutex_; + std::map> watchdogIdMap_; + + int32_t watchdogId_; }; } } // namespace OHOS diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index 419f784..b1e57b3 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -59,8 +59,8 @@ public: int32_t CreateNodeDir(std::string dir); int32_t CreateNodeFile(std::string filePath); void UpdateWorkBeforeRealStart(std::shared_ptr work); - void OnConditionReady(std::shared_ptr>> workStatusVector); + void WatchdogTimeOut(std::shared_ptr workStatus); std::shared_ptr GetHandler() { diff --git a/services/native/src/watchdog.cpp b/services/native/src/watchdog.cpp new file mode 100644 index 0000000..cdede48 --- /dev/null +++ b/services/native/src/watchdog.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "watchdog.h" + +#include "work_sched_hilog.h" +#include "work_policy_manager.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +const std::string WORK_SCHEDULER_WATCHDOG = "WorkSchedulerWatchdog"; + +Watchdog::Watchdog(const std::shared_ptr& service) : service_(service) +{ + std::shared_ptr eventRunner = AppExecFwk::EventRunner::Create(WORK_SCHEDULER_WATCHDOG); + if (eventRunner.get() != nullptr) { + SetEventRunner(eventRunner); + } +} + +bool Watchdog::AddWatchdog(int32_t watchdogId, int32_t interval) +{ + WS_HILOGD("AddWatchdog %{public}d", watchdogId); + return SendEvent(watchdogId, 0, interval); +} + +void Watchdog::RemoveWatchdog(int32_t watchdogId) +{ + WS_HILOGD("RemoveWatchdog %{public}d", watchdogId); + RemoveEvent(watchdogId); +} + +void Watchdog::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) +{ + if (event == nullptr) { + return; + } + int32_t watchdogId = event->GetInnerEventId(); + if (service_ != nullptr) { + service_->WatchdogTimeOut(watchdogId); + } else { + WS_HILOGD("service is null"); + } +} +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 6938d47..d9dfa3b 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -24,15 +24,21 @@ #include "work_scheduler_service.h" #include "work_event_handler.h" +#include "watchdog.h" + using namespace std; using namespace OHOS::AppExecFwk; namespace OHOS { namespace WorkScheduler { namespace { -static const int64_t DELAY_TIME_LONG = 30000; -static const int64_t DELAY_TIME_SHORT = 5000; +const int64_t DELAY_TIME_LONG = 30000; +const int64_t DELAY_TIME_SHORT = 5000; +const int MAX_WATCHDOG_ID = 1000; +const int INIT_WATCHDOG_ID = 1; +const int WATCHDOG_TIME = 5000; } + WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) { std::lock_guard lock(conditionReadyMutex_); @@ -53,6 +59,8 @@ bool WorkPolicyManager::Init() WS_HILOGE("WorkPolicyManager::%{public}s failed due to handler_ is nullptr", __func__); return false; } + watchdog_ = std::make_shared(wmsptr->GetWorkPolicyManager()); + watchdogId_ = INIT_WATCHDOG_ID; return true; } @@ -306,7 +314,18 @@ void WorkPolicyManager::RealStartWork(std::shared_ptr topWork) topWork->MarkStatus(WorkStatus::Status::RUNNING); wmsptr->UpdateWorkBeforeRealStart(topWork); RemoveFromReadyQueue(topWork); - workConnManager_->StartWork(topWork); + bool ret = workConnManager_->StartWork(topWork); + if (ret) { + AddWatchdogForWork(topWork); + } +} + +void WorkPolicyManager::AddWatchdogForWork(std::shared_ptr workStatus) +{ + int watchId = NewWatchDogId(); + watchdog_->AddWatchdog(watchId, WATCHDOG_TIME); + std::lock_guard lock(watchdogIdMapMutex_); + watchdogIdMap_.emplace(watchId, workStatus); } void WorkPolicyManager::SendRetrigger(int64_t delaytime) @@ -320,6 +339,23 @@ void WorkPolicyManager::SendRetrigger(int64_t delaytime) handler_->SendEvent(InnerEvent::Get(WorkEventHandler::RETRIGGER_MSG, 0), delaytime); } +void WorkPolicyManager::WatchdogTimeOut(int32_t watchdogId) +{ + WS_HILOGI("WatchdogTimeOut."); + std::shared_ptr workStatus = GetWorkFromWatchdog(watchdogId); + auto wmsptr = wss_.promote(); + if (wmsptr == nullptr) { + WS_HILOGE("Workscheduler service is null"); + return; + } + wmsptr->WatchdogTimeOut(workStatus); +} + +std::shared_ptr WorkPolicyManager::GetWorkFromWatchdog(int32_t id) { + std::lock_guard lock(watchdogIdMapMutex_); + return watchdogIdMap_.at(id); +} + list> WorkPolicyManager::ObtainAllWorks(int32_t &uid) { WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); @@ -388,5 +424,13 @@ void WorkPolicyManager::Dump(string& result) result.append("3. GetMaxRunningCount:"); result.append(to_string(GetMaxRunningCount())); } + +int32_t WorkPolicyManager::NewWatchDogId() +{ + if (watchdogId_ == MAX_WATCHDOG_ID) { + watchdogId_ = INIT_WATCHDOG_ID; + } + return watchdogId_++; +} } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 4e8620f..fd2b417 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -319,6 +319,11 @@ bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, return true; } +void WorkSchedulerService::WatchdogTimeOut(std::shared_ptr workStatus) +{ + StopWorkInner(workStatus, workStatus->uid_, false); +} + bool IsInList(list &list, std::string myWork) { for (auto work : list) { diff --git a/utils/native/include/work_sched_utils.h b/utils/native/include/work_sched_utils.h index 68cc1df..afd70c5 100644 --- a/utils/native/include/work_sched_utils.h +++ b/utils/native/include/work_sched_utils.h @@ -28,7 +28,6 @@ public: static int GetCurrentAccountId(); static int32_t GetUserIdByUid(int32_t uid); - static const int INVALID_DATA = -1; }; } // namespace WorkScheduler -- Gitee From 05179fdad291b7ef16f61cbf805ad20b5586b929 Mon Sep 17 00:00:00 2001 From: chenming Date: Fri, 11 Feb 2022 11:48:03 +0800 Subject: [PATCH 27/29] add memory Signed-off-by: chenming --- .../native/include/policy/memory_policy.h | 1 + services/native/include/work_policy_manager.h | 3 +++ services/native/src/policy/memory_policy.cpp | 11 +++++++- services/native/src/work_policy_manager.cpp | 11 ++++++++ .../native/src/work_scheduler_service.cpp | 26 +++---------------- 5 files changed, 29 insertions(+), 23 deletions(-) diff --git a/services/native/include/policy/memory_policy.h b/services/native/include/policy/memory_policy.h index b1084b8..f684225 100644 --- a/services/native/include/policy/memory_policy.h +++ b/services/native/include/policy/memory_policy.h @@ -34,6 +34,7 @@ public: const int32_t COUNT_MEMORY_LOW = 2; const int32_t COUNT_MEMORY_NORMAL = 3; private: + int32_t GetMemAvailable(); std::shared_ptr workPolicyManager_; }; } diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index 9884ea0..a9f8300 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -61,6 +61,8 @@ public: void SendRetrigger(int64_t delayTime); void AddAppRemoveListener(std::shared_ptr listener); void WatchdogTimeOut(int32_t watchdogId); + void SetFixMemory(int32_t memory); + int32_t GetFixMemory(); private: int32_t GetMaxRunningCount(); @@ -98,6 +100,7 @@ private: std::map> watchdogIdMap_; int32_t watchdogId_; + int32_t fixMemory_; }; } } // namespace OHOS diff --git a/services/native/src/policy/memory_policy.cpp b/services/native/src/policy/memory_policy.cpp index fb36a9e..cf47f70 100644 --- a/services/native/src/policy/memory_policy.cpp +++ b/services/native/src/policy/memory_policy.cpp @@ -24,12 +24,21 @@ MemoryPolicy::MemoryPolicy(shared_ptr workPolicyManager) { workPolicyManager_ = workPolicyManager; } + MemoryPolicy::~MemoryPolicy() { } -int32_t GetMemAvailable() +int32_t MemoryPolicy::GetMemAvailable() { + int32_t fixMemory; + if (workPolicyManager_ != nullptr) { + fixMemory = workPolicyManager_->GetFixMemory(); + if (fixMemory != -1) { + WS_HILOGD("fix memory:%{public}d", fixMemory); + return fixMemory; + } + } int32_t memAvailable; FILE *fp = fopen("/proc/meminfo", "r"); if (fp == NULL) { diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index d9dfa3b..4113758 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -61,6 +61,7 @@ bool WorkPolicyManager::Init() } watchdog_ = std::make_shared(wmsptr->GetWorkPolicyManager()); watchdogId_ = INIT_WATCHDOG_ID; + fixMemory_ = -1; return true; } @@ -432,5 +433,15 @@ int32_t WorkPolicyManager::NewWatchDogId() } return watchdogId_++; } + +int32_t WorkPolicyManager::GetFixMemory() +{ + return fixMemory_; +} + +void WorkPolicyManager::SetFixMemory(int32_t memory) +{ + fixMemory_ = memory; +} } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index fd2b417..9797465 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -56,7 +56,7 @@ const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(wss.GetRefP static const string ALL_INFO = "All"; static const string WORK_QUEUE_INFO = "WorkQueue"; static const string WORK_POLICY_INFO = "WorkPolicy"; -static const string EXTENSION = "Extension"; +static const string SET_DEFAULT_MEMORY = "SetDefaultMemory"; static const string CHECK_BUNDLE = "CheckBundle"; } @@ -85,6 +85,7 @@ void WorkSchedulerService::OnStart() GetHandler()->SendEvent(InnerEvent::Get(WorkEventHandler::INIT_PERSISTED_MSG, 0), 15000); checkBundle_ = true; ready_ = true; + WS_HILOGE("OnStart and add system ability success."); } @@ -392,27 +393,8 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vector systemAbilityManager = - SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr) { - return false; - } - sptr remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); - if (remoteObject == nullptr) { - WS_HILOGI("WorkSchedulerExtension Failed to get ability manager service."); - return false; - } - sptr abilityMgr_ = iface_cast(remoteObject); - if ((abilityMgr_ == nullptr) || (abilityMgr_->AsObject() == nullptr)) { - WS_HILOGI("WorkSchedulerExtension Failed to get system ability manager services ability"); - return false; - } - - sptr connection(new (std::nothrow) WorkSchedulerConnection()); - abilityMgr_->ConnectAbility(want, connection, nullptr, 100); + } else if (dumpOption[1] == SET_DEFAULT_MEMORY) { + workPolicyManager_->SetFixMemory(std::stoi(dumpOption[2])); return true; } else if (dumpOption[1] == WORK_QUEUE_INFO) { DumpWorkQueueInfo(dumpInfo); -- Gitee From 6a5110954c933d8d7cfe04aa58d8c67f493597e0 Mon Sep 17 00:00:00 2001 From: chenming Date: Fri, 11 Feb 2022 15:19:53 +0800 Subject: [PATCH 28/29] add dump Signed-off-by: chenming --- interfaces/kits/js/napi/include/common.h | 2 - interfaces/kits/js/napi/src/common.cpp | 4 -- services/native/include/work_policy_manager.h | 8 ++- services/native/include/work_queue_manager.h | 4 ++ .../native/include/work_scheduler_service.h | 4 +- services/native/include/work_status.h | 3 +- .../native/src/conditions/timer_listener.cpp | 8 ++- services/native/src/work_policy_manager.cpp | 31 +++++++++- services/native/src/work_queue_manager.cpp | 12 ++++ .../native/src/work_scheduler_service.cpp | 61 ++++++++++++++++--- 10 files changed, 114 insertions(+), 23 deletions(-) diff --git a/interfaces/kits/js/napi/include/common.h b/interfaces/kits/js/napi/include/common.h index 338cb20..1960991 100644 --- a/interfaces/kits/js/napi/include/common.h +++ b/interfaces/kits/js/napi/include/common.h @@ -21,8 +21,6 @@ namespace OHOS { namespace WorkScheduler { -static const int MIN_REPEAT_INTERVAL = 1200 * 1000; - struct CallbackPromiseInfo { napi_ref callback = nullptr; napi_deferred deferred = nullptr; diff --git a/interfaces/kits/js/napi/src/common.cpp b/interfaces/kits/js/napi/src/common.cpp index e666f8d..4fe196b 100644 --- a/interfaces/kits/js/napi/src/common.cpp +++ b/interfaces/kits/js/napi/src/common.cpp @@ -152,10 +152,6 @@ bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo WS_HILOGI("RepeatCycleTime not set, just ignore other repeat set."); return false; } - if (repeatCycleTime < MIN_REPEAT_INTERVAL) { - WS_HILOGI("RepeatCycleTime set must not be less than %{public}d.", MIN_REPEAT_INTERVAL); - return false; - } bool isRepeat = Common::GetBoolProperty(env, objValue, "isRepeat"); int32_t repeatCount = Common::GetIntProperty(env, objValue, "repeatCount"); diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index a9f8300..13d879a 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -45,7 +45,7 @@ public: void AddPolicyFilter(std::shared_ptr filter); bool AddWork(std::shared_ptr workStatus, int32_t uid); bool RemoveWork(std::shared_ptr workStatus, int32_t uid); - bool StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel); + bool StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel, bool isTimeOut); bool CancelWork(std::shared_ptr workStatus, int32_t uid); bool StopAndClearWorks(int32_t uid); bool IsLastWorkTimeout(int32_t workId, int32_t uid); @@ -63,6 +63,10 @@ public: void WatchdogTimeOut(int32_t watchdogId); void SetFixMemory(int32_t memory); int32_t GetFixMemory(); + void SetRepeatCycleTimeMin(uint32_t repeatCycleTimeMax); + uint32_t GetRepeatCycleTimeMin(); + void SetWatchdogTime(int time); + int GetWatchdogTime(); private: int32_t GetMaxRunningCount(); @@ -101,6 +105,8 @@ private: int32_t watchdogId_; int32_t fixMemory_; + uint32_t repeatCycleTimeMin_; + int watchdogTime_; }; } } // namespace OHOS diff --git a/services/native/include/work_queue_manager.h b/services/native/include/work_queue_manager.h index 5ddf23c..0c0e23c 100644 --- a/services/native/include/work_queue_manager.h +++ b/services/native/include/work_queue_manager.h @@ -43,6 +43,8 @@ public: void OnConditionChanged(WorkCondition::Type conditionType, std::shared_ptr conditionVal); bool StopAndClearWorks(std::list> workList); + void SetTimeCycle(int time); + int GetTimeCycle(); void Dump(std::string& result); private: @@ -52,6 +54,8 @@ private: const wptr wss_; std::map> queueMap_; std::map> listenerMap_; + + int timeCycle_; }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/include/work_scheduler_service.h b/services/native/include/work_scheduler_service.h index b1e57b3..9820306 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -101,7 +101,9 @@ private: void DumpWorkQueueInfo(std::vector &dumpInfo); void DumpWorkPolicyInfo(std::vector &dumpInfo); bool CheckWorkInfo(WorkInfo &workInfo, int32_t &uid); - bool StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel); + bool StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel, bool isTimeOut); + bool CheckCondition(WorkInfo& workInfo); + void DumpDebugInfo(std::vector &dumpInfo); }; } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/include/work_status.h b/services/native/include/work_status.h index 1dbf63c..cee6e61 100644 --- a/services/native/include/work_status.h +++ b/services/native/include/work_status.h @@ -62,10 +62,11 @@ public: void Dump(std::string& result); void UpdateTimerIfNeed(); bool NeedRemove(); + + bool lastTimeout_ {false}; private: Status currentStatus_; time_t baseTime_; - bool lastTimeout_ {false}; void MarkTimeout(); bool IsSameUser(); }; diff --git a/services/native/src/conditions/timer_listener.cpp b/services/native/src/conditions/timer_listener.cpp index cd38ee7..b189c87 100644 --- a/services/native/src/conditions/timer_listener.cpp +++ b/services/native/src/conditions/timer_listener.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace WorkScheduler { -const int TIME_CYCLE = 10 * 60 * 60; // 10min TimerListener::TimerListener(std::shared_ptr workQueueManager) { workQueueManager_ = workQueueManager; @@ -42,7 +41,12 @@ bool TimerListener::Start() if (!handler_) { handler_ = std::make_shared(eventRunner_, workQueueManager_); } - handler_->SendEvent(AppExecFwk::InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), TIME_CYCLE); + if (workQueueManager_ == nullptr) { + WS_HILOGD("workQueueManager_ is null"); + return false; + } + int time = workQueueManager_->GetTimeCycle(); + handler_->SendEvent(AppExecFwk::InnerEvent::Get(WorkQueueEventHandler::TIMER_TICK, 0), time); return true; } diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 4113758..6880d32 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -36,7 +36,8 @@ const int64_t DELAY_TIME_LONG = 30000; const int64_t DELAY_TIME_SHORT = 5000; const int MAX_WATCHDOG_ID = 1000; const int INIT_WATCHDOG_ID = 1; -const int WATCHDOG_TIME = 5000; +const int WATCHDOG_TIME = 2 * 60 * 1000; +const uint32_t CYCLE_TIME_MIN_DEFAULT = 20 * 60 * 1000; } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) @@ -62,6 +63,8 @@ bool WorkPolicyManager::Init() watchdog_ = std::make_shared(wmsptr->GetWorkPolicyManager()); watchdogId_ = INIT_WATCHDOG_ID; fixMemory_ = -1; + repeatCycleTimeMin_ = CYCLE_TIME_MIN_DEFAULT; + watchdogTime_ = WATCHDOG_TIME; return true; } @@ -140,11 +143,13 @@ void WorkPolicyManager::RemoveFromReadyQueue(std::shared_ptr workSta conditionReadyQueue_->RemoveUnReady(); } -bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t uid, const bool needCancel) +bool WorkPolicyManager::StopWork(std::shared_ptr workStatus, int32_t uid, + const bool needCancel, bool isTimeOut) { WS_HILOGI("WorkPolicyManager::StopWork"); bool hasCanceled = false; if (workStatus->IsRunning()) { + workStatus->lastTimeout_ = isTimeOut; workConnManager_->StopWork(workStatus); if (!workStatus->IsRepeating()) { workStatus->MarkStatus(WorkStatus::Status::REMOVED); @@ -324,7 +329,7 @@ void WorkPolicyManager::RealStartWork(std::shared_ptr topWork) void WorkPolicyManager::AddWatchdogForWork(std::shared_ptr workStatus) { int watchId = NewWatchDogId(); - watchdog_->AddWatchdog(watchId, WATCHDOG_TIME); + watchdog_->AddWatchdog(watchId, watchdogTime_); std::lock_guard lock(watchdogIdMapMutex_); watchdogIdMap_.emplace(watchId, workStatus); } @@ -443,5 +448,25 @@ void WorkPolicyManager::SetFixMemory(int32_t memory) { fixMemory_ = memory; } + +void WorkPolicyManager::SetRepeatCycleTimeMin(uint32_t repeatCycleTimeMax) +{ + repeatCycleTimeMin_ = repeatCycleTimeMax; +} + +uint32_t WorkPolicyManager::GetRepeatCycleTimeMin() +{ + return repeatCycleTimeMin_; +} + +void WorkPolicyManager::SetWatchdogTime(int time) +{ + watchdogTime_ = time; +} + +int WorkPolicyManager::WorkPolicyManager::GetWatchdogTime() +{ + return watchdogTime_; +} } // namespace WorkScheduler } // namespace OHOS \ No newline at end of file diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index 720b487..a5af27d 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -18,12 +18,15 @@ using namespace std; namespace OHOS { namespace WorkScheduler { +const int TIME_CYCLE = 10 * 60 * 60; // 10min + WorkQueueManager::WorkQueueManager(const wptr& wss) : wss_(wss) { } bool WorkQueueManager::Init() { + timeCycle_ = TIME_CYCLE; return true; } @@ -136,5 +139,14 @@ void WorkQueueManager::Dump(string& result) result.append("]\n"); } } + +void WorkQueueManager::SetTimeCycle(int time) +{ + timeCycle_ = time; +} + +int WorkQueueManager::GetTimeCycle() { + return timeCycle_; +} } // namespace WorkScheduler } // namespace OHOS diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index 9797465..abe2d52 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -56,8 +56,12 @@ const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(wss.GetRefP static const string ALL_INFO = "All"; static const string WORK_QUEUE_INFO = "WorkQueue"; static const string WORK_POLICY_INFO = "WorkPolicy"; -static const string SET_DEFAULT_MEMORY = "SetDefaultMemory"; +static const string SET_FIX_MEMORY = "SetFixMemory"; +static const string SET_REPEAT_CYCLE_TIME_MIN = "SetRepeatCycleTimeMin"; +static const string SET_WATCHDOG_TIME = "SetWatchdogTime"; +static const string SET_CYCLE_TIME = "SetCycleTime"; static const string CHECK_BUNDLE = "CheckBundle"; +static const string DEBUG_INFO = "DebugInfo"; } WorkSchedulerService::WorkSchedulerService() : SystemAbility(WORK_SCHEDULE_SERVICE_ID, true) {} @@ -233,12 +237,31 @@ bool WorkSchedulerService::CheckWorkInfo(WorkInfo &workInfo, int32_t &uid) return false; } +bool WorkSchedulerService::CheckCondition(WorkInfo& workInfo) +{ + if (workInfo.GetConditionMap()->size() > 1) { + return true; + } + if (workInfo.GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { + uint32_t time = workInfo.GetConditionMap()->at(WorkCondition::Type::TIMER)->uintVal; + if (time < workPolicyManager_->GetRepeatCycleTimeMin()) { + WS_HILOGE("fail, set time:%{public}d must more than %{public}d", time, + workPolicyManager_->GetRepeatCycleTimeMin()); + return false; + } + } + return true; +} + bool WorkSchedulerService::StartWork(WorkInfo& workInfo) { int32_t uid = IPCSkeleton::GetCallingUid(); if (checkBundle_ && !CheckWorkInfo(workInfo, uid)) { return false; } + if (!CheckCondition(workInfo)) { + return false; + } WS_HILOGD("WorkSchedulerService::StartWork workInfo %{public}s/%{public}s ID: %{public}d, uid: %{public}d", workInfo.GetBundleName().c_str(), workInfo.GetAbilityName().c_str(), workInfo.GetWorkId(), uid); shared_ptr workStatus = make_shared(workInfo, uid); @@ -292,7 +315,7 @@ bool WorkSchedulerService::StopWork(WorkInfo& workInfo) WS_HILOGD("StopWorkInner, workStatus is nullptr"); return false; } - return StopWorkInner(workStatus, uid, false); + return StopWorkInner(workStatus, uid, false, false); } bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) @@ -303,7 +326,7 @@ bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) WS_HILOGD("StopWorkInner, workStatus is nullptr"); return false; } - StopWorkInner(workStatus, uid, true); + StopWorkInner(workStatus, uid, true, false); if (workStatus->persisted_) { std::lock_guard lock(mutex_); persistedMap_.erase(workStatus->workId_); @@ -312,9 +335,10 @@ bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) return true; } -bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, int32_t uid, const bool needCancel) +bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, int32_t uid, + const bool needCancel, bool isTimeOut) { - if (workPolicyManager_->StopWork(workStatus, uid, needCancel)) { + if (workPolicyManager_->StopWork(workStatus, uid, needCancel, isTimeOut)) { workQueueManager_->CancelWork(workStatus); } return true; @@ -322,7 +346,7 @@ bool WorkSchedulerService::StopWorkInner(std::shared_ptr workStatus, void WorkSchedulerService::WatchdogTimeOut(std::shared_ptr workStatus) { - StopWorkInner(workStatus, workStatus->uid_, false); + StopWorkInner(workStatus, workStatus->uid_, false, true); } bool IsInList(list &list, std::string myWork) @@ -393,13 +417,25 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vectorSetFixMemory(std::stoi(dumpOption[2])); return true; + } else if (dumpOption[1] == SET_REPEAT_CYCLE_TIME_MIN) { + workPolicyManager_->SetRepeatCycleTimeMin(std::stoi(dumpOption[2])); + return true; + } else if (dumpOption[1] == SET_WATCHDOG_TIME) { + workPolicyManager_->SetWatchdogTime(std::stoi(dumpOption[2])); + return true; + } else if (dumpOption[1] == SET_CYCLE_TIME) { + workQueueManager_->SetTimeCycle(std::stoi(dumpOption[2])); + return true; } else if (dumpOption[1] == WORK_QUEUE_INFO) { DumpWorkQueueInfo(dumpInfo); } else if (dumpOption[1] == WORK_POLICY_INFO) { DumpWorkPolicyInfo(dumpInfo); + } else if (dumpOption[1] == DEBUG_INFO) { + DumpDebugInfo(dumpInfo); + return true; } else { WS_HILOGI("Dump need right param."); dumpInfo.push_back(string("dump need right param.")); @@ -439,10 +475,17 @@ void WorkSchedulerService::UpdateWorkBeforeRealStart(std::shared_ptr } } +void WorkSchedulerService::DumpDebugInfo(std::vector &dumpInfo) +{ + dumpInfo.push_back("Need check bundle:" + std::to_string(checkBundle_)); + dumpInfo.push_back("Fix Memory:" + std::to_string(workPolicyManager_->GetFixMemory())); + dumpInfo.push_back("Repeat cycle time min:" + std::to_string(workPolicyManager_->GetRepeatCycleTimeMin())); + dumpInfo.push_back("Watchdog time:" + std::to_string(workPolicyManager_->GetWatchdogTime())); + dumpInfo.push_back("Check cycle time:" + std::to_string(workQueueManager_->GetTimeCycle())); +} + void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) { - string info = "Need check bundle:" + std::to_string(checkBundle_); - dumpInfo.push_back(info); DumpWorkQueueInfo(dumpInfo); DumpWorkPolicyInfo(dumpInfo); } -- Gitee From 44c4424274ea208de088033e5bada4b28c79a90a Mon Sep 17 00:00:00 2001 From: chenming Date: Fri, 11 Feb 2022 15:59:00 +0800 Subject: [PATCH 29/29] add dumpinfo Signed-off-by: chenming --- .../test/unittest/src/workinfo_test.cpp | 14 +++++++++ .../work_scheduler_jsunit.test.js | 30 +++++++++---------- services/native/include/work_policy_manager.h | 3 -- services/native/src/work_policy_manager.cpp | 12 -------- services/native/src/work_queue_manager.cpp | 2 +- .../native/src/work_scheduler_service.cpp | 13 +++----- 6 files changed, 34 insertions(+), 40 deletions(-) diff --git a/frameworks/test/unittest/src/workinfo_test.cpp b/frameworks/test/unittest/src/workinfo_test.cpp index 9af3ce0..d47bdf9 100644 --- a/frameworks/test/unittest/src/workinfo_test.cpp +++ b/frameworks/test/unittest/src/workinfo_test.cpp @@ -41,6 +41,7 @@ void WorkInfoTest::TearDown() * @tc.name WorkInfoTest001 * @tc.desc Set WorkId to WorkInfo * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest001, Function | MediumTest | Level0) { @@ -53,6 +54,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest001, Function | MediumTest | Level0) * @tc.name WorkInfoTest002 * @tc.desc Set bundleName and abilityName to WorkInfo * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest002, Function | MediumTest | Level0) { @@ -66,6 +68,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest002, Function | MediumTest | Level0) * @tc.name WorkInfoTest003 * @tc.desc Set workInfo persisted * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest003, Function | MediumTest | Level0) { @@ -80,6 +83,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest003, Function | MediumTest | Level0) * @tc.name WorkInfoTest004 * @tc.desc Set workInfo charger condition charging * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest004, Function | MediumTest | Level0) { @@ -92,6 +96,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest004, Function | MediumTest | Level0) * @tc.name WorkInfoTest005 * @tc.desc Set workInfo charger condiiton discharging * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest005, Function | MediumTest | Level0) { @@ -104,6 +109,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest005, Function | MediumTest | Level0) * @tc.name WorkInfoTest006 * @tc.desc Set workInfo battery condition battery changed * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest006, Function | MediumTest | Level0) { @@ -116,6 +122,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest006, Function | MediumTest | Level0) * @tc.name WorkInfoTest007 * @tc.desc Set workInfo battery condition battery low * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest007, Function | MediumTest | Level0) { @@ -128,6 +135,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest007, Function | MediumTest | Level0) * @tc.name WorkInfoTest008 * @tc.desc Set workInfo battery condition battery okey * @tc.type FUNC + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 */ HWTEST_F (WorkInfoTest, WorkInfoTest008, Function | MediumTest | Level0) { @@ -140,6 +148,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest008, Function | MediumTest | Level0) * @tc.name WorkInfoTest009 * @tc.desc Set workInfo storage condition storage change * @tc.type FUNC + * @tc.require: SR000GGTN9 AR000GH89M */ HWTEST_F (WorkInfoTest, WorkInfoTest009, Function | MediumTest | Level0) { @@ -152,6 +161,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest009, Function | MediumTest | Level0) * @tc.name WorkInfoTest010 * @tc.desc Set workInfo storage condition storage low * @tc.type FUNC + * @tc.require: SR000GGTN8 AR000GH89J AR000GH89K AR000GH89L */ HWTEST_F (WorkInfoTest, WorkInfoTest010, Function | MediumTest | Level0) { @@ -164,6 +174,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest010, Function | MediumTest | Level0) * @tc.name WorkInfoTest011 * @tc.desc Set workInfo storage condition storage ok * @tc.type FUNC + * @tc.require: SR000GGTNB AR000GH89Q */ HWTEST_F (WorkInfoTest, WorkInfoTest011, Function | MediumTest | Level0) { @@ -176,6 +187,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest011, Function | MediumTest | Level0) * @tc.name WorkInfoTest012 * @tc.desc Set workInfo network condition * @tc.type FUNC + * @tc.require: SR000GGTNA AR000GH89P AR000GH89N AR000GH89O */ HWTEST_F (WorkInfoTest, WorkInfoTest012, Function | MediumTest | Level0) { @@ -188,6 +200,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest012, Function | MediumTest | Level0) * @tc.name WorkInfoTest013 * @tc.desc Set workInfo repeat time condition repeat count 3 * @tc.type FUNC + * @tc.require: SR000GGTNA AR000GH89P AR000GH89N AR000GH89O */ HWTEST_F (WorkInfoTest, WorkInfoTest013, Function | MediumTest | Level0) { @@ -202,6 +215,7 @@ HWTEST_F (WorkInfoTest, WorkInfoTest013, Function | MediumTest | Level0) * @tc.name WorkInfoTest014 * @tc.desc Set workInfo repeat time condition repeat * @tc.type FUNC + * @tc.require: SR000GGTNA AR000GH89P AR000GH89N AR000GH89O */ HWTEST_F (WorkInfoTest, WorkInfoTest014, Function | MediumTest | Level0) { diff --git a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js index 8d7d581..df7aba5 100644 --- a/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -49,7 +49,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest001 * @tc.desc: test work scheduler work id < 0 * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ it("WorkSchedulerJsTest001", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest001---------------------------'); @@ -67,7 +67,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest002 * @tc.desc: test work scheduler work id = 0 * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ it("WorkSchedulerJsTest002", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest002---------------------------'); @@ -86,7 +86,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest003 * @tc.desc: test work scheduler without bundle name. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C */ it("WorkSchedulerJsTest003", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest003---------------------------'); @@ -104,7 +104,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest004 * @tc.desc: test work scheduler without ability name. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C */ it("WorkSchedulerJsTest004", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest004---------------------------'); @@ -122,7 +122,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest005 * @tc.desc: test work scheduler without conditions. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C */ it("WorkSchedulerJsTest005", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest005---------------------------'); @@ -140,7 +140,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest006 * @tc.desc: test work scheduler success. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89D */ it("WorkSchedulerJsTest006", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest006---------------------------'); @@ -159,7 +159,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest007 * @tc.desc: test stopWork. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89D */ it("WorkSchedulerJsTest007", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest007---------------------------'); @@ -183,7 +183,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest008 * @tc.desc: test stopWork. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ it("WorkSchedulerJsTest008", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest008---------------------------'); @@ -207,7 +207,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest009 * @tc.desc: test getWorkStatus callback. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ it("WorkSchedulerJsTest009", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest009---------------------------'); @@ -241,7 +241,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest010 * @tc.desc: test getWorkStatus promise. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ it("WorkSchedulerJsTest010", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest010---------------------------'); @@ -276,7 +276,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest011 * @tc.desc: test obtainAllWorks callback. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ it("WorkSchedulerJsTest011", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest011---------------------------'); @@ -310,7 +310,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest012 * @tc.desc: test obtainAllWorks promise. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ it("WorkSchedulerJsTest012", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest012---------------------------'); @@ -344,7 +344,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest013 * @tc.desc: test stopAndClearWorks. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ it("WorkSchedulerJsTest013", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest013---------------------------'); @@ -368,7 +368,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest014 * @tc.desc: test isLastWorkTimeOut callback. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89D */ it("WorkSchedulerJsTest014", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest014---------------------------'); @@ -389,7 +389,7 @@ describe("WorkSchedulerJsTest", function () { * @tc.name: WorkSchedulerJsTest015 * @tc.desc: test isLastWorkTimeOut promise. * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTN7 AR000GH89D */ it("WorkSchedulerJsTest015", 0, async function (done) { console.info('----------------------WorkSchedulerJsTest015---------------------------'); diff --git a/services/native/include/work_policy_manager.h b/services/native/include/work_policy_manager.h index 13d879a..94de050 100644 --- a/services/native/include/work_policy_manager.h +++ b/services/native/include/work_policy_manager.h @@ -63,8 +63,6 @@ public: void WatchdogTimeOut(int32_t watchdogId); void SetFixMemory(int32_t memory); int32_t GetFixMemory(); - void SetRepeatCycleTimeMin(uint32_t repeatCycleTimeMax); - uint32_t GetRepeatCycleTimeMin(); void SetWatchdogTime(int time); int GetWatchdogTime(); @@ -105,7 +103,6 @@ private: int32_t watchdogId_; int32_t fixMemory_; - uint32_t repeatCycleTimeMin_; int watchdogTime_; }; } diff --git a/services/native/src/work_policy_manager.cpp b/services/native/src/work_policy_manager.cpp index 6880d32..8f79cd2 100644 --- a/services/native/src/work_policy_manager.cpp +++ b/services/native/src/work_policy_manager.cpp @@ -37,7 +37,6 @@ const int64_t DELAY_TIME_SHORT = 5000; const int MAX_WATCHDOG_ID = 1000; const int INIT_WATCHDOG_ID = 1; const int WATCHDOG_TIME = 2 * 60 * 1000; -const uint32_t CYCLE_TIME_MIN_DEFAULT = 20 * 60 * 1000; } WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) @@ -63,7 +62,6 @@ bool WorkPolicyManager::Init() watchdog_ = std::make_shared(wmsptr->GetWorkPolicyManager()); watchdogId_ = INIT_WATCHDOG_ID; fixMemory_ = -1; - repeatCycleTimeMin_ = CYCLE_TIME_MIN_DEFAULT; watchdogTime_ = WATCHDOG_TIME; return true; } @@ -449,16 +447,6 @@ void WorkPolicyManager::SetFixMemory(int32_t memory) fixMemory_ = memory; } -void WorkPolicyManager::SetRepeatCycleTimeMin(uint32_t repeatCycleTimeMax) -{ - repeatCycleTimeMin_ = repeatCycleTimeMax; -} - -uint32_t WorkPolicyManager::GetRepeatCycleTimeMin() -{ - return repeatCycleTimeMin_; -} - void WorkPolicyManager::SetWatchdogTime(int time) { watchdogTime_ = time; diff --git a/services/native/src/work_queue_manager.cpp b/services/native/src/work_queue_manager.cpp index a5af27d..5dba13a 100644 --- a/services/native/src/work_queue_manager.cpp +++ b/services/native/src/work_queue_manager.cpp @@ -22,11 +22,11 @@ const int TIME_CYCLE = 10 * 60 * 60; // 10min WorkQueueManager::WorkQueueManager(const wptr& wss) : wss_(wss) { + timeCycle_ = TIME_CYCLE; } bool WorkQueueManager::Init() { - timeCycle_ = TIME_CYCLE; return true; } diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index abe2d52..212c83f 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -59,7 +59,6 @@ static const string WORK_POLICY_INFO = "WorkPolicy"; static const string SET_FIX_MEMORY = "SetFixMemory"; static const string SET_REPEAT_CYCLE_TIME_MIN = "SetRepeatCycleTimeMin"; static const string SET_WATCHDOG_TIME = "SetWatchdogTime"; -static const string SET_CYCLE_TIME = "SetCycleTime"; static const string CHECK_BUNDLE = "CheckBundle"; static const string DEBUG_INFO = "DebugInfo"; } @@ -244,9 +243,9 @@ bool WorkSchedulerService::CheckCondition(WorkInfo& workInfo) } if (workInfo.GetConditionMap()->count(WorkCondition::Type::TIMER) > 0) { uint32_t time = workInfo.GetConditionMap()->at(WorkCondition::Type::TIMER)->uintVal; - if (time < workPolicyManager_->GetRepeatCycleTimeMin()) { + if (time < workQueueManager_->GetTimeCycle()) { WS_HILOGE("fail, set time:%{public}d must more than %{public}d", time, - workPolicyManager_->GetRepeatCycleTimeMin()); + workQueueManager_->GetTimeCycle()); return false; } } @@ -420,13 +419,10 @@ bool WorkSchedulerService::ShellDump(const vector &dumpOption, vectorSetFixMemory(std::stoi(dumpOption[2])); return true; - } else if (dumpOption[1] == SET_REPEAT_CYCLE_TIME_MIN) { - workPolicyManager_->SetRepeatCycleTimeMin(std::stoi(dumpOption[2])); - return true; } else if (dumpOption[1] == SET_WATCHDOG_TIME) { workPolicyManager_->SetWatchdogTime(std::stoi(dumpOption[2])); return true; - } else if (dumpOption[1] == SET_CYCLE_TIME) { + } else if (dumpOption[1] == SET_REPEAT_CYCLE_TIME_MIN) { workQueueManager_->SetTimeCycle(std::stoi(dumpOption[2])); return true; } else if (dumpOption[1] == WORK_QUEUE_INFO) { @@ -479,9 +475,8 @@ void WorkSchedulerService::DumpDebugInfo(std::vector &dumpInfo) { dumpInfo.push_back("Need check bundle:" + std::to_string(checkBundle_)); dumpInfo.push_back("Fix Memory:" + std::to_string(workPolicyManager_->GetFixMemory())); - dumpInfo.push_back("Repeat cycle time min:" + std::to_string(workPolicyManager_->GetRepeatCycleTimeMin())); + dumpInfo.push_back("Repeat cycle time min:" + std::to_string(workQueueManager_->GetTimeCycle())); dumpInfo.push_back("Watchdog time:" + std::to_string(workPolicyManager_->GetWatchdogTime())); - dumpInfo.push_back("Check cycle time:" + std::to_string(workQueueManager_->GetTimeCycle())); } void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) -- Gitee