1/*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "handler_checker.h"
17#include "ipc_skeleton.h"
18#include "xcollie_utils.h"
19
20namespace OHOS {
21namespace HiviewDFX {
22void HandlerChecker::ScheduleCheck()
23{
24    if (!isCompleted_ || handler_ == nullptr) {
25        return;
26    }
27    if (name_.compare(IPC_FULL) == 0) {
28        auto fb = [] {
29            IPCDfx::BlockUntilThreadAvailable();
30        };
31        if (!handler_->PostTask(fb, "IpcCheck Task", 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) {
32            XCOLLIE_LOGE("XCollie IpcCheck Task PostTask failed.");
33        }
34    }
35
36    isCompleted_.store(false);
37    taskSlow = false;
38    auto weak = weak_from_this();
39    auto f = [weak] () {
40        auto self = weak.lock();
41        if (self) {
42            self->isCompleted_.store(true);
43        }
44    };
45    if (!handler_->PostTask(f, "XCollie Watchdog Task", 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) {
46        XCOLLIE_LOGE("XCollie Watchdog Task PostTask False.");
47    }
48}
49
50int HandlerChecker::GetCheckState()
51{
52    if (isCompleted_) {
53        taskSlow = false;
54        return CheckStatus::COMPLETED;
55    } else {
56        if (!taskSlow) {
57            taskSlow = true;
58            return CheckStatus::WAITED_HALF;
59        } else {
60            return CheckStatus::WAITING;
61        }
62    }
63}
64
65std::string HandlerChecker::GetDumpInfo()
66{
67    std::string ret;
68    if (handler_ != nullptr) {
69        HandlerDumper handlerDumper;
70        handler_->Dump(handlerDumper);
71        ret = handlerDumper.GetDumpInfo();
72    }
73    return ret;
74}
75
76
77std::shared_ptr<AppExecFwk::EventHandler> HandlerChecker::GetHandler() const
78{
79    return handler_;
80}
81
82void HandlerDumper::Dump(const std::string &message)
83{
84    XCOLLIE_LOGD("message is %{public}s", message.c_str());
85    dumpInfo_ += message;
86}
87
88std::string HandlerDumper::GetTag()
89{
90    return "";
91}
92
93std::string HandlerDumper::GetDumpInfo()
94{
95    return dumpInfo_;
96}
97} // end of namespace HiviewDFX
98} // end of namespace OHOS
99