diff --git a/bundle.json b/bundle.json index fbff8384dceba984ada5351927a954d316876c8c..75fd9b80951bd4307aeac5cc8467de02946cc498 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/unittest:workinfotest", + "//foundation/resourceschedule/work_scheduler/interfaces/test/unittest:js_unittest" ] } } diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ec6624ec880057bcc33179613cc9f698cecd6a7c --- /dev/null +++ b/frameworks/BUILD.gn @@ -0,0 +1,54 @@ +# 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" ] +} + +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_service_path}/zidl/src/work_sched_service_proxy.cpp", + ] + + configs = [ ":worksched_private_config" ] + + public_configs = [ ":worksched_public_config" ] + + deps = [ + "${worksched_utils_path}:workschedutils", + "//third_party/jsoncpp", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:runtime", + "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}" +} diff --git a/frameworks/extension/BUILD.gn b/frameworks/extension/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f397de639bfb35bfd8091276d1af50f93e29584e --- /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 = [ + "${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", + ] + + configs = [ ":worksched_private_config" ] + + public_configs = [ ":worksched_public_config" ] + + 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", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:runtime", + "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}" +} diff --git a/frameworks/extension/include/iwork_scheduler.h b/frameworks/extension/include/iwork_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..22b1c9aa385037f8ef17bad9f427242b014f2eb1 --- /dev/null +++ b/frameworks/extension/include/iwork_scheduler.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 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 0000000000000000000000000000000000000000..81ec17c161287c92e2b7f5ad5023e21653fea980 --- /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 0000000000000000000000000000000000000000..37cbb4525a666b552ac6ad7bfd2341ff961042fd --- /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 0000000000000000000000000000000000000000..d5f325d056493fa3e6777121add8f4b5dbd4b29c --- /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 0000000000000000000000000000000000000000..ca981814cfd5b5d9f2e42004dde629a8892c982a --- /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 0000000000000000000000000000000000000000..9f78832cd68f27e71d30fa204a14f761acdf91e5 --- /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 0000000000000000000000000000000000000000..da856b1ac913d082398ce9de8de59d8f68f3181d --- /dev/null +++ b/frameworks/extension/src/js_work_scheduler_extension.cpp @@ -0,0 +1,201 @@ +/* + * 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__); + + AbilityRuntime::HandleScope handleScope(jsRuntime_); + NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* jCommonEventData = nativeEngine.CreateObject(); + + 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() +{ + 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) +{ + 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 0000000000000000000000000000000000000000..b62b0c3cff22b382854245d9d77a81aab7573e62 --- /dev/null +++ b/frameworks/extension/src/js_work_scheduler_extension_context.cpp @@ -0,0 +1,54 @@ +/* + * 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 "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) + { + std::unique_ptr( + static_cast(data)); + } +private: + std::weak_ptr context_; +}; +} // namespace + +NativeValue* CreateJsWorkSchedulerExtensionContext(NativeEngine& engine, + std::shared_ptr context) +{ + 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 0000000000000000000000000000000000000000..c5f20b8c3fc8c2a9ba54875b583fcfd58d5d4f1b --- /dev/null +++ b/frameworks/extension/src/work_scheduler_extension.cpp @@ -0,0 +1,64 @@ +/* + * 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.h" + +#include "ability_loader.h" +#include "js_work_scheduler_extension.h" + +namespace OHOS { +namespace WorkScheduler { +WorkSchedulerExtension* WorkSchedulerExtension::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new WorkSchedulerExtension(); + } + 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) +{ + 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) { + 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 0000000000000000000000000000000000000000..47edff3c93e8902494ad22abda511e059810a6dc --- /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 0000000000000000000000000000000000000000..e94d4303e6ba18895f94546eb0dd2709c88e3003 --- /dev/null +++ b/frameworks/extension/src/work_scheduler_extension_module_loader.cpp @@ -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. + */ + +#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_sched_service.h b/frameworks/include/iwork_sched_service.h new file mode 100644 index 0000000000000000000000000000000000000000..34855fac8b22ff367a6efd6aa0bb65609957323c --- /dev/null +++ b/frameworks/include/iwork_sched_service.h @@ -0,0 +1,54 @@ +/* + * 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_IWORK_SCHED_SERVICE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 72% rename from interfaces/innerkits/native/include/work_condition.h rename to frameworks/include/work_condition.h index 0491c412eadb833ba87ca7c16bcecebed4b4d128..8f549d40a026923708a928623fc1daaeb5c31366 100644 --- a/interfaces/innerkits/native/include/work_condition.h +++ b/frameworks/include/work_condition.h @@ -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, @@ -46,28 +40,25 @@ public: NETWORK_TYPE_BLUETOOTH, NETWORK_TYPE_WIFI_P2P, NETWORK_TYPE_ETHERNET, - NETWORK_TYPE_DISCONNECT, 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, @@ -83,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 new file mode 100644 index 0000000000000000000000000000000000000000..b18f0bffaef1cfebe4e70fcb4ac0f38b5a48e1ea --- /dev/null +++ b/frameworks/include/work_info.h @@ -0,0 +1,73 @@ +/* + * 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_INFO_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..3f7b127b3b35017aacc51088b03fe833f7d7b51b --- /dev/null +++ b/frameworks/include/workscheduler_srv_client.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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKSCHEDDULER_SRV_CLIENT_H \ No newline at end of file diff --git a/frameworks/src/work_info.cpp b/frameworks/src/work_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e279e3abe13b1d301a060179b245267c22fe70f1 --- /dev/null +++ b/frameworks/src/work_info.cpp @@ -0,0 +1,369 @@ +/* + * 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_info.h" + +#include "work_sched_common.h" + +namespace OHOS { +namespace WorkScheduler { +WorkInfo::WorkInfo() {} + +WorkInfo::~WorkInfo() {} + +void WorkInfo::SetWorkId(int32_t workId) +{ + workId_ = workId; +} + +void WorkInfo::SetElement(std::string bundleName, std::string abilityName) +{ + bundleName_ = bundleName; + abilityName_ = abilityName; +} + +void WorkInfo::RequestPersisted(bool persisted) +{ + persisted_ = persisted; +} + +void WorkInfo::RequestNetworkType(WorkCondition::Network condition) +{ + 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) +{ + std::shared_ptr chargerCondition = std::make_shared(); + chargerCondition->boolVal = isCharging; + chargerCondition->enumVal = static_cast(condition); + conditionMap_.emplace(WorkCondition::Type::CHARGER, chargerCondition); +} + +void WorkInfo::RequestBatteryLevel(int32_t battLevel) +{ + std::shared_ptr batteryLevelCondition = std::make_shared(); + batteryLevelCondition->intVal = battLevel; + conditionMap_.emplace(WorkCondition::Type::BATTERY_LEVEL, batteryLevelCondition); +} + +void WorkInfo::RequestBatteryStatus(WorkCondition::BatteryStatus condition) +{ + 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) +{ + 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) +{ + std::shared_ptr repeatCycle = std::make_shared(); + repeatCycle->uintVal = timeInterval; + repeatCycle->intVal = cycle; + repeatCycle->boolVal = false; + conditionMap_.emplace(WorkCondition::Type::TIMER, repeatCycle); +} + +void WorkInfo::RequestRepeatCycle(uint32_t timeInterval) +{ + std::shared_ptr repeatCycle = std::make_shared(); + repeatCycle->uintVal = timeInterval; + repeatCycle->boolVal = true; + conditionMap_.emplace(WorkCondition::Type::TIMER, repeatCycle); +} + +int32_t WorkInfo::GetWorkId() +{ + return workId_; +} + +std::string WorkInfo::GetBundleName() +{ + return bundleName_; +} + +std::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::CHARGING_UNKNOWN; +} + +int32_t WorkInfo::GetBatteryLevel() +{ + if (conditionMap_.count(WorkCondition::Type::BATTERY_LEVEL) > 0) { + return conditionMap_.at(WorkCondition::Type::BATTERY_LEVEL)->intVal; + } + return -1; +} + +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; +} + +std::shared_ptr>> WorkInfo::GetConditionMap() +{ + return std::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_ = std::map>(); + for (size_t i = 0; i < mapsize; i++) { + int32_t key = parcel.ReadInt32(); + auto condition = std::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; +} + +std::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; + std::ostringstream os; + std::unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + jsonWriter->write(root, &os); + std::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(std::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 0000000000000000000000000000000000000000..43ab5c522024a300689cb00c753e7ddfef455e6d --- /dev/null +++ b/frameworks/src/workscheduler_srv_client.cpp @@ -0,0 +1,188 @@ +/* + * 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("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_CLIENT_CONNECT_SERVICE_FAILED; + } + deathRecipient_ = sptr(new WorkSchedulerDeathRecipient()); + if (deathRecipient_ == nullptr) { + WS_HILOGE("Failed to create WorkScheduelrDeathRecipient!"); + return E_CLIENT_CONNECT_SERVICE_FAILED; + } + if ((remoteObject_->IsProxyObject()) && (!remoteObject_->AddDeathRecipient(deathRecipient_))) { + WS_HILOGE("Add death recipient to WorkSchedulerService failed!"); + return E_CLIENT_CONNECT_SERVICE_FAILED; + } + iWorkSchedService_ = iface_cast(remoteObject_); + WS_HILOGD("Connecting WorkSchedService success."); + 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("StartWork"); + 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("StopWork"); + 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("StopAndCancelWork"); + 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("StopAndClearWorks"); + if (Connect() != ERR_OK) { + WS_HILOGE("StopAndClearWorks connect service failed!"); + return false; + } + return iWorkSchedService_->StopAndClearWorks(); +} + +ErrCode WorkSchedulerSrvClient::IsLastWorkTimeout(int32_t workId, bool &result) +{ + WS_HILOGD("IsLastWorkTimeout"); + ErrCode errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + result = iWorkSchedService_->IsLastWorkTimeout(workId); + return ERR_OK; +} + +ErrCode WorkSchedulerSrvClient::ObtainAllWorks(std::list> &workInfos) +{ + WS_HILOGD("ObtainAllWorks"); + 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("GetWorkStatus"); + if (workId <= 0) { + return E_WORK_ID_INVALID; + } + ErrCode code = Connect(); + if (code != ERR_OK) { + return code; + } + int32_t uid = IPCSkeleton::GetCallingUid(); + workInfo = iWorkSchedService_->GetWorkStatus(uid, workId); + if (workInfo == nullptr) { + return E_GET_WORK_STATUS_ERROR; + } + return ERR_OK; +} + +bool WorkSchedulerSrvClient::ShellDump(const std::vector &dumpOption, + std::vector &dumpInfo) +{ + 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())); + 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/unittest/BUILD.gn similarity index 70% rename from test/constanttest/BUILD.gn rename to frameworks/test/unittest/BUILD.gn index 427ff52589f7bdd54c0d15f17409989854c4b554..cc79dcac4941d55996df02089287ee2f76e7d2d8 100644 --- a/test/constanttest/BUILD.gn +++ b/frameworks/test/unittest/BUILD.gn @@ -14,13 +14,13 @@ import("//build/test.gni") import("//foundation/resourceschedule/work_scheduler/workscheduler.gni") -module_output_path = "work_scheduler/constanttest" -ohos_systemtest("WorkSchedulerConstantTest") { +module_output_path = "work_scheduler/work_info_unittest" +ohos_systemtest("WorkSchedulerWorkInfoTest") { module_out_path = module_output_path - sources = [ "constant_test.cpp" ] + sources = [ "src/workinfo_test.cpp" ] - include_dirs = [ "${worksched_native_innerkits_path}/native/include" ] + include_dirs = [ "include" ] cflags = [] @@ -28,13 +28,17 @@ ohos_systemtest("WorkSchedulerConstantTest") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ "//third_party/googletest:gtest_main" ] + deps = [ + "${worksched_frameworks_path}:workschedclient", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp", + ] external_deps = [ "utils_base:utils" ] } -group("constanttest") { +group("workinfotest") { testonly = true - deps = [ ":WorkSchedulerConstantTest" ] + deps = [ ":WorkSchedulerWorkInfoTest" ] } diff --git a/frameworks/test/unittest/include/workinfo_test.h b/frameworks/test/unittest/include/workinfo_test.h new file mode 100644 index 0000000000000000000000000000000000000000..b37c3f47a8cd8f48a37375fb5c3cc525fc29d12e --- /dev/null +++ b/frameworks/test/unittest/include/workinfo_test.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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORKINFO_TEST_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..d47bdf96931ea1a65527666874131be919cda21a --- /dev/null +++ b/frameworks/test/unittest/src/workinfo_test.cpp @@ -0,0 +1,229 @@ +/* + * 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" + +#include "work_info.h" + +using namespace std; +using namespace testing::ext; + +namespace OHOS { +namespace WorkScheduler { +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 + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 + */ +HWTEST_F (WorkInfoTest, WorkInfoTest001, Function | MediumTest | 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 + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 + */ +HWTEST_F (WorkInfoTest, WorkInfoTest002, Function | MediumTest | 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 + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 + */ +HWTEST_F (WorkInfoTest, WorkInfoTest003, Function | MediumTest | 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 + * @tc.require: SR000GGTN6 AR000GH896 AR000GH897 AR000GH898 + */ +HWTEST_F (WorkInfoTest, WorkInfoTest004, Function | MediumTest | Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestChargerType(true, WorkCondition::Charger::CHARGING_PLUGGED_ANY); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGING_PLUGGED_ANY); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestChargerType(false, WorkCondition::Charger::CHARGING_UNPLUGGED); + EXPECT_EQ(workInfo.GetChargerType(), WorkCondition::Charger::CHARGING_UNPLUGGED); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_STATUS_LOW_OR_OKAY); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestBatteryStatus(WorkCondition::BatteryStatus::BATTERY_STATUS_LOW); + EXPECT_EQ(workInfo.GetBatteryStatus(), WorkCondition::BatteryStatus::BATTERY_STATUS_LOW); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + 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 change + * @tc.type FUNC + * @tc.require: SR000GGTN9 AR000GH89M + */ +HWTEST_F (WorkInfoTest, WorkInfoTest009, Function | MediumTest | Level0) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_LOW_OR_OKAY); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_LOW); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_LOW); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestStorageLevel(WorkCondition::Storage::STORAGE_LEVEL_OKAY); + EXPECT_EQ(workInfo.GetStorageLevel(), WorkCondition::Storage::STORAGE_LEVEL_OKAY); +} + +/** + * @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) +{ + WorkInfo workInfo = WorkInfo(); + workInfo.RequestNetworkType(WorkCondition::Network::NETWORK_TYPE_ANY); + EXPECT_EQ(workInfo.GetNetworkType(), WorkCondition::Network::NETWORK_TYPE_ANY); +} + +/** + * @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) +{ + 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 + * @tc.require: SR000GGTNA AR000GH89P AR000GH89N AR000GH89O + */ +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/@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 ac4f3bdc8906927e5a5c52e5de9c9a7ef54b7ad3..79af9ba1e6473c3f3615c39d9e68e4d65b782d2f 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", + "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", ] 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 0000000000000000000000000000000000000000..1960991029b801872870dcf32a261775ba488c0e --- /dev/null +++ b/interfaces/kits/js/napi/include/common.h @@ -0,0 +1,61 @@ +/* + * 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_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 Common { +public: + static napi_value NapiGetNull(napi_env env); + 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); + 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); + +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); +}; +} +} +#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 0000000000000000000000000000000000000000..801265b276f81b504840cbdb8648e1b7757a983d --- /dev/null +++ b/interfaces/kits/js/napi/include/get_work_status.h @@ -0,0 +1,28 @@ +/* + * 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_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 0000000000000000000000000000000000000000..3f856cca37eaa748ff81eded2afd5b7f9d10a0c0 --- /dev/null +++ b/interfaces/kits/js/napi/include/is_last_work_time_out.h @@ -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. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_IS_LAST_WORK_TIMEOUT + +#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 0000000000000000000000000000000000000000..7efd7acb6eb5863c614db14dd4a282d2c1585227 --- /dev/null +++ b/interfaces/kits/js/napi/include/obtain_all_works.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_OBTAIN_ALL_WORKS + +#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 0000000000000000000000000000000000000000..4b0cc6c16de6edd6d441282fd8a77da6a4c8e570 --- /dev/null +++ b/interfaces/kits/js/napi/include/start_work.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_START_WORK + +#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 0000000000000000000000000000000000000000..46357294ce67c8ec3c5058c2951ea0f8eebdb705 --- /dev/null +++ b/interfaces/kits/js/napi/include/stop_and_clear_works.h @@ -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. + */ +#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 "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 0000000000000000000000000000000000000000..d3bf174ef5dbce42ae6a2efed0d6362cc4d18458 --- /dev/null +++ b/interfaces/kits/js/napi/include/stop_work.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_INTERFACES_KITS_NAPI_INCLUDE_STOP_WORK + +#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 69be5cfd8a188cb0c881e57808b7a3360c5e7a38..69d07945f29af6274a353408ed2eb20ed5956f70 100644 --- a/interfaces/kits/js/napi/include/workscheduler_napi.h +++ b/interfaces/kits/js/napi/include/workscheduler_napi.h @@ -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" @@ -49,10 +48,10 @@ 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} }; -} -} +} // 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 new file mode 100644 index 0000000000000000000000000000000000000000..4fe196b7c0189f86cfe0b88856ed55962e65149d --- /dev/null +++ b/interfaces/kits/js/napi/src/common.cpp @@ -0,0 +1,422 @@ +/* + * 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 "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_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) +{ + napi_value result = nullptr; + napi_get_null(env, &result); + return result; +} + +bool Common::GetBaseWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ + // 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; + } + + // 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::CHARGING_UNPLUGGED); + hasCondition = true; + } else { + if (chargerType == UNSET_INT_PARAM) { + 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::CHARGING_PLUGGED_ANY); + WS_HILOGI("ChargeType info is invalid, just ignore set."); + } + hasCondition = true; + } + 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 >= BATTERY_LEVEL_MIN && batteryLevel <= BATTERY_LEVEL_MAX) { + workInfo.RequestBatteryLevel(batteryLevel); + hasCondition = true; + } else { + WS_HILOGI("BatteryLevel set is invalid, just ignore set."); + } + + // 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."); + } + 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."); + } + return hasCondition; +} + +bool Common::GetRepeatInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ + 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; + } + + 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) { + if (repeatCount > 0) { + WS_HILOGI("RepeatCount has been set , ignore isRepeat."); + workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount); + } else { + workInfo.RequestRepeatCycle(repeatCycleTime); + } + return true; + } else { + if (repeatCount < 0) { + WS_HILOGI("RepeatCount is invalid, ignore."); + return false; + } + workInfo.RequestRepeatCycle(repeatCycleTime, repeatCount); + return true; + } +} + +bool Common::GetWorkInfo(napi_env env, napi_value objValue, WorkInfo &workInfo) +{ + // 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_INT_PARAM; + 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 ? TRUE_PARAM : FALSE_PARAM; + } + } + return UNSET_INT_PARAM; +} + +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 UNSET_STRING_PARAM; +} + +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); + + // Set base info. + napi_value napiWorkId = nullptr; + napi_value napiBundleName = nullptr; + napi_value napiAbilityName = 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_set_named_property(env, napiWork, "workId", napiWorkId); + napi_set_named_property(env, napiWork, "bundleName", napiBundleName); + napi_set_named_property(env, napiWork, "abilityName", napiAbilityName); + + // 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; +} + +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); + } +} +} +} \ 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 new file mode 100644 index 0000000000000000000000000000000000000000..599ad9aa0d913c445ba7f96f0a68d256ae048234 --- /dev/null +++ b/interfaces/kits/js/napi/src/get_work_status.cpp @@ -0,0 +1,123 @@ +/* + * 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 "get_work_status.h" + +#include "common.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; +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("Get work status napi begin."); + + // 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)); + + WS_HILOGD("Get work status napi end."); + 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 0000000000000000000000000000000000000000..d7578cfce9966ea4867a6177ce635310da11645a --- /dev/null +++ b/interfaces/kits/js/napi/src/is_last_work_time_out.cpp @@ -0,0 +1,127 @@ +/* + * 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 "is_last_work_time_out.h" + +#include "common.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; +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("IsLastWorkTimeOut napi begin."); + + // 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)); + + WS_HILOGD("IsLastWorkTimeOut napi end."); + 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 0000000000000000000000000000000000000000..efd264983afaabaff1e1cfc7985338530cd0c07b --- /dev/null +++ b/interfaces/kits/js/napi/src/obtain_all_works.cpp @@ -0,0 +1,116 @@ +/* + * 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 "obtain_all_works.h" + +#include "common.h" +#include "workscheduler_srv_client.h" +#include "work_sched_hilog.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("ObtainAllWorks napi begin."); + + // 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)); + WS_HILOGD("ObtainAllWorks napi end."); + 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 0000000000000000000000000000000000000000..365f286acdfee48adc221552bd7d5f8bcbcfa83f --- /dev/null +++ b/interfaces/kits/js/napi/src/start_work.cpp @@ -0,0 +1,52 @@ +/* + * 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 "start_work.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("Start work napi begin."); + + // 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, it should be object"); + + // 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; +} +} +} 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 0000000000000000000000000000000000000000..d206a2b355da85840fee9de3a8db7abdb9e9c47d --- /dev/null +++ b/interfaces/kits/js/napi/src/stop_and_clear_works.cpp @@ -0,0 +1,32 @@ +/* + * 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 "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("StopAndClearWorks napi begin"); + napi_value napiValue = nullptr; + bool result = WorkSchedulerSrvClient::GetInstance().StopAndClearWorks(); + NAPI_CALL(env, napi_get_boolean(env, result, &napiValue)); + WS_HILOGD("StopAndClearWorks napi end. result: %{public}s", result ? "true" : "false"); + return napiValue; +} +} +} 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 0000000000000000000000000000000000000000..c478988c1cf6266abd0eecec5c471014ffdb56a3 --- /dev/null +++ b/interfaces/kits/js/napi/src/stop_work.cpp @@ -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. + */ +#include "stop_work.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 NEED_CANCEL_INDEX = 1; +static const int32_t STOP_WORK_PARAMS = 2; + +napi_value StopWork(napi_env env, napi_callback_info info) +{ + WS_HILOGD("Stop Work napi begin."); + + // 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 + 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); + + // Check workInfo and call service. + bool result; + if (!getWorkRes) { + WS_HILOGD("Work info create failed."); + result = false; + } else { + 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; +} +} +} \ 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 c39f61a36b165c8d6987a4bdd2b88940637676ed..6a2dde6012063419776fed3688eb4749484a3325 100644 --- a/interfaces/kits/js/napi/src/workscheduler_napi.cpp +++ b/interfaces/kits/js/napi/src/workscheduler_napi.cpp @@ -14,6 +14,13 @@ */ #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" @@ -30,7 +37,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("Work scheduler napi init."); + 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 +60,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; @@ -52,15 +68,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), @@ -72,49 +91,46 @@ 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__); 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(MODULE_JS_NAPI, "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(MODULE_JS_NAPI, "%{public}s: return", __func__); - return jsthis; + + return res; } 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; 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), + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_ANY), + &charging_plugged_any); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_AC), + &charging_plugged_ac); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_USB), + &charging_plugged_usb); + napi_create_uint32(env, static_cast(WorkCondition::Charger::CHARGING_PLUGGED_WIRELESS), &charging_plugged_wireless); napi_property_descriptor desc[] = { @@ -125,8 +141,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; @@ -134,36 +150,32 @@ 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; + 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(MODULE_JS_NAPI, "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(MODULE_JS_NAPI, "%{public}s: return", __func__); - return jsthis; + + return res; } 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 +184,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; @@ -181,25 +193,20 @@ 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__); 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(MODULE_JS_NAPI, "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(MODULE_JS_NAPI, "%{public}s: return", __func__); - return jsthis; + return res; } 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; @@ -219,7 +226,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; @@ -227,20 +235,17 @@ 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__); 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(MODULE_JS_NAPI, "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(MODULE_JS_NAPI, "%{public}s: return", __func__); - return jsthis; + + return res; } /* @@ -251,5 +256,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/kits/js/napi/work_scheduler_extension/BUILD.gn b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..adc23e7114f1f58339080c70b43ed1df1fdf7d24 --- /dev/null +++ b/interfaces/kits/js/napi/work_scheduler_extension/BUILD.gn @@ -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. + +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 0000000000000000000000000000000000000000..7736cff2196c16187de1719a187503f7e2e85d2d --- /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 0000000000000000000000000000000000000000..c9c37a7c06abb6ae29a436d73b666bc15e9964ec --- /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 0000000000000000000000000000000000000000..513168e4cc3b0e3e9d3f027467ba50dca59a870f --- /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 0000000000000000000000000000000000000000..0a6957a58b50dfdd2c350fcd39e896348f9d06df --- /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 0000000000000000000000000000000000000000..54e9d0f84ff1e252276c83a9c566f4af9cfb1414 --- /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/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..470a8eddd390c2302f6dea079ae62d0bb6b6c7fb --- /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/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 0000000000000000000000000000000000000000..a7dc22c0d54044132b7fb73dfbea20e8c0d0014b --- /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 0000000000000000000000000000000000000000..df7aba5b41449748bc42c9fb922cdc4bf9d1a9e9 --- /dev/null +++ b/interfaces/test/unittest/work_scheduler_jsunittest/work_scheduler_jsunit.test.js @@ -0,0 +1,408 @@ +/* + * 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: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("WorkSchedulerJsTest001", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest001---------------------------'); + let workInfo = { + workId: -1, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("WorkSchedulerJsTest002", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest002---------------------------'); + let workInfo = { + workId: 0, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C + */ + 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: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C + */ + it("WorkSchedulerJsTest004", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest004---------------------------'); + let workInfo = { + workId: 4, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89A AR000GH89B AR000GH89C + */ + it("WorkSchedulerJsTest005", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest005---------------------------'); + let workInfo = { + workId: 5, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89D + */ + it("WorkSchedulerJsTest006", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest006---------------------------'); + let workInfo = { + workId: 6, + bundleName: "com.example.myapplication", + abilityName: "com.mytest.abilityName", + storageRequest: workScheduler.StorageRequest.STORAGE_LEVEL_OKAY + } + var res = workScheduler.startWork(workInfo); + expect(res).assertEqual(true) + done(); + }) + + /* + * @tc.name: WorkSchedulerJsTest007 + * @tc.desc: test stopWork. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89D + */ + it("WorkSchedulerJsTest007", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest007---------------------------'); + let workInfo = { + workId: 7, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("WorkSchedulerJsTest008", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest008---------------------------'); + let workInfo = { + workId: 8, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("WorkSchedulerJsTest009", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest009---------------------------'); + let workInfo = { + workId: 9, + bundleName: "com.example.myapplication", + 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(9, (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: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("WorkSchedulerJsTest010", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest010---------------------------'); + let workInfo = { + workId: 10, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("WorkSchedulerJsTest011", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest011---------------------------'); + let workInfo = { + workId: 11, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("WorkSchedulerJsTest012", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest012---------------------------'); + let workInfo = { + workId: 12, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("WorkSchedulerJsTest013", 0, async function (done) { + console.info('----------------------WorkSchedulerJsTest013---------------------------'); + let workInfo = { + workId: 13, + bundleName: "com.example.myapplication", + 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: SR000GGTN7 AR000GH89D + */ + 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: SR000GGTN7 AR000GH89D + */ + 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/sa_profile/1904.xml b/sa_profile/1904.xml index 958b9e7c8c3b4a02bff2f2b608f7f64025822687..edb1b0c336c9f789f362c0cb78f21ba6cd60ea6b 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 cac1e495a0dbce1e4430b6a0827b7404925186b5..c58842ac58a4fed3477d82577289a8767a98c5b7 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 c1c874c4758535abedd7b9b84dc79977f02ca66d..d1aad818f085f604fbd80f3fa85adaecaa44d634 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 f80d5c773c4f741065deb902d77af9bfb729c3b1..01b7e504b5fa918809a7a8e0bd8da2f98595bc0a 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -13,22 +13,64 @@ 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/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/watchdog.cpp", + "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_sched_service_stub.cpp", + "zidl/src/work_scheduler_proxy.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:app_manager", + "ability_runtime:want", + "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", + "thermal_manager_native:thermalsrv_client", "utils_base:utils", ] 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 0000000000000000000000000000000000000000..4c202f2254840331312789183833ad1f33431b78 --- /dev/null +++ b/services/native/include/conditions/battery_level_listener.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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_LEVEL_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_LEVEL_LISTENER_H + +#include + +#include "common_event_subscriber.h" +#include "icondition_listener.h" +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueueManager; +class BatteryLevelListener; +class BatteryLevelEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + BatteryLevelEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryLevelListener &listener); + ~BatteryLevelEventSubscriber() override = default; + void OnReceiveEvent(const EventFwk::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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..b7c3de037dcde556455cd9cb95b6ac1e5e996900 --- /dev/null +++ b/services/native/include/conditions/battery_status_listener.h @@ -0,0 +1,52 @@ +/* + * 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_CONDITIONS_BATTERY_STATUS_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_BATTERY_STATUS_LISTENER_H + +#include + +#include "common_event_subscriber.h" +#include "icondition_listener.h" +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueueManager; +class BatteryStatusListener; +class BatteryStatusEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + BatteryStatusEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryStatusListener &listener); + ~BatteryStatusEventSubscriber() override = default; + void OnReceiveEvent(const EventFwk::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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..3fde124d26cfa413200ffc4a70e9346efe0b5508 --- /dev/null +++ b/services/native/include/conditions/charger_listener.h @@ -0,0 +1,52 @@ +/* + * 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_CONDITIONS_CHARGER_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_CHARGER_LISTENER_H + +#include + +#include "common_event_subscriber.h" +#include "icondition_listener.h" +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueueManager; +class ChargerListener; +class ChargerEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + ChargerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + ChargerListener &listener); + ~ChargerEventSubscriber() override = default; + void OnReceiveEvent(const EventFwk::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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_CHARGER_LISTENER_H \ No newline at end of file diff --git a/services/native/include/conditions/icondition_listener.h b/services/native/include/conditions/icondition_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..100d3b6f0049c5635616afed96891360da45917c --- /dev/null +++ b/services/native/include/conditions/icondition_listener.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_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_H + +#include + +#include "detector_value.h" +#include "work_condition.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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_ICONDITION_LISTENER_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 0000000000000000000000000000000000000000..56f4589ce1d5881724e248c6cfc10c6cfa16f07a --- /dev/null +++ b/services/native/include/conditions/network_listener.h @@ -0,0 +1,49 @@ +/* + * 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_CONDITIONS_NETWORK_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_NETWORK_LISTENER_H + +#include + +#include "common_event_subscriber.h" +#include "icondition_listener.h" +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class NetworkListener; +class NetworkEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + NetworkEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, NetworkListener &listener); + ~NetworkEventSubscriber() override = default; + void OnReceiveEvent(const EventFwk::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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..508ac58efb19ea9c5f3cf5508077e3ffe79c3a76 --- /dev/null +++ b/services/native/include/conditions/storage_listener.h @@ -0,0 +1,51 @@ +/* + * 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_CONDITIONS_STORAGE_LISTENER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_CONDITIONS_STORAGE_LISTENER_H + +#include + +#include "common_event_subscriber.h" +#include "icondition_listener.h" +#include "work_queue_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkQueueManager; +class StorageListener; +class StorageEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + StorageEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, StorageListener &listener); + ~StorageEventSubscriber() override = default; + void OnReceiveEvent(const EventFwk::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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..d8f5c6aa02fd183f94b3544791d77a30081389f6 --- /dev/null +++ b/services/native/include/conditions/timer_listener.h @@ -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. + */ +#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_event_handler.h" +#include "work_queue_manager.h" +#include "work_scheduler_service.h" + +namespace OHOS { +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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..94243a3b3d5d10831ae9c12bd909ce6899875b7b --- /dev/null +++ b/services/native/include/detector_value.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_DETECTOR_VALUE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_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), strVal(strVal) {} +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_DETECTOR_VALUE_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 0000000000000000000000000000000000000000..ebe6e8e1e084a22c6b27d8e2c5e9da7ef00f446d --- /dev/null +++ b/services/native/include/ipolicy_listener.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_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_DETECTOR_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 0000000000000000000000000000000000000000..fcb3fff9f6138ed32bf8f39186665cbb039445eb --- /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/ipolicy_filter.h b/services/native/include/policy/ipolicy_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..54e5d86a3ac5a404f3e0ceecf9c54127adf3d00b --- /dev/null +++ b/services/native/include/policy/ipolicy_filter.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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_FILTER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_IPOLICY_FILTER_H + +#include + +namespace OHOS { +namespace WorkScheduler { +class IPolicyFilter { +public: + virtual ~IPolicyFilter() = default; + virtual int32_t getPolicyMaxRunning(); + static const int32_t CANNOT_RUNNING_MORE = -1; + static const int32_t MAX_RUNNING_COUNT = 3; +}; +} // namespace WorkScheduler +} // namespace OHOS +#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 new file mode 100644 index 0000000000000000000000000000000000000000..f684225901ba5ab21bd9f0a6e62b024d40b3c065 --- /dev/null +++ b/services/native/include/policy/memory_policy.h @@ -0,0 +1,42 @@ +/* + * 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_MEMORY_POLICY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_MEMORY_POLICY_H + +#include + +#include "ipolicy_filter.h" +#include "work_policy_manager.h" + +namespace OHOS { +namespace WorkScheduler { +class MemoryPolicy : public IPolicyFilter { +public: + MemoryPolicy(std::shared_ptr workPolicyManager); + ~MemoryPolicy(); + 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 = 1; + const int32_t COUNT_MEMORY_LOW = 2; + const int32_t COUNT_MEMORY_NORMAL = 3; +private: + int32_t GetMemAvailable(); + std::shared_ptr workPolicyManager_; +}; +} +} +#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 new file mode 100644 index 0000000000000000000000000000000000000000..2c6ee2e9d498a1ea53b4b973645d822cbafd71b3 --- /dev/null +++ b/services/native/include/policy/thermal_policy.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 FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_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 getPolicyMaxRunning() override; +private: + std::shared_ptr workPolicyManager_; + 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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_THERMAL_POLICY_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 0000000000000000000000000000000000000000..f7e852b87162d1f307a8a0237777928efe63bb16 --- /dev/null +++ b/services/native/include/policy_type.h @@ -0,0 +1,26 @@ +/* + * 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_POLICY_TYPE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_POLICY_TYPE_H + +namespace OHOS { +namespace WorkScheduler { +enum PolicyType { + APP_REMOVED = 0 +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_POLICY_TYPE_H \ No newline at end of file diff --git a/services/native/include/watchdog.h b/services/native/include/watchdog.h new file mode 100644 index 0000000000000000000000000000000000000000..c6badc03ecb0eae25f4bd5f6728186c536fdb2cc --- /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_conn_manager.h b/services/native/include/work_conn_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..82427fe4f6d3ac0ba19f4c1294ce2c9c6d19b8af --- /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_scheduler_connection.h" +#include "work_status.h" +#include "errors.h" + +namespace OHOS { +using namespace Utils; +namespace WorkScheduler { +class WorkConnManager { +public: + bool StartWork(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 eventIdMap_; +}; +} // 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 0000000000000000000000000000000000000000..b8e5191cb2d770840f218637ed24049e3fd26d46 --- /dev/null +++ b/services/native/include/work_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_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, + INIT_PERSISTED_MSG, + }; + 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 0000000000000000000000000000000000000000..94de0500eb55367a639952031b9e90e5d3ddd136 --- /dev/null +++ b/services/native/include/work_policy_manager.h @@ -0,0 +1,111 @@ +/* + * 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_SERVICES_POLICY_MANAGER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICES_POLICY_MANAGER_H +#include +#include +#include +#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" +#include "work_queue.h" +#include "work_scheduler_service.h" +#include "work_sched_common.h" +#include "work_status.h" + +namespace OHOS { +namespace WorkScheduler { +class WorkSchedulerService; +class WorkEventHandler; +class AppRemovedListener; +class Watchdog; +class WorkPolicyManager { +public: + const size_t MAX_WORK_COUNT_PER_UID = 10; + 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, 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); + 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); + void AddAppRemoveListener(std::shared_ptr listener); + void WatchdogTimeOut(int32_t watchdogId); + void SetFixMemory(int32_t memory); + int32_t GetFixMemory(); + void SetWatchdogTime(int time); + int GetWatchdogTime(); + +private: + int32_t GetMaxRunningCount(); + 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 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(); + int32_t NewWatchDogId(); + void AddWatchdogForWork(std::shared_ptr workStatus); + std::shared_ptr GetWorkFromWatchdog(int32_t id); + + const wptr wss_; + std::shared_ptr workConnManager_; + std::shared_ptr handler_; + + std::mutex uidMapMutex_; + std::map> uidQueueMap_; + + std::mutex conditionReadyMutex_; + std::shared_ptr conditionReadyQueue_; + + std::list> policyFilters_; + std::shared_ptr appRemovedListener_; + + std::shared_ptr watchdog_; + + std::mutex watchdogIdMapMutex_; + std::map> watchdogIdMap_; + + int32_t watchdogId_; + int32_t fixMemory_; + int watchdogTime_; +}; +} +} // namespace OHOS + +#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 new file mode 100644 index 0000000000000000000000000000000000000000..86395bf74a05e0dad1fca3db5c1bac3979dbaeb7 --- /dev/null +++ b/services/native/include/work_queue.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_QUEUE_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 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_; +}; +class WorkComp { +public: + bool operator () (const std::shared_ptr w1, const std::shared_ptr w2); +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 0000000000000000000000000000000000000000..427787b76f1386f67e8ba6e766b534eb2e5db3e9 --- /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 0000000000000000000000000000000000000000..0c0e23c23b50accd850fdf6ae1f51ab088f5f5d7 --- /dev/null +++ b/services/native/include/work_queue_manager.h @@ -0,0 +1,62 @@ +/* + * 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_QUEUE_MANAGER_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 "conditions/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 CancelWork(std::shared_ptr workStatus); + + 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: + std::vector> GetReayQueue(WorkCondition::Type conditionType, + std::shared_ptr conditionVal); + std::mutex mutex_; + const wptr wss_; + std::map> queueMap_; + std::map> listenerMap_; + + int timeCycle_; +}; +} // namespace WorkScheduler +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 0000000000000000000000000000000000000000..bd0f8e381273cbb2a29faa85a8391535938985bb --- /dev/null +++ b/services/native/include/work_scheduler_connection.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 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 StopWork(); + 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 42bf7d8030180a534e0b244bfab5e022430e1ac2..9820306f7311dc3ec49dcccdc46da109e489dd58 100644 --- a/services/native/include/work_scheduler_service.h +++ b/services/native/include/work_scheduler_service.h @@ -13,31 +13,98 @@ * 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 "refbase.h" -#include "singleton.h" -#include "system_ability.h" -#include "system_ability_definition.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +#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" +#include "work_sched_service_stub.h" +#include "work_status.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; + void InitPersisted(); + 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); + void WatchdogTimeOut(std::shared_ptr workStatus); + + std::shared_ptr GetHandler() + { + return handler_; + } + + std::shared_ptr GetWorkQueueManager() + { + return workQueueManager_; + } + + std::shared_ptr GetWorkPolicyManager() + { + return workPolicyManager_; + } private: - bool Init(); + const char* PERSISTED_FILE_PATH = "/data/workscheduler/persisted"; + const char* PERSISTED_PATH = "/data/workscheduler/"; + const char* PERSISTED_FILE = "persisted"; + + std::shared_ptr workQueueManager_; + std::shared_ptr workPolicyManager_; + std::mutex mutex_; + std::map> persistedMap_; bool ready_ {false}; + std::shared_ptr handler_; + std::shared_ptr eventRunner_; + bool checkBundle_; + + bool Init(); + void WorkQueueManagerInit(); + bool WorkPolicyManagerInit(); + void RefreshPersistedWorks(); + std::list> ReadPersistedWorks(); + void InitPersistedWork(WorkInfo& workInfo); + void DumpAllInfo(std::vector &dumpInfo); + 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 isTimeOut); + bool CheckCondition(WorkInfo& workInfo); + void DumpDebugInfo(std::vector &dumpInfo); }; } // 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/include/work_status.h b/services/native/include/work_status.h new file mode 100644 index 0000000000000000000000000000000000000000..cee6e61a99e82dac2a6d32d25f31ab43107ac402 --- /dev/null +++ b/services/native/include/work_status.h @@ -0,0 +1,76 @@ +/* + * 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, + 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_; + 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(); + bool IsLastWorkTimeout(); + void OnConditionChanged(WorkCondition::Type &type, std::shared_ptr value); + void MarkRound(); + void MarkStatus(Status status); + Status GetStatus(); + void Dump(std::string& result); + void UpdateTimerIfNeed(); + bool NeedRemove(); + + bool lastTimeout_ {false}; +private: + Status currentStatus_; + time_t baseTime_; + void MarkTimeout(); + bool IsSameUser(); +}; +} // 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 0000000000000000000000000000000000000000..b55313610a2fd76bd793dfa6aa9e337d21657ea6 --- /dev/null +++ b/services/native/src/conditions/battery_level_listener.cpp @@ -0,0 +1,92 @@ +/* + * 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 "conditions/battery_level_listener.h" + +#include "battery_info.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "matching_skills.h" +#include "want.h" + +namespace OHOS { +namespace WorkScheduler { +BatteryLevelEventSubscriber::BatteryLevelEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryLevelListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void BatteryLevelEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + const std::string action = data.GetWant().GetAction(); + + 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, + std::make_shared(battCap, 0, 0, std::string())); + } + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +std::shared_ptr CreateBatteryEventSubscriber(BatteryLevelListener &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(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +BatteryLevelListener::~BatteryLevelListener() +{ + this->Stop(); +} + +bool BatteryLevelListener::Start() +{ + WS_HILOGI("BatteryLevelListener Start"); + this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool BatteryLevelListener::Stop() +{ + WS_HILOGI("BatteryLevelListener Stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void BatteryLevelListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr 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 new file mode 100644 index 0000000000000000000000000000000000000000..c35a7a8d0dd926ebebf682b4f3442874881a97af --- /dev/null +++ b/services/native/src/conditions/battery_status_listener.cpp @@ -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. + */ +#include "conditions/battery_status_listener.h" + +#include "battery_info.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "matching_skills.h" +#include "want.h" + +namespace OHOS { +namespace WorkScheduler { +BatteryStatusEventSubscriber::BatteryStatusEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + BatteryStatusListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void BatteryStatusEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + const std::string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_LOW) { + WS_HILOGI("Condition changed: BATTERY_STATUS_LOW"); + listener_.OnConditionChanged(WorkCondition::Type::BATTERY_STATUS, + 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, + std::make_shared(WorkCondition::BATTERY_STATUS_OKAY, 0, 0, std::string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +std::shared_ptr CreateBatteryEventSubscriber(BatteryStatusListener &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(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +BatteryStatusListener::~BatteryStatusListener() +{ + this->Stop(); +} + +bool BatteryStatusListener::Start() +{ + WS_HILOGI("BatteryStatusListener Start"); + this->commonEventSubscriber = CreateBatteryEventSubscriber(*this); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool BatteryStatusListener::Stop() +{ + WS_HILOGI("BatteryStatusListener Stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void BatteryStatusListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr 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 new file mode 100644 index 0000000000000000000000000000000000000000..6f3f4c0ad3d9cfce742479a8bf13dbec6bbab143 --- /dev/null +++ b/services/native/src/conditions/charger_listener.cpp @@ -0,0 +1,127 @@ +/* + * 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 "conditions/charger_listener.h" + +#include "battery_info.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "matching_skills.h" +#include "want.h" + +namespace OHOS { +namespace WorkScheduler { +ChargerEventSubscriber::ChargerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + ChargerListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void ChargerEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + const std::string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + int code = data.GetCode(); + if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + int type = atoi(data.GetData().c_str()); + switch (type) { + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_AC): + WS_HILOGI("Condition changed: CHARGER_PLUGGED_AC"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + std::make_shared(WorkCondition::CHARGING_PLUGGED_AC, + 0, 0, std::string())); + break; + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_USB): + WS_HILOGI("Condition changed: CHARGER_PLUGGED_USB"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + std::make_shared(WorkCondition::CHARGING_PLUGGED_USB, + 0, 0, std::string())); + break; + case static_cast(PowerMgr::BatteryPluggedType::PLUGGED_TYPE_WIRELESS): + WS_HILOGI("Condition changed: CHARGER_WIRELESS"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + std::make_shared(WorkCondition::CHARGING_PLUGGED_WIRELESS, + 0, 0, std::string())); + break; + default: + break; + } + } + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) { + int code = data.GetCode(); + if (code == PowerMgr::BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE) { + int type = atoi(data.GetData().c_str()); + 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"); + listener_.OnConditionChanged(WorkCondition::Type::CHARGER, + std::make_shared(WorkCondition::CHARGING_UNPLUGGED, 0, 0, std::string())); + break; + default: + break; + } + } + } +} + +std::shared_ptr CreateChargerEventSubscriber(ChargerListener &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(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +ChargerListener::~ChargerListener() +{ + this->Stop(); +} + +bool ChargerListener::Start() +{ + WS_HILOGI("ChargerListener start"); + this->commonEventSubscriber = CreateChargerEventSubscriber(*this); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool ChargerListener::Stop() +{ + WS_HILOGI("ChargerListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void ChargerListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr 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 new file mode 100644 index 0000000000000000000000000000000000000000..401a07027a8dbbb43bb6a433dd06b390db966715 --- /dev/null +++ b/services/native/src/conditions/network_listener.cpp @@ -0,0 +1,89 @@ +/* + * 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 "conditions/network_listener.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "matching_skills.h" +#include "want.h" + +namespace OHOS { +namespace WorkScheduler { +NetworkEventSubscriber::NetworkEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + NetworkListener &listener) : CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void NetworkEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + const std::string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE) { + WS_HILOGI("Condition changed: WIFI_CONN_STATE"); + listener_.OnConditionChanged(WorkCondition::Type::NETWORK, + std::make_shared(WorkCondition::NETWORK_TYPE_WIFI, 0, 0, std::string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +std::shared_ptr CreateNetworkEventSubscriber(NetworkListener &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(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +NetworkListener::~NetworkListener() +{ + this->Stop(); +} + +bool NetworkListener::Start() +{ + WS_HILOGI("NetworkListener start"); + this->commonEventSubscriber = CreateNetworkEventSubscriber(*this); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool NetworkListener::Stop() +{ + WS_HILOGI("NetworkListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void NetworkListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr 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 new file mode 100644 index 0000000000000000000000000000000000000000..166db421808d0082d2270e87cc30cf3df4cf16f7 --- /dev/null +++ b/services/native/src/conditions/storage_listener.cpp @@ -0,0 +1,94 @@ +/* + * 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 "conditions/storage_listener.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "matching_skills.h" +#include "want.h" + +namespace OHOS { +namespace WorkScheduler { +StorageEventSubscriber::StorageEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + StorageListener &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {} + +void StorageEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + const std::string action = data.GetWant().GetAction(); + WS_HILOGI("OnReceiveEvent get action: %{public}s", action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_STORAGE_LOW) { + WS_HILOGI("Condition changed: STORAGE_LOW"); + listener_.OnConditionChanged(WorkCondition::Type::STORAGE, + 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, + std::make_shared(WorkCondition::STORAGE_LEVEL_OKAY, 0, 0, std::string())); + } else { + WS_HILOGI("OnReceiveEvent action is invalid"); + } +} + +std::shared_ptr CreateStorageEventSubscriber(StorageListener &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(std::shared_ptr workQueueManager) +{ + workQueueManager_ = workQueueManager; +} + +StorageListener::~StorageListener() +{ + this->Stop(); +} + +bool StorageListener::Start() +{ + WS_HILOGI("StorageListener start"); + this->commonEventSubscriber = CreateStorageEventSubscriber(*this); + return EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber); +} + +bool StorageListener::Stop() +{ + WS_HILOGI("StorageListener stop"); + if (this->commonEventSubscriber != nullptr) { + bool result = EventFwk::CommonEventManager::UnSubscribeCommonEvent(this->commonEventSubscriber); + if (result) { + this->commonEventSubscriber = nullptr; + } + return result; + } + return true; +} + +void StorageListener::OnConditionChanged(WorkCondition::Type conditionType, + std::shared_ptr 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 new file mode 100644 index 0000000000000000000000000000000000000000..b189c870e4979a05cdd6b6f1fe5c7da6050c36de --- /dev/null +++ b/services/native/src/conditions/timer_listener.cpp @@ -0,0 +1,61 @@ +/* + * 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 "conditions/timer_listener.h" + +#include "work_queue_event_handler.h" + +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_ = AppExecFwk::EventRunner::Create(TIMER_LISTENER); + if (eventRunner_ == nullptr) { + WS_HILOGD("Init failed due to create EventHandler"); + return false; + } + } + if (!handler_) { + handler_ = std::make_shared(eventRunner_, workQueueManager_); + } + 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; +} + +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 0000000000000000000000000000000000000000..f2aa114c7b4bc0fe96e137e934c534bf9d02e767 --- /dev/null +++ b/services/native/src/policy/app_removed_listener.cpp @@ -0,0 +1,87 @@ +/* + * 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 { +static const std::string UID_PARAM = "uid"; +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_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); + auto detectorVal = make_shared(uid, 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_CHANGED); + 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 0000000000000000000000000000000000000000..cf47f7091160bce67c8d020865e278e21d8e7cdd --- /dev/null +++ b/services/native/src/policy/memory_policy.cpp @@ -0,0 +1,80 @@ +/* + * 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 "policy/memory_policy.h" + +#include + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +MemoryPolicy::MemoryPolicy(shared_ptr workPolicyManager) +{ + workPolicyManager_ = workPolicyManager; +} + +MemoryPolicy::~MemoryPolicy() +{ +} + +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) { + WS_HILOGE("GetMemAvailable file open failed."); + memAvailable = IPolicyFilter::CANNOT_RUNNING_MORE; + } + char buf[128]; + int buff_len = 128; + const char mem_name[] = "MemAvailable"; + char name[20]; + int32_t value = -1; + while (fgets(buf, buff_len, fp) != NULL) { + sscanf(buf, "%s%d", name, &value); + string sname = name; + if (sname.find(mem_name) != string::npos) { + memAvailable = value; + break; + } + } + fclose(fp); + fp = nullptr; + return memAvailable; +} + +int32_t MemoryPolicy::getPolicyMaxRunning() +{ + int32_t memAvailable = GetMemAvailable(); + WS_HILOGI("mem_available: %{public}d", memAvailable); + if (memAvailable <= MEM_CRUCIAL) { + return COUNT_MEMORY_CRUCIAL; + } + if (memAvailable <= MEM_LOW && memAvailable > MEM_CRUCIAL) { + return COUNT_MEMORY_LOW; + } + WS_HILOGI("memory left normal"); + return COUNT_MEMORY_NORMAL; +} +} // 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 0000000000000000000000000000000000000000..3413ebdf6784599977b9f0e185ea9549b60c9ccf --- /dev/null +++ b/services/native/src/policy/thermal_policy.cpp @@ -0,0 +1,49 @@ +/* + * 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 "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::getPolicyMaxRunning() +{ + auto& thermalMgrClient = ThermalMgrClient::GetInstance(); + ThermalLevel thermalLevel = thermalMgrClient.GetThermalLevel(); + 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/watchdog.cpp b/services/native/src/watchdog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cdede48488596c02dbcf2bf3b9387b1a0df3ffe5 --- /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_conn_manager.cpp b/services/native/src/work_conn_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..529efb36f31378038bda88bf88e6425691046cde --- /dev/null +++ b/services/native/src/work_conn_manager.cpp @@ -0,0 +1,127 @@ +/* + * 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" +#include +#include +#include +#include +#include + +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()); + 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; + } + AddConnInfo(workStatus->workId_, connection); + return true; +} + +bool WorkConnManager::DisConnect(sptr connect) +{ + 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_event_handler.cpp b/services/native/src/work_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c116a88d2fd583cb38cf89f70bbdf3310e4306c2 --- /dev/null +++ b/services/native/src/work_event_handler.cpp @@ -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. + */ + +#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; + } + case INIT_PERSISTED_MSG: { + wssptr->InitPersisted(); + 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 new file mode 100644 index 0000000000000000000000000000000000000000..8f79cd2c11c366cf6bb1ae62e9aedb0bcf234cec --- /dev/null +++ b/services/native/src/work_policy_manager.cpp @@ -0,0 +1,460 @@ +/* + * 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 "work_scheduler_service.h" +#include "work_event_handler.h" + +#include "watchdog.h" + +using namespace std; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace WorkScheduler { +namespace { +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 = 2 * 60 * 1000; +} + +WorkPolicyManager::WorkPolicyManager(const wptr& wss) : wss_(wss) +{ + std::lock_guard lock(conditionReadyMutex_); + conditionReadyQueue_ = std::make_shared(); +} + +bool WorkPolicyManager::Init() +{ + WS_HILOGI("WorkPolicyManager::Init"); + 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; + } + watchdog_ = std::make_shared(wmsptr->GetWorkPolicyManager()); + watchdogId_ = INIT_WATCHDOG_ID; + fixMemory_ = -1; + watchdogTime_ = WATCHDOG_TIME; + return true; +} + +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"); + std::lock_guard lock(uidMapMutex_); + if (uidQueueMap_.count(uid) > 0) { + 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; + } + uidQueueMap_.at(uid)->Push(workStatus); + } else { + WS_HILOGD("uidQueue(%{public}d) not exists, create", uid); + uidQueueMap_.emplace(uid, make_shared()); + 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::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); + ret = uidQueueMap_.at(uid)->Remove(workStatus); + if (uidQueueMap_.count(uid) <= 0) { + uidQueueMap_.erase(uid); + } + } + return ret; +} + +shared_ptr WorkPolicyManager::FindWorkStatus(WorkInfo& workInfo, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::FindWorkStatus"); + std::lock_guard lock(uidMapMutex_); + if (uidQueueMap_.count(uid) > 0) { + return uidQueueMap_.at(uid)->Find(WorkStatus::MakeWorkId(workInfo.GetWorkId(), uid)); + } + return nullptr; +} + +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); + if (uidQueueMap_.at(uid)->GetSize() <= 0) { + uidQueueMap_.erase(uid); + } + } +} + +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 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); + RemoveFromUidQueue(workStatus, uid); + RemoveFromReadyQueue(workStatus); + hasCanceled = true; + } else { + workStatus->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } + } + + if (!hasCanceled && needCancel) { + RemoveFromUidQueue(workStatus, uid); + RemoveFromReadyQueue(workStatus); + hasCanceled = true; + } + + CheckWorkToRun(); + return hasCanceled; +} + +bool WorkPolicyManager::CancelWork(shared_ptr workStatus, int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::CancelWork"); + 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; +} + +bool WorkPolicyManager::StopAndClearWorks(int32_t uid) +{ + WS_HILOGI("WorkPolicyManager::StopAndClearWorks"); + std::lock_guard lock(uidMapMutex_); + if (uidQueueMap_.count(uid) > 0) { + auto queue = uidQueueMap_.at(uid); + for (auto it : queue->GetWorkList()) { + workConnManager_->StopWork(it); + it->MarkStatus(WorkStatus::Status::REMOVED); + RemoveFromReadyQueue(it); + } + queue->ClearAll(); + uidQueueMap_.erase(uid); + } + CheckWorkToRun(); + return true; +} + +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); + if (workStatus != nullptr) { + return workStatus->IsLastWorkTimeout(); + } + } + return false; +} + +void WorkPolicyManager::OnConditionReady(shared_ptr>> workStatusVector) +{ + WS_HILOGI("WorkPolicyManager::%{public}s enter", __func__); + if (workStatusVector == nullptr) { + return; + } + AddToReadyQueue(workStatusVector); + CheckWorkToRun(); +} + +void WorkPolicyManager::AddToReadyQueue(shared_ptr>> workStatusVector) +{ + std::lock_guard lock(conditionReadyMutex_); + conditionReadyQueue_->Push(workStatusVector); +} + +int32_t WorkPolicyManager::GetMaxRunningCount() +{ + int32_t currentMaxRunning = IPolicyFilter::MAX_RUNNING_COUNT; + for (auto policyFilter : policyFilters_) { + int32_t policyMaxRunning = policyFilter->getPolicyMaxRunning(); + if (policyMaxRunning < currentMaxRunning) { + currentMaxRunning = policyMaxRunning; + } + } + return currentMaxRunning; +} + +int32_t WorkPolicyManager::GetRunningCount() +{ + WS_HILOGI("WorkPolicyManager::GetRunningCount"); + std::lock_guard lock(uidMapMutex_); + 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: { + auto ws = wss_.promote(); + ws->StopAndClearWorksByUid(detectorVal->intVal); + break; + } + default: {} + } + CheckWorkToRun(); +} + +void WorkPolicyManager::CheckWorkToRun() +{ + WS_HILOGI("CheckWorkToRun"); + RemoveAllUnReady(); + if (handler_ == nullptr) { + WS_HILOGE("handler lock() returns nullptr"); + return; + } + handler_->RemoveEvent(WorkEventHandler::RETRIGGER_MSG); + shared_ptr topWork = GetWorkToRun(); + if (topWork == nullptr) { + WS_HILOGD("no condition ready work not running, return."); + return; + } + if (GetRunningCount() < GetMaxRunningCount()) { + WS_HILOGD("running count < max running count"); + RealStartWork(topWork); + SendRetrigger(DELAY_TIME_SHORT); + } else { + WS_HILOGD("trigger delay: %{public}lld", DELAY_TIME_LONG); + SendRetrigger(DELAY_TIME_LONG); + } + 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); + bool ret = workConnManager_->StartWork(topWork); + if (ret) { + AddWatchdogForWork(topWork); + } +} + +void WorkPolicyManager::AddWatchdogForWork(std::shared_ptr workStatus) +{ + int watchId = NewWatchDogId(); + watchdog_->AddWatchdog(watchId, watchdogTime_); + std::lock_guard lock(watchdogIdMapMutex_); + watchdogIdMap_.emplace(watchId, workStatus); +} + +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); + 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__); + std::lock_guard lock(uidMapMutex_); + 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__); + 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)); + if (workStatus != nullptr) { + return workStatus->workInfo_; + } + } + return nullptr; +} + +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(); + } + return allWorks; +} + +void WorkPolicyManager::DumpConditionReadyQueue(string& result) +{ + std::lock_guard lock(conditionReadyMutex_); + conditionReadyQueue_->Dump(result); +} + +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())); +} + +int32_t WorkPolicyManager::NewWatchDogId() +{ + if (watchdogId_ == MAX_WATCHDOG_ID) { + watchdogId_ = INIT_WATCHDOG_ID; + } + return watchdogId_++; +} + +int32_t WorkPolicyManager::GetFixMemory() +{ + return fixMemory_; +} + +void WorkPolicyManager::SetFixMemory(int32_t memory) +{ + fixMemory_ = memory; +} + +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.cpp b/services/native/src/work_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ee6a528b51ee885160503539ae6d10f277846d7 --- /dev/null +++ b/services/native/src/work_queue.cpp @@ -0,0 +1,185 @@ +/* + * 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_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::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: { + break; + } + default: {} + } + vector> result; + for (auto it : workList_) { + it->OnConditionChanged(type, value); + if (it->IsReady()) { + result.emplace_back(it); + } else { + if (it->IsReadyStatus()) { + it->MarkStatus(WorkStatus::Status::WAIT_CONDITION); + } + } + } + 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()); + auto work = workList_.begin(); + shared_ptr workStatus = nullptr; + while (work != workList_.end()) { + if ((*work)->GetStatus() == WorkStatus::CONDITION_READY) { + workStatus = *work; + break; + } + work++; + } + return workStatus; +} + +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::CONDITION_READY); + }); +} + +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); + } +} + +void WorkQueue::ClearAll() +{ + workList_.clear(); +} + +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 0000000000000000000000000000000000000000..25cf7843c33500058355782f9eb2d99de0eaa8e2 --- /dev/null +++ b/services/native/src/work_queue_event_handler.cpp @@ -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. + */ + +#include "work_queue_event_handler.h" + +#include "work_sched_common.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +static const int TIMER_TICK_DELAY = 600000; + +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), TIMER_TICK_DELAY); + break; + } + default: { + return; + } + } +} +} // 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 0000000000000000000000000000000000000000..5dba13ac087575c585b0042d467c8098e1fbc21b --- /dev/null +++ b/services/native/src/work_queue_manager.cpp @@ -0,0 +1,152 @@ +/* + * 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_queue_manager.h" + +using namespace std; + +namespace OHOS { +namespace WorkScheduler { +const int TIME_CYCLE = 10 * 60 * 60; // 10min + +WorkQueueManager::WorkQueueManager(const wptr& wss) : wss_(wss) +{ + timeCycle_ = TIME_CYCLE; +} + +bool WorkQueueManager::Init() +{ + return true; +} + +bool WorkQueueManager::AddListener(WorkCondition::Type type, shared_ptr listener) +{ + std::lock_guard lock(mutex_); + 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()); + std::lock_guard lock(mutex_); + 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) +{ + 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) { + 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::CancelWork(shared_ptr workStatus) +{ + std::lock_guard lock(mutex_); + WS_HILOGD("WorkQueueManager::%{public}s workStatus ID: %{public}s", __func__, workStatus->workId_.c_str()); + for (auto it : queueMap_) { + it.second->CancelWork(workStatus); + if (queueMap_.count(it.first) == 0) { + listenerMap_.at(it.first)->Stop(); + } + } + return true; +} + +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); + 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) +{ + for (auto &it : workList) { + CancelWork(it); + } + return true; +} + +void WorkQueueManager::Dump(string& result) +{ + 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; + 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"); + } +} + +void WorkQueueManager::SetTimeCycle(int time) +{ + timeCycle_ = time; +} + +int WorkQueueManager::GetTimeCycle() { + return timeCycle_; +} +} // 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 0000000000000000000000000000000000000000..2f740a3a60051a119df7798f978761aa568a282e --- /dev/null +++ b/services/native/src/work_scheduler_connection.cpp @@ -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. + */ + +#include "work_scheduler_connection.h" + +#include "work_sched_hilog.h" + +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) +{ + proxy_ = (new (std::nothrow) WorkSchedulerProxy(remoteObject)); + proxy_->OnWorkStart(); + WS_HILOGI("OnAbilityConnectDone"); +} + +void WorkSchedulerConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + WS_HILOGI("OnAbilityDisconnectDone"); +} +} // namespace WorkScheduler +} // namespace OHOS diff --git a/services/native/src/work_scheduler_service.cpp b/services/native/src/work_scheduler_service.cpp index f628a6b179ecb3bad5c1c3d45bdab76231dbd477..212c83f3afaf0c4dcbd0d4306c1b8573303ce9c6 100644 --- a/services/native/src/work_scheduler_service.cpp +++ b/services/native/src/work_scheduler_service.cpp @@ -12,16 +12,55 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #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 "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 "json/json.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; 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 SET_FIX_MEMORY = "SetFixMemory"; +static const string SET_REPEAT_CYCLE_TIME_MIN = "SetRepeatCycleTimeMin"; +static const string SET_WATCHDOG_TIME = "SetWatchdogTime"; +static const string CHECK_BUNDLE = "CheckBundle"; +static const string DEBUG_INFO = "DebugInfo"; } WorkSchedulerService::WorkSchedulerService() : SystemAbility(WORK_SCHEDULE_SERVICE_ID, true) {} @@ -30,19 +69,485 @@ 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; } + GetHandler()->SendEvent(InnerEvent::Get(WorkEventHandler::INIT_PERSISTED_MSG, 0), 15000); + checkBundle_ = true; ready_ = true; - WS_HILOGI(MODULE_SERVICE, "OnStart and add system ability success."); + + 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); + } +} + +list> WorkSchedulerService::ReadPersistedWorks() +{ + 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 (!eventRunner_) { + eventRunner_ = AppExecFwk::EventRunner::Create(WORKSCHEDULER_SERVICE_NAME); + } + if (eventRunner_ == nullptr) { + WS_HILOGE("Init failed due to create EventRunner"); + return false; + } + handler_ = std::make_shared(eventRunner_, wss); + WorkQueueManagerInit(); + if (!WorkPolicyManagerInit()) { + WS_HILOGE("init failed due to work policy manager init."); + return false; + } + + WS_HILOGI("init success."); + return true; +} + +void WorkSchedulerService::WorkQueueManagerInit() +{ + WS_HILOGD("WorkQueueManagerInit come in"); + if (workQueueManager_ == nullptr) { + workQueueManager_ = make_shared(wss); + } + + auto networkListener = 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_); + + 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() +{ + 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); + + auto appRemoveListener = make_shared(workPolicyManager_); + workPolicyManager_->AddAppRemoveListener(appRemoveListener); + WS_HILOGI("work policy manager init success."); + return true; +} + +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 = WorkSchedUtils::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::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 < workQueueManager_->GetTimeCycle()) { + WS_HILOGE("fail, set time:%{public}d must more than %{public}d", time, + workQueueManager_->GetTimeCycle()); + 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); + bool ret = false; + if (workPolicyManager_->AddWork(workStatus, uid)) { + 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"); + } + 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; + int currentAccountId = WorkSchedUtils::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); + } + } + 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) { + WS_HILOGD("StopWorkInner, workStatus is nullptr"); + return false; + } + return StopWorkInner(workStatus, uid, false, false); +} + +bool WorkSchedulerService::StopAndCancelWork(WorkInfo& workInfo) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + shared_ptr workStatus = workPolicyManager_->FindWorkStatus(workInfo, uid); + if (workStatus == nullptr) { + WS_HILOGD("StopWorkInner, workStatus is nullptr"); + return false; + } + StopWorkInner(workStatus, uid, true, false); + 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, bool isTimeOut) +{ + if (workPolicyManager_->StopWork(workStatus, uid, needCancel, isTimeOut)) { + workQueueManager_->CancelWork(workStatus); + } + return true; +} + +void WorkSchedulerService::WatchdogTimeOut(std::shared_ptr workStatus) +{ + StopWorkInner(workStatus, workStatus->uid_, false, true); +} + +bool IsInList(list &list, std::string myWork) +{ + for (auto work : list) { + if (work.compare(myWork) == 0) { + return true; + } + } + return false; +} + +bool WorkSchedulerService::StopAndClearWorks() +{ + return StopAndClearWorksByUid(IPCSkeleton::GetCallingUid()); +} + +bool WorkSchedulerService::StopAndClearWorksByUid(int32_t uid) +{ + WS_HILOGD("StopAndClearWorksByUid:%{public}d", 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); + } + } + RefreshPersistedWorks(); + } + return ret; +} + +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] == CHECK_BUNDLE) { + if (dumpOption[2] == "true") { + checkBundle_ = true; + } else if (dumpOption[2] == "false") { + checkBundle_ = false; + } + } else if (dumpOption[1] == SET_FIX_MEMORY) { + workPolicyManager_->SetFixMemory(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_REPEAT_CYCLE_TIME_MIN) { + 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.")); + 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::UpdateWorkBeforeRealStart(std::shared_ptr work) +{ + if (work == nullptr) { + return; + } + work->UpdateTimerIfNeed(); + if (work->NeedRemove()) { + workQueueManager_->RemoveWork(work); + } +} + +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(workQueueManager_->GetTimeCycle())); + dumpInfo.push_back("Watchdog time:" + std::to_string(workPolicyManager_->GetWatchdogTime())); +} + +void WorkSchedulerService::DumpAllInfo(vector &dumpInfo) +{ + DumpWorkQueueInfo(dumpInfo); + DumpWorkPolicyInfo(dumpInfo); +} + +void WorkSchedulerService::RefreshPersistedWorks() +{ + 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(); + 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(); + 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; +} + +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; +} + +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; + } +} + +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() +{ + if (!IsSameUser()) { + 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) { + return false; + } + 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; + } + 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; +} + +bool WorkStatus::IsRunning() +{ + return currentStatus_ == RUNNING; +} + +bool WorkStatus::IsReadyStatus() +{ + return currentStatus_ == CONDITION_READY; +} + +bool WorkStatus::IsRemoved() +{ + return currentStatus_ == REMOVED; +} + +bool WorkStatus::IsLastWorkTimeout() +{ + return lastTimeout_; +} + +bool WorkStatus::IsRepeating() +{ + if (workInfo_->GetConditionMap()->count(WorkCondition::Type::TIMER) <= 0) { + return false; + } + 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("\"status\":") + to_string(currentStatus_) + ",\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"); + } + 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 +} // namespace OHOS \ 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 0000000000000000000000000000000000000000..c9b72be3d521d75be75f172074f69e96fdeacd7c --- /dev/null +++ b/services/zidl/include/work_sched_service_proxy.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHED_SERVICE_PROXY_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..ed35e2b67d36c60da871c07ee0061bc24fd83a4b --- /dev/null +++ b/services/zidl/include/work_sched_service_stub.h @@ -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. + */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_WORK_SCHEDULER_SERVICE_STUB_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 0000000000000000000000000000000000000000..7000074750dd2c5c9f384079fa2ef0efa27cd73c --- /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 0000000000000000000000000000000000000000..72badc3b1409b1a603a9b4b7bcb6c11ab6a4fd52 --- /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 0000000000000000000000000000000000000000..e226155d244db84eca3b086707b16ba45e04b840 --- /dev/null +++ b/services/zidl/include/work_scheduler_stub_imp.h @@ -0,0 +1,42 @@ +/* + * 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 { +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_sched_service_proxy.cpp b/services/zidl/src/work_sched_service_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2936e0b62aed3c7451a996b533bd63411bada38 --- /dev/null +++ b/services/zidl/src/work_sched_service_proxy.cpp @@ -0,0 +1,248 @@ +/* + * 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_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_HILOGD("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); + + int ret = remote->SendRequest(static_cast(IWorkSchedService::OBTAIN_ALL_WORKS), data, reply, option); + if (ret != ERR_OK) { + WS_HILOGE("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 = reply.ReadParcelable(); + WS_HILOGD("WP read from parcel, workInfo ID: %{public}d", workInfo->GetWorkId()); + workInfos.emplace_back(std::make_shared(*workInfo)); + } + WS_HILOGD("WorkSchedServiceProxy::%{public}s return list size: %{public}d", __func__, workInfos.size()); + 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 = reply.ReadParcelable(); + if (workInfo == nullptr) { + return nullptr; + } + 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; + } + 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 0000000000000000000000000000000000000000..6c8de2893dfe7fa5b96ad6a7aa2589870b1ecd62 --- /dev/null +++ b/services/zidl/src/work_sched_service_stub.cpp @@ -0,0 +1,175 @@ +/* + * 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_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("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): { + int32_t ret = StartWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_WORK): { + int32_t ret = StopWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_AND_CANCEL_WORK): { + int32_t ret = StopAndCancelWorkStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::STOP_AND_CLEAR_WORKS): { + int32_t ret = StopAndClearWorksStub(data); + WS_HILOGD("%{public}s ret is ERR_OK ? %{public}s", __func__, (ret == ERR_OK) ? "true" : "false"); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::IS_LAST_WORK_TIMEOUT): { + int32_t ret = IsLastWorkTimeoutStub(data); + reply.WriteBool(ret == ERR_OK); + return ret; + } + case static_cast(IWorkSchedService::OBTAIN_ALL_WORKS): { + std::list> workInfos = ObtainAllWorksStub(data); + size_t worksize = workInfos.size(); + WS_HILOGD("BUFOAWF OBTAIN_ALL_WORKS worksize returns %{public}d", worksize); + reply.WriteInt32(worksize); + for (auto workInfo : workInfos) { + reply.WriteParcelable(&*workInfo); + } + 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; + } + 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) +{ + if (!StopAndClearWorks()) { + WS_HILOGE("StopAndClearWorks failed"); + return E_STOP_AND_CLEAR_WORKS_FAILED; + } + 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) +{ + int32_t pid = 0, uid = 0; + READ_PARCEL_WITHOUT_RET(data, Int32, uid); + READ_PARCEL_WITHOUT_RET(data, Int32, pid); + return ObtainAllWorks(uid, pid); +} + +std::shared_ptr WorkSchedServiceStub::GetWorkStatusStub(MessageParcel& data) +{ + 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 0000000000000000000000000000000000000000..e15fc46c679ad86753a5c71e8e72ae018e90e1e0 --- /dev/null +++ b/services/zidl/src/work_scheduler_proxy.cpp @@ -0,0 +1,38 @@ +/* + * 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); + + Remote()->SendRequest(COMMAND_ON_WORK_START, data, reply, option); +} + +void WorkSchedulerProxy::OnWorkStop() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + Remote()->SendRequest(COMMAND_ON_WORK_STOP, data, reply, option); +} +} // 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 0000000000000000000000000000000000000000..54382335d83f2dfcddc904a721d954a6dab8c2ef --- /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 0000000000000000000000000000000000000000..898fb42536e934b1e43d4fe4b31d8c02e95c5df6 --- /dev/null +++ b/services/zidl/src/work_scheduler_stub_imp.cpp @@ -0,0 +1,42 @@ +/* + * 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__); + } +} + +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__); + } +} +} // 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 5e6cbf256990f721d473ae3ddda5ab139e8b1b44..0000000000000000000000000000000000000000 --- 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 0000000000000000000000000000000000000000..151825e9e7fbb2c7b00abe3ba7e8126e8f60488f --- /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 0000000000000000000000000000000000000000..4e695398916dab6c89240b7e54977bca8b6ec06d --- /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 0000000000000000000000000000000000000000..d8d3540577d06c60b3a05f3d18bfa4c7e9f66a2a --- /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 0000000000000000000000000000000000000000..00efa21a346471a46944bf585c53ef44f8f4c3d8 --- /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 0000000000000000000000000000000000000000..cc62f41f502d8eb5da991f5f44dd9e2e258328ea --- /dev/null +++ b/utils/dump/src/event_publisher.cpp @@ -0,0 +1,140 @@ +/* + * 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 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"; + 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[TYPE_PARAM] == NETWORK) { + PublishNetworkEvent(dumpOption, dumpInfo); + } else if (dumpOption[TYPE_PARAM] == CHARGING) { + PublishChargingEvent(dumpOption, dumpInfo); + } else if (dumpOption[TYPE_PARAM] == STORAGE) { + PublishStorageEvent(dumpOption, dumpInfo); + } else if (dumpOption[TYPE_PARAM] == 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[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 { + 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[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[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[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[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); + 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[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[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 { + 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 0000000000000000000000000000000000000000..430a0b495ce1bb104434a2e84fcea7f2b9327b6d --- /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 0000000000000000000000000000000000000000..536f460b1b49c694498c686b9f6755b3c859061f --- /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 0000000000000000000000000000000000000000..c46159a21603f16dba9f7f44a2d8cc2fc34bb0d8 --- /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 68% rename from utils/BUILD.gn rename to utils/native/BUILD.gn index 8cf59f666e157021584547b9e0d7763e99bdf1fd..aba267fd1e515830cc05f9ba9d8904a3643975b6 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,25 @@ 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", + "${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/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h new file mode 100644 index 0000000000000000000000000000000000000000..17a8088afdf3d7b3b0cba59a9ab148c125cb318b --- /dev/null +++ b/utils/native/include/delayed_sp_singleton.h @@ -0,0 +1,74 @@ +/* + * 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_UTILS_SP_SINGLETON_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_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 // 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 new file mode 100644 index 0000000000000000000000000000000000000000..dcb2be23342ecffcb46bf786b1582f0a2338f9ca --- /dev/null +++ b/utils/native/include/work_sched_common.h @@ -0,0 +1,96 @@ +/* + * 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_UTILS_COMMON_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_COMMON_H + +#include + +#include + +#include "work_sched_errors.h" +#include "work_sched_hilog.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< namespace OHOS { namespace WorkScheduler { -// WorkScheduler's module const defined. enum { WORKSCHED_MODULE_TYPE = 0x00, }; @@ -29,18 +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 d5d75288d4ee8b33ea9e645338374514b8f40f27..58415e22391bfb4cf668e0dcc72aa874db001136 100644 --- a/utils/native/include/work_sched_hilog.h +++ b/utils/native/include/work_sched_hilog.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,90 +12,65 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H +#define FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H -#ifndef WORK_SCHED_UTILS_HILOG_H -#define WORK_SCHED_UTILS_HILOG_H +#include -#define CONFIG_HILOG -#ifdef CONFIG_HILOG #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; + static void SetLogLevel(const WorkSchedLogLevel &level) + { + level_ = level; + } -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 const WorkSchedLogLevel &GetLogLevel() + { + return 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 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 +#endif // FOUNDATION_RESOURCESCHEDULE_WORKSCHEDULER_UTILS_HILOG_H \ No newline at end of file diff --git a/utils/native/include/work_sched_utils.h b/utils/native/include/work_sched_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..afd70c5d1d447dfe0f04b6f565c0af1ab38704c5 --- /dev/null +++ b/utils/native/include/work_sched_utils.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_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(); + static int32_t GetUserIdByUid(int32_t uid); + static const int INVALID_DATA = -1; +}; +} // 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 new file mode 100644 index 0000000000000000000000000000000000000000..f62058dca42f756137bd15ae00fc070d35518c9c --- /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); +} +} +} \ 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 0000000000000000000000000000000000000000..214beac0d0df1f6316f2296097dc8d01c51c51b6 --- /dev/null +++ b/utils/native/src/work_sched_utils.cpp @@ -0,0 +1,60 @@ +/* + * 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; +} + +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 diff --git a/workscheduler.gni b/workscheduler.gni index d16adbd619502d3ff40c6e69b36d8e6c469f1007..7a671b1b38538a708915d4edb645317039cd32ce 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