diff --git a/OAT.xml b/OAT.xml old mode 100755 new mode 100644 index eead9a2d3..3f53b0694 --- a/OAT.xml +++ b/OAT.xml @@ -59,9 +59,13 @@ Note:If the text contains special characters, please escape them according to th + + + + @@ -70,6 +74,13 @@ Note:If the text contains special characters, please escape them according to th + + + + + + + diff --git a/build/config.gni b/build/config.gni index 2721b5505..777c98e4d 100755 --- a/build/config.gni +++ b/build/config.gni @@ -14,8 +14,7 @@ OHOS_PROFILER_DIR = get_path_info("..", "abspath") OHOS_PROFILER_3RDPARTY_DIR = get_path_info("../../../third_party/", "abspath") OHOS_PROFILER_3RDPARTY_GRPC_DIR = "${OHOS_PROFILER_3RDPARTY_DIR}/grpc" -OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR = - "${OHOS_PROFILER_3RDPARTY_DIR}/protobuf" +OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR = "${OHOS_PROFILER_3RDPARTY_DIR}/protobuf" OHOS_PROFILER_3RDPARTY_GOOGLETEST_DIR = "${OHOS_PROFILER_3RDPARTY_DIR}/googletest" @@ -31,5 +30,7 @@ print("build_l2 =", build_l2) print("OHOS_PROFILER_DIR = ", OHOS_PROFILER_DIR) print("OHOS_PROFILER_3RDPARTY_DIR = ", OHOS_PROFILER_3RDPARTY_DIR) print("OHOS_PROFILER_3RDPARTY_GRPC_DIR = ", OHOS_PROFILER_3RDPARTY_GRPC_DIR) -print("OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR = ", OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR) -print("OHOS_PROFILER_3RDPARTY_GOOGLETEST_DIR", OHOS_PROFILER_3RDPARTY_GOOGLETEST_DIR) +print("OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR = ", + OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR) +print("OHOS_PROFILER_3RDPARTY_GOOGLETEST_DIR", + OHOS_PROFILER_3RDPARTY_GOOGLETEST_DIR) diff --git a/device/BUILD.gn b/device/BUILD.gn old mode 100755 new mode 100644 index 16555dc98..476d36642 --- a/device/BUILD.gn +++ b/device/BUILD.gn @@ -17,10 +17,12 @@ group("hiprofiler_targets") { deps = [ "cmds:hiprofiler_cmd", "plugins/api:hiprofiler_plugins", + "plugins/bytrace_plugin:bytraceplugin", + "plugins/cpu_plugin:cpudataplugin", + "plugins/cpu_plugin:cpudataplugintest", "plugins/memory_plugin:memdataplugin", "services/profiler_service:hiprofilerd", "services/shared_memory:shared_memory", - "plugins/bytrace_plugin:bytraceplugin", ] } @@ -29,6 +31,7 @@ group("unittest") { deps = [ "base/test:unittest", "plugins/api/test:unittest", + "plugins/cpu_plugin/test:unittest", "plugins/memory_plugin/test:unittest", "services/ipc/test:unittest", "services/plugin_service/test:unittest", diff --git a/device/base/BUILD.gn b/device/base/BUILD.gn old mode 100755 new mode 100644 index 8fbd228f4..baecf98fb --- a/device/base/BUILD.gn +++ b/device/base/BUILD.gn @@ -21,7 +21,7 @@ config("hiprofiler_test_config") { cflags += [ "-g" ] } - if (enable_coverage && current_toolchain == host_toolchain) { + if (enable_coverage) { cflags += [ # clang coverage options: "--coverage", @@ -36,19 +36,26 @@ config("hiprofiler_test_config") { config("hiprofiler_base_config") { include_dirs = [ "include", - "//utils/native/base/include" + "//utils/native/base/include", ] } ohos_source_set("hiprofiler_base") { sources = [ + "src/epoll_event_poller.cpp", + "src/event_notifier.cpp", + "src/i_semaphore.cpp", + "src/posix_semaphore.cpp", + "src/pthread_semaphore.cpp", "src/schedule_task_manager.cpp", + "src/std_semaphore.cpp", ] public_configs = [ ":hiprofiler_test_config", ":hiprofiler_base_config", ] + public_deps = [ "//utils/native/base:utilsecurec" ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] if (build_l2) { diff --git a/device/base/config.gni b/device/base/config.gni old mode 100755 new mode 100644 diff --git a/device/base/include/epoll_event_poller.h b/device/base/include/epoll_event_poller.h new file mode 100644 index 000000000..8560ddd2a --- /dev/null +++ b/device/base/include/epoll_event_poller.h @@ -0,0 +1,83 @@ +/* + * 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 EPOLL_EVENT_POLLER_H +#define EPOLL_EVENT_POLLER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "nocopyable.h" + +class EpollEventPoller { +public: + explicit EpollEventPoller(int timeOut); + ~EpollEventPoller(); + + using OnReadableCallback = std::function; + using OnWritableCallback = std::function; + + bool AddFileDescriptor(int fd, const OnReadableCallback& onReadable, const OnWritableCallback& onWritable = {}); + + bool RemoveFileDescriptor(int fd); + + bool Init(); + bool Start(); + bool Stop(); + bool Finalize(); + +private: + enum State { + INITIAL, + INITIED, + STARTED, + }; + static constexpr int INVALID_FD = -1; + struct EventContext { + int fd = INVALID_FD; + OnReadableCallback onReadable; + OnWritableCallback onWritable; + }; + using EventContextPtr = std::shared_ptr; + + void Run(); + bool UpdateEvent(int op, const EventContextPtr& ctx); + void HandleEvent(int events, const EventContext& ctx); + + bool AddContextLocked(const EventContextPtr& ctx); + bool RemoveContextLocked(const EventContextPtr& ctx); + + void OnNotify(); + bool Notify(uint64_t value = 1); + +private: + std::mutex mutex_; + std::mutex vecMutex_; + std::thread pollThread_; + int timeOut_ = 0; + int epollFd_ = INVALID_FD; + int eventFd_ = INVALID_FD; + std::atomic state_ = INITIAL; + std::atomic running_ = false; + std::vector fileDescriptors_; + std::unordered_map context_; + + DISALLOW_COPY_AND_MOVE(EpollEventPoller); +}; +#endif // EPOLL_EVENT_POLLER_H diff --git a/device/base/include/event_notifier.h b/device/base/include/event_notifier.h new file mode 100644 index 000000000..dd43c74d5 --- /dev/null +++ b/device/base/include/event_notifier.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef EVENT_NOTIFIER_H +#define EVENT_NOTIFIER_H + +#include +#include +#include "nocopyable.h" + +class EventNotifier; + +using EventNotifierPtr = std::shared_ptr; + +class EventNotifier { +public: + enum { + NONBLOCK = (1u << 0), + SEMAPHORE = (1u << 1), + }; + + static EventNotifierPtr Create(unsigned int initValue = 0, unsigned int mask = 0); + static EventNotifierPtr CreateWithFd(int fd); + + int GetFd() const; + + bool IsNonBlocking() const; + bool IsSemaphore() const; + + uint64_t Take() const; + bool Post(uint64_t value) const; + + EventNotifier(unsigned int initValue, unsigned int mask); + EventNotifier(int fd); + ~EventNotifier(); + +private: + int fd_; + int flags_; + + DISALLOW_COPY_AND_MOVE(EventNotifier); +}; + +#endif // EVENT_NOTIFIER_H \ No newline at end of file diff --git a/device/base/include/i_semaphore.h b/device/base/include/i_semaphore.h new file mode 100644 index 000000000..83f86c637 --- /dev/null +++ b/device/base/include/i_semaphore.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 OHOS_PROFILER_ABSTRACT_SEMAPHORE_H +#define OHOS_PROFILER_ABSTRACT_SEMAPHORE_H + +#include +#include + +class ISemaphore { +public: + virtual ~ISemaphore() {} + virtual bool Wait() = 0; + virtual bool TryWait() = 0; + bool TimedWait(int seconds) + { + return TimedWait(seconds, 0); + } + virtual bool TimedWait(int seconds, int nanoSeconds) = 0; + virtual bool Post() = 0; + virtual unsigned int Value() const = 0; +}; +using SemaphorePtr = std::shared_ptr; + +enum SemaphoreFactoryType : int { STD_SEMAPHORE_FACTORY, POSIX_SEMAPHORE_FACTORY, PTHREAD_SEMAPHORE_FACTORY }; + +class ISemaphoreFactory { +public: + virtual SemaphorePtr Create(unsigned int value) = 0; +}; + +ISemaphoreFactory& GetSemaphoreFactory(SemaphoreFactoryType type = STD_SEMAPHORE_FACTORY); + +#endif // OHOS_PROFILER_ABSTRACT_SEMAPHORE_H \ No newline at end of file diff --git a/device/base/include/logging.h b/device/base/include/logging.h old mode 100755 new mode 100644 index 0c4b912de..a0b3d1f55 --- a/device/base/include/logging.h +++ b/device/base/include/logging.h @@ -13,44 +13,52 @@ * limitations under the License. */ -#ifndef LOGGING_H -#define LOGGING_H +#ifndef OHOS_PROFILER_LOGGING_H +#define OHOS_PROFILER_LOGGING_H + +#undef NDEBUG #ifndef LOG_TAG -#define LOG_TAG "" +#define LOG_TAG "Hiprofiler" +#endif + +#define PROFILER_SUBSYSTEM 0x0000 +#ifndef LOG_DOMAIN +#define LOG_DOMAIN PROFILER_SUBSYSTEM +#endif + +#ifndef UNUSED_PARAMETER +#define UNUSED_PARAMETER(x) ((void)x) #endif #ifdef HAVE_HILOG #include "hilog/log.h" - -#undef LOG_TAG -#define LOG_TAG "Hiprofiler" - -#else +#include +#else // HAVE_HILOG #include #include #include -#include #include +#include #include #include #include -static inline long GetTid() +static inline long GetTid(void) { return syscall(SYS_gettid); } enum { - HILOG_UNKNOWN = 0, - HILOG_DEFAULT, - HILOG_VERBOSE, - HILOG_DEBUG, - HILOG_INFO, - HILOG_WARN, - HILOG_ERROR, - HILOG_FATAL, - HILOG_SILENT, + LOG_UNKNOWN = 0, + LOG_DEFAULT, + LOG_VERBOSE, + LOG_DEBUG, + LOG_INFO, + LOG_WARN, + LOG_ERROR, + LOG_FATAL, + LOG_SILENT, }; namespace { @@ -66,60 +74,136 @@ static inline std::string GetTimeStr() localtime_r(&ts.tv_sec, &tmStruct); size_t used = strftime(timeStr, sizeof(timeStr), "%m-%d %H:%M:%S", &tmStruct); snprintf_s(&timeStr[used], sizeof(timeStr) - used, sizeof(timeStr) - used - 1, ".%03ld", - ts.tv_nsec / NS_PER_MS_LOG); + ts.tv_nsec / NS_PER_MS_LOG); return timeStr; } -typedef const char *ConstCharPtr; +typedef const char* ConstCharPtr; -static inline int HiLogPrintArgs(int prio, ConstCharPtr tag, ConstCharPtr fmt, va_list vargs) +static inline int HiLogPrintArgs(int prio, int domain, ConstCharPtr tag, ConstCharPtr fmt, va_list vargs) { static std::mutex mtx; static std::vector prioNames = {"U", " ", "V", "D", "I", "W", "E", "F", "S"}; std::unique_lock lock(mtx); - int count = - fprintf(stderr, "%s %7d %7ld %5s %s ", GetTimeStr().c_str(), getpid(), GetTid(), prioNames[prio].c_str(), tag); + int count = fprintf(stderr, "%04x %s %7d %7ld %5s %s ", domain, GetTimeStr().c_str(), getpid(), GetTid(), + prioNames[prio].c_str(), tag); + if (count < 0) { + return 0; + } count += vfprintf(stderr, fmt, vargs); count += fprintf(stderr, "\n"); + fflush(stderr); return count; } -static inline int __hilog_log_print(int prio, ConstCharPtr tag, ConstCharPtr fmt, ...) +static inline int HiLogPrint(int type, int prio, int domain, ConstCharPtr tag, ConstCharPtr fmt, ...) { - int count; + int count = 0; va_list vargs; + UNUSED_PARAMETER(type); va_start(vargs, fmt); - count = HiLogPrintArgs(prio, tag, fmt, vargs); + count = HiLogPrintArgs(prio, domain, tag, fmt, vargs); va_end(vargs); return count; } -#define HILOG_DEBUG(LOG_CORE, fmt, ...) __hilog_log_print(HILOG_DEBUG, LOG_TAG, fmt, ##__VA_ARGS__) -#define HILOG_INFO(LOG_CORE, fmt, ...) __hilog_log_print(HILOG_INFO, LOG_TAG, fmt, ##__VA_ARGS__) -#define HILOG_WARN(LOG_CORE, fmt, ...) __hilog_log_print(HILOG_WARN, LOG_TAG, fmt, ##__VA_ARGS__) -#define HILOG_ERROR(LOG_CORE, fmt, ...) __hilog_log_print(HILOG_ERROR, LOG_TAG, fmt, ##__VA_ARGS__) - +#ifndef LOG_CORE +#define LOG_CORE 0 #endif +#define HILOG_DEBUG(LOG_CORE, fmt, ...) HiLogPrint(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, fmt, ##__VA_ARGS__) +#define HILOG_INFO(LOG_CORE, fmt, ...) HiLogPrint(LOG_CORE, LOG_INFO, LOG_DOMAIN, LOG_TAG, fmt, ##__VA_ARGS__) +#define HILOG_WARN(LOG_CORE, fmt, ...) HiLogPrint(LOG_CORE, LOG_WARN, LOG_DOMAIN, LOG_TAG, fmt, ##__VA_ARGS__) +#define HILOG_ERROR(LOG_CORE, fmt, ...) HiLogPrint(LOG_CORE, LOG_ERROR, LOG_DOMAIN, LOG_TAG, fmt, ##__VA_ARGS__) + +#endif // HAVE_HILOG + +#ifndef NDEBUG +#include +namespace logging { +inline void StringReplace(std::string& str, const std::string& oldStr, const std::string& newStr) +{ + std::string::size_type pos = 0u; + while ((pos = str.find(oldStr, pos)) != std::string::npos) { + str.replace(pos, oldStr.length(), newStr); + pos += newStr.length(); + } +} + +static inline std::string StringFormat(const char* fmt, ...) +{ + va_list vargs; + char buf[1024] = {0}; + std::string format(fmt); + StringReplace(format, "%{public}", "%"); + + va_start(vargs, fmt); + if (vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, format.c_str(), vargs) < 0) { + return nullptr; + } + + va_end(vargs); + return buf; +} +} // logging + +#ifdef HILOG_DEBUG +#undef HILOG_DEBUG +#endif + +#ifdef HILOG_INFO +#undef HILOG_INFO +#endif + +#ifdef HILOG_WARN +#undef HILOG_WARN +#endif + +#ifdef HILOG_ERROR +#undef HILOG_ERROR +#endif + +#ifdef HILOG_PRINT +#undef HILOG_PRINT +#endif + +#ifdef HAVE_HILOG +#define HILOG_PRINT(type, level, fmt, ...) \ + HiLogPrint(type, level, LOG_DOMAIN, LOG_TAG, "%{public}s", logging::StringFormat(fmt, ##__VA_ARGS__).c_str()) +#else +#define HILOG_PRINT(type, level, fmt, ...) \ + HiLogPrint(type, level, LOG_DOMAIN, LOG_TAG, "%s", logging::StringFormat(fmt, ##__VA_ARGS__).c_str()) +#endif + +#define HILOG_DEBUG(type, fmt, ...) HILOG_PRINT(type, LOG_DEBUG, fmt, ##__VA_ARGS__) +#define HILOG_INFO(type, fmt, ...) HILOG_PRINT(type, LOG_INFO, fmt, ##__VA_ARGS__) +#define HILOG_WARN(type, fmt, ...) HILOG_PRINT(type, LOG_WARN, fmt, ##__VA_ARGS__) +#define HILOG_ERROR(type, fmt, ...) HILOG_PRINT(type, LOG_ERROR, fmt, ##__VA_ARGS__) +#endif // NDEBUG + #define STD_PTR(K, T) std::K##_ptr -#define CHECK_NOTNULL(ptr, retval, fmt, ...) \ - do { \ - if (ptr == nullptr) { \ - HILOG_WARN(LOG_CORE, "CHECK_NOTNULL(%s) in %s:%d FAILED, " fmt, #ptr, __func__, __LINE__, ##__VA_ARGS__); \ - return retval; \ - } \ - } while (0) +#define NO_RETVAL /* retval */ -#define CHECK_TRUE(expr, retval, fmt, ...) \ +#define CHECK_NOTNULL(ptr, retval, fmt, ...) \ do { \ - if (!(expr)) { \ - HILOG_WARN(LOG_CORE, "CHECK_TRUE(%s) in %s:%d FAILED, " fmt, #expr, __func__, __LINE__, ##__VA_ARGS__); \ + if (ptr == nullptr) { \ + HILOG_WARN(LOG_CORE, "CHECK_NOTNULL(%{public}s) in %{public}s:%{public}d FAILED, " fmt, #ptr, __func__, \ + __LINE__, ##__VA_ARGS__); \ return retval; \ } \ } while (0) +#define CHECK_TRUE(expr, retval, fmt, ...) \ + do { \ + if (!(expr)) { \ + HILOG_WARN(LOG_CORE, "CHECK_TRUE(%{public}s) in %{public}s:%{public}d FAILED, " fmt, #expr, __func__, \ + __LINE__, ##__VA_ARGS__); \ + return retval; \ + } \ + } while (0) + #define RETURN_IF(expr, retval, fmt, ...) \ do { \ if ((expr)) { \ diff --git a/device/base/include/schedule_task_manager.h b/device/base/include/schedule_task_manager.h index 0ce47f5dc..9edc9e460 100644 --- a/device/base/include/schedule_task_manager.h +++ b/device/base/include/schedule_task_manager.h @@ -13,11 +13,12 @@ * limitations under the License. */ -#ifndef SCHEDULE_TASK_MANAGER_H -#define SCHEDULE_TASK_MANAGER_H +#ifndef OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H +#define OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H #include #include +#include #include #include #include @@ -26,6 +27,7 @@ #include #include "logging.h" +#include "nocopyable.h" class ScheduleTaskManager { public: @@ -58,7 +60,7 @@ private: std::function callback; std::chrono::milliseconds repeatInterval; std::chrono::milliseconds initialDelay; - TimePoint lastRunTime; + TimePoint nextRunTime; }; using SharedTask = STD_PTR(shared, Task); using WeakTask = STD_PTR(weak, Task); @@ -69,15 +71,17 @@ private: void ScheduleThread(); - bool TakeFront(TimePoint& time, WeakTask& task); + WeakTask TakeFront(); private: mutable std::mutex taskMutex_; std::condition_variable taskCv_; std::atomic runScheduleThread_ = true; - std::multimap timeMap_; - std::unordered_map taskMap_; + std::multimap timeMap_; // schedule list + std::unordered_map taskMap_; // task details std::thread scheduleThread_; + + DISALLOW_COPY_AND_MOVE(ScheduleTaskManager); }; -#endif // !SCHEDULE_TASK_MANAGER_H \ No newline at end of file +#endif // !OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H \ No newline at end of file diff --git a/device/base/src/epoll_event_poller.cpp b/device/base/src/epoll_event_poller.cpp new file mode 100644 index 000000000..a52b59d41 --- /dev/null +++ b/device/base/src/epoll_event_poller.cpp @@ -0,0 +1,248 @@ +/* + * 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 "epoll_event_poller.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "logging.h" + +EpollEventPoller::EpollEventPoller(int timeOut) : timeOut_(timeOut), epollFd_(INVALID_FD), eventFd_(INVALID_FD) {} + +EpollEventPoller::~EpollEventPoller() +{ + if (state_ == STARTED) { + HILOG_INFO(LOG_CORE, "need Stop in destructor!"); + Stop(); + } + if (state_ == INITIED) { + HILOG_INFO(LOG_CORE, "need Finalize in dtor!"); + Finalize(); + } +} + +bool EpollEventPoller::AddFileDescriptor(int fd, + const OnReadableCallback& onReadable, + const OnWritableCallback& onWritable) +{ + auto ctx = std::make_shared(); + CHECK_NOTNULL(ctx, false, "create EventContext FAILED!"); + ctx->fd = fd; + ctx->onReadable = onReadable; + ctx->onWritable = onWritable; + + std::unique_lock lock(mutex_); + CHECK_TRUE(AddContextLocked(ctx), false, "add context for %d failed!", fd); + return Notify(); +} + +bool EpollEventPoller::RemoveFileDescriptor(int fd) +{ + std::unique_lock lock(mutex_); + auto it = context_.find(fd); + CHECK_TRUE(it != context_.end(), false, "fd %d not found in poll set!", fd); + + auto ctx = it->second; + CHECK_NOTNULL(ctx, false, "ctx null!"); + CHECK_TRUE(RemoveContextLocked(ctx), false, "remove context for %d failed!", fd); + return Notify(); +} + +bool EpollEventPoller::AddContextLocked(const EventContextPtr& ctx) +{ + context_[ctx->fd] = ctx; + return UpdateEvent(EPOLL_CTL_ADD, ctx); +} + +bool EpollEventPoller::RemoveContextLocked(const EventContextPtr& ctx) +{ + context_.erase(ctx->fd); + CHECK_TRUE(UpdateEvent(EPOLL_CTL_DEL, ctx), false, "update fd %d ctx FAILED!", ctx->fd); + return true; +} + +static std::string EpollOpName(int op) +{ + if (op == EPOLL_CTL_ADD) { + return "ADD"; + } + if (op == EPOLL_CTL_DEL) { + return "DEL"; + } + if (op == EPOLL_CTL_MOD) { + return "MOD"; + } + return ""; +} + +bool EpollEventPoller::UpdateEvent(int op, const EventContextPtr& ctx) +{ + struct epoll_event event = {}; + if (ctx->onReadable) { + event.events |= EPOLLIN; + } + if (ctx->onWritable) { + event.events |= EPOLLOUT; + } + event.data.ptr = ctx.get(); + + std::string name = EpollOpName(op).c_str(); + HILOG_DEBUG(LOG_CORE, "poll set %s %d %x start!", name.c_str(), ctx->fd, event.events); + int retval = epoll_ctl(epollFd_, op, ctx->fd, &event); + CHECK_TRUE(retval == 0, false, "epoll_ctl %s failed, %s", name.c_str(), strerror(errno)); + HILOG_DEBUG(LOG_CORE, "poll set %s %d %x done!", name.c_str(), ctx->fd, event.events); + return true; +} + +void EpollEventPoller::Run() +{ + pthread_setname_np(pthread_self(), "EventPoller"); + std::vector eventVec; + while (running_) { + { + std::unique_lock lock(mutex_); + eventVec.resize(context_.size()); + } + int retval = TEMP_FAILURE_RETRY(epoll_wait(epollFd_, eventVec.data(), eventVec.size(), timeOut_)); + CHECK_TRUE(retval >= 0, NO_RETVAL, "epoll_wait failed, %s!", strerror(errno)); + if (retval == 0) { + HILOG_INFO(LOG_CORE, "epoll_wait %dms timeout!", timeOut_); + continue; + } + for (int i = 0; i < retval; i++) { + auto ctx = reinterpret_cast(eventVec[i].data.ptr); + if (ctx != nullptr) { + HandleEvent(eventVec[i].events, *ctx); + } + } + } +} + +void EpollEventPoller::HandleEvent(int events, const EventContext& ctx) +{ + if (events & EPOLLIN) { + if (ctx.onReadable) { + ctx.onReadable(); + } + } else if (events & EPOLLOUT) { + if (ctx.onWritable) { + ctx.onWritable(); + } + } +} + +void EpollEventPoller::OnNotify() +{ + uint64_t value = 0; + CHECK_TRUE(read(eventFd_, &value, sizeof(value)) == sizeof(value), NO_RETVAL, "read eventfd FAILED!"); + HILOG_DEBUG(LOG_CORE, "OnNotify %llu done!", static_cast(value)); +} + +bool EpollEventPoller::Notify(uint64_t value) +{ + auto nbytes = write(eventFd_, &value, sizeof(value)); + CHECK_TRUE(static_cast(nbytes) == sizeof(value), false, "write eventfd FAILED!"); + HILOG_DEBUG(LOG_CORE, "Notify %llu done!", static_cast(value)); + return true; +} + +bool EpollEventPoller::Init() +{ + HILOG_INFO(LOG_CORE, "Init %d", state_.load()); + CHECK_TRUE(state_ == INITIAL, false, "Init FAIL %d", state_.load()); + + int epollFd = epoll_create1(EPOLL_CLOEXEC); + CHECK_TRUE(epollFd >= 0, false, "epoll_create failed, %s!", strerror(errno)); + fileDescriptors_.push_back(epollFd); + + int eventFd = eventfd(0, O_CLOEXEC | O_NONBLOCK); + CHECK_TRUE(eventFd >= 0, false, "create event fd failed, %s", strerror(errno)); + fileDescriptors_.push_back(eventFd); + + auto eventFdCtx = std::make_shared(); + CHECK_NOTNULL(eventFdCtx, false, "create EventContext failed!"); + eventFdCtx->fd = eventFd; + eventFdCtx->onReadable = std::bind(&EpollEventPoller::OnNotify, this); + + std::unique_lock lock(mutex_); + epollFd_ = epollFd; + eventFd_ = eventFd; + AddContextLocked(eventFdCtx); + HILOG_INFO(LOG_CORE, "EpollEventPoller::Init %d done!", state_.load()); + state_ = INITIED; + return true; +} + +bool EpollEventPoller::Finalize() +{ + if (state_ == STARTED) { + HILOG_INFO(LOG_CORE, "need Stop in Finalize!"); + Stop(); + } + + HILOG_INFO(LOG_CORE, "Finalize %d", state_.load()); + CHECK_TRUE(state_ == INITIED, false, "Finalize FAIL %d", state_.load()); + + std::unique_lock lock(mutex_); + std::vector contextVec; + for (auto& ctxPair : context_) { + contextVec.push_back(ctxPair.second); + } + for (auto ctxPtr : contextVec) { + HILOG_DEBUG(LOG_CORE, "remove context for %d", ctxPtr->fd); + RemoveContextLocked(ctxPtr); + } + + for (int fd : fileDescriptors_) { + close(fd); + } + fileDescriptors_.clear(); + + epollFd_ = INVALID_FD; + eventFd_ = INVALID_FD; + state_ = INITIAL; + return true; +} + +bool EpollEventPoller::Start() +{ + HILOG_INFO(LOG_CORE, "%s %d", __func__, state_.load()); + CHECK_TRUE(state_ == INITIED, false, "Start FAIL %d", state_.load()); + + running_ = true; + pollThread_ = std::thread(&EpollEventPoller::Run, this); + state_ = STARTED; + return true; +} + +bool EpollEventPoller::Stop() +{ + CHECK_TRUE(state_ == STARTED, false, "Stop FAIL %d", state_.load()); + + running_ = false; + Notify(); + if (pollThread_.joinable()) { + pollThread_.join(); + } + state_ = INITIED; + return true; +} diff --git a/device/base/src/event_notifier.cpp b/device/base/src/event_notifier.cpp new file mode 100644 index 000000000..9fa1167bf --- /dev/null +++ b/device/base/src/event_notifier.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "event_notifier.h" + +#include +#include +#include +#include +#include +#include + +#include "logging.h" + +#ifndef EFD_SEMAPHORE +#define EFD_SEMAPHORE 1 +#endif + +EventNotifierPtr EventNotifier::Create(unsigned int initValue, unsigned int mask) +{ + return std::make_shared(initValue, mask); +} + +EventNotifierPtr EventNotifier::CreateWithFd(int fd) +{ + return std::make_shared(fd); +} + +EventNotifier::EventNotifier(unsigned int initValue, unsigned int mask) : fd_(-1), flags_(O_CLOEXEC) +{ + if (mask & NONBLOCK) { + flags_ |= O_NONBLOCK; + } + if (mask & SEMAPHORE) { + flags_ |= EFD_SEMAPHORE; + } + fd_ = eventfd(initValue, flags_); + CHECK_TRUE(fd_ >= 0, NO_RETVAL, "create eventfd FAILED, %s", strerror(errno)); + HILOG_DEBUG(LOG_CORE, "EventNotifier create eventfd %d done!", fd_); +} + +EventNotifier::EventNotifier(int fd) : fd_(fd) +{ + int flags = fcntl(fd_, F_GETFL); + CHECK_TRUE(flags >= 0, NO_RETVAL, "get flags of fd %d FAILED, %s", fd, strerror(errno)); + HILOG_DEBUG(LOG_CORE, "EventNotifier bind eventfd %d done!", fd_); +} + +EventNotifier::~EventNotifier() +{ + HILOG_DEBUG(LOG_CORE, "EventNotifier close eventfd %d", fd_); + close(fd_); +} + +int EventNotifier::GetFd() const +{ + return fd_; +} + +bool EventNotifier::IsNonBlocking() const +{ + return flags_ & O_NONBLOCK; +} + +bool EventNotifier::IsSemaphore() const +{ + return flags_ & EFD_SEMAPHORE; +} + +uint64_t EventNotifier::Take() const +{ + uint64_t value = UINT64_MAX; + int retval = TEMP_FAILURE_RETRY(read(fd_, &value, sizeof(value))); + CHECK_TRUE(retval == sizeof(value), false, "read value from eventfd %d failed, %s!", fd_, strerror(errno)); + return value; +} + +bool EventNotifier::Post(uint64_t value) const +{ + int retval = TEMP_FAILURE_RETRY(write(fd_, &value, sizeof(value))); + CHECK_TRUE(retval == sizeof(value), false, "write value to eventfd %d failed, %s!", fd_, strerror(errno)); + return true; +} diff --git a/device/base/src/i_semaphore.cpp b/device/base/src/i_semaphore.cpp new file mode 100644 index 000000000..c2eaee006 --- /dev/null +++ b/device/base/src/i_semaphore.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "i_semaphore.h" +#include "posix_semaphore.h" +#include "pthread_semaphore.h" +#include "std_semaphore.h" + +ISemaphoreFactory& GetSemaphoreFactory(SemaphoreFactoryType type) +{ + static StdSemaphoreFactory stdFactory; + if (type == STD_SEMAPHORE_FACTORY) { + return stdFactory; + } else if (type == POSIX_SEMAPHORE_FACTORY) { + static PosixSemaphoreFactory posxiFactory; + return posxiFactory; + } else if (type == PTHREAD_SEMAPHORE_FACTORY) { + // static PthreadSemaphoreFactory pthreadFactory; + return stdFactory; + } + return stdFactory; +} \ No newline at end of file diff --git a/device/base/src/posix_semaphore.cpp b/device/base/src/posix_semaphore.cpp new file mode 100644 index 000000000..3e5877704 --- /dev/null +++ b/device/base/src/posix_semaphore.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "posix_semaphore.h" + +#include + +namespace { +constexpr int NS_PER_SEC = 1000 * 1000 * 1000; +} + +PosixSemaphore::PosixSemaphore(unsigned int value) +{ + sem_init(&sem_, 0, value); +} + +PosixSemaphore::~PosixSemaphore() +{ + sem_destroy(&sem_); +} + +bool PosixSemaphore::Wait() +{ + return sem_wait(&sem_) == 0; +} + +bool PosixSemaphore::TryWait() +{ + return sem_trywait(&sem_) == 0; +} + +bool PosixSemaphore::TimedWait(int seconds, int nanoSeconds) +{ + struct timespec ts = { 0, 0 }; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += seconds; + ts.tv_nsec += nanoSeconds; + ts.tv_sec += ts.tv_nsec / NS_PER_SEC; + ts.tv_nsec %= NS_PER_SEC; + return sem_timedwait(&sem_, &ts) == 0; +} + +bool PosixSemaphore::Post() +{ + return sem_post(&sem_) == 0; +} + +unsigned PosixSemaphore::Value() const +{ + int value = 0; + sem_getvalue(&sem_, &value); + return value; +} + +SemaphorePtr PosixSemaphoreFactory::Create(unsigned int value) +{ + return std::make_shared(value); +} diff --git a/device/base/src/posix_semaphore.h b/device/base/src/posix_semaphore.h new file mode 100644 index 000000000..0f9d88e83 --- /dev/null +++ b/device/base/src/posix_semaphore.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_PROFILER_POSIX_SEMAPHORE_H +#define OHOS_PROFILER_POSIX_SEMAPHORE_H + +#include +#include + +#include "i_semaphore.h" + +class PosixSemaphore : public ISemaphore { +public: + explicit PosixSemaphore(unsigned int value); + ~PosixSemaphore(); + + bool Wait() override; + bool TryWait() override; + bool TimedWait(int seconds, int nanoSeconds) override; + bool Post() override; + unsigned Value() const override; + +private: + mutable sem_t sem_ = {}; +}; + +class PosixSemaphoreFactory : public ISemaphoreFactory { +public: + SemaphorePtr Create(unsigned int value) override; +}; + +#endif // OHOS_PROFILER_POSIX_SEMAPHORE_H \ No newline at end of file diff --git a/device/base/src/pthread_semaphore.cpp b/device/base/src/pthread_semaphore.cpp new file mode 100644 index 000000000..ef660a163 --- /dev/null +++ b/device/base/src/pthread_semaphore.cpp @@ -0,0 +1,100 @@ +/* + * 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 "pthread_semaphore.h" + +#include + +namespace { +constexpr int NS_PER_SEC = 1000 * 1000 * 1000; +} + +PthreadSemaphore::PthreadSemaphore(unsigned int value) : value_(value) +{ + pthread_mutex_init(&mutex_, nullptr); + pthread_cond_init(&cond_, nullptr); +} + +PthreadSemaphore::~PthreadSemaphore() +{ + pthread_cond_destroy(&cond_); + pthread_mutex_destroy(&mutex_); +} + +bool PthreadSemaphore::Wait() +{ + pthread_mutex_lock(&mutex_); + while (value_ == 0) { + pthread_cond_wait(&cond_, &mutex_); + } + --value_; + pthread_mutex_unlock(&mutex_); + return true; +} + +bool PthreadSemaphore::TryWait() +{ + pthread_mutex_lock(&mutex_); + bool retval = TryWaitLocked(); + pthread_mutex_unlock(&mutex_); + return retval; +} + +bool PthreadSemaphore::TimedWait(int seconds, int nanoSeconds) +{ + pthread_mutex_lock(&mutex_); + if (value_) { + struct timespec ts = { 0, 0 }; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += seconds; + ts.tv_nsec += nanoSeconds; + ts.tv_sec += ts.tv_nsec / NS_PER_SEC; + ts.tv_nsec %= NS_PER_SEC; + pthread_cond_timedwait(&cond_, &mutex_, &ts); + } + bool retval = TryWaitLocked(); + pthread_mutex_unlock(&mutex_); + return retval; +} + +bool PthreadSemaphore::TryWaitLocked() +{ + if (value_ == 0) { + return false; + } + --value_; + return true; +} + +bool PthreadSemaphore::Post() +{ + pthread_mutex_lock(&mutex_); + ++value_; + pthread_mutex_unlock(&mutex_); + pthread_cond_broadcast(&cond_); + return true; +} + +unsigned int PthreadSemaphore::Value() const +{ + pthread_mutex_lock(&mutex_); + unsigned int val = value_; + pthread_mutex_unlock(&mutex_); + return val; +} + +SemaphorePtr PthreadSemaphoreFactory::Create(unsigned int value) +{ + return std::make_shared(value); +} diff --git a/device/base/src/pthread_semaphore.h b/device/base/src/pthread_semaphore.h new file mode 100644 index 000000000..5000d6855 --- /dev/null +++ b/device/base/src/pthread_semaphore.h @@ -0,0 +1,46 @@ +/* + * 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 OHOS_PROFILER_PTHREAD_SEMAPHORE_H +#define OHOS_PROFILER_PTHREAD_SEMAPHORE_H + +#include +#include + +#include "i_semaphore.h" + +class PthreadSemaphore : public ISemaphore { +public: + explicit PthreadSemaphore(unsigned int value); + ~PthreadSemaphore(); + + bool Wait() override; + bool TryWait() override; + bool TimedWait(int seconds, int nanoSeconds) override; + bool Post() override; + unsigned int Value() const override; + +private: + bool TryWaitLocked(); + mutable pthread_mutex_t mutex_ {}; + mutable pthread_cond_t cond_ {}; + volatile unsigned int value_ = 0; +}; + +class PthreadSemaphoreFactory : public ISemaphoreFactory { +public: + SemaphorePtr Create(unsigned int value) override; +}; + +#endif // OHOS_PROFILER_PTHREAD_SEMAPHORE_H \ No newline at end of file diff --git a/device/base/src/schedule_task_manager.cpp b/device/base/src/schedule_task_manager.cpp index 8735b28df..c03491a98 100644 --- a/device/base/src/schedule_task_manager.cpp +++ b/device/base/src/schedule_task_manager.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "logging.h" #include "securec.h" @@ -36,22 +37,27 @@ ScheduleTaskManager& ScheduleTaskManager::GetInstance() ScheduleTaskManager::ScheduleTaskManager() { + runScheduleThread_ = true; scheduleThread_ = std::thread(&ScheduleTaskManager::ScheduleThread, this); } ScheduleTaskManager::~ScheduleTaskManager() { Shutdown(); - if (scheduleThread_.joinable()) { - scheduleThread_.join(); - } } void ScheduleTaskManager::Shutdown() { - std::lock_guard guard(taskMutex_); - runScheduleThread_ = false; + bool expect = true; + if (!runScheduleThread_.compare_exchange_strong(expect, false)) { + return; + } taskCv_.notify_one(); + if (scheduleThread_.joinable()) { + scheduleThread_.join(); + } + taskMap_.clear(); + timeMap_.clear(); } std::chrono::milliseconds ScheduleTaskManager::NormalizeInterval(std::chrono::milliseconds interval) @@ -77,12 +83,14 @@ bool ScheduleTaskManager::ScheduleTask(const std::string& name, const std::chrono::milliseconds& repeatInterval, std::chrono::milliseconds initialDelay) { + auto currentTime = Clock::now(); auto task = std::make_shared(); task->name = name; task->callback = callback; task->initialDelay = initialDelay; task->repeatInterval = NormalizeInterval(repeatInterval); + task->nextRunTime = currentTime + initialDelay; std::lock_guard guard(taskMutex_); if (taskMap_.count(name) > 0) { @@ -91,26 +99,28 @@ bool ScheduleTaskManager::ScheduleTask(const std::string& name, } taskMap_[name] = task; - timeMap_.insert(std::make_pair(Clock::now() + initialDelay, task)); + timeMap_.insert(std::make_pair(task->nextRunTime, task)); taskCv_.notify_one(); - HILOG_DEBUG(LOG_CORE, "add schedule %s, total: %zu ", name.c_str(), taskMap_.size()); + HILOG_DEBUG(LOG_CORE, "add schedule %s done, total: %zu", name.c_str(), taskMap_.size()); return true; } bool ScheduleTaskManager::UnscheduleTask(const std::string& name) { - HILOG_DEBUG(LOG_CORE, "del schedule %s, total: %zu", name.c_str(), taskMap_.size()); std::unique_lock lck(taskMutex_); + HILOG_DEBUG(LOG_CORE, "del schedule %s start, total: %zu", name.c_str(), taskMap_.size()); auto it = taskMap_.find(name); if (it != taskMap_.end()) { taskMap_.erase(it); + HILOG_DEBUG(LOG_CORE, "del schedule %s done, remain: %zu", name.c_str(), taskMap_.size()); return true; } + HILOG_DEBUG(LOG_CORE, "del schedule %s pass, total: %zu", name.c_str(), taskMap_.size()); return false; } -bool ScheduleTaskManager::TakeFront(TimePoint& time, WeakTask& task) +ScheduleTaskManager::WeakTask ScheduleTaskManager::TakeFront() { std::unique_lock lck(taskMutex_); @@ -120,54 +130,68 @@ bool ScheduleTaskManager::TakeFront(TimePoint& time, WeakTask& task) } if (!runScheduleThread_) { - return false; + return {}; } - time = timeMap_.begin()->first; - task = timeMap_.begin()->second; + auto task = timeMap_.begin()->second; timeMap_.erase(timeMap_.begin()); - return true; + return task; } void ScheduleTaskManager::DumpTask(const SharedTask& task) { if (task) { - long msecs = std::chrono::duration_cast(task->lastRunTime.time_since_epoch()).count(); - HILOG_DEBUG(LOG_CORE, "{name = %s, interval = %lld, delay = %lld, lastRun = %ld}", - task->name.c_str(), task->repeatInterval.count(), task->initialDelay.count(), msecs); + long msecs = std::chrono::duration_cast(task->nextRunTime.time_since_epoch()).count(); + HILOG_DEBUG(LOG_CORE, + "{name = %{public}s, interval = %{public}lld, delay = %{public}lld, nextRunTime = %{public}ld}", + task->name.c_str(), task->repeatInterval.count(), task->initialDelay.count(), msecs); } } void ScheduleTaskManager::ScheduleThread() { - while (true) { + pthread_setname_np(pthread_self(), "SchedTaskMgr"); + while (runScheduleThread_) { // take front task from task queue - TimePoint targetTime; - WeakTask targetTask; - if (!TakeFront(targetTime, targetTask)) { + WeakTask weakTask = TakeFront(); + if (!runScheduleThread_) { break; } + TimePoint targetTime; + { + auto taskTime = weakTask.lock(); // promote to shared_ptr + if (!taskTime) { + // task cancelled with UnschduleTask or not a repeat task + continue; + } + targetTime = taskTime->nextRunTime; + } + // delay to target time auto currentTime = Clock::now(); if (targetTime >= currentTime) { std::this_thread::sleep_for(targetTime - currentTime); } - // promote to shared_ptr - auto task = targetTask.lock(); - DumpTask(task); + auto taskRepeat = weakTask.lock(); + if (!taskRepeat) { + // task cancelled with UnschduleTask or not a repeat task + continue; + } - if (task != nullptr) { - // call task callback - task->callback(); - task->lastRunTime = currentTime; + // call task callback + taskRepeat->callback(); + taskRepeat->nextRunTime = targetTime + taskRepeat->repeatInterval; - // re-insert task to map if it's a repeat task - if (task->repeatInterval.count() != 0) { - std::unique_lock guard(taskMutex_); - timeMap_.insert(std::make_pair(targetTime + task->repeatInterval, task)); - } + if (taskRepeat->repeatInterval.count() != 0) { + // repeat task, re-insert task to timeMap + std::unique_lock guard(taskMutex_); + timeMap_.insert(std::make_pair(taskRepeat->nextRunTime, taskRepeat)); + } else { + // not a repeat task. + std::unique_lock guard(taskMutex_); + taskMap_.erase(taskRepeat->name); } } } diff --git a/device/base/src/std_semaphore.cpp b/device/base/src/std_semaphore.cpp new file mode 100644 index 000000000..3bae57cdf --- /dev/null +++ b/device/base/src/std_semaphore.cpp @@ -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. + */ +#include "std_semaphore.h" + +StdSemaphore::StdSemaphore(unsigned int value) : value_(value) {} + +StdSemaphore::~StdSemaphore() {} + +bool StdSemaphore::Wait() +{ + std::unique_lock lock(mutex_); + while (value_ == 0) { + condVar_.wait(lock); + } + --value_; + return true; +} + +bool StdSemaphore::TryWait() +{ + std::unique_lock lock(mutex_); + return TryWaitLocked(); +} + +bool StdSemaphore::TryWaitLocked() +{ + if (value_ == 0) { + return false; + } + --value_; + return true; +} + +bool StdSemaphore::TimedWait(int seconds, int nanoSeconds) +{ + std::unique_lock lock(mutex_); + if (value_ == 0) { + auto timePoint = std::chrono::steady_clock::now(); + timePoint += std::chrono::seconds(seconds); + timePoint += std::chrono::nanoseconds(nanoSeconds); + condVar_.wait_until(lock, timePoint); + } + return TryWaitLocked(); +} + +bool StdSemaphore::Post() +{ + { + std::unique_lock lock(mutex_); + ++value_; + } + condVar_.notify_all(); + return true; +} + +unsigned StdSemaphore::Value() const +{ + return value_; +} + +SemaphorePtr StdSemaphoreFactory::Create(unsigned int value) +{ + return std::make_shared(value); +} diff --git a/device/base/src/std_semaphore.h b/device/base/src/std_semaphore.h new file mode 100644 index 000000000..3bc64bd6e --- /dev/null +++ b/device/base/src/std_semaphore.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_PROFILER_STD_SEMAPHORE_H +#define OHOS_PROFILER_STD_SEMAPHORE_H + +#include +#include +#include "i_semaphore.h" +#include "nocopyable.h" + +class StdSemaphore : public ISemaphore { +public: + explicit StdSemaphore(unsigned int value); + ~StdSemaphore(); + bool Wait() override; + bool TryWait() override; + bool TimedWait(int seconds, int nanoSeconds) override; + bool Post() override; + unsigned int Value() const override; + +private: + bool TryWaitLocked(); + + mutable std::mutex mutex_; + std::condition_variable condVar_; + volatile unsigned int value_; + + DISALLOW_COPY_AND_MOVE(StdSemaphore); +}; + +class StdSemaphoreFactory : public ISemaphoreFactory { +public: + SemaphorePtr Create(unsigned int value) override; +}; + +#endif // OHOS_PROFILER_STD_SEMAPHORE_H \ No newline at end of file diff --git a/device/base/test/BUILD.gn b/device/base/test/BUILD.gn old mode 100755 new mode 100644 index 69f42ea3f..d0390d1ad --- a/device/base/test/BUILD.gn +++ b/device/base/test/BUILD.gn @@ -16,7 +16,7 @@ import("../../base/config.gni") module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" config("module_private_config") { - visibility = [":*"] + visibility = [ ":*" ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] } @@ -28,26 +28,22 @@ ohos_unittest("hiprofiler_base_ut") { "../:hiprofiler_base", "//third_party/googletest:gtest", ] - configs = [ - ":module_private_config" - ] + configs = [ ":module_private_config" ] include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] sources = [ + "unittest/epoll_event_poller_test.cpp", "unittest/schedule_task_manager_test.cpp", + "unittest/semaphore_test.cpp", ] cflags = [ "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", + "-Dprivate=public", #allow test code access private members ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" } group("unittest") { testonly = true - deps = [ - ":hiprofiler_base_ut", - ] + deps = [ ":hiprofiler_base_ut" ] } diff --git a/device/base/test/unittest/epoll_event_poller_test.cpp b/device/base/test/unittest/epoll_event_poller_test.cpp new file mode 100644 index 000000000..06b85f60e --- /dev/null +++ b/device/base/test/unittest/epoll_event_poller_test.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "epoll_event_poller.h" +#include "event_notifier.h" +#include "logging.h" + +using namespace testing::ext; + +namespace { +constexpr int DEFAULT_POLL_INTERVAL = 1000; +} + +namespace { +class EpollEventPollerTest : public testing::Test { +protected: + std::unique_ptr eventPoller; + void SetUp() override + { + eventPoller = std::make_unique(DEFAULT_POLL_INTERVAL); + } + + void TearDown() override {} +}; + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: CtorDtor. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, CtorDtor, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: InitFinalize. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitFinalize, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitFinalize start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Finalize()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: InitFinalize. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitOnly, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitOnly start!"); + EXPECT_TRUE(eventPoller->Init()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: Init 2 times Finalize 1 time. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, Init2Finalize1, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.Init2Finalize1 start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_FALSE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Finalize()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: InitStartStopFinalize. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitStartStopFinalize, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartStopFinalize start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Start()); + EXPECT_TRUE(eventPoller->Stop()); + EXPECT_TRUE(eventPoller->Finalize()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: InitStartStop. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitStartStop, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartStop start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Start()); + EXPECT_TRUE(eventPoller->Stop()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: InitStart. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitStart, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStart start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Start()); +} + +/** + * @tc.name: EpollEventPollerTest + * @tc.desc: AddFd. + * @tc.type: FUNC + */ +HWTEST_F(EpollEventPollerTest, InitStartAddFd, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartAddFd start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Start()); + + int eventFd = eventfd(0, O_CLOEXEC | O_NONBLOCK); + uint64_t readValue = 0; + auto onReadable = [&readValue, &eventFd]() { + read(eventFd, &readValue, sizeof(readValue)); + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartAddFd read %" PRIu64, readValue); + }; + EXPECT_TRUE(eventPoller->AddFileDescriptor(eventFd, onReadable)); + + uint64_t writeValue = 1234; + int writeSize = sizeof(writeValue); // run -t UT -ss developtools + EXPECT_EQ(write(eventFd, &writeValue, writeSize), writeSize); + + std::this_thread::yield(); + usleep(15 * 1000); + EXPECT_EQ(readValue, writeValue); + + EXPECT_TRUE(eventPoller->Stop()); + EXPECT_TRUE(eventPoller->Finalize()); + + close(eventFd); +} + +HWTEST_F(EpollEventPollerTest, InitStartAddEventFd, TestSize.Level1) +{ + ASSERT_NE(eventPoller, nullptr); + + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartAddFd start!"); + EXPECT_TRUE(eventPoller->Init()); + EXPECT_TRUE(eventPoller->Start()); + + auto notifier = EventNotifier::Create(0, EventNotifier::NONBLOCK); + uint64_t readValue = 0; + auto onReadable = [&readValue, ¬ifier]() { + readValue = notifier->Take(); + HILOG_INFO(LOG_CORE, "EpollEventPollerTest.InitStartAddFd read %" PRIu64, readValue); + }; + EXPECT_TRUE(eventPoller->AddFileDescriptor(notifier->GetFd(), onReadable)); + + uint64_t writeValue = 1234; + pid_t pid = fork(); + EXPECT_GE(pid, 0); + if (pid == 0) { + int evFd = dup(notifier->GetFd()); + auto evNotifier = EventNotifier::CreateWithFd(evFd); + evNotifier->Post(writeValue); + _exit(0); + } else if (pid > 0) { + int wstatus = 0; + waitpid(pid, &wstatus, 0); + } + + std::this_thread::yield(); + usleep(15 * 1000); + EXPECT_EQ(readValue, writeValue); + + EXPECT_TRUE(eventPoller->Stop()); + EXPECT_TRUE(eventPoller->Finalize()); +} +} // namespace \ No newline at end of file diff --git a/device/base/test/unittest/event_notifier_test.cpp b/device/base/test/unittest/event_notifier_test.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/device/base/test/unittest/schedule_task_manager_test.cpp b/device/base/test/unittest/schedule_task_manager_test.cpp old mode 100755 new mode 100644 index 580d5a3ee..189b3a919 --- a/device/base/test/unittest/schedule_task_manager_test.cpp +++ b/device/base/test/unittest/schedule_task_manager_test.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include "schedule_task_manager.h" @@ -26,7 +27,10 @@ namespace { class ScheduleTaskManagerTest : public testing::Test { protected: static void SetUpTestCase() {} - static void TearDownTestCase() {} + static void TearDownTestCase() + { + ScheduleTaskManager::GetInstance().Shutdown(); + } }; /** @@ -55,6 +59,8 @@ HWTEST_F(ScheduleTaskManagerTest, ScheduleTaskOneshot, TestSize.Level1) std::this_thread::sleep_for(initalDelay + initalDelay); EXPECT_EQ(count.load(), 1); + + scheduleTaskManager.Shutdown(); } /** @@ -72,15 +78,27 @@ HWTEST_F(ScheduleTaskManagerTest, ScheduleTaskRepeated, TestSize.Level1) ScheduleTaskManager scheduleTaskManager; EXPECT_TRUE(scheduleTaskManager.ScheduleTask( - "task-2", [&]() { count++; }, repeatInterval, initalDelay)); + "task-2", + [&]() { + count++; + struct timeval tv; + gettimeofday(&tv, nullptr); + printf("[%ld.%06ld] count: %d\n", tv.tv_sec, tv.tv_usec, count.load()); + }, + repeatInterval, initalDelay)); int expected = 0; std::this_thread::sleep_for(initalDelay + initalDelay); for (int i = 0; i < cnt; i++) { expected++; + struct timeval tv = { 0, 0 }; + gettimeofday(&tv, nullptr); + printf("[%ld.%06ld] expected: %d\n", tv.tv_sec, tv.tv_usec, expected); EXPECT_EQ(count.load(), expected); std::this_thread::sleep_for(repeatInterval); } + + scheduleTaskManager.Shutdown(); } /** @@ -99,19 +117,27 @@ HWTEST_F(ScheduleTaskManagerTest, UnscheduleTask, TestSize.Level1) ScheduleTaskManager scheduleTaskManager; EXPECT_TRUE(scheduleTaskManager.ScheduleTask( - taskName, [&]() { count++; }, repeatInterval)); + taskName, + [&]() { + count++; + struct timeval tv; + gettimeofday(&tv, nullptr); + printf("[%ld.%06ld] count: %d\n", tv.tv_sec, tv.tv_usec, count.load()); + }, + repeatInterval)); int expected = 0; std::this_thread::sleep_for(initalDelay); for (int i = 0; i < cnt; i++) { std::this_thread::sleep_for(repeatInterval); expected++; + struct timeval tv = { 0, 0 }; + gettimeofday(&tv, nullptr); + printf("[%ld.%06ld] expected: %d\n", tv.tv_sec, tv.tv_usec, expected); EXPECT_EQ(count.load(), expected); } EXPECT_TRUE(scheduleTaskManager.UnscheduleTask(taskName)); scheduleTaskManager.Shutdown(); - - EXPECT_EQ(count.load(), expected); } } // namespace \ No newline at end of file diff --git a/device/base/test/unittest/semaphore_test.cpp b/device/base/test/unittest/semaphore_test.cpp new file mode 100644 index 000000000..4ba6cfba1 --- /dev/null +++ b/device/base/test/unittest/semaphore_test.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "i_semaphore.h" + +namespace { +using namespace testing::ext; + +class SemaphoreTest : public testing::Test { +protected: + static void SetUpTestCase() {} + static void TearDownTestCase() {} +}; + +/** + * @tc.name: SemaphoreTest + * @tc.desc: CtorDtor. + * @tc.type: FUNC + */ +HWTEST_F(SemaphoreTest, CtorDtor, TestSize.Level1) +{ + auto semaphore = GetSemaphoreFactory().Create(0); + EXPECT_NE(semaphore, nullptr); +} + +/** + * @tc.name: SemaphoreTest + * @tc.desc: Wait. + * @tc.type: FUNC + */ +HWTEST_F(SemaphoreTest, Wait, TestSize.Level1) +{ + auto semaphore = GetSemaphoreFactory().Create(1); + ASSERT_NE(semaphore, nullptr); + EXPECT_TRUE(semaphore->Wait()); +} + +/** + * @tc.name: SemaphoreTest + * @tc.desc: Post. + * @tc.type: FUNC + */ +HWTEST_F(SemaphoreTest, Post, TestSize.Level1) +{ + auto semaphore = GetSemaphoreFactory().Create(0); + ASSERT_NE(semaphore, nullptr); + EXPECT_TRUE(semaphore->Post()); +} + +/** + * @tc.name: SemaphoreTest + * @tc.desc: Post. + * @tc.type: FUNC + */ +HWTEST_F(SemaphoreTest, WaitPost, TestSize.Level1) +{ + auto readySem = GetSemaphoreFactory().Create(0); + auto finishSem = GetSemaphoreFactory().Create(0); + ASSERT_NE(readySem, nullptr); + ASSERT_NE(finishSem, nullptr); + + auto done = std::make_shared(false); + ASSERT_NE(done, nullptr); + + std::thread bgThread([=]() { + readySem->Wait(); + *done = true; + finishSem->Post(); + }); + + EXPECT_TRUE(readySem->Post()); + EXPECT_TRUE(finishSem->Wait()); + EXPECT_TRUE(*done); + + bgThread.join(); +} +} // namespace \ No newline at end of file diff --git a/device/cmds/BUILD.gn b/device/cmds/BUILD.gn old mode 100755 new mode 100644 index 300c5ea89..d5ec6c80b --- a/device/cmds/BUILD.gn +++ b/device/cmds/BUILD.gn @@ -24,9 +24,7 @@ ohos_source_set("command_line") { include_dirs = [ "include" ] } ohos_executable("hiprofiler_cmd") { - sources = [ - "src/main.cpp", - ] + sources = [ "src/main.cpp" ] include_dirs = [ "include" ] deps = [ ":command_line", diff --git a/device/cmds/include/command_param.h b/device/cmds/include/command_param.h old mode 100755 new mode 100644 diff --git a/device/cmds/include/command_param_switch.h b/device/cmds/include/command_param_switch.h old mode 100755 new mode 100644 diff --git a/device/cmds/include/command_param_text.h b/device/cmds/include/command_param_text.h old mode 100755 new mode 100644 diff --git a/device/cmds/src/command_param.cpp b/device/cmds/src/command_param.cpp old mode 100755 new mode 100644 index 04a241d42..bc90a8ab2 --- a/device/cmds/src/command_param.cpp +++ b/device/cmds/src/command_param.cpp @@ -28,5 +28,5 @@ void CommandParam::AddFilter(const std::string& filterName) bool CommandParam::IsInFilter(const std::string& filterName) { return std::any_of(paramFilter_.begin(), paramFilter_.end(), - [filterName](std::string s) { return s == filterName; }); + [filterName](const std::string& s) { return s == filterName; }); } \ No newline at end of file diff --git a/device/cmds/src/command_param_switch.cpp b/device/cmds/src/command_param_switch.cpp old mode 100755 new mode 100644 diff --git a/device/cmds/src/command_param_text.cpp b/device/cmds/src/command_param_text.cpp old mode 100755 new mode 100644 diff --git a/device/cmds/src/main.cpp b/device/cmds/src/main.cpp index 5bb8046f3..1a2baae39 100644 --- a/device/cmds/src/main.cpp +++ b/device/cmds/src/main.cpp @@ -89,21 +89,30 @@ std::unique_ptr MakeCreateRequest(const std::string& confi const std::string& keepSecond, const std::string& outputFileName) { auto request = std::make_unique(); - auto sessionConfig = request->mutable_session_config(); - if (!request || !sessionConfig) { + if (!request) { return nullptr; } std::string content = ReadConfigContent(configFileName); if (content.empty()) { + printf("config file empty!"); return nullptr; } + printf("================================\n"); + printf("CONFIG: read %zu bytes from %s:\n%s", content.size(), configFileName.c_str(), content.c_str()); if (!google::protobuf::TextFormat::ParseFromString(content, request.get())) { - printf("config file [%s] format error!\n", configFileName.c_str()); + printf("config file [%s] parse FAILED!\n", configFileName.c_str()); return nullptr; } - request->set_request_id(0); + auto sessionConfig = request->mutable_session_config(); + if (!sessionConfig) { + return nullptr; + } + + request->set_request_id(1); + printf("--------------------------------\n"); + printf("keepSecond: %s,\noutputFileName: %s\n", keepSecond.c_str(), outputFileName.c_str()); if (!keepSecond.empty()) { int ks = std::stoi(keepSecond); if (ks > 0) { @@ -113,6 +122,15 @@ std::unique_ptr MakeCreateRequest(const std::string& confi if (!outputFileName.empty()) { sessionConfig->set_result_file(outputFileName); } + + content.clear(); + if (!google::protobuf::TextFormat::PrintToString(*request.get(), &content)) { + printf("config message format FAILED!\n"); + return nullptr; + } + printf("--------------------------------\n"); + printf("CONFIG: final config content:\n%s", content.c_str()); + printf("================================\n"); return request; } @@ -196,9 +214,6 @@ int main(int argc, char* argv[]) bool isHelp = false; pCmdLine->AddParamSwitch("--help", "-h", isHelp, "make some help"); - bool isBackground = false; - pCmdLine->AddParamSwitch("--background", "-d", isBackground, "run in background"); - std::vector argvVector; for (int i = 0; i < argc; i++) { argvVector.push_back(argv[i]); @@ -207,7 +222,7 @@ int main(int argc, char* argv[]) pCmdLine->PrintHelp(); exit(0); } - if (isGetGrpcAddr) { + if (isGetGrpcAddr) { // handle get port auto profilerStub = GetProfilerServiceStub(); if (profilerStub == nullptr) { printf("FAIL\nGet profiler service stub failed!\n"); @@ -229,13 +244,13 @@ int main(int argc, char* argv[]) return 0; } - if (!configFileName.empty()) { - // Read the configFileName,convert to protobuf object,structure 'CreateSession',Send 'StartSession' command to - // profilerd - if (StartSession(configFileName, traceKeepSecond, outputFileName)) { - printf("OK\ntracing...\n"); - } - exit(0); + if (configFileName.empty()) { // normal case + printf("FAIL\nconfig file argument must sepcified!"); + return 1; + } + // Read the configFileName, call 'CreateSession', and 'StartSession' + if (StartSession(configFileName, traceKeepSecond, outputFileName)) { + printf("OK\ntracing...\n"); } return 0; diff --git a/device/format-code.sh b/device/format-code.sh old mode 100755 new mode 100644 diff --git a/device/ohos_test.xml b/device/ohos_test.xml new file mode 100644 index 000000000..9905287ce --- /dev/null +++ b/device/ohos_test.xml @@ -0,0 +1,546 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/device/plugins/api/BUILD.gn b/device/plugins/api/BUILD.gn old mode 100755 new mode 100644 index 6c60c6d54..90c926312 --- a/device/plugins/api/BUILD.gn +++ b/device/plugins/api/BUILD.gn @@ -35,12 +35,13 @@ ohos_source_set("plugins_sources") { "../../base/include/", "${OHOS_PROFILER_DIR}/interfaces/kits", "//utils/native/base/include", + "//third_party/boringssl/src/include", ] sources = [ "src/buffer_writer.cpp", "src/command_poller.cpp", - "src/plugin_module.cpp", "src/plugin_manager.cpp", + "src/plugin_module.cpp", "src/plugin_watcher.cpp", "src/writer_adapter.cpp", ] @@ -49,7 +50,9 @@ ohos_source_set("plugins_sources") { "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", "../../base:hiprofiler_base", - "//utils/native/base:utilsbase", + "//third_party/boringssl:crypto", + "//third_party/boringssl:crypto", + "//utils/native/base:utilsecurec", ] public_configs = [ ":hiprofiler_plugins_config" ] if (current_toolchain != host_toolchain) { @@ -62,12 +65,8 @@ ohos_source_set("plugins_sources") { } ohos_executable("hiprofiler_plugins") { - deps = [ - ":plugins_sources", - ] - sources = [ - "src/main.cpp", - ] + deps = [ ":plugins_sources" ] + sources = [ "src/main.cpp" ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] if (build_l2) { diff --git a/device/plugins/api/include/manager_interface.h b/device/plugins/api/include/manager_interface.h new file mode 100644 index 000000000..bd5fb9c92 --- /dev/null +++ b/device/plugins/api/include/manager_interface.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PLUGIN_INTERFACE_H +#define PLUGIN_INTERFACE_H + +#include +#include +#include +#include + +class ProfilerPluginConfig; +class PluginResult; +class CommandPoller; + +class ManagerInterface { +public: + virtual ~ManagerInterface() {} + + virtual bool LoadPlugin(const std::string& pluginPath) = 0; + virtual bool UnloadPlugin(const std::string& pluginPath) = 0; + virtual bool UnloadPlugin(const uint32_t pluginId) = 0; + + // CommandPoller will call the following four interfaces after receiving the command + virtual bool CreatePluginSession(const std::vector& config) = 0; + virtual bool DestroyPluginSession(const std::vector& pluginIds) = 0; + virtual bool StartPluginSession(const std::vector& pluginIds, + const std::vector& config) = 0; + virtual bool StopPluginSession(const std::vector& pluginIds) = 0; + + virtual bool CreateWriter(std::string pluginName, uint32_t bufferSize, int smbFd, int eventFd) = 0; + virtual bool ResetWriter(uint32_t pluginId) = 0; + virtual void SetCommandPoller(const std::shared_ptr& p) = 0; +}; + +#endif // PLUGIN_INTERFACE_H \ No newline at end of file diff --git a/device/plugins/api/include/writer.h b/device/plugins/api/include/writer.h old mode 100755 new mode 100644 diff --git a/device/plugins/api/src/buffer_writer.cpp b/device/plugins/api/src/buffer_writer.cpp index 9996f33cc..58c9f49b1 100644 --- a/device/plugins/api/src/buffer_writer.cpp +++ b/device/plugins/api/src/buffer_writer.cpp @@ -15,50 +15,89 @@ #include "buffer_writer.h" #include "command_poller.h" +#include "common_types.pb.h" #include "logging.h" #include "plugin_service_types.pb.h" #include "share_memory_allocator.h" +#include +#include +#include +#include + BufferWriter::BufferWriter(std::string name, uint32_t size, - int fd, - const CommandPollerPtr& cp, + int smbFd, + int eventFd, uint32_t pluginId) : pluginName_(name) { - HILOG_DEBUG(LOG_CORE, "CreateMemoryBlockRemote %s %d %d", name.c_str(), size, fd); - shareMemoryBlock_ = ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote(name, size, fd); + HILOG_INFO(LOG_CORE, "BufferWriter %s %d [%d] [%d]", name.c_str(), size, smbFd, eventFd); + shareMemoryBlock_ = ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote(name, size, smbFd); if (shareMemoryBlock_ == nullptr) { - HILOG_DEBUG(LOG_CORE, "shareMemoryBlock_ == nullptr="); + HILOG_DEBUG(LOG_CORE, "create shareMemoryBlock_ failed!"); } - commandPoller_ = cp; + eventNotifier_ = EventNotifier::CreateWithFd(eventFd); pluginId_ = pluginId; + lastFlushTime_ = std::chrono::steady_clock::now(); } BufferWriter::~BufferWriter() { + HILOG_DEBUG(LOG_CORE, "BufferWriter destroy eventfd = %d!", eventNotifier_ ? eventNotifier_->GetFd() : -1); + eventNotifier_ = nullptr; ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote(pluginName_); } +void BufferWriter::Report() const +{ + HILOG_DEBUG(LOG_CORE, "BufferWriter stats B: %" PRIu64 ", P: %d, W:%" PRIu64 ", F: %d", + bytesCount_.load(), bytesPending_.load(), writeCount_.load(), flushCount_.load()); +} + +void BufferWriter::DoStats(long bytes) +{ + ++writeCount_; + bytesCount_ += bytes; + bytesPending_ += bytes; +} + long BufferWriter::Write(const void* data, size_t size) { - if (shareMemoryBlock_ == nullptr) { + if (shareMemoryBlock_ == nullptr || data == nullptr || size == 0) { return false; } - HILOG_DEBUG(LOG_CORE, "BufferWriter Write %zu", size); - return shareMemoryBlock_->PutRaw(reinterpret_cast(data), static_cast(size)); + + ProfilerPluginData pluginData; + pluginData.set_name(pluginName_); + pluginData.set_status(0); + pluginData.set_data(data, size); + + struct timespec ts = { 0, 0 }; + clock_gettime(CLOCK_REALTIME, &ts); + + pluginData.set_clock_id(ProfilerPluginData::CLOCKID_REALTIME); + pluginData.set_tv_sec(ts.tv_sec); + pluginData.set_tv_nsec(ts.tv_nsec); + + DoStats(pluginData.ByteSizeLong()); + return shareMemoryBlock_->PutMessage(pluginData); } -bool BufferWriter::WriteProtobuf(google::protobuf::Message& pmsg) +bool BufferWriter::WriteMessage(const google::protobuf::Message& pmsg) { if (shareMemoryBlock_ == nullptr) { return false; } - HILOG_DEBUG(LOG_CORE, "BufferWriter Write %zu", pmsg.ByteSizeLong()); - return shareMemoryBlock_->PutProtobuf(pmsg); + DoStats(pmsg.ByteSizeLong()); + return shareMemoryBlock_->PutMessage(pmsg); } bool BufferWriter::Flush() { + ++flushCount_; + eventNotifier_->Post(flushCount_.load()); + lastFlushTime_ = std::chrono::steady_clock::now(); + bytesPending_ = 0; return true; } diff --git a/device/plugins/api/src/buffer_writer.h b/device/plugins/api/src/buffer_writer.h old mode 100755 new mode 100644 index 5f8456627..8fbeeb1fa --- a/device/plugins/api/src/buffer_writer.h +++ b/device/plugins/api/src/buffer_writer.h @@ -16,7 +16,9 @@ #ifndef BUFFER_WRITER_H #define BUFFER_WRITER_H +#include #include +#include "event_notifier.h" #include "plugin_module_api.h" #include "share_memory_allocator.h" #include "writer.h" @@ -27,18 +29,33 @@ using CommandPollerPtr = STD_PTR(shared, CommandPoller); class BufferWriter : public Writer { public: - BufferWriter(std::string name, uint32_t size, int fd, const CommandPollerPtr& cp, uint32_t pluginId); + BufferWriter(std::string name, + uint32_t size, + int smbFd, + int eventFd, + uint32_t pluginId); ~BufferWriter(); long Write(const void* data, size_t size) override; bool Flush() override; - bool WriteProtobuf(google::protobuf::Message& pmsg); + bool WriteMessage(const google::protobuf::Message& pmsg); + +private: + void DoStats(long bytes); + void Report() const; private: std::string pluginName_; std::shared_ptr shareMemoryBlock_; - CommandPollerPtr commandPoller_; - uint32_t pluginId_; + EventNotifierPtr eventNotifier_ = nullptr; + std::chrono::steady_clock::time_point lastFlushTime_; + std::atomic bytesCount_ = 0; + std::atomic bytesPending_ = 0; + std::atomic writeCount_ = 0; + std::atomic flushCount_ = 0; + uint32_t pluginId_ = 0; }; +using BufferWriterPtr = STD_PTR(shared, BufferWriter); + #endif // BUFFER_WRITER_H diff --git a/device/plugins/api/src/command_poller.cpp b/device/plugins/api/src/command_poller.cpp index 7b84a4335..60d0ca698 100644 --- a/device/plugins/api/src/command_poller.cpp +++ b/device/plugins/api/src/command_poller.cpp @@ -17,8 +17,14 @@ #include "plugin_manager.h" #include "socket_context.h" -CommandPoller::CommandPoller(const PluginManagerPtr& p) - : requestIdAutoIncrease_(1), pluginManager_(p) +#include +#include + +namespace { +constexpr int SLEEP_TIME = 10; +} + +CommandPoller::CommandPoller(const ManagerInterfacePtr& p) : requestIdAutoIncrease_(1), pluginManager_(p) { Connect(DEFAULT_UNIX_SOCKET_PATH); } @@ -45,13 +51,17 @@ bool CommandPoller::OnCreateSessionCmd(const CreateSessionCmd& cmd, SocketContex HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd FAIL 1"); return false; } - int fd = -1; + int smbFd = -1; + int eventFd = -1; if (bufferSize != 0) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd bufferSize = %d", bufferSize); - fd = context.ReceiveFileDiscriptor(); - HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd fd = %d", fd); + smbFd = context.ReceiveFileDiscriptor(); + eventFd = context.ReceiveFileDiscriptor(); + int flags = fcntl(eventFd, F_GETFL); + HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd smbFd = %d, eventFd = %d", smbFd, eventFd); + HILOG_DEBUG(LOG_CORE, "eventFd flags = %X", flags); } - if (!pluginManager->CreateWriter(config.name(), bufferSize, fd)) { + if (!pluginManager->CreateWriter(config.name(), bufferSize, smbFd, eventFd)) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd CreateWriter FAIL"); return false; } @@ -128,7 +138,7 @@ bool CommandPoller::OnStopSessionCmd(const StopSessionCmd& cmd) const bool CommandPoller::OnGetCommandResponse(SocketContext& context, ::GetCommandResponse& response) { HILOG_DEBUG(LOG_CORE, "OnGetCommandResponse"); - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); NotifyResultRequest nrr; nrr.set_request_id(1); nrr.set_command_id(response.command_id()); diff --git a/device/plugins/api/src/command_poller.h b/device/plugins/api/src/command_poller.h old mode 100755 new mode 100644 index bc4b31898..53edea65b --- a/device/plugins/api/src/command_poller.h +++ b/device/plugins/api/src/command_poller.h @@ -18,7 +18,7 @@ #include -class PluginManager; +class ManagerInterface; class CreateSessionCmd; class DestroySessionCmd; class StartSessionCmd; @@ -27,11 +27,11 @@ class StopSessionCmd; #include "logging.h" #include "plugin_service.ipc.h" -using PluginManagerPtr = STD_PTR(shared, PluginManager); +using ManagerInterfacePtr = STD_PTR(shared, ManagerInterface); class CommandPoller final : public IPluginServiceClient { public: - explicit CommandPoller(const PluginManagerPtr& p); + explicit CommandPoller(const ManagerInterfacePtr& p); ~CommandPoller(); bool OnCreateSessionCmd(const CreateSessionCmd& cmd, SocketContext& context) const; @@ -46,7 +46,7 @@ protected: private: uint32_t requestIdAutoIncrease_; - std::weak_ptr pluginManager_; + std::weak_ptr pluginManager_; }; #endif // !COMMAND_POLLER_H \ No newline at end of file diff --git a/device/plugins/api/src/main.cpp b/device/plugins/api/src/main.cpp old mode 100755 new mode 100644 index 3ed95273e..3dae87b44 --- a/device/plugins/api/src/main.cpp +++ b/device/plugins/api/src/main.cpp @@ -47,8 +47,15 @@ int main(int argc, char* argv[]) pluginManager->SetCommandPoller(commandPoller); PluginWatcher watcher(pluginManager); - watcher.ScanPlugins(pluginDir); - watcher.WatchPlugins(pluginDir); + if (!watcher.ScanPlugins(pluginDir)) { + HILOG_DEBUG(LOG_CORE, "Scan pluginDir:%s failed!", DEFAULT_PLUGIN_PATH); + return 0; + } + + if (!watcher.WatchPlugins(pluginDir)) { + HILOG_DEBUG(LOG_CORE, "Monitor pluginDir:%s failed!", DEFAULT_PLUGIN_PATH); + return 0; + } while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_ONE_SECOND)); diff --git a/device/plugins/api/src/plugin_manager.cpp b/device/plugins/api/src/plugin_manager.cpp index e531a5a79..052fe926e 100644 --- a/device/plugins/api/src/plugin_manager.cpp +++ b/device/plugins/api/src/plugin_manager.cpp @@ -15,12 +15,49 @@ #include "plugin_manager.h" +#include #include +#include #include "command_poller.h" #include "logging.h" +#include "openssl/sha.h" #include "plugin_service_types.pb.h" +namespace { +constexpr int FILE_READ_CHUNK_SIZE = 4096; +constexpr char HEX_CHARS[] = "0123456789abcdef"; + +#define HHB(v) (((v) & 0xF0) >> 4) +#define LHB(v) ((v) & 0x0F) + +std::string ComputeFileSha256(const std::string& path) +{ + uint8_t out[SHA256_DIGEST_LENGTH]; + uint8_t buffer[FILE_READ_CHUNK_SIZE]; + + SHA256_CTX sha; + SHA256_Init(&sha); + + size_t nbytes = 0; + std::unique_ptr fptr(fopen(path.c_str(), "rb"), fclose); + while ((nbytes = fread(buffer, 1, sizeof(buffer), fptr.get())) > 0) { + SHA256_Update(&sha, buffer, nbytes); + } + SHA256_Final(out, &sha); + + std::string result; + result.reserve(SHA256_DIGEST_LENGTH + SHA256_DIGEST_LENGTH); + for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { + result.push_back(HEX_CHARS[HHB(out[i])]); + result.push_back(HEX_CHARS[LHB(out[i])]); + } + + HILOG_DEBUG(LOG_CORE, "SHA256(%s): %s", path.c_str(), result.c_str()); + return result; +} +} // namespace + PluginManager::~PluginManager() {} void PluginManager::SetCommandPoller(const CommandPollerPtr& p) @@ -30,7 +67,7 @@ void PluginManager::SetCommandPoller(const CommandPollerPtr& p) bool PluginManager::AddPlugin(const std::string& pluginPath) { - PluginModuleInfo info; + PluginModuleInfo info = {0}; if (pluginIds_.find(pluginPath) != pluginIds_.end()) { HILOG_DEBUG(LOG_CORE, "already add"); @@ -62,7 +99,7 @@ bool PluginManager::AddPlugin(const std::string& pluginPath) RegisterPluginRequest request; request.set_request_id(commandPoller_->GetRequestId()); request.set_path(pluginPath); - request.set_sha256(""); + request.set_sha256(ComputeFileSha256(pluginPath)); request.set_name(pluginPath); request.set_buffer_size_hint(0); RegisterPluginResponse response; @@ -203,22 +240,22 @@ bool PluginManager::StartPluginSession(const std::vector& pluginIds, HILOG_DEBUG(LOG_CORE, "plugin not find"); return false; } - auto configData = pluginModules_[id]->GetConfigData(); - if (!pluginModules_[id]->StartSession( - reinterpret_cast(configData.c_str()), configData.size())) { + auto plugin = pluginModules_[id]; + auto cfgData = plugin->GetConfigData(); + if (!plugin->StartSession(reinterpret_cast(cfgData.c_str()), cfgData.size())) { return false; } - if (pluginModules_[id]->GetSampleMode() == PluginModule::POLLING) { + if (plugin->GetSampleMode() == PluginModule::POLLING) { if (idx > config.size()) { HILOG_WARN(LOG_CORE, "idx %zu out of size %zu", idx, config.size()); return false; } - uint32_t sampleInterval = config[idx].sample_interval(); + auto interval = ScheduleTaskManager::ms(config[idx].sample_interval()); std::string pluginName = config[idx].name(); - HILOG_DEBUG(LOG_CORE, "sampleInterval = %d", sampleInterval); - HILOG_DEBUG(LOG_CORE, "name = %s", pluginName.c_str()); - if (!scheduleTaskManager_.ScheduleTask(pluginName, std::bind(&PluginManager::PullResult, this, id), - ScheduleTaskManager::ms(sampleInterval))) { + HILOG_DEBUG(LOG_CORE, "interval = %ld", static_cast(interval.count())); + HILOG_DEBUG(LOG_CORE, "pluginName = %s", pluginName.c_str()); + auto callback = std::bind(&PluginManager::PullResult, this, id); + if (!scheduleTaskManager_.ScheduleTask(pluginName, callback, interval)) { HILOG_DEBUG(LOG_CORE, "ScheduleTask failed"); return false; } @@ -282,10 +319,8 @@ bool PluginManager::SubmitResult(const PluginResult& pluginResult) bool PluginManager::PullResult(uint32_t pluginId) { - HILOG_INFO(LOG_CORE, "%s: ready!", __func__); uint32_t size = 0; - std::string name; - HILOG_DEBUG(LOG_CORE, "PullResult pluginId = %d", pluginId); + std::string name = ""; auto it = pluginModules_.find(pluginId); if (it == pluginModules_.end()) { HILOG_DEBUG(LOG_CORE, "plugin not find"); @@ -293,19 +328,16 @@ bool PluginManager::PullResult(uint32_t pluginId) } pluginModules_[pluginId]->GetBufferSizeHint(size); pluginModules_[pluginId]->GetPluginName(name); - std::unique_ptr buffer {new (std::nothrow) uint8_t[size]}; + std::unique_ptr buffer(new (std::nothrow) uint8_t[size]); if (buffer == nullptr) { HILOG_DEBUG(LOG_CORE, "buffer new failed!"); - } else { - HILOG_DEBUG(LOG_CORE, "buffer new success!"); + return false; } int length = it->second->ReportResult(buffer.get(), size); if (length < 0) { return false; } - HILOG_DEBUG(LOG_CORE, "PullResult length = %d", length); - HILOG_DEBUG(LOG_CORE, "PullResult name = %s", name.c_str()); ProfilerPluginData pluginData; pluginData.set_name(name); @@ -319,14 +351,15 @@ bool PluginManager::PullResult(uint32_t pluginId) pluginData.set_tv_sec(ts.tv_sec); pluginData.set_tv_nsec(ts.tv_nsec); - auto writer = pluginModules_[pluginId]->GetWriter(); + auto writer = std::static_pointer_cast(pluginModules_[pluginId]->GetWriter()); CHECK_NOTNULL(writer, false, "PullResult GetWriter nullptr"); - std::static_pointer_cast(writer)->WriteProtobuf(pluginData); + writer->WriteMessage(pluginData); + writer->Flush(); return true; } -bool PluginManager::CreateWriter(std::string pluginName, uint32_t bufferSize, int fd) +bool PluginManager::CreateWriter(std::string pluginName, uint32_t bufferSize, int smbFd, int eventFd) { auto it = pluginIds_.find(pluginName); if (it == pluginIds_.end()) { @@ -338,7 +371,7 @@ bool PluginManager::CreateWriter(std::string pluginName, uint32_t bufferSize, in if (bufferSize > 0) { HILOG_DEBUG(LOG_CORE, "%s Use ShareMemory %d", pluginName.c_str(), bufferSize); pluginModules_[index]->RegisterWriter( - std::make_shared(pluginName, bufferSize, fd, commandPoller_, index)); + std::make_shared(pluginName, bufferSize, smbFd, eventFd, index)); } else { HILOG_ERROR(LOG_CORE, "no shared memory buffer allocated!"); return false; diff --git a/device/plugins/api/src/plugin_manager.h b/device/plugins/api/src/plugin_manager.h index efac5576b..a622a9be2 100644 --- a/device/plugins/api/src/plugin_manager.h +++ b/device/plugins/api/src/plugin_manager.h @@ -21,6 +21,7 @@ #include #include +#include "manager_interface.h" #include "plugin_module.h" #include "schedule_task_manager.h" @@ -28,7 +29,7 @@ class ProfilerPluginConfig; class PluginResult; class CommandPoller; -class PluginManager { +class PluginManager : public ManagerInterface { public: virtual ~PluginManager(); bool AddPlugin(const std::string& pluginPath); @@ -50,7 +51,7 @@ public: // for test virtual bool SubmitResult(const PluginResult& pluginResult); - bool CreateWriter(std::string pluginName, uint32_t bufferSize, int fd); + bool CreateWriter(std::string pluginName, uint32_t bufferSize, int smbFd, int eventFd); bool ResetWriter(uint32_t pluginId); void SetCommandPoller(const CommandPollerPtr& p); diff --git a/device/plugins/api/src/plugin_module.cpp b/device/plugins/api/src/plugin_module.cpp index 98f9242da..01a0bd4bd 100644 --- a/device/plugins/api/src/plugin_module.cpp +++ b/device/plugins/api/src/plugin_module.cpp @@ -137,7 +137,7 @@ bool PluginModule::BindFunctions() return false; } if (structPtr_ == nullptr) { - structPtr_ = (PluginModuleStruct*)dlsym(handle_, "g_pluginModule"); + structPtr_ = static_cast(dlsym(handle_, "g_pluginModule")); if (structPtr_ == nullptr) { HILOG_DEBUG(LOG_CORE, "structPtr_ == nullptr"); return false; @@ -165,7 +165,6 @@ bool PluginModule::StartSession(const uint8_t* buffer, uint32_t size) HILOG_DEBUG(LOG_CORE, "plugin not load"); return false; } - HILOG_DEBUG(LOG_CORE, "size = %u, ", size); if (structPtr_ != nullptr && structPtr_->callbacks != nullptr) { if (structPtr_->callbacks->onPluginSessionStart) { @@ -192,8 +191,6 @@ bool PluginModule::StopSession() int32_t PluginModule::ReportResult(uint8_t* buffer, uint32_t size) { - HILOG_INFO(LOG_CORE, "%s: ready!", __func__); - HILOG_DEBUG(LOG_CORE, "ReportResult"); if (handle_ == nullptr) { HILOG_DEBUG(LOG_CORE, "plugin not open"); return -1; @@ -203,15 +200,11 @@ int32_t PluginModule::ReportResult(uint8_t* buffer, uint32_t size) first_ = false; } else { std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now(); - std::chrono::duration interval = - std::chrono::duration_cast>(t1 - lastTime_); - HILOG_DEBUG(LOG_CORE, "the id equals %u interval is %d milli seconds", size, interval.count()); lastTime_ = t1; } if (structPtr_ != nullptr && structPtr_->callbacks != nullptr) { if (structPtr_->callbacks->onPluginReportResult != nullptr) { - HILOG_INFO(LOG_CORE, "%s: call plugin ready!", __func__); return structPtr_->callbacks->onPluginReportResult(buffer, size); } } @@ -223,6 +216,11 @@ bool PluginModule::RegisterWriter(const BufferWriterPtr writer) { writerAdapter_ = std::make_shared(); writerAdapter_->SetWriter(writer); + + if (writer == nullptr) { + HILOG_INFO(LOG_CORE, "BufferWriter is null, update WriterAdapter only!"); + return true; + } if (structPtr_ != nullptr && structPtr_->callbacks != nullptr) { if (structPtr_->callbacks->onRegisterWriterStruct != nullptr) { return structPtr_->callbacks->onRegisterWriterStruct(writerAdapter_->GetStruct()); diff --git a/device/plugins/api/src/plugin_watcher.cpp b/device/plugins/api/src/plugin_watcher.cpp old mode 100755 new mode 100644 index 7f0c58d08..d69874378 --- a/device/plugins/api/src/plugin_watcher.cpp +++ b/device/plugins/api/src/plugin_watcher.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -54,7 +55,7 @@ PluginWatcher::~PluginWatcher() monitorThread_.join(); } -void PluginWatcher::ScanPlugins(const std::string& pluginDir) +bool PluginWatcher::ScanPlugins(const std::string& pluginDir) { DIR* dir = nullptr; struct dirent* entry = nullptr; @@ -63,7 +64,7 @@ void PluginWatcher::ScanPlugins(const std::string& pluginDir) HILOG_INFO(LOG_CORE, "scan plugin from directory %s", fullpath); dir = opendir(fullpath); if (dir == nullptr) { - return; + return false; } while (true) { entry = readdir(dir); @@ -80,10 +81,10 @@ void PluginWatcher::ScanPlugins(const std::string& pluginDir) } } closedir(dir); - return; + return true; } -void PluginWatcher::WatchPlugins(const std::string& pluginDir) +bool PluginWatcher::WatchPlugins(const std::string& pluginDir) { char fullpath[PATH_MAX + 1] = {0}; realpath(pluginDir.c_str(), fullpath); @@ -91,66 +92,80 @@ void PluginWatcher::WatchPlugins(const std::string& pluginDir) int wd = inotify_add_watch(inotifyFd_, fullpath, IN_ALL_EVENTS); if (wd < 0) { HILOG_INFO(LOG_CORE, "inotify_add_watch add directory %s failed", pluginDir.c_str()); - return; + return false; } HILOG_INFO(LOG_CORE, "inotify_add_watch add directory %s success", fullpath); std::lock_guard guard(mtx_); wdToDir_.insert(std::pair(wd, std::string(fullpath))); + return true; } -void PluginWatcher::Monitor() + + +bool PluginWatcher::MonitorIsSet() { const struct inotify_event* event = nullptr; char buffer[MAX_BUF_SIZE] = {'\0'}; - struct timeval time; char* ptr = nullptr; - int ret = 0; + ssize_t readLength = read(inotifyFd_, buffer, MAX_BUF_SIZE); + if (readLength == -1) { + return false; + } + for (ptr = buffer; ptr < buffer + readLength; ptr += sizeof(struct inotify_event) + event->len) { + event = reinterpret_cast(ptr); + std::unique_lock guard(mtx_, std::adopt_lock); + const std::string& pluginDir = wdToDir_[event->wd]; + guard.unlock(); + if (event->mask & IN_ISDIR) { + continue; + } + std::string fileName = event->name; + size_t pos = fileName.rfind(".so"); + if ((pos == std::string::npos) || (pos != fileName.length() - strlen(".so"))) { + continue; + } + switch (event->mask) { + case IN_CLOSE_WRITE: + case IN_MOVED_TO: + OnPluginAdded(pluginDir + '/' + fileName); + break; + case IN_DELETE: + case IN_MOVED_FROM: + OnPluginRemoved(pluginDir + '/' + fileName); + break; + default: + break; + } + } + if (memset_s(buffer, MAX_BUF_SIZE, 0, MAX_BUF_SIZE) != 0) { + HILOG_ERROR(LOG_CORE, "memset_s error!"); + } + return true; +} + + + +void PluginWatcher::Monitor() +{ + struct timeval time; + + pthread_setname_np(pthread_self(), "PluginWatcher"); while (runMonitor_) { fd_set rFds; FD_ZERO(&rFds); FD_SET(inotifyFd_, &rFds); time.tv_sec = 1; time.tv_usec = 0; - ret = select(inotifyFd_ + 1, &rFds, nullptr, nullptr, &time); + int ret = select(inotifyFd_ + 1, &rFds, nullptr, nullptr, &time); if (ret < 0) { continue; } else if (!ret) { continue; } else if (FD_ISSET(inotifyFd_, &rFds)) { - ssize_t readLength = read(inotifyFd_, buffer, MAX_BUF_SIZE); - if (readLength == -1) { + if (!MonitorIsSet()) { continue; } - for (ptr = buffer; ptr < buffer + readLength; ptr += sizeof(struct inotify_event) + event->len) { - event = reinterpret_cast(ptr); - std::unique_lock guard(mtx_, std::adopt_lock); - const std::string& pluginDir = wdToDir_[event->wd]; - guard.unlock(); - if (event->mask & IN_ISDIR) { - continue; - } - std::string fileName = event->name; - size_t pos = fileName.rfind(".so"); - if (pos == std::string::npos || (pos != fileName.length() - strlen(".so"))) { - continue; - } - switch (event->mask) { - case IN_CLOSE_WRITE: - case IN_MOVED_TO: - OnPluginAdded(pluginDir + '/' + fileName); - break; - case IN_DELETE: - case IN_MOVED_FROM: - OnPluginRemoved(pluginDir + '/' + fileName); - break; - default: - break; - } - } - if (memset_s(buffer, MAX_BUF_SIZE, 0, MAX_BUF_SIZE) != EOK) { - HILOG_ERROR(LOG_CORE, "memset_s error!"); - } } } } diff --git a/device/plugins/api/src/plugin_watcher.h b/device/plugins/api/src/plugin_watcher.h old mode 100755 new mode 100644 index 41902af2e..f5382142b --- a/device/plugins/api/src/plugin_watcher.h +++ b/device/plugins/api/src/plugin_watcher.h @@ -31,10 +31,8 @@ class PluginWatcher { public: explicit PluginWatcher(const PluginManagerPtr& pluginManager); ~PluginWatcher(); - - void ScanPlugins(const std::string& pluginDir); - - void WatchPlugins(const std::string& pluginDir); + bool ScanPlugins(const std::string& pluginDir); + bool WatchPlugins(const std::string& pluginDir); private: int inotifyFd_; @@ -43,11 +41,10 @@ private: std::thread monitorThread_; std::mutex mtx_; bool runMonitor_; - virtual void OnPluginAdded(const std::string& pluginPath); virtual void OnPluginRemoved(const std::string& pluginPath); - void MonitorEventName(uint32_t mask, const std::string& fileName, const std::string& pluginDir); void Monitor(); + bool MonitorIsSet(); }; #endif // !PLUGIN_WATCHER_H diff --git a/device/plugins/api/src/writer_adapter.cpp b/device/plugins/api/src/writer_adapter.cpp old mode 100755 new mode 100644 index ee8f9a343..4402143e5 --- a/device/plugins/api/src/writer_adapter.cpp +++ b/device/plugins/api/src/writer_adapter.cpp @@ -40,7 +40,8 @@ const WriterStruct* WriterAdapter::GetStruct() long WriterAdapter::WriteFunc(WriterStruct* writer, const void* data, size_t size) { - WriterAdapter* writerAdaptor = reinterpret_cast(writer); + static_assert(offsetof(WriterAdapter, writerStruct_) == 0, "unexpected alignment of writerStruct_!"); + WriterAdapter* writerAdaptor = reinterpret_cast(writer); // 转成 WriterAdapter* if (writerAdaptor && writerAdaptor->writer_) { return writerAdaptor->writer_->Write(data, size); } diff --git a/device/plugins/api/src/writer_adapter.h b/device/plugins/api/src/writer_adapter.h old mode 100755 new mode 100644 diff --git a/device/plugins/api/test/BUILD.gn b/device/plugins/api/test/BUILD.gn old mode 100755 new mode 100644 index 7d9c9d9a9..0cc9d181e --- a/device/plugins/api/test/BUILD.gn +++ b/device/plugins/api/test/BUILD.gn @@ -16,49 +16,43 @@ import("../../../base/config.gni") module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" config("module_private_config") { - visibility = [":*"] + visibility = [ ":*" ] } config("cflags_config") { cflags = [ "-Wno-sign-compare", "-pthread", - "-Dprivate=public", #allow test code access private members - "-Dprotected=public", #allow test code access private members + "-Dprivate=public", #allow test code access private members + "-Dprotected=public", #allow test code access private members ] } ohos_unittest("hiprofiler_plugins_ut") { module_out_path = module_output_path deps = [ - "../:plugins_sources", "${OHOS_PROFILER_DIR}/device/services/plugin_service:hiprofiler_plugin_service", "${OHOS_PROFILER_DIR}/device/services/profiler_service:profiler_service", + "../:plugins_sources", "//third_party/googletest:gmock", "//third_party/googletest:gtest", ] - include_dirs = [ - "//third_party/googletest/googletest/include/gtest", - ] + include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] sources = [ - "unittest/writer_adapter_test.cpp", + "unittest/buffer_write_test.cpp", + "unittest/command_poller_test.cpp", "unittest/plugin_manager_test.cpp", + "unittest/plugin_module_test.cpp", "unittest/plugin_watcher_test.cpp", - "unittest/services_ipc_test.cpp", - "unittest/services_profiler_service_test.cpp", - "unittest/services_shared_memory_test.cpp", - "unittest/services_plugin_service_test.cpp", + "unittest/writer_adapter_test.cpp", ] configs = [ ":cflags_config" ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" } group("unittest") { testonly = true - deps = [ - ":hiprofiler_plugins_ut", - ] + deps = [ ":hiprofiler_plugins_ut" ] } diff --git a/device/plugins/api/test/unittest/buffer_write_test.cpp b/device/plugins/api/test/unittest/buffer_write_test.cpp new file mode 100644 index 000000000..4197fb63a --- /dev/null +++ b/device/plugins/api/test/unittest/buffer_write_test.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "buffer_writer.h" +#include "plugin_service_types.pb.h" + +using namespace testing::ext; + +namespace { +constexpr uint32_t SMB1_SIZE = 10 * 4096; +constexpr uint32_t SMB2_SIZE = 10 * 4096; +const std::string SMB1_NAME = "testsmb1"; +const std::string SMB2_NAME = "testsmb2"; +const std::string PLUGIN_NAME = "testplugin"; +void *g_smbAddr1 = nullptr; +void *g_smbAddr2 = nullptr; +int g_smbFd1 = 0; +int g_smbFd2 = 0; + +int InitShareMemory1() +{ + int fd = syscall(SYS_memfd_create, SMB1_NAME.c_str(), 0); + CHECK_TRUE(fd >= 0, false, "CreateBlock FAIL SYS_memfd_create"); + + int check = ftruncate(fd, SMB1_SIZE); + if (check < 0) { + close(fd); + HILOG_ERROR(LOG_CORE, "CreateBlock ftruncate ERR : %s", strerror(errno)); + return -1; + } + + g_smbAddr1 = mmap(nullptr, SMB1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (g_smbAddr1 == MAP_FAILED) { + close(fd); + HILOG_ERROR(LOG_CORE, "CreateBlock g_smbAddr1 mmap ERR : %s", strerror(errno)); + return -1; + } + + ShareMemoryBlock::BlockHeader* header_ = reinterpret_cast(g_smbAddr1); + + // initialize header infos + header_->info.readOffset_ = 0; + header_->info.writeOffset_ = 0; + header_->info.memorySize_ = SMB1_SIZE - sizeof(ShareMemoryBlock::BlockHeader); + header_->info.bytesCount_ = 0; + header_->info.chunkCount_ = 0; + + return fd; +} + +int InitShareMemory2() +{ + int fd = syscall(SYS_memfd_create, SMB2_NAME.c_str(), 0); + CHECK_TRUE(fd >= 0, false, "CreateBlock FAIL SYS_memfd_create"); + + int check = ftruncate(fd, SMB2_SIZE); + if (check < 0) { + close(fd); + HILOG_ERROR(LOG_CORE, "CreateBlock ftruncate ERR : %s", strerror(errno)); + return -1; + } + + g_smbAddr2 = mmap(nullptr, SMB2_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (g_smbAddr2 == MAP_FAILED) { + close(fd); + HILOG_ERROR(LOG_CORE, "CreateBlock g_smbAddr2 mmap ERR : %s", strerror(errno)); + return -1; + } + + ShareMemoryBlock::BlockHeader* header_ = reinterpret_cast(g_smbAddr2); + + // initialize header infos + header_->info.readOffset_ = 0; + header_->info.writeOffset_ = 0; + header_->info.memorySize_ = SMB2_SIZE - sizeof(ShareMemoryBlock::BlockHeader); + header_->info.bytesCount_ = 0; + header_->info.chunkCount_ = 0; + + return fd; +} + +class BufferWriteTest : public ::testing::Test { +protected: + static void SetUpTestCase() + { + g_smbFd1 = InitShareMemory1(); + g_smbFd2 = InitShareMemory2(); + printf("SetUpTestCase success\n"); + } + static void TearDownTestCase() {} +}; + +bool CheckBuffer(uint8_t *buffer, size_t size) +{ + ShareMemoryBlock::BlockHeader* header_ = reinterpret_cast(g_smbAddr1); + uint8_t *cmpaddr = (uint8_t *)g_smbAddr1 + sizeof(ShareMemoryBlock::BlockHeader) + header_->info.readOffset_; + uint32_t cmpsize = *(uint32_t*)cmpaddr; + cmpaddr = cmpaddr + sizeof(uint32_t); + ProfilerPluginData pluginData; + pluginData.ParseFromArray(cmpaddr, cmpsize); + const char* data = pluginData.data().c_str(); + + header_->info.readOffset_ = header_->info.writeOffset_; + if (memcmp(buffer, data, size) == 0) { + return true; + } + return false; +} + + +bool CheckMessage(uint8_t *buffer, size_t size) +{ + ShareMemoryBlock::BlockHeader* header_ = reinterpret_cast(g_smbAddr2); + uint8_t *cmpaddr = (uint8_t *)g_smbAddr2 + sizeof(ShareMemoryBlock::BlockHeader) + header_->info.readOffset_; + cmpaddr = cmpaddr + sizeof(uint32_t); + header_->info.readOffset_ = header_->info.writeOffset_; + + if (memcmp(buffer, cmpaddr, size) == 0) { + return true; + } + return false; +} + +/** + * @tc.name: plugin + * @tc.desc: Write data to shared memory through writer. + * @tc.type: FUNC + */ +HWTEST_F(BufferWriteTest, WriteTest, TestSize.Level1) +{ + auto write = std::make_shared(PLUGIN_NAME, SMB1_SIZE, g_smbFd1, -1, 0); + + uint8_t buffer1[] = {0x55, 0xAA, 0x55, 0xAA}; + uint8_t buffer2[] = {0x11, 0x22, 0x33, 0x44}; + uint8_t buffer3[] = {0xAA, 0xBB, 0xCC, 0xDD}; + + EXPECT_TRUE(write->Write(buffer1, sizeof(buffer1))); + EXPECT_TRUE(CheckBuffer(buffer1, sizeof(buffer1))); + EXPECT_TRUE(write->Write(buffer2, sizeof(buffer2))); + EXPECT_TRUE(CheckBuffer(buffer2, sizeof(buffer2))); + EXPECT_TRUE(write->Write(buffer3, sizeof(buffer3))); + EXPECT_TRUE(CheckBuffer(buffer3, sizeof(buffer3))); + EXPECT_FALSE(write->Write(nullptr, 0)); +} + +/** + * @tc.name: plugin + * @tc.desc: Write data to shared memory through writer. + * @tc.type: FUNC + */ +HWTEST_F(BufferWriteTest, WriteMessageTest, TestSize.Level1) +{ + uint8_t data[1024]; + auto write = std::make_shared(PLUGIN_NAME, SMB2_SIZE, g_smbFd2, -1, 0); + + ProfilerPluginConfig configData; + configData.set_name("111"); + configData.set_plugin_sha256("222"); + configData.set_sample_interval(1000); + size_t size = configData.ByteSizeLong(); + configData.SerializeToArray(data, size); + + EXPECT_TRUE(write->WriteMessage(configData)); + EXPECT_TRUE(CheckMessage(data, size)); + + ProfilerPluginState stateData; + stateData.set_name("st"); + stateData.set_state(ProfilerPluginState::IN_SESSION); + size = stateData.ByteSizeLong(); + stateData.SerializeToArray(data, size); + + EXPECT_TRUE(write->WriteMessage(stateData)); + EXPECT_TRUE(CheckMessage(data, size)); + + + ProfilerPluginData pluginData; + pluginData.set_name("test"); + pluginData.set_status(1); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + pluginData.set_clock_id(ProfilerPluginData::CLOCKID_REALTIME); + pluginData.set_tv_sec(ts.tv_sec); + pluginData.set_tv_nsec(ts.tv_nsec); + size = pluginData.ByteSizeLong(); + pluginData.SerializeToArray(data, size); + + EXPECT_TRUE(write->WriteMessage(pluginData)); + EXPECT_TRUE(CheckMessage(data, size)); +} +} // namespace \ No newline at end of file diff --git a/device/plugins/api/test/unittest/command_poller_test.cpp b/device/plugins/api/test/unittest/command_poller_test.cpp new file mode 100644 index 000000000..1576ff82e --- /dev/null +++ b/device/plugins/api/test/unittest/command_poller_test.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "command_poller.h" + +#include "plugin_manager.h" +#include "plugin_service.ipc.h" +#include "socket_context.h" + +using namespace testing::ext; + +namespace { +class PluginManagerStub final : public ManagerInterface { +public: + virtual bool LoadPlugin(const std::string& pluginPath) override + { + if (pluginPath == "existplugin") { + return true; + } else if (pluginPath == "noexistplugin") { + return false; + } + return true; + } + virtual bool UnloadPlugin(const std::string& pluginPath) + { + if (pluginPath == "existplugin") { + return true; + } else if (pluginPath == "noexistplugin") { + return false; + } + return true; + } + virtual bool UnloadPlugin(const uint32_t pluginId) + { + if (pluginId == 0) { + return false; + } + return true; + } + + virtual bool CreatePluginSession(const std::vector& config) + { + if (config[0].name() == "existplugin") { + return true; + } else if (config[0].name() == "noexistplugin") { + return false; + } + return true; + } + virtual bool DestroyPluginSession(const std::vector& pluginIds) + { + if (pluginIds[0] != 1) { + return false; + } + return true; + } + virtual bool StartPluginSession(const std::vector& pluginIds, + const std::vector& config) + { + if (pluginIds[0] == 0) { + return false; + } + + if (config[0].name() == "existplugin") { + return true; + } else if (config[0].name() == "noexistplugin") { + return false; + } + return true; + } + virtual bool StopPluginSession(const std::vector& pluginIds) + { + if (pluginIds[0] == 0) { + return false; + } + return true; + } + + virtual bool CreateWriter(std::string pluginName, uint32_t bufferSize, int smbFd, int eventFd) + { + if (bufferSize == 0) { + return false; + } + return true; + } + virtual bool ResetWriter(uint32_t pluginId) + { + if (pluginId == 0) { + return false; + } + return true; + } + virtual void SetCommandPoller(const std::shared_ptr& p) + { + this->commandPoller_ = p; + } +private: + CommandPollerPtr commandPoller_; +}; + + +class CommandPollerTest : public ::testing::Test { +protected: + static void SetUpTestCase() {} + static void TearDownTestCase() {} +}; + +HWTEST_F(CommandPollerTest, CreateCmdTest, TestSize.Level1) +{ + auto pluginManage = std::make_shared(); + auto commandPoller = std::make_shared(pluginManage); + pluginManage->SetCommandPoller(commandPoller); + + CreateSessionCmd successCmd; + CreateSessionCmd failed1Cmd; + CreateSessionCmd failed2Cmd; + CreateSessionCmd failed3Cmd; + SocketContext ctx; + + successCmd.add_buffer_sizes(1024); + successCmd.add_plugin_configs()->set_name("existplugin"); + + failed1Cmd.add_buffer_sizes(0); + failed1Cmd.add_plugin_configs()->set_name("existplugin"); + + failed2Cmd.add_buffer_sizes(0); + failed2Cmd.add_plugin_configs()->set_name("noexistplugin"); + + failed3Cmd.add_buffer_sizes(1); + failed3Cmd.add_plugin_configs()->set_name("noexistplugin"); + EXPECT_TRUE(commandPoller->OnCreateSessionCmd(successCmd, ctx)); + EXPECT_FALSE(commandPoller->OnCreateSessionCmd(failed1Cmd, ctx)); + EXPECT_FALSE(commandPoller->OnCreateSessionCmd(failed2Cmd, ctx)); + EXPECT_FALSE(commandPoller->OnCreateSessionCmd(failed3Cmd, ctx)); +} + +HWTEST_F(CommandPollerTest, StartCmdTest, TestSize.Level1) +{ + auto pluginManage = std::make_shared(); + auto commandPoller = std::make_shared(pluginManage); + pluginManage->SetCommandPoller(commandPoller); + + StartSessionCmd successCmd; + successCmd.add_plugin_ids(1); + successCmd.add_plugin_configs()->set_name("existplugin"); + StartSessionCmd failed1Cmd; + + failed1Cmd.add_plugin_ids(0); + failed1Cmd.add_plugin_configs()->set_name("existplugin"); + + StartSessionCmd failed2Cmd; + failed2Cmd.add_plugin_ids(1); + failed2Cmd.add_plugin_configs()->set_name("noexistplugin"); + + EXPECT_TRUE(commandPoller->OnStartSessionCmd(successCmd)); + EXPECT_FALSE(commandPoller->OnStartSessionCmd(failed1Cmd)); + EXPECT_FALSE(commandPoller->OnStartSessionCmd(failed2Cmd)); +} + +HWTEST_F(CommandPollerTest, StopCmdTest, TestSize.Level1) +{ + auto pluginManage = std::make_shared(); + auto commandPoller = std::make_shared(pluginManage); + pluginManage->SetCommandPoller(commandPoller); + + StopSessionCmd successCmd; + successCmd.add_plugin_ids(1); + StopSessionCmd failedCmd; + failedCmd.add_plugin_ids(0); + EXPECT_TRUE(commandPoller->OnStopSessionCmd(successCmd)); + EXPECT_FALSE(commandPoller->OnStopSessionCmd(failedCmd)); +} + +HWTEST_F(CommandPollerTest, DestoryCmdTest, TestSize.Level1) +{ + auto pluginManage = std::make_shared(); + auto commandPoller = std::make_shared(pluginManage); + pluginManage->SetCommandPoller(commandPoller); + DestroySessionCmd successCmd; + DestroySessionCmd failed1Cmd; + DestroySessionCmd failed2Cmd; + DestroySessionCmd failed3Cmd; + successCmd.add_plugin_ids(1); + failed1Cmd.add_plugin_ids(0); + failed2Cmd.add_plugin_ids(2); + failed3Cmd.add_plugin_ids(3); + EXPECT_TRUE(commandPoller->OnDestroySessionCmd(successCmd)); + EXPECT_FALSE(commandPoller->OnDestroySessionCmd(failed1Cmd)); + EXPECT_FALSE(commandPoller->OnDestroySessionCmd(failed2Cmd)); + EXPECT_FALSE(commandPoller->OnDestroySessionCmd(failed3Cmd)); +} +} \ No newline at end of file diff --git a/device/plugins/api/test/unittest/plugin_manager_test.cpp b/device/plugins/api/test/unittest/plugin_manager_test.cpp index e268ac39e..ab13d1e72 100644 --- a/device/plugins/api/test/unittest/plugin_manager_test.cpp +++ b/device/plugins/api/test/unittest/plugin_manager_test.cpp @@ -32,8 +32,12 @@ using google::protobuf::Message; using namespace testing::ext; namespace { +constexpr int DEFAULT_BUFFER_SIZE = 4096; +constexpr int DEFAULT_SLEEP_TIME = 1000; const static std::string SUCCESS_PLUGIN_NAME = "libmemdataplugin.z.so"; -std::string g_testPluginDir("/data/local/tmp/"); +std::string g_testPluginDir("/system/lib/"); +int g_hiprofilerProcessNum = -1; +const std::string DEFAULT_HIPROFILERD_PATH("/system/lib/hiprofilerd"); class PluginManagerTest : public ::testing::Test { protected: @@ -54,10 +58,29 @@ protected: printf("======> pluginDir = %s\n", g_testPluginDir.c_str()); std::this_thread::sleep_for(TEMP_DELAY); + + int processNum = fork(); + std::cout << "processNum : " << processNum << std::endl; + if (processNum == 0) { + // start running hiprofilerd + std::string cmd = "chmod 777 " + DEFAULT_HIPROFILERD_PATH; + std::cout << "cmd : " << cmd << std::endl; + system(cmd.c_str()); + execl(DEFAULT_HIPROFILERD_PATH.c_str(), nullptr, nullptr); + _exit(1); + } else { + g_hiprofilerProcessNum = processNum; + } + + std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_SLEEP_TIME)); printf("SetUpTestCase success\n"); } + static void TearDownTestCase() { + std::string stopCmd = "kill " + std::to_string(g_hiprofilerProcessNum); + std::cout << "stop command : " << stopCmd << std::endl; + std::unique_ptr pipe(popen(stopCmd.c_str(), "r"), pclose); } }; @@ -75,33 +98,30 @@ HWTEST_F(PluginManagerTest, SuccessPlugin, TestSize.Level1) const uint8_t configData[] = {0x30, 0x01, 0x38, 0x01, 0x42, 0x01, 0x01}; ProfilerPluginConfig config; const std::vector pluginIdsVector = {1}; - config.set_name(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME); + config.set_name(g_testPluginDir + SUCCESS_PLUGIN_NAME); config.set_config_data((const void*)configData, 7); - config.set_sample_interval(1000); + config.set_sample_interval(DEFAULT_SLEEP_TIME); - EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->UnloadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->AddPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->AddPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->RemovePlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->RemovePlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->AddPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->UnloadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); + EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_FALSE(pluginManage->UnloadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->AddPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_FALSE(pluginManage->AddPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->RemovePlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_FALSE(pluginManage->RemovePlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->AddPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->LoadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->UnloadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); - EXPECT_FALSE(pluginManage->LoadPlugin(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME)); + EXPECT_TRUE(pluginManage->LoadPlugin(g_testPluginDir + SUCCESS_PLUGIN_NAME)); std::vector configVec; configVec.push_back(config); - EXPECT_FALSE(pluginManage->CreatePluginSession(configVec)); - - EXPECT_FALSE(pluginManage->StartPluginSession(pluginIdsVector, configVec)); + EXPECT_TRUE(pluginManage->CreatePluginSession(configVec)); + EXPECT_TRUE(pluginManage->StartPluginSession(pluginIdsVector, configVec)); std::this_thread::sleep_for(TEMP_DELAY); - - EXPECT_FALSE(pluginManage->StopPluginSession(pluginIdsVector)); - - EXPECT_FALSE(pluginManage->DestroyPluginSession(pluginIdsVector)); + EXPECT_TRUE(pluginManage->StopPluginSession(pluginIdsVector)); + EXPECT_TRUE(pluginManage->DestroyPluginSession(pluginIdsVector)); } /** @@ -112,7 +132,14 @@ HWTEST_F(PluginManagerTest, SuccessPlugin, TestSize.Level1) HWTEST_F(PluginManagerTest, GetSampleMode, TestSize.Level1) { PluginModule pluginModule; - pluginModule.GetSampleMode(); + if (pluginModule.structPtr_ && pluginModule.structPtr_->callbacks) { + if (pluginModule.structPtr_->callbacks->onPluginReportResult != nullptr) { + EXPECT_EQ(pluginModule.GetSampleMode(), PluginModule::SampleMode::POLLING); + } else if (pluginModule.structPtr_->callbacks->onRegisterWriterStruct != nullptr) { + EXPECT_EQ(pluginModule.GetSampleMode(), PluginModule::SampleMode::STREAMING); + } + } + EXPECT_EQ(pluginModule.GetSampleMode(), PluginModule::SampleMode::UNKNOWN); } /** @@ -124,25 +151,30 @@ HWTEST_F(PluginManagerTest, PluginManager, TestSize.Level1) { PluginManager pluginManager; PluginModuleInfo info; - pluginManager.UnloadPlugin(0); + EXPECT_FALSE(pluginManager.UnloadPlugin(0)); PluginResult pluginResult; - pluginManager.SubmitResult(pluginResult); - pluginManager.PullResult(0); - pluginManager.CreateWriter("", 0, -1); - pluginManager.ResetWriter(-1); + EXPECT_FALSE(pluginManager.SubmitResult(pluginResult)); + EXPECT_FALSE(pluginManager.PullResult(0)); + EXPECT_FALSE(pluginManager.CreateWriter("", 0, -1, -1)); + EXPECT_FALSE(pluginManager.ResetWriter(-1)); PluginModule pluginModule; - pluginModule.ComputeSha256(); - pluginModule.Unload(); - pluginModule.GetInfo(info); + EXPECT_EQ(pluginModule.ComputeSha256(), ""); + EXPECT_FALSE(pluginModule.Unload()); + EXPECT_FALSE(pluginModule.GetInfo(info)); std::string str("memory-plugin"); - pluginModule.GetPluginName(str); + EXPECT_FALSE(pluginModule.GetPluginName(str)); uint32_t num = 0; - pluginModule.GetBufferSizeHint(num); - pluginModule.IsLoaded(); + EXPECT_FALSE(pluginModule.GetBufferSizeHint(num)); + EXPECT_FALSE(pluginModule.IsLoaded()); - BufferWriter bufferWriter("", 0, -1, nullptr, 0); - bufferWriter.Write(nullptr, 0); - bufferWriter.Flush(); + BufferWriter bufferWriter("test", DEFAULT_BUFFER_SIZE, -1, -1, 0); + + EXPECT_EQ(bufferWriter.shareMemoryBlock_, nullptr); + EXPECT_FALSE(bufferWriter.Write(str.data(), str.size())); + bufferWriter.shareMemoryBlock_ = + ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("test", DEFAULT_BUFFER_SIZE); + EXPECT_TRUE(bufferWriter.Write(str.data(), str.size())); + EXPECT_TRUE(bufferWriter.Flush()); } } // namespace diff --git a/device/plugins/api/test/unittest/plugin_module_test.cpp b/device/plugins/api/test/unittest/plugin_module_test.cpp new file mode 100644 index 000000000..5f61b952b --- /dev/null +++ b/device/plugins/api/test/unittest/plugin_module_test.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "plugin_module.h" +#include "common_types.pb.h" + +using namespace testing::ext; + +namespace { +const static std::string SUCCESS_PLUGIN_NAME = "libmemdataplugin.z.so"; +constexpr size_t READ_BUFFER_SIZE = 4 * 1024 * 1024; +std::string g_testPluginDir("/system/lib/"); + +class PluginModuleTest : public ::testing::Test { +protected: + static constexpr auto TEMP_DELAY = std::chrono::milliseconds(20); + static void SetUpTestCase() + { +#if defined(__i386__) || defined(__x86_64__) + char pluginDir[PATH_MAX + 1] = {0}; + if (readlink("/proc/self/exe", pluginDir, PATH_MAX) > 0) { + char* pos = strrchr(pluginDir, '/'); + if (pos != nullptr) { + *(pos++) = '\0'; + printf("-----> pluginModuleDir = %s\n", pluginDir); + g_testPluginDir = pluginDir; + } + } +#endif + printf("======> pluginModuleDir = %s\n", g_testPluginDir.c_str()); + + std::this_thread::sleep_for(TEMP_DELAY); + printf("SetUpTestCase success\n"); + } + + static void TearDownTestCase() {} +}; + +/** + * @tc.name: plugin + * @tc.desc: pluginmodule normal test. + * @tc.type: FUNC + */ +HWTEST_F(PluginModuleTest, PluginModuleNormal, TestSize.Level1) +{ + std::string pluginPath = g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME; + PluginModuleInfo info; + auto plugin = std::make_shared(pluginPath); + EXPECT_TRUE(plugin->Load()); + EXPECT_TRUE(plugin->BindFunctions()); + EXPECT_TRUE(plugin->GetInfo(info)); + EXPECT_TRUE(plugin->IsLoaded()); + + uint32_t size = 0; + plugin->GetBufferSizeHint(size); + EXPECT_EQ(size, READ_BUFFER_SIZE); + + std::string name; + plugin->GetPluginName(name); + EXPECT_STREQ(name.c_str(), "memory-plugin"); + + const uint8_t configData[] = {74, 1, 10}; + ProfilerPluginConfig config; + config.set_name(g_testPluginDir + "/" + SUCCESS_PLUGIN_NAME); + config.set_config_data((const void*)configData, 3); + config.set_sample_interval(1000); + plugin->SetConfigData(config.config_data()); + + std::string cfgData = plugin->GetConfigData(); + EXPECT_EQ(cfgData.c_str()[0], 74); + EXPECT_EQ(cfgData.c_str()[1], 1); + EXPECT_EQ(cfgData.c_str()[2], 10); + + std::unique_ptr buffer(new (std::nothrow) uint8_t[size]); + EXPECT_NE(buffer, nullptr); + EXPECT_TRUE(plugin->StartSession(reinterpret_cast(cfgData.c_str()), cfgData.size())); + EXPECT_NE(plugin->ReportResult(buffer.get(), size), 0); + EXPECT_TRUE(plugin->StopSession()); + + EXPECT_TRUE(plugin->StartSession(nullptr, 0)); + EXPECT_EQ(plugin->ReportResult(buffer.get(), size), 0); + EXPECT_TRUE(plugin->StopSession()); + + EXPECT_TRUE(plugin->StartSession(reinterpret_cast(cfgData.c_str()), cfgData.size())); + EXPECT_NE(plugin->ReportResult(nullptr, 0), 0); + EXPECT_NE(plugin->ReportResult(nullptr, 0), -1); + EXPECT_TRUE(plugin->StopSession()); + + EXPECT_TRUE(plugin->StartSession(nullptr, 0)); + EXPECT_EQ(plugin->ReportResult(nullptr, 0), 0); + EXPECT_TRUE(plugin->StopSession()); + + EXPECT_TRUE(plugin->Unload()); + EXPECT_FALSE(plugin->IsLoaded()); +} + +/** + * @tc.name: plugin + * @tc.desc: pluginmodule abnormal test. + * @tc.type: FUNC + */ +HWTEST_F(PluginModuleTest, PluginModuleAbnormal, TestSize.Level1) +{ + std::string pluginPath = "invalid.z.so"; + PluginModuleInfo info; + auto plugin = std::make_shared(pluginPath); + EXPECT_FALSE(plugin->Load()); + EXPECT_FALSE(plugin->BindFunctions()); + EXPECT_FALSE(plugin->GetInfo(info)); + EXPECT_FALSE(plugin->IsLoaded()); + + uint32_t size = 0; + plugin->GetBufferSizeHint(size); + EXPECT_EQ(size, 0); + + std::string name; + plugin->GetPluginName(name); + EXPECT_STREQ(name.c_str(), ""); + + std::unique_ptr buffer(new (std::nothrow) uint8_t[size]); + EXPECT_NE(buffer, nullptr); + EXPECT_FALSE(plugin->StartSession(nullptr, 0)); + EXPECT_EQ(plugin->ReportResult(buffer.get(), size), -1); + EXPECT_FALSE(plugin->StopSession()); + EXPECT_FALSE(plugin->Unload()); +} +} // namespace diff --git a/device/plugins/api/test/unittest/plugin_watcher_test.cpp b/device/plugins/api/test/unittest/plugin_watcher_test.cpp old mode 100755 new mode 100644 index be85da446..621c11b72 --- a/device/plugins/api/test/unittest/plugin_watcher_test.cpp +++ b/device/plugins/api/test/unittest/plugin_watcher_test.cpp @@ -29,27 +29,15 @@ using namespace testing::ext; namespace { -static std::vector g_cmpFileList; -static std::vector g_createFileList = { - "lib_6.so", "lib_5.so", "lib_8.so", "lib_4.so", "test1.txt" -}; -std::vector g_createFdList; - -static std::vector g_addFileList = { - "libadd_6.so", "libadd_5.so", "libadd_8.so", "libadd_4.so", "test2.txt" -}; - -static std::vector g_expectFileList = { - "libadd_6.so", "libadd_5.so", "libadd_8.so", "libadd_4.so", - "lib_6.so", "lib_5.so", "lib_8.so", "lib_4.so" -}; - -static int g_defaultFileMode = 0777; +constexpr int DEAFULT_FILE_MODE = 0777; #if defined(__i386__) || defined(__x86_64__) const static std::string DEFAULT_TEST_PATH = "./"; #else -const static std::string DEFAULT_TEST_PATH = "/data/local/tmp/"; +const static std::string DEFAULT_TEST_PATH_1 = "/data/local/tmp/watchertest/1/"; +const static std::string DEFAULT_TEST_PATH_2 = "/data/local/tmp/watchertest/2/"; +const static std::string DEFAULT_TEST_PATH_3 = "/data/local/tmp/watchertest/3/"; +const static std::string NO_EXIST_TEST_PATH = "/data/local/tmp/noexist/"; #endif class PluginWatchTest : public ::testing::Test { @@ -58,8 +46,98 @@ protected: static void SetUpTestCase() {} static void TearDownTestCase() {} - void SetUp() override {} - void TearDown() override {} + void SetUp() override + { + std::string cmd = "mkdir -p " + DEFAULT_TEST_PATH_1; + system(cmd.c_str()); + cmd = "mkdir -p " + DEFAULT_TEST_PATH_2; + system(cmd.c_str()); + cmd = "mkdir -p " + DEFAULT_TEST_PATH_3; + system(cmd.c_str()); + sort(expectFileList.begin(), expectFileList.end()); + } + + void TearDown() override + { + cmpFileList.clear(); + } + + void OnPluginAddedStub(const std::string& path) + { + cmpFileList.push_back(path); + sort(cmpFileList.begin(), cmpFileList.end()); + } + + void OnPluginRemovedStub(const std::string& path) + { + for (auto iter = cmpFileList.cbegin(); iter != cmpFileList.cend(); iter++) { + if (*iter == path) { + cmpFileList.erase(iter); + break; + } + } + } + + void CreateFile(std::string dirPath) const + { + for (auto it : createFileList) { + int fd = creat((dirPath + it).c_str(), DEAFULT_FILE_MODE); + close(fd); + } + } + + void AddFile(std::string dirPath) const + { + for (auto it : addFileList) { + int fd = creat((dirPath + it).c_str(), DEAFULT_FILE_MODE); + if (fd < 0) { + return; + } + write(fd, "testcase", 1); + close(fd); + } + } + + void DeleteFile(std::string dirPath) const + { + for (auto it : createFileList) { + remove((dirPath + it).c_str()); + } + for (auto it : addFileList) { + remove((dirPath + it).c_str()); + } + } + + bool CheckFileList(std::string dirPath) const + { + if (cmpFileList.size() != expectFileList.size()) { + return false; + } + + for (size_t i = 0; i < cmpFileList.size(); i++) { + if (cmpFileList.at(i) != (dirPath + expectFileList.at(i))) { + return false; + } + } + + return true; + } + +private: + std::vector cmpFileList; + + const std::vector createFileList = { + "lib_6.so", "lib_5.so", "lib_8.so", "lib_4.so", "test1.txt" + }; + + const std::vector addFileList = { + "libadd_6.so", "libadd_5.so", "libadd_8.so", "libadd_4.so", "test2.txt" + }; + + std::vector expectFileList = { + "libadd_6.so", "libadd_5.so", "libadd_8.so", "libadd_4.so", + "lib_6.so", "lib_5.so", "lib_8.so", "lib_4.so" + }; }; class MockPluginWatcher : public PluginWatcher { @@ -70,82 +148,9 @@ public: MOCK_METHOD1(OnPluginRemoved, void(const std::string&)); }; -static void OnPluginAddedStub(const std::string& path) -{ - g_cmpFileList.push_back(path); - sort(g_cmpFileList.begin(), g_cmpFileList.end()); - return; -} - -static void OnPluginRemovedStub(const std::string& path) -{ - for (auto iter = g_cmpFileList.cbegin(); iter != g_cmpFileList.cend(); iter++) { - if (*iter == path) { - g_cmpFileList.erase(iter); - break; - } - } - - return; -} - -static void CreateFile() -{ - for (auto it : g_createFileList) { - int fd = creat(it.c_str(), g_defaultFileMode); - g_createFdList.push_back(fd); - } -} - -static void AddFile() -{ - for (auto it : g_addFileList) { - int fd = creat(it.c_str(), g_defaultFileMode); - if (fd < 0) { - return; - } - write(fd, "testcase", 1); - close(fd); - } - - return; -} - -static void DeleteFile() -{ - for (auto it : g_createFileList) { - for (auto fd : g_createFdList) { - close(fd); - } - remove(it.c_str()); - } - for (auto it : g_addFileList) { - remove(it.c_str()); - } - return; -} - -static bool CheckFileList() -{ - sort(g_expectFileList.begin(), g_expectFileList.end()); - if (g_expectFileList.size() != g_cmpFileList.size()) { - return false; - } - - for (size_t i = 0; i < g_expectFileList.size(); i++) { - char fullpath[PATH_MAX + 1] = {0}; - realpath(g_expectFileList.at(i).c_str(), fullpath); - if (g_cmpFileList.at(i) != fullpath) { - return false; - } - } - - return true; -} - /** * @tc.name: plugin - * @tc.desc: Monitor the plugin loading in the test directory. + * @tc.desc: Monitor single plugin dir. * @tc.type: FUNC */ HWTEST_F(PluginWatchTest, SingleWatchDirTest, TestSize.Level1) @@ -153,32 +158,81 @@ HWTEST_F(PluginWatchTest, SingleWatchDirTest, TestSize.Level1) auto pluginManage = std::make_shared(); MockPluginWatcher watcher(pluginManage); - EXPECT_CALL(watcher, OnPluginAdded(testing::_)).WillRepeatedly(testing::Invoke(OnPluginAddedStub)); - EXPECT_CALL(watcher, OnPluginRemoved(testing::_)).WillRepeatedly(testing::Invoke(OnPluginRemovedStub)); + EXPECT_CALL(watcher, OnPluginAdded(testing::_)).WillRepeatedly( + testing::Invoke(this, &PluginWatchTest::OnPluginAddedStub)); + EXPECT_CALL(watcher, OnPluginRemoved(testing::_)).WillRepeatedly( + testing::Invoke(this, &PluginWatchTest::OnPluginRemovedStub)); + CreateFile(DEFAULT_TEST_PATH_1); - g_createFdList.clear(); - CreateFile(); - watcher.ScanPlugins(DEFAULT_TEST_PATH); - watcher.WatchPlugins(DEFAULT_TEST_PATH); + EXPECT_TRUE(watcher.ScanPlugins(DEFAULT_TEST_PATH_1)); + EXPECT_TRUE(watcher.WatchPlugins(DEFAULT_TEST_PATH_1)); usleep(TEMP_DELAY); - AddFile(); + AddFile(DEFAULT_TEST_PATH_1); usleep(TEMP_DELAY); - EXPECT_EQ(CheckFileList(), false); - DeleteFile(); + EXPECT_EQ(CheckFileList(DEFAULT_TEST_PATH_1), true); + DeleteFile(DEFAULT_TEST_PATH_1); usleep(TEMP_DELAY); - EXPECT_EQ(g_cmpFileList.empty(), true); + EXPECT_EQ(cmpFileList.size(), 0); } /** * @tc.name: plugin - * @tc.desc: Plug-in process exception test. + * @tc.desc: Monitor multi plugin dir. * @tc.type: FUNC */ -HWTEST_F(PluginWatchTest, OnPluginAdded, TestSize.Level1) +HWTEST_F(PluginWatchTest, MultiWatchDirTest, TestSize.Level1) { - const auto pluginManage = std::make_shared(); - PluginWatcher pluginWatcher(pluginManage); - pluginWatcher.OnPluginAdded(""); - pluginWatcher.OnPluginRemoved(""); + auto pluginManage = std::make_shared(); + MockPluginWatcher watcher(pluginManage); + + EXPECT_CALL(watcher, OnPluginAdded(testing::_)).WillRepeatedly( + testing::Invoke(this, &PluginWatchTest::OnPluginAddedStub)); + EXPECT_CALL(watcher, OnPluginRemoved(testing::_)).WillRepeatedly( + testing::Invoke(this, &PluginWatchTest::OnPluginRemovedStub)); + CreateFile(DEFAULT_TEST_PATH_1); + EXPECT_TRUE(watcher.ScanPlugins(DEFAULT_TEST_PATH_1)); + EXPECT_TRUE(watcher.WatchPlugins(DEFAULT_TEST_PATH_1)); + usleep(TEMP_DELAY); + AddFile(DEFAULT_TEST_PATH_1); + usleep(TEMP_DELAY); + EXPECT_EQ(CheckFileList(DEFAULT_TEST_PATH_1), true); + DeleteFile(DEFAULT_TEST_PATH_1); + usleep(TEMP_DELAY); + EXPECT_EQ(cmpFileList.size(), 0); + + CreateFile(DEFAULT_TEST_PATH_2); + EXPECT_TRUE(watcher.ScanPlugins(DEFAULT_TEST_PATH_2)); + EXPECT_TRUE(watcher.WatchPlugins(DEFAULT_TEST_PATH_2)); + usleep(TEMP_DELAY); + AddFile(DEFAULT_TEST_PATH_2); + usleep(TEMP_DELAY); + EXPECT_EQ(CheckFileList(DEFAULT_TEST_PATH_2), true); + DeleteFile(DEFAULT_TEST_PATH_2); + usleep(TEMP_DELAY); + EXPECT_EQ(cmpFileList.size(), 0); + + CreateFile(DEFAULT_TEST_PATH_3); + EXPECT_TRUE(watcher.ScanPlugins(DEFAULT_TEST_PATH_3)); + EXPECT_TRUE(watcher.WatchPlugins(DEFAULT_TEST_PATH_3)); + usleep(TEMP_DELAY); + AddFile(DEFAULT_TEST_PATH_3); + usleep(TEMP_DELAY); + EXPECT_EQ(CheckFileList(DEFAULT_TEST_PATH_3), true); + DeleteFile(DEFAULT_TEST_PATH_3); + usleep(TEMP_DELAY); + EXPECT_EQ(cmpFileList.size(), 0); +} + +/** + * @tc.name: plugin + * @tc.desc: Exception test. + * @tc.type: FUNC + */ +HWTEST_F(PluginWatchTest, ExceptionTest, TestSize.Level1) +{ + auto pluginManage = std::make_shared(); + MockPluginWatcher watcher(pluginManage); + EXPECT_FALSE(watcher.ScanPlugins(NO_EXIST_TEST_PATH)); + EXPECT_FALSE(watcher.WatchPlugins(NO_EXIST_TEST_PATH)); } } // namespace diff --git a/device/plugins/api/test/unittest/services_ipc_test.cpp b/device/plugins/api/test/unittest/services_ipc_test.cpp deleted file mode 100644 index 50ba6cf01..000000000 --- a/device/plugins/api/test/unittest/services_ipc_test.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "client_map.h" -#include "plugin_service.ipc.h" -#include "service_entry.h" -#include "socket_context.h" -#include "unix_socket_client.h" -#include "unix_socket_server.h" - -using namespace testing::ext; - -namespace { -class ServicesIpcTest : public ::testing::Test { -protected: - static constexpr auto TEMP_DELAY = std::chrono::milliseconds(10); - static void SetUpTestCase() {} - static void TearDownTestCase() {} -}; - -/** - * @tc.name: ipc - * @tc.desc: Socket send/recv interface. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, ProtocolProc, TestSize.Level1) -{ - ServiceBase serviceBase; - SocketContext socketContext; - ASSERT_FALSE(serviceBase.ProtocolProc(socketContext, 0, nullptr, 0)); - ASSERT_TRUE(!socketContext.SendRaw(-1, nullptr, 0, 0)); - ASSERT_TRUE(!socketContext.SendFileDescriptor(-1)); - ASSERT_EQ(socketContext.ReceiveFileDiscriptor(), -1); - ASSERT_EQ(socketContext.RawProtocolProc(-1, nullptr, -1), -1); -} - -/** - * @tc.name: ipc - * @tc.desc: Client link. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, ClientSocket, TestSize.Level1) -{ - ServiceEntry serviceEntry; - ClientMap::GetInstance().PutClientSocket(0, serviceEntry); - ASSERT_EQ(ClientMap::GetInstance().AutoRelease(), 1); - - ClientConnection* clientConnection = new ClientConnection(0, serviceEntry); - ASSERT_EQ(clientConnection->RawProtocolProc(-1, nullptr, 0), -1); -} - -/** - * @tc.name: plugin - * @tc.desc: Abnormal client link. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, unixSocketClient, TestSize.Level1) -{ - UnixSocketClient unixSocketClient; - ServiceBase serviceBase; - ASSERT_TRUE(!unixSocketClient.Connect("asdf", serviceBase)); -} - -/** - * @tc.name: plugin - * @tc.desc: Start unixSocket Server. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, UnixSocketServer, TestSize.Level1) -{ - UnixSocketServer unixSocketServer; - - unixSocketServer.UnixSocketAccept(nullptr); - - ServiceEntry serviceEntry; - ASSERT_TRUE(unixSocketServer.StartServer("", serviceEntry)); -} - -/** - * @tc.name: plugin - * @tc.desc: Server process monitoring. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, ServiceEntry, TestSize.Level1) -{ - ServiceEntry serviceEntry; - IPluginServiceServer pluginService; - serviceEntry.StartServer("test_unix_socket_service_entry"); - serviceEntry.RegisterService(pluginService); - serviceEntry.FindServiceByName(pluginService.serviceName_); - - std::this_thread::sleep_for(TEMP_DELAY); - - GetTimeMS(); - GetTimeUS(); - GetTimeNS(); - - IPluginServiceClient pluginClient; - ASSERT_FALSE(pluginClient.Connect("")); - std::this_thread::sleep_for(TEMP_DELAY); -} -} // namespace \ No newline at end of file diff --git a/device/plugins/api/test/unittest/services_plugin_service_test.cpp b/device/plugins/api/test/unittest/services_plugin_service_test.cpp deleted file mode 100755 index 4842db515..000000000 --- a/device/plugins/api/test/unittest/services_plugin_service_test.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "plugin_service.h" -#include "plugin_session.h" -#include "profiler_data_repeater.h" - -using namespace testing::ext; -using PluginServicePtr = STD_PTR(shared, PluginService); - -class ServicesPluginServiceTest : public ::testing::Test { -protected: - static void SetUpTestCase() {} - static void TearDownTestCase() {} -}; - -/** - * @tc.name: plugin - * @tc.desc: Session flow test, get session id by plugin name. - * @tc.type: FUNC - */ -HWTEST_F(ServicesPluginServiceTest, PluginService1, TestSize.Level1) -{ - PluginServicePtr pluginService = std::make_shared(); - ProfilerPluginConfig ppc; - ppc.set_name("abc.so"); - ppc.set_plugin_sha256("ASDFAADSF"); - ppc.set_sample_interval(20); - - pluginService->CreatePluginSession(ppc, std::make_shared(4096)); - pluginService->StartPluginSession(ppc); - pluginService->StopPluginSession("abc.so"); - pluginService->DestroyPluginSession("abc.so"); - pluginService->GetPluginIdByName("abc.so"); -} - -/** - * @tc.name: plugin - * @tc.desc: Session flow test, get plugin status. - * @tc.type: FUNC - */ -HWTEST_F(ServicesPluginServiceTest, PluginService2, TestSize.Level1) -{ - PluginServicePtr pluginService = std::make_shared(); - ProfilerPluginConfig ppc; - ppc.set_name("abc.so"); - ppc.set_plugin_sha256("ASDFAADSF"); - ppc.set_sample_interval(20); - - ProfilerSessionConfig::BufferConfig bc; - bc.set_pages(1); - bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); - - pluginService->CreatePluginSession(ppc, bc, std::make_shared(4096)); - pluginService->StartPluginSession(ppc); - pluginService->StopPluginSession("abc.so"); - pluginService->GetPluginStatus(); - - PluginInfo pi; - pi.id = 0; - pi.name = "abc.so"; - pi.path = "abc.so"; - pi.sha256 = "asdfasdf"; - pluginService->RemovePluginInfo(pi); -} diff --git a/device/plugins/api/test/unittest/services_profiler_service_test.cpp b/device/plugins/api/test/unittest/services_profiler_service_test.cpp deleted file mode 100644 index ed4a84fce..000000000 --- a/device/plugins/api/test/unittest/services_profiler_service_test.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "logging.h" -#include "plugin_service.h" -#include "plugin_session.h" -#include "profiler_capability_manager.h" -#include "profiler_data_repeater.h" -#include "profiler_service.h" -#include "result_demuxer.h" -#include "trace_file_reader.h" -#include "trace_file_writer.h" - -using namespace testing::ext; - -namespace { -#if defined(__i386__) || defined(__x86_64__) -const std::string DEFAULT_TEST_PATH("./"); -#else -const std::string DEFAULT_TEST_PATH("/data/local/tmp/"); -#endif - -using PluginServicePtr = STD_PTR(shared, PluginService); -using ProfilerDataRepeaterPtr = STD_PTR(shared, ProfilerDataRepeater); -using ProfilerServicePtr = STD_PTR(shared, ProfilerService); -using ProfilerPluginDataPtr = STD_PTR(shared, ProfilerPluginData); - -constexpr int DATA_MAX_SIZE = 10; - -class ServicesProfilerServiceTest : public ::testing::Test { -protected: - ProfilerPluginConfig config; - ProfilerSessionConfig::BufferConfig bufferConfig; - PluginInfo pluginInfo; - PluginServicePtr service; - ProfilerDataRepeaterPtr repeater; - ProfilerServicePtr service_; - std::unique_ptr context_; - std::atomic requestCounter{0}; - - static void SetUpTestCase() {} - static void TearDownTestCase() {} - - void SetUp() override - { - config.set_name("test_session"); - bufferConfig.set_pages(0); - pluginInfo.name = config.name(); - service = std::make_shared(); - repeater = std::make_shared(DATA_MAX_SIZE); - if (service) { - service->AddPluginInfo(pluginInfo); - } - - service_ = std::make_shared(service); - context_ = std::make_unique(); - } - void TearDown() override - { - if (service) { - service->RemovePluginInfo(pluginInfo); - } - ProfilerCapabilityManager::GetInstance().pluginCapabilities_.clear(); - } -}; - -/** - * @tc.name: plugin - * @tc.desc: Plugin session flow test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, PluginSession, TestSize.Level1) -{ - auto session = std::make_shared(config, nullptr, nullptr); - EXPECT_NE(session, nullptr); - EXPECT_FALSE(session->IsAvailable()); - - EXPECT_FALSE(session->Create()); - config.set_name("test_session2"); - session = std::make_shared(config, service, repeater); - repeater->Size(); - - session.reset(); - config.set_name("test_session3"); - session = std::make_shared(config, service, repeater); - - ASSERT_NE(session->GetState(), PluginSession::CREATED); - EXPECT_FALSE(session->Start()); - ASSERT_NE(session->GetState(), PluginSession::STARTED); - EXPECT_FALSE(session->Stop()); - ASSERT_NE(session->GetState(), PluginSession::CREATED); - EXPECT_FALSE(session->Destroy()); - EXPECT_EQ(session->GetState(), PluginSession::INITIAL); - - // recreate is OK - EXPECT_FALSE(session->Create()); - EXPECT_FALSE(session->Destroy()); - repeater->Reset(); -} - -/** - * @tc.name: plugin - * @tc.desc: Streaming session test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, TraceFileWriter, TestSize.Level1) -{ - std::string path = "trace.bin"; - auto writer = std::make_shared(path); - EXPECT_NE(writer, nullptr); - - std::string testData = "Hello, Wrold!"; - EXPECT_EQ(writer->Write(testData.data(), testData.size()), sizeof(uint32_t) + testData.size()); - EXPECT_EQ(writer->Flush(), true); - - ProfilerPluginData pluginData; - pluginData.set_name("ABC"); - pluginData.set_status(0); - pluginData.set_data("DEF"); - EXPECT_GT(writer->Write(pluginData), 0); -} - -/** - * @tc.name: plugin - * @tc.desc: Streaming session test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, TraceFileReader, TestSize.Level1) -{ - std::string path = "trace-write-msg.bin"; - auto writer = std::make_shared(path); - ASSERT_NE(writer, nullptr); - - constexpr int n = 100; - for (int i = 1; i <= n; i++) { - ProfilerPluginData pluginData{}; - pluginData.set_name("test_name"); - pluginData.set_status(i); - pluginData.set_data("Hello, Wrold!"); - long bytes = writer->Write(pluginData); - EXPECT_EQ(bytes, sizeof(uint32_t) + pluginData.ByteSizeLong()); - HILOG_INFO(LOG_CORE, "[%d/%d] write %ld bytes to %s.", i, n, bytes, path.c_str()); - } - writer.reset(); // make sure write done! - - auto reader = std::make_shared(); - ASSERT_NE(reader, nullptr); - ASSERT_TRUE(reader->Open(path)); - for (int i = 1; i <= n; i++) { - ProfilerPluginData data{}; - long bytes = reader->Read(data); - HILOG_INFO(LOG_CORE, "data = {%s, %d, %s}", data.name().c_str(), data.status(), data.data().c_str()); - HILOG_INFO(LOG_CORE, "read %ld bytes from %s", bytes, path.c_str()); - } - - ASSERT_TRUE(reader->Open(path)); - long bytes = 0; - do { - ProfilerPluginData data{}; - bytes = reader->Read(data); - HILOG_INFO(LOG_CORE, "data = {%s, %d, %s}", data.name().c_str(), data.status(), data.data().c_str()); - HILOG_INFO(LOG_CORE, "read %ld bytes from %s", bytes, path.c_str()); - } while (bytes > 0); - - ASSERT_EQ(reader->Read(nullptr, 0), 0); -} - -/** - * @tc.name: service - * @tc.desc: Streaming session report result test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ResultDemuxer1, TestSize.Level1) -{ - std::string path = "demux.bin"; - ProfilerDataRepeaterPtr repeater = std::make_shared(DATA_MAX_SIZE); - - auto demuxer = std::make_shared(repeater); - EXPECT_NE(demuxer, nullptr); - demuxer->SetTraceWriter(nullptr); - - auto writer = std::make_shared(path); - EXPECT_NE(writer, nullptr); - demuxer->SetTraceWriter(writer); - - const int putCount = 20; - const int putDelayUs = 10 * 1000; - demuxer->StartTakeResults(); - std::thread dataProducer([=] { - for (int i = 0; i < putCount; i++) { - auto pluginData = std::make_shared(); - ASSERT_NE(pluginData, nullptr); - pluginData->set_name("test-" + std::to_string(i)); - pluginData->set_status(i); - repeater->PutPluginData(pluginData); - HILOG_DEBUG(LOG_CORE, "put test data %d...", i); - usleep(putDelayUs); - } - repeater->PutPluginData(nullptr); - }); - - HILOG_DEBUG(LOG_CORE, "wating producer thread done..."); - dataProducer.join(); -} - -/** - * @tc.name: service - * @tc.desc: Streaming session report result test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ResultDemuxer2, TestSize.Level1) -{ - std::string path = "demux.bin"; - ProfilerDataRepeaterPtr repeater = std::make_shared(DATA_MAX_SIZE); - - auto demuxer = std::make_shared(repeater); - ASSERT_NE(demuxer, nullptr); - - auto writer = std::make_shared(path); - EXPECT_NE(writer, nullptr); - demuxer->SetTraceWriter(writer); - - const int putCount = 30; - const int putDelayUs = 10 * 1000; - demuxer->StartTakeResults(); - std::thread dataProducer([=] { - for (int i = 0; i < putCount; i++) { - auto pluginData = std::make_shared(); - ASSERT_NE(pluginData, nullptr); - pluginData->set_name("AB-" + std::to_string(i)); - pluginData->set_status(i); - - HILOG_DEBUG(LOG_CORE, "put test data %d...", i); - if (!repeater->PutPluginData(pluginData)) { - HILOG_WARN(LOG_CORE, "put test data %d FAILED!", i); - break; - } - usleep(putDelayUs); - } - }); - - usleep((putCount / 2) * putDelayUs); - demuxer->StopTakeResults(); - - repeater->Close(); - HILOG_DEBUG(LOG_CORE, "wating producer thread done..."); - dataProducer.join(); -} - -/** - * @tc.name: server - * @tc.desc: Profiler capacity management. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ProfilerCapabilityManager, TestSize.Level1) -{ - std::vector caps = ProfilerCapabilityManager::GetInstance().GetCapabilities(); - for (int i = 0; i < caps.size(); i++) { - auto cap = caps[i]; - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().RemoveCapability(cap.name())); - } - caps.clear(); - - EXPECT_EQ(ProfilerCapabilityManager::GetInstance().GetCapability("xxx"), nullptr); - EXPECT_EQ(ProfilerCapabilityManager::GetInstance().GetCapabilities().size(), 0); - - caps = ProfilerCapabilityManager::GetInstance().GetCapabilities(); - EXPECT_EQ(caps.size(), 0); - - const int n = 10; - for (int i = 0; i < n; i++) { - ProfilerPluginCapability cap; - cap.set_path("/system/lib/libcap_" + std::to_string(i) + ".so"); - cap.set_name("cap_" + std::to_string(i)); - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(cap)); - EXPECT_EQ(ProfilerCapabilityManager::GetInstance().GetCapabilities().size(), i + 1); - } - - for (int i = 0; i < n; i++) { - ProfilerPluginCapability cap; - cap.set_name("cap_" + std::to_string(i)); - auto capPtr = ProfilerCapabilityManager::GetInstance().GetCapability(cap.name()); - ASSERT_NE(capPtr, nullptr); - EXPECT_EQ(capPtr->name(), cap.name()); - } - - ProfilerPluginCapability cap1; - cap1.set_path("/system/lib/libcap1.so"); - cap1.set_name("cap1"); - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(cap1)); - - cap1.set_path("/system/lib/libcap2.so"); - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().UpdateCapability(cap1.name(), cap1)); - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().RemoveCapability(cap1.name())); - - caps = ProfilerCapabilityManager::GetInstance().GetCapabilities(); - EXPECT_EQ(caps.size(), n); - for (int i = 0; i < caps.size(); i++) { - auto cap = caps[i]; - EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().RemoveCapability(cap.name())); - - EXPECT_EQ(ProfilerCapabilityManager::GetInstance().GetCapabilities().size(), n - (i + 1)); - } -} - -/** - * @tc.name: server - * @tc.desc: Profiler data repeater. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ProfilerDataRepeater, TestSize.Level1) -{ - const int itemCounts = 10000; - const int bufferSize = itemCounts; - auto inDataRepeater = std::make_shared(bufferSize); - ASSERT_NE(inDataRepeater, nullptr); - - auto outDataRepeater = std::make_shared(bufferSize); - ASSERT_NE(outDataRepeater, nullptr); - - auto f = [](int x) { return 2 * x + 1; }; - std::thread worker([&]() { - for (int i = 0; i < itemCounts; i++) { - auto xData = inDataRepeater->TakePluginData(); - - // compute in worker thread - int x = xData ? std::stoi(xData->data()) : 0; - int y = f(x); - - auto yData = std::make_shared(); - yData->set_data(std::to_string(y)); - outDataRepeater->PutPluginData(yData); - } - }); - - std::vector yVec; - for (int i = 0; i < itemCounts; i++) { - int x0 = i; - auto xData = std::make_shared(); - xData->set_data(std::to_string(x0)); - inDataRepeater->PutPluginData(xData); - - int y0 = f(x0); - yVec.push_back(y0); - } - worker.join(); - - std::vector pluginDataVec; - auto count = outDataRepeater->TakePluginData(pluginDataVec); - EXPECT_EQ(count, yVec.size()); - - for (size_t i = 0; i < pluginDataVec.size(); i++) { - auto yData = pluginDataVec[i]; - int y = yData ? std::stoi(yData->data()) : 0; - EXPECT_EQ(y, yVec[i]); - } -} - -/** - * @tc.name: server - * @tc.desc: Session flow test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ProfilerService1, TestSize.Level1) -{ - ASSERT_NE(service_, nullptr); - ASSERT_NE(context_, nullptr); - - GetCapabilitiesRequest request; - GetCapabilitiesResponse response; - - ProfilerPluginCapability cap; - cap.set_name("cap1"); - ProfilerCapabilityManager::GetInstance().AddCapability(cap); - - request.set_request_id(++requestCounter); - auto status = service_->GetCapabilities(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - EXPECT_GT(response.capabilities_size(), 0); - HILOG_DEBUG(LOG_CORE, "GetCapabilities, capabilities_size = %d", response.capabilities_size()); -} - -/** - * @tc.name: server - * @tc.desc: Session flow test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesProfilerServiceTest, ProfilerService2, TestSize.Level1) -{ - ASSERT_NE(service_, nullptr); - ASSERT_NE(context_, nullptr); - - CreateSessionRequest request; - CreateSessionResponse response; - - auto status = service_->CreateSession(context_.get(), &request, &response); - EXPECT_NE(status.error_code(), grpc::StatusCode::OK); - - StartSessionRequest startrequest; - StartSessionResponse startresponse; - startrequest.set_session_id(0); - startrequest.set_request_id(++requestCounter); - status = service_->StartSession(context_.get(), &startrequest, &startresponse); - EXPECT_NE(status.error_code(), grpc::StatusCode::OK); - - StopSessionRequest stoprequest; - StopSessionResponse stopresponse; - stoprequest.set_session_id(0); - stoprequest.set_request_id(++requestCounter); - status = service_->StopSession(context_.get(), &stoprequest, &stopresponse); - EXPECT_NE(status.error_code(), grpc::StatusCode::OK); - - DestroySessionRequest destroyrequest; - DestroySessionResponse destroyresponse; - destroyrequest.set_session_id(0); - destroyrequest.set_request_id(++requestCounter); - status = service_->DestroySession(context_.get(), &destroyrequest, &destroyresponse); - EXPECT_NE(status.error_code(), grpc::StatusCode::OK); -} -} // namespace diff --git a/device/plugins/api/test/unittest/services_shared_memory_test.cpp b/device/plugins/api/test/unittest/services_shared_memory_test.cpp deleted file mode 100755 index bcec802f0..000000000 --- a/device/plugins/api/test/unittest/services_shared_memory_test.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "plugin_service_types.pb.h" -#include "share_memory_allocator.h" -#include "share_memory_block.h" - -using namespace testing::ext; - -namespace { -class ServicesSharedMemoryTest : public ::testing::Test { -protected: - static void SetUpTestCase() {} - static void TearDownTestCase() {} -}; - -/** - * @tc.name: server - * @tc.desc: Shared memory flow test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesSharedMemoryTest, SharedMemoryBlock, TestSize.Level1) -{ - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); - - shareMemoryBlock.GetName(); - shareMemoryBlock.GetSize(); - shareMemoryBlock.GetfileDescriptor(); - - shareMemoryBlock.SetDropType(ShareMemoryBlock::DropType::DROP_NONE); - int8_t data[100]; - for (int i = 0; i < 20; i++) { - *((uint32_t*)data) = i; - shareMemoryBlock.PutRaw(data, 100); - } - int8_t* p = shareMemoryBlock.GetFreeMemory(100); - ASSERT_TRUE(p == nullptr); - do { - p = const_cast(shareMemoryBlock.GetDataPoint()); - printf("%p,p=%d\n", p, *((int*)p)); - } while (shareMemoryBlock.Next() && shareMemoryBlock.GetDataSize() > 0); - - NotifyResultResponse response; - response.set_status(123); - ASSERT_TRUE(shareMemoryBlock.PutProtobuf(response)); - ASSERT_TRUE(shareMemoryBlock.GetDataSize() > 0); - response.ParseFromArray(shareMemoryBlock.GetDataPoint(), shareMemoryBlock.GetDataSize()); - ASSERT_TRUE(response.status() == 123); - - ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); -} - -/** - * @tc.name: server - * @tc.desc: Shared memory abnormal flow test. - * @tc.type: FUNC - */ -HWTEST_F(ServicesSharedMemoryTest, SharedMemoryAllocator, TestSize.Level1) -{ - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1) == - nullptr); // 创建内存块大小<1024,返回空 - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1024) != nullptr); // 成功创建 - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1024) == - nullptr); // 创建同名内存块返回空 - - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); - ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("or")); // 释放不存在的内存块返回-1 -} -} // namespace \ No newline at end of file diff --git a/device/plugins/api/test/unittest/writer_adapter_test.cpp b/device/plugins/api/test/unittest/writer_adapter_test.cpp old mode 100755 new mode 100644 index 27ebad777..cd6e6841b --- a/device/plugins/api/test/unittest/writer_adapter_test.cpp +++ b/device/plugins/api/test/unittest/writer_adapter_test.cpp @@ -34,8 +34,8 @@ protected: HWTEST_F(WriterAdapterTest, Writer, TestSize.Level1) { WriterAdapter writerAdapter; - writerAdapter.GetWriter(); - writerAdapter.GetStruct(); + EXPECT_EQ(writerAdapter.GetWriter(), nullptr); + EXPECT_EQ(writerAdapter.GetStruct(), &writerAdapter.writerStruct_); } /** @@ -46,7 +46,7 @@ HWTEST_F(WriterAdapterTest, Writer, TestSize.Level1) HWTEST_F(WriterAdapterTest, Func, TestSize.Level1) { WriterAdapter writerAdapter; - writerAdapter.WriteFunc(nullptr, nullptr, 0); - writerAdapter.FlushFunc(nullptr); + EXPECT_EQ(writerAdapter.WriteFunc(nullptr, nullptr, 0), 0); + EXPECT_FALSE(writerAdapter.FlushFunc(nullptr)); } } // namespace \ No newline at end of file diff --git a/device/plugins/bytrace_plugin/BUILD.gn b/device/plugins/bytrace_plugin/BUILD.gn old mode 100755 new mode 100644 index 1881f832b..059043ee8 --- a/device/plugins/bytrace_plugin/BUILD.gn +++ b/device/plugins/bytrace_plugin/BUILD.gn @@ -10,7 +10,6 @@ # 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("../../base/config.gni") @@ -27,14 +26,13 @@ config("bytraceplugin_config") { ohos_shared_library("bytraceplugin") { output_name = "bytraceplugin" - sources = [ - "src/bytrace_module.cpp", - ] + sources = [ "src/bytrace_module.cpp" ] public_configs = [ ":bytraceplugin_config" ] public_deps = [ - "${OHOS_PROFILER_DIR}/protos/types/plugins/bytrace_plugin:bytrace_plugin_protos_cpp", "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", + "${OHOS_PROFILER_DIR}/protos/types/plugins/bytrace_plugin:bytrace_plugin_protos_cpp", + "//utils/native/base:utilsecurec", ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] @@ -48,14 +46,10 @@ ohos_shared_library("bytraceplugin") { subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" } -ohos_executable("test_bytraceplugin") { +ohos_executable("test_bytrace_plugin") { output_name = "test_bytraceplugin" - sources = [ - "src/run_test.cpp", - ] - deps = [ - ":bytraceplugin", - ] + sources = [ "src/run_test.cpp" ] + deps = [ ":bytraceplugin" ] install_enable = true subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" } diff --git a/device/plugins/bytrace_plugin/include/bytrace_module.h b/device/plugins/bytrace_plugin/include/bytrace_module.h old mode 100755 new mode 100644 index 1319c8bbd..ac2c941f3 --- a/device/plugins/bytrace_plugin/include/bytrace_module.h +++ b/device/plugins/bytrace_plugin/include/bytrace_module.h @@ -16,13 +16,12 @@ #ifndef BYTRACE_MODULE_H #define BYTRACE_MODULE_H -#include #include "plugin_module_api.h" int BytracePluginSessionStart(const uint8_t* configData, const uint32_t configSize); -int BytraceRegisterWriterStruct(WriterStruct* writer); +int BytraceRegisterWriterStruct(const WriterStruct* writer); -int BytracePluginSessionStop(); +int BytracePluginSessionStop(void); #endif // BYTRACE_MODULE_H \ No newline at end of file diff --git a/device/plugins/bytrace_plugin/src/bytrace_module.cpp b/device/plugins/bytrace_plugin/src/bytrace_module.cpp index de2e2005b..028552208 100644 --- a/device/plugins/bytrace_plugin/src/bytrace_module.cpp +++ b/device/plugins/bytrace_plugin/src/bytrace_module.cpp @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "bytrace_module.h" +#include #include #include #include @@ -27,101 +27,136 @@ #include "securec.h" namespace { -const std::string CMD_PATH = "/system/bin/bytrace"; -int g_processNum = -1; constexpr uint32_t MAX_BUFFER_SIZE = 4 * 1024 * 1024; +constexpr uint32_t READ_BUFFER_SIZE = 4096; +const std::string DEFAULT_FILE = "/local/data/tmp/bytrace.txt"; -bool RunWithConfig(const BytracePluginConfig& config) +std::mutex g_taskMutex; + +struct BytraceInfo { + bool isRoot; + uint32_t buffSize; + uint32_t time; + std::string clockType; + std::string outFile; + std::vector categoryVec; +}; +std::unique_ptr g_bytraceInfo = nullptr; + +void ParseConfig(const BytracePluginConfig& config) { - std::vector args; - args.push_back("bytrace"); if (config.buffe_size() != 0) { - args.push_back("-b"); - args.push_back(std::to_string(config.buffe_size())); - } - if (config.time() != 0) { - args.push_back("-t"); - args.push_back(std::to_string(config.time())); + g_bytraceInfo->buffSize = config.buffe_size(); } + g_bytraceInfo->time = config.time(); + g_bytraceInfo->isRoot = config.is_root(); if (!config.clock().empty()) { - args.push_back("--trace_clock"); - args.push_back(config.clock()); + g_bytraceInfo->clockType = config.clock(); } if (!config.outfile_name().empty()) { - args.push_back("-o"); - args.push_back(config.outfile_name()); + g_bytraceInfo->outFile = config.outfile_name(); } if (!config.categories().empty()) { for (std::string category : config.categories()) { - args.push_back(category); + g_bytraceInfo->categoryVec.push_back(category); } } +} - std::vector params; - std::string cmdPrintStr = ""; - for (std::string& it : args) { - cmdPrintStr += (it + " "); - params.push_back(const_cast(it.c_str())); +bool RunCommand(const std::string& cmd) +{ + HILOG_INFO(LOG_CORE, "BytraceCall::start running commond: %s", cmd.c_str()); + std::unique_ptr pipe(popen(cmd.data(), "r"), pclose); + CHECK_TRUE(pipe, false, "BytraceCall::RunCommand: create popen FAILED!"); + + if (g_bytraceInfo->time == 0) { + return true; } - params.push_back(nullptr); - HILOG_INFO(LOG_CORE, "call bytrace::Run: %s", cmdPrintStr.c_str()); - - execv(CMD_PATH.data(), ¶ms[0]); + std::array buffer; + std::string result; + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + HILOG_INFO(LOG_CORE, "BytraceCall::RunCommand result: %s", result.data()); return true; } + +bool BeginTrace() +{ + // two case: real-time and offline type. + std::string beginCmd; + if (g_bytraceInfo->isRoot) { + beginCmd = "su root "; + } + beginCmd += "bytrace "; + if (g_bytraceInfo->buffSize != 0) { + beginCmd += " -b " + std::to_string(g_bytraceInfo->buffSize); + } + if (!g_bytraceInfo->clockType.empty()) { + beginCmd += " --trace_clock " + g_bytraceInfo->clockType; + } + // real-time: time is set 0. + if (g_bytraceInfo->time == 0) { + // if time is not set 1s(must >= 1), bytrace tool will use 5s by dafault. + beginCmd += " -t 1 "; + beginCmd += " --trace_begin "; + } else { + beginCmd += " -t " + std::to_string(g_bytraceInfo->time); + beginCmd += " -o "; + beginCmd += g_bytraceInfo->outFile; + beginCmd += " "; + } + for (const std::string& category : g_bytraceInfo->categoryVec) { + beginCmd += category; + beginCmd += " "; + } + return RunCommand(beginCmd); +} + +bool StopTrace() +{ + std::string finishCmd; + if (g_bytraceInfo->isRoot) { + finishCmd = "su root "; + } + finishCmd += "bytrace --trace_finish --trace_dump"; + if (g_bytraceInfo->outFile.empty()) { + g_bytraceInfo->outFile = DEFAULT_FILE; + } + finishCmd += " -o "; + finishCmd += g_bytraceInfo->outFile; + return RunCommand(finishCmd); +} } // namespace int BytracePluginSessionStart(const uint8_t* configData, const uint32_t configSize) { + std::lock_guard guard(g_taskMutex); BytracePluginConfig config; - HILOG_INFO(LOG_CORE, "BytracePluginSessionStart %u", configSize); - CHECK_TRUE(config.ParseFromArray(configData, configSize), 0, "parse config FAILED!"); - - g_processNum = fork(); - CHECK_TRUE(g_processNum >= 0, -1, "create process FAILED!"); - - if (g_processNum == 0) { - // child process - CHECK_TRUE(RunWithConfig(config), 0, "run bytrace FAILED!"); - _exit(0); - } - - return 0; -} - -int BytraceRegisterWriterStruct(const WriterStruct* writer) -{ + int res = config.ParseFromArray(configData, configSize); + CHECK_TRUE(res, 0, "BytracePluginSessionStart, parse config FAILED! configSize: %u", configSize); + g_bytraceInfo = std::make_unique(); + ParseConfig(config); + res = BeginTrace(); + CHECK_TRUE(res, 0, "BytracePluginSessionStart, bytrace begin FAILED!"); return 0; } int BytracePluginSessionStop() { - if (g_processNum > 0) { - // parent process - int status = 0; - // judge if child process have exited. - if (waitpid(g_processNum, &status, WNOHANG) == 0) { - // send SIGKILL to child process. - if (kill(g_processNum, SIGINT)) { - HILOG_WARN(LOG_CORE, "BytracePluginSessionStop kill child process failed."); - } else { - HILOG_INFO(LOG_CORE, "BytracePluginSessionStop kill child process success."); - } - } - // report child process exit status. - if (WIFEXITED(status)) { - HILOG_INFO(LOG_CORE, "child %d exit with status %d!", g_processNum, - WEXITSTATUS(static_cast(status))); - } else if (WIFSIGNALED(status)) { - HILOG_INFO(LOG_CORE, "child %d exit with signal %d!", g_processNum, - WTERMSIG(static_cast(status))); - } else if (WIFSTOPPED(status)) { - HILOG_INFO(LOG_CORE, "child %d stopped by signal %d", g_processNum, - WSTOPSIG(static_cast(status))); - } else { - HILOG_INFO(LOG_CORE, "child %d otherwise", g_processNum); - } + std::lock_guard guard(g_taskMutex); + // real-time type nead finish trace. + if (g_bytraceInfo->time == 0) { + int res = StopTrace(); + CHECK_TRUE(res, 0, "BytracePluginSessionStop, bytrace finish FAILED!"); } + g_bytraceInfo = nullptr; + return 0; +} + +int BytraceRegisterWriterStruct(const WriterStruct* writer) +{ + HILOG_INFO(LOG_CORE, "writer %p", writer); return 0; } @@ -132,4 +167,4 @@ static PluginModuleCallbacks g_callbacks = { BytraceRegisterWriterStruct, }; -PluginModuleStruct g_pluginModule = {&g_callbacks, "bytrace_plugin", MAX_BUFFER_SIZE}; +PluginModuleStruct g_pluginModule = {&g_callbacks, "bytrace_plugin", MAX_BUFFER_SIZE}; \ No newline at end of file diff --git a/device/plugins/bytrace_plugin/src/run_test.cpp b/device/plugins/bytrace_plugin/src/run_test.cpp index b07c0681b..0f933d9ed 100644 --- a/device/plugins/bytrace_plugin/src/run_test.cpp +++ b/device/plugins/bytrace_plugin/src/run_test.cpp @@ -25,15 +25,15 @@ constexpr uint32_t BUFFE_SIZE = 1024; int main() { - WriterStruct writer; - BytraceRegisterWriterStruct(&writer); - BytracePluginConfig config; + config.set_outfile_name("/data/local/tmp/bytrace.txt"); config.set_clock("boot"); config.set_time(TRACE_TIME); config.set_buffe_size(BUFFE_SIZE); - config.set_outfile_name("/data/local/tmp/bytrace.txt"); config.add_categories("sched"); + config.add_categories("freq"); + config.add_categories("idle"); + config.add_categories("workq"); std::vector buffer(config.ByteSizeLong()); CHECK_TRUE(config.SerializeToArray(buffer.data(), buffer.size()), 0, "Serialize config FAILED!"); diff --git a/device/plugins/cpu_plugin/BUILD.gn b/device/plugins/cpu_plugin/BUILD.gn new file mode 100644 index 000000000..68a215987 --- /dev/null +++ b/device/plugins/cpu_plugin/BUILD.gn @@ -0,0 +1,75 @@ +# 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("//build/ohos.gni") +import("../../base/config.gni") + +ohos_shared_library("cpudataplugin") { + output_name = "cpudataplugin" + sources = [ + "../memory_plugin/src/buffer_splitter.cpp", + "src/cpu_data_plugin.cpp", + "src/cpu_module.cpp", + ] + include_dirs = [ + "include", + "../memory_plugin/include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + "//utils/native/base/include", + ] + deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", + "${OHOS_PROFILER_DIR}/protos/types/plugins/cpu_data:cpu_data_cpp", + "//utils/native/base:utilsecurec", + ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + if (build_l2) { + external_deps = [ "shared_library:libhilog" ] + } else { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } + } + public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] + install_enable = true + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" +} + +ohos_executable("cpudataplugintest") { + output_name = "cpudataplugintest" + sources = [ "src/test_main.cpp" ] + include_dirs = [ + "include", + "../api/include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + ] + deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", + "${OHOS_PROFILER_DIR}/protos/types/plugins/cpu_data:cpu_data_cpp", + ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + if (build_l2) { + external_deps = [ "shared_library:libhilog" ] + } else { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } + } + public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] + install_enable = true + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" +} diff --git a/device/plugins/cpu_plugin/include/cpu_data_plugin.h b/device/plugins/cpu_plugin/include/cpu_data_plugin.h new file mode 100644 index 000000000..fec0273fc --- /dev/null +++ b/device/plugins/cpu_plugin/include/cpu_data_plugin.h @@ -0,0 +1,116 @@ +/* + * 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 CPU_DATA_PLUGIN_H +#define CPU_DATA_PLUGIN_H + +#include +#include +#include +#include + +#include "cpu_plugin_config.pb.h" +#include "cpu_plugin_result.pb.h" +#include "logging.h" + +enum ErrorType { + RET_NULL_ADDR, + RET_IVALID_PID, + RET_TGID_VALUE_NULL, + RET_FAIL = -1, + RET_SUCC = 0, +}; + +enum ProcessCpuTimeType { + PROCESS_UTIME = 0, + PROCESS_STIME, + PROCESS_CUTIME, + PROCESS_CSTIME, + PROCESS_UNSPECIFIED, +}; + +enum SystemCpuTimeType { + SYSTEM_USER = 1, + SYSTEM_NICE, + SYSTEM_SYSTEM, + SYSTEM_IDLE, + SYSTEM_IOWAIT, + SYSTEM_IRQ, + SYSTEM_SOFTIRQ, + SYSTEM_STEAL, + SYSTEM_UNSPECIFIED, +}; + +class CpuDataPlugin { +public: + CpuDataPlugin(); + ~CpuDataPlugin(); + int Start(const uint8_t* configData, uint32_t configSize); + int Report(uint8_t* configData, uint32_t configSize); + int Stop(); + +private: + int32_t ReadFile(std::string& fileName); + void SetTimestamp(SampleTimeStamp& timestamp); + + int64_t GetUserHz(); + int64_t GetCpuUsageTime(std::vector& cpuUsageVec); + void WriteProcessCpuUsage(CpuUsageInfo& cpuUsageInfo, const char* pFile, uint32_t fileLen); + void GetSystemCpuTime(std::vector& cpuUsageVec, int64_t& usageTime, int64_t& time); + void WriteSystemCpuUsage(CpuUsageInfo& cpuUsageInfo, const char* pFile, uint32_t fileLen); + void WriteCpuUsageInfo(CpuData& data); + + bool addTidBySort(int32_t tid); + DIR* OpenDestDir(std::string& dirPath); + int32_t GetValidTid(DIR* dirp); + ThreadState GetThreadState(const char threadState); + void WriteThread(ThreadInfo& threadInfo, const char* pFile, uint32_t fileLen, int32_t tid); + void WriteSingleThreadInfo(CpuData& data, int32_t tid); + void WriteThreadInfo(CpuData& data); + + int32_t GetCpuFrequency(std::string fileName); + int GetCpuCoreSize(); + int32_t GetMaxCpuFrequencyIndex(); + void SetCpuFrequency(CpuCoreUsageInfo& cpuCore, int32_t coreNum); + + // for UT + void SetPath(std::string path) + { + path_ = path; + } + void SetFreqPath(std::string path); + +private: + /* data */ + CpuConfig protoConfig_; + void* buffer_; + std::string path_; + int32_t err_; + + int pid_; + std::vector tidVec_; + int64_t prevProcessCpuTime_; + int64_t prevSystemCpuTime_; + int64_t prevSystemBootTime_; + std::map prevThreadCpuTimeMap_; + std::map prevCoreSystemCpuTimeMap_; + std::map prevCoreSystemBootTimeMap_; + std::vector maxFrequencyVec_; + std::vector minFrequencyVec_; + int32_t maxFreqIndex_; + std::string freqPath_; +}; + +#endif diff --git a/device/plugins/cpu_plugin/src/cpu_data_plugin.cpp b/device/plugins/cpu_plugin/src/cpu_data_plugin.cpp new file mode 100644 index 000000000..4cf4005a3 --- /dev/null +++ b/device/plugins/cpu_plugin/src/cpu_data_plugin.cpp @@ -0,0 +1,567 @@ +/* + * 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 "cpu_data_plugin.h" + +#include +#include + +#include "buffer_splitter.h" + +namespace { +constexpr size_t READ_BUFFER_SIZE = 1024 * 16; +constexpr int SYSTEM_STAT_COUNT = 9; +constexpr int STAT_COUNT = 17; +constexpr int STAT_START = 13; +constexpr int THREAD_NAME_POS = 1; +constexpr int THREAD_STATE_POS = 2; +constexpr int CPU_USER_HZ_L = 100; +constexpr int CPU_USER_HZ_H = 1000; +constexpr int CPU_HZ_H = 10; + +const std::string FREQUENCY_PATH = "/sys/devices/system/cpu"; +const std::string FREQUENCY_MIN_PATH = "/cpufreq/cpuinfo_min_freq"; +const std::string FREQUENCY_MAX_PATH = "/cpufreq/cpuinfo_max_freq"; +const std::string FREQUENCY_CUR_PATH = "/cpufreq/cpuinfo_cur_freq"; +constexpr int CPU_FREQUENCY_KHZ = 1000; +} // namespace + +CpuDataPlugin::CpuDataPlugin() +{ + buffer_ = nullptr; + path_ = "/proc/"; + err_ = -1; + pid_ = -1; + prevProcessCpuTime_ = 0; + prevSystemCpuTime_ = 0; + prevSystemBootTime_ = 0; + maxFreqIndex_ = -1; + freqPath_ = FREQUENCY_PATH; +} + +CpuDataPlugin::~CpuDataPlugin() +{ + HILOG_INFO(LOG_CORE, "plugin:~CpuDataPlugin!"); + if (buffer_ != nullptr) { + free(buffer_); + buffer_ = nullptr; + } + + tidVec_.clear(); + prevThreadCpuTimeMap_.clear(); + prevCoreSystemCpuTimeMap_.clear(); + prevCoreSystemBootTimeMap_.clear(); + maxFrequencyVec_.clear(); + minFrequencyVec_.clear(); +} + +int CpuDataPlugin::Start(const uint8_t* configData, uint32_t configSize) +{ + buffer_ = malloc(READ_BUFFER_SIZE); + if (buffer_ == nullptr) { + HILOG_ERROR(LOG_CORE, "plugin:malloc buffer_ fail"); + return RET_FAIL; + } + + if (protoConfig_.ParseFromArray(configData, configSize) <= 0) { + HILOG_ERROR(LOG_CORE, "plugin:ParseFromArray failed"); + return RET_FAIL; + } + + if (protoConfig_.pid() > 0) { + pid_ = protoConfig_.pid(); + } else { + HILOG_ERROR(LOG_CORE, "plugin:Invalid pid"); + return RET_FAIL; + } + HILOG_INFO(LOG_CORE, "plugin:start success!"); + return RET_SUCC; +} + +int CpuDataPlugin::Report(uint8_t* data, uint32_t dataSize) +{ + CpuData dataProto; + uint32_t length; + + WriteCpuUsageInfo(dataProto); + WriteThreadInfo(dataProto); + + length = dataProto.ByteSizeLong(); + if (length > dataSize) { + return -length; + } + if (dataProto.SerializeToArray(data, length) > 0) { + return length; + } + return 0; +} + +int CpuDataPlugin::Stop() +{ + if (buffer_ != nullptr) { + free(buffer_); + buffer_ = nullptr; + } + + tidVec_.clear(); + prevThreadCpuTimeMap_.clear(); + prevCoreSystemCpuTimeMap_.clear(); + prevCoreSystemBootTimeMap_.clear(); + HILOG_INFO(LOG_CORE, "plugin:stop success!"); + return 0; +} + +int32_t CpuDataPlugin::ReadFile(std::string& fileName) +{ + int fd = -1; + ssize_t bytesRead = 0; + + fd = open(fileName.c_str(), O_RDONLY | O_CLOEXEC); + if (fd == -1) { + HILOG_ERROR(LOG_CORE, "Failed to open(%s), errno=%d", fileName.c_str(), errno); + err_ = errno; + return RET_FAIL; + } + if (buffer_ == nullptr) { + HILOG_ERROR(LOG_CORE, "%s:Empty address, buffer_ is NULL", __func__); + err_ = RET_NULL_ADDR; + close(fd); + return RET_FAIL; + } + bytesRead = read(fd, buffer_, READ_BUFFER_SIZE - 1); + if (bytesRead <= 0) { + close(fd); + HILOG_ERROR(LOG_CORE, "Failed to read(%s), errno=%d", fileName.c_str(), errno); + err_ = errno; + return RET_FAIL; + } + close(fd); + + return bytesRead; +} + +void CpuDataPlugin::SetTimestamp(SampleTimeStamp& timestamp) +{ + timespec time; + clock_gettime(CLOCK_MONOTONIC, &time); + timestamp.set_tv_sec(time.tv_sec); + timestamp.set_tv_nsec(time.tv_nsec); +} + +int64_t CpuDataPlugin::GetUserHz() +{ + int64_t hz = -1; + int64_t user_hz = sysconf(_SC_CLK_TCK); + switch (user_hz) { + case CPU_USER_HZ_L: + hz = CPU_HZ_H; + break; + case CPU_USER_HZ_H: + hz = 1; + break; + default: + break; + } + return hz; +} + +int64_t CpuDataPlugin::GetCpuUsageTime(std::vector& cpuUsageVec) +{ + int64_t utime, stime, cutime, cstime, usageTime; + utime = atoi(cpuUsageVec[PROCESS_UTIME].c_str()); + stime = atoi(cpuUsageVec[PROCESS_STIME].c_str()); + cutime = atoi(cpuUsageVec[PROCESS_CUTIME].c_str()); + cstime = atoi(cpuUsageVec[PROCESS_CSTIME].c_str()); + usageTime = (utime + stime + cutime + cstime) * GetUserHz(); + + return usageTime; +} + +void CpuDataPlugin::WriteProcessCpuUsage(CpuUsageInfo& cpuUsageInfo, const char* pFile, uint32_t fileLen) +{ + BufferSplitter totalbuffer(const_cast(pFile), fileLen + 1); + std::vector cpuUsageVec; + for (int i = 0; i < STAT_COUNT; i++) { + totalbuffer.NextWord(' '); + if (!totalbuffer.CurWord()) { + return; + } + + if (i < STAT_START) { + continue; + } else { + std::string curWord = std::string(totalbuffer.CurWord(), totalbuffer.CurWordSize()); + cpuUsageVec.push_back(curWord); + } + } + + // 获取到的数据不包含utime、stime、cutime、cstime四个数值时返回 + if (cpuUsageVec.size() != PROCESS_UNSPECIFIED) { + HILOG_ERROR(LOG_CORE, "Failed to get process cpu usage, size=%d", cpuUsageVec.size()); + return; + } + + int64_t usageTime = GetCpuUsageTime(cpuUsageVec); + cpuUsageInfo.set_prev_process_cpu_time_ms(prevProcessCpuTime_); + cpuUsageInfo.set_process_cpu_time_ms(usageTime); + prevProcessCpuTime_ = usageTime; +} + +int32_t CpuDataPlugin::GetCpuFrequency(std::string fileName) +{ + int32_t frequency = 0; + int32_t ret = ReadFile(fileName); + if (ret == RET_FAIL) { + HILOG_ERROR(LOG_CORE, "read %s file failed", fileName.c_str()); + } else { + frequency = atoi((char*)buffer_); + } + return frequency; +} + +int CpuDataPlugin::GetCpuCoreSize() +{ + int coreSize = 0; + DIR* procDir = nullptr; + procDir = OpenDestDir(freqPath_); + if (procDir == nullptr) { + HILOG_ERROR(LOG_CORE, "procDir is nullptr"); + return -1; + } + + while (struct dirent* dirEnt = readdir(procDir)) { + if (dirEnt->d_type != DT_DIR) { + continue; + } + if (strncmp(dirEnt->d_name, "cpu", strlen("cpu")) == 0) { + coreSize++; + } + } + + return coreSize; +} + +int32_t CpuDataPlugin::GetMaxCpuFrequencyIndex() +{ + int coreSize = GetCpuCoreSize(); + int index = -1; + int32_t maxFreq = -1; + maxFrequencyVec_.clear(); + minFrequencyVec_.clear(); + for (int i = 0; i < coreSize; i++) { + std::string fileName = freqPath_ + "/cpu" + std::to_string(i) + FREQUENCY_MAX_PATH; + int32_t maxFrequency = GetCpuFrequency(fileName); + maxFrequencyVec_.push_back(maxFrequency); + fileName = freqPath_ + "/cpu" + std::to_string(i) + FREQUENCY_MIN_PATH; + int32_t minFrequency = GetCpuFrequency(fileName); + minFrequencyVec_.push_back(minFrequency); + + if (maxFreq < maxFrequency) { + maxFreq = maxFrequency; + index = i; + } + } + + // 单核或所有核最大频率相同,默认小核 + if (coreSize == 1 || (coreSize > 1 && index == 0 && maxFreq == maxFrequencyVec_[1])) { + index = -1; + } + + return index; +} + +void CpuDataPlugin::SetCpuFrequency(CpuCoreUsageInfo& cpuCore, int32_t coreNum) +{ + // 第一次获取最大频率核位置,并保存各核最大最小频率到vector + if (maxFrequencyVec_.empty() || minFrequencyVec_.empty()) { + maxFreqIndex_ = GetMaxCpuFrequencyIndex(); + } + std::string fileName = freqPath_ + "/cpu" + std::to_string(coreNum) + FREQUENCY_CUR_PATH; + int32_t curFrequency = GetCpuFrequency(fileName) / CPU_FREQUENCY_KHZ; + int32_t maxFrequency = maxFrequencyVec_[coreNum] / CPU_FREQUENCY_KHZ; + int32_t minFrequency = minFrequencyVec_[coreNum] / CPU_FREQUENCY_KHZ; + + if (coreNum == maxFreqIndex_) { + cpuCore.set_is_little_core(false); + } else { + cpuCore.set_is_little_core(true); + } + CpuCoreFrequency* frequency = cpuCore.mutable_frequency(); + frequency->set_min_frequency_khz(minFrequency); + frequency->set_max_frequency_khz(maxFrequency); + frequency->set_cur_frequency_khz(curFrequency); +} + +void CpuDataPlugin::GetSystemCpuTime(std::vector& cpuUsageVec, int64_t& usageTime, int64_t& time) +{ + // 获取到的数据不包含user, nice, system, idle, iowait, irq, softirq, steal八个数值时返回 + if (cpuUsageVec.size() != SYSTEM_UNSPECIFIED) { + HILOG_ERROR(LOG_CORE, "Failed to get system cpu usage, size=%d", cpuUsageVec.size()); + return; + } + + int64_t user, nice, system, idle, iowait, irq, softirq, steal; + user = atoi(cpuUsageVec[SYSTEM_USER].c_str()); + nice = atoi(cpuUsageVec[SYSTEM_NICE].c_str()); + system = atoi(cpuUsageVec[SYSTEM_SYSTEM].c_str()); + idle = atoi(cpuUsageVec[SYSTEM_IDLE].c_str()); + iowait = atoi(cpuUsageVec[SYSTEM_IOWAIT].c_str()); + irq = atoi(cpuUsageVec[SYSTEM_IRQ].c_str()); + softirq = atoi(cpuUsageVec[SYSTEM_SOFTIRQ].c_str()); + steal = atoi(cpuUsageVec[SYSTEM_STEAL].c_str()); + + usageTime = (user + nice + system + irq + softirq + steal) * GetUserHz(); + time = (usageTime + idle + iowait) * GetUserHz(); +} + +void CpuDataPlugin::WriteSystemCpuUsage(CpuUsageInfo& cpuUsageInfo, const char* pFile, uint32_t fileLen) +{ + BufferSplitter totalbuffer(const_cast(pFile), fileLen + 1); + std::vector cpuUsageVec; + int64_t usageTime, time; + size_t cpuLength = strlen("cpu"); + + do { + totalbuffer.NextWord(' '); + if (strncmp(totalbuffer.CurWord(), "cpu", cpuLength) != 0) { + return; + } + + for (int i = 0; i < SYSTEM_STAT_COUNT; i++) { + if (!totalbuffer.CurWord()) { + return; + } + std::string curWord = std::string(totalbuffer.CurWord(), totalbuffer.CurWordSize()); + cpuUsageVec.push_back(curWord); + totalbuffer.NextWord(' '); + } + + GetSystemCpuTime(cpuUsageVec, usageTime, time); + if (strcmp(cpuUsageVec[0].c_str(), "cpu") == 0) { + cpuUsageInfo.set_prev_system_cpu_time_ms(prevSystemCpuTime_); + cpuUsageInfo.set_prev_system_boot_time_ms(prevSystemBootTime_); + cpuUsageInfo.set_system_cpu_time_ms(usageTime); + cpuUsageInfo.set_system_boot_time_ms(time); + prevSystemCpuTime_ = usageTime; + prevSystemBootTime_ = time; + } else { + std::string core = std::string(cpuUsageVec[0].c_str() + cpuLength, cpuUsageVec[0].size() - cpuLength); + int32_t coreNum = atoi(core.c_str()); + // 第一次获取数据时需要将前一个数据置为0 + if (prevCoreSystemCpuTimeMap_.size() == static_cast(coreNum)) { + prevCoreSystemCpuTimeMap_[coreNum] = 0; + prevCoreSystemBootTimeMap_[coreNum] = 0; + } + CpuCoreUsageInfo* cpuCore = cpuUsageInfo.add_cores(); + cpuCore->set_cpu_core(coreNum); + cpuCore->set_prev_system_cpu_time_ms(prevCoreSystemCpuTimeMap_[coreNum]); + cpuCore->set_prev_system_boot_time_ms(prevCoreSystemBootTimeMap_[coreNum]); + cpuCore->set_system_cpu_time_ms(usageTime); + cpuCore->set_system_boot_time_ms(time); + + SetCpuFrequency(*cpuCore, coreNum); + prevCoreSystemCpuTimeMap_[coreNum] = usageTime; + prevCoreSystemBootTimeMap_[coreNum] = time; + } + + cpuUsageVec.clear(); + usageTime = 0; + time = 0; + } while (totalbuffer.NextLine()); +} + +void CpuDataPlugin::WriteCpuUsageInfo(CpuData& data) +{ + // write process info + std::string fileName = path_ + std::to_string(pid_) + "/stat"; + int32_t ret = ReadFile(fileName); + if (ret == RET_FAIL) { + HILOG_ERROR(LOG_CORE, "read /proc/pid/stat file failed"); + return; + } + if ((buffer_ == nullptr) || (ret == 0)) { + HILOG_ERROR(LOG_CORE, "%s:invalid params, read buffer_ is NULL", __func__); + return; + } + auto* cpuUsageInfo = data.mutable_cpu_usage_info(); + WriteProcessCpuUsage(*cpuUsageInfo, (char*)buffer_, ret); + + // write system info + fileName = path_ + "stat"; + ret = ReadFile(fileName); + if (ret == RET_FAIL) { + HILOG_ERROR(LOG_CORE, "read /proc/stat file failed"); + return; + } + if ((buffer_ == nullptr) || (ret == 0)) { + HILOG_ERROR(LOG_CORE, "%s:invalid params, read buffer_ is NULL", __func__); + return; + } + WriteSystemCpuUsage(*cpuUsageInfo, (char*)buffer_, ret); + + auto* timestamp = cpuUsageInfo->mutable_timestamp(); + SetTimestamp(*timestamp); +} + +bool CpuDataPlugin::addTidBySort(int32_t tid) +{ + auto tidsEnd = tidVec_.end(); + auto it = std::lower_bound(tidVec_.begin(), tidsEnd, tid); + if (it != tidsEnd && *it == tid) { + return false; + } + it = tidVec_.insert(it, std::move(tid)); + return true; +} + +DIR* CpuDataPlugin::OpenDestDir(std::string& dirPath) +{ + DIR* destDir = nullptr; + + destDir = opendir(dirPath.c_str()); + if (destDir == nullptr) { + HILOG_ERROR(LOG_CORE, "Failed to opendir(%s), errno=%d", dirPath.c_str(), errno); + } + + return destDir; +} + +int32_t CpuDataPlugin::GetValidTid(DIR* dirp) +{ + if (!dirp) { + return 0; + } + while (struct dirent* dirEnt = readdir(dirp)) { + if (dirEnt->d_type != DT_DIR) { + continue; + } + + int32_t tid = atoi(dirEnt->d_name); + if (tid) { + return tid; + } + } + return 0; +} + +ThreadState CpuDataPlugin::GetThreadState(const char threadState) +{ + ThreadState state = THREAD_UNSPECIFIED; + switch (threadState) { + case 'R': + state = THREAD_RUNNING; + break; + case 'S': + state = THREAD_SLEEPING; + break; + case 'T': + state = THREAD_STOPPED; + break; + case 'D': + state = THREAD_WAITING; + break; + default: + break; + } + + return state; +} + +void CpuDataPlugin::WriteThread(ThreadInfo& threadInfo, const char* pFile, uint32_t fileLen, int32_t tid) +{ + BufferSplitter totalbuffer(const_cast(pFile), fileLen + 1); + std::vector cpuUsageVec; + for (int i = 0; i < STAT_COUNT; i++) { + totalbuffer.NextWord(' '); + if (!totalbuffer.CurWord()) { + return; + } + + if (i == THREAD_NAME_POS) { + std::string curWord = std::string(totalbuffer.CurWord() + 1, totalbuffer.CurWordSize() - sizeof(")")); + threadInfo.set_thread_name(curWord); + } else if (i == THREAD_STATE_POS) { + std::string curWord = std::string(totalbuffer.CurWord(), totalbuffer.CurWordSize()); + ThreadState state = GetThreadState(curWord[0]); + threadInfo.set_thread_state(state); + } else if (i >= STAT_START) { + std::string curWord = std::string(totalbuffer.CurWord(), totalbuffer.CurWordSize()); + cpuUsageVec.push_back(curWord); + } + } + + // 获取到的数据不包含utime、stime、cutime、cstime四个数值时返回 + if (cpuUsageVec.size() != PROCESS_UNSPECIFIED) { + HILOG_ERROR(LOG_CORE, "Failed to get thread cpu usage, size=%d", cpuUsageVec.size()); + return; + } + + // 第一次获取该线程数据时需要将前一个数据置为0 + if (prevThreadCpuTimeMap_.find(tid) == prevThreadCpuTimeMap_.end()) { + prevThreadCpuTimeMap_[tid] = 0; + } + + int64_t usageTime = GetCpuUsageTime(cpuUsageVec); + threadInfo.set_prev_thread_cpu_time_ms(prevThreadCpuTimeMap_[tid]); + threadInfo.set_thread_cpu_time_ms(usageTime); + prevThreadCpuTimeMap_[tid] = usageTime; + threadInfo.set_tid(tid); + + auto* timestamp = threadInfo.mutable_timestamp(); + SetTimestamp(*timestamp); +} + +void CpuDataPlugin::WriteSingleThreadInfo(CpuData& data, int32_t tid) +{ + std::string fileName = path_ + std::to_string(pid_) + "/task/" + std::to_string(tid) + "/stat"; + int32_t ret = ReadFile(fileName); + if (ret == RET_FAIL) { + HILOG_ERROR(LOG_CORE, "%s:read tid file failed", fileName.c_str()); + return; + } + if ((buffer_ == nullptr) || (ret == 0)) { + HILOG_ERROR(LOG_CORE, "%s:invalid params, read buffer_ is NULL", __func__); + return; + } + auto* threadInfo = data.add_thread_info(); + WriteThread(*threadInfo, (char*)buffer_, ret, tid); +} + +void CpuDataPlugin::WriteThreadInfo(CpuData& data) +{ + DIR* procDir = nullptr; + std::string path = path_ + std::to_string(pid_) + "/task"; + procDir = OpenDestDir(path); + if (procDir == nullptr) { + return; + } + + while (int32_t tid = GetValidTid(procDir)) { + if (find(tidVec_.begin(), tidVec_.end(), tid) == tidVec_.end()) { + addTidBySort(tid); + } + } + + for (unsigned int i = 0; i < tidVec_.size(); i++) { + WriteSingleThreadInfo(data, tidVec_[i]); + } + closedir(procDir); +} + +// for UT +void CpuDataPlugin::SetFreqPath(std::string path) +{ + freqPath_ = path + FREQUENCY_PATH; +} diff --git a/device/plugins/cpu_plugin/src/cpu_module.cpp b/device/plugins/cpu_plugin/src/cpu_module.cpp new file mode 100644 index 000000000..d3d30d081 --- /dev/null +++ b/device/plugins/cpu_plugin/src/cpu_module.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "cpu_data_plugin.h" +#include "plugin_module_api.h" + +namespace { +constexpr uint32_t MAX_BUFFER_SIZE = 4 * 1024 * 1024; +std::unique_ptr g_plugin = nullptr; +std::mutex g_taskMutex; +} // namespace + +static int CpuDataPluginSessionStart(const uint8_t* configData, uint32_t configSize) +{ + std::lock_guard guard(g_taskMutex); + g_plugin = std::make_unique(); + return g_plugin->Start(configData, configSize); +} + +static int CpuPluginReportResult(uint8_t* bufferData, uint32_t bufferSize) +{ + std::lock_guard guard(g_taskMutex); + return g_plugin->Report(bufferData, bufferSize); +} + +static int CpuPluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + HILOG_INFO(LOG_CORE, "%s:stop Session success!", __func__); + g_plugin->Stop(); + g_plugin = nullptr; + return 0; +} + +static PluginModuleCallbacks g_callbacks = { + CpuDataPluginSessionStart, + CpuPluginReportResult, + CpuPluginSessionStop, +}; + +PluginModuleStruct g_pluginModule = {&g_callbacks, "cpu-plugin", MAX_BUFFER_SIZE}; diff --git a/device/plugins/cpu_plugin/src/test_main.cpp b/device/plugins/cpu_plugin/src/test_main.cpp new file mode 100644 index 000000000..986cfe6bd --- /dev/null +++ b/device/plugins/cpu_plugin/src/test_main.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "cpu_plugin_config.pb.h" +#include "cpu_plugin_result.pb.h" +#include "plugin_module_api.h" + +namespace { +constexpr int TEST_PID = 10; +int g_testCount = 10; +} // namespace + +static void Report(PluginModuleStruct*& cpuPlugin, std::vector& dataBuffer) +{ + while (g_testCount--) { + int len = cpuPlugin->callbacks->onPluginReportResult(dataBuffer.data(), cpuPlugin->resultBufferSizeHint); + std::cout << "test:filler buffer length = " << len << std::endl; + + if (len > 0) { + CpuData cpuData; + cpuData.ParseFromArray(dataBuffer.data(), len); + std::cout << "test:ParseFromArray length = " << len << std::endl; + + CpuUsageInfo cpuUsageInfo = cpuData.cpu_usage_info(); + std::cout << "prev_process_cpu_time_ms:" << cpuUsageInfo.prev_process_cpu_time_ms() << std::endl; + std::cout << "prev_system_cpu_time_ms:" << cpuUsageInfo.prev_system_cpu_time_ms() << std::endl; + std::cout << "prev_system_boot_time_ms:" << cpuUsageInfo.prev_system_boot_time_ms() << std::endl; + std::cout << "process_cpu_time_ms:" << cpuUsageInfo.process_cpu_time_ms() << std::endl; + std::cout << "system_cpu_time_ms:" << cpuUsageInfo.system_cpu_time_ms() << std::endl; + std::cout << "system_boot_time_ms:" << cpuUsageInfo.system_boot_time_ms() << std::endl; + + for (int i = 0; i < cpuUsageInfo.cores_size(); i++) { + CpuCoreUsageInfo cpuCoreUsageInfo = cpuUsageInfo.cores()[i]; + std::cout << "cpu_core:" << cpuCoreUsageInfo.cpu_core() << std::endl; + std::cout << "prev_system_cpu_time_ms:" << cpuCoreUsageInfo.prev_system_cpu_time_ms() << std::endl; + std::cout << "prev_system_boot_time_ms:" << cpuCoreUsageInfo.prev_system_boot_time_ms() << std::endl; + std::cout << "system_cpu_time_ms:" << cpuCoreUsageInfo.system_cpu_time_ms() << std::endl; + std::cout << "system_boot_time_ms:" << cpuCoreUsageInfo.system_boot_time_ms() << std::endl; + std::cout << "min_frequency_khz:" << cpuCoreUsageInfo.frequency().min_frequency_khz() << std::endl; + std::cout << "max_frequency_khz:" << cpuCoreUsageInfo.frequency().max_frequency_khz() << std::endl; + std::cout << "cur_frequency_khz:" << cpuCoreUsageInfo.frequency().cur_frequency_khz() << std::endl; + std::cout << "is_little_core:" << cpuCoreUsageInfo.is_little_core() << std::endl; + } + std::cout << "timestamp.tv_sec : " << cpuUsageInfo.timestamp().tv_sec() << std::endl; + std::cout << "timestamp.tv_nsec : " << cpuUsageInfo.timestamp().tv_nsec() << std::endl; + + for (int i = 0; i < cpuData.thread_info_size(); i++) { + ThreadInfo threadInfo = cpuData.thread_info()[i]; + std::cout << "tid : " << threadInfo.tid() << std::endl; + std::cout << "thread_name : " << threadInfo.thread_name() << std::endl; + std::cout << "thread_state : " << threadInfo.thread_state() << std::endl; + std::cout << "prev_thread_cpu_time_ms : " << threadInfo.prev_thread_cpu_time_ms() << std::endl; + std::cout << "thread_cpu_time_ms : " << threadInfo.thread_cpu_time_ms() << std::endl; + std::cout << "timestamp.tv_sec : " << threadInfo.timestamp().tv_sec() << std::endl; + std::cout << "timestamp.tv_nsec : " << threadInfo.timestamp().tv_nsec() << std::endl; + } + } + + std::cout << "test:sleep...................." << std::endl; + sleep(1); + } +} + +int main() +{ + CpuConfig protoConfig; + void* handle = dlopen("./libcpudataplugin.z.so", RTLD_LAZY); + if (handle == nullptr) { + std::cout << "test:dlopen err: " << dlerror() << std::endl; + return 0; + } + std::cout << "test:handle = " << handle << std::endl; + PluginModuleStruct* cpuPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); + std::cout << "test:name = " << cpuPlugin->name << std::endl; + std::cout << "test:buffer size = " << cpuPlugin->resultBufferSizeHint << std::endl; + + // Serialize config + protoConfig.set_pid(TEST_PID); + int configLength = protoConfig.ByteSizeLong(); + std::vector configBuffer(configLength); + int ret = protoConfig.SerializeToArray(configBuffer.data(), configLength); + std::cout << "test:configLength = " << configLength << std::endl; + std::cout << "test:serialize success start plugin ret = " << ret << std::endl; + + // run plugin + std::vector dataBuffer(cpuPlugin->resultBufferSizeHint); + cpuPlugin->callbacks->onPluginSessionStart(configBuffer.data(), configLength); + Report(cpuPlugin, dataBuffer); + cpuPlugin->callbacks->onPluginSessionStop(); + + return 0; +} diff --git a/device/plugins/cpu_plugin/test/BUILD.gn b/device/plugins/cpu_plugin/test/BUILD.gn new file mode 100644 index 000000000..9cf042a9a --- /dev/null +++ b/device/plugins/cpu_plugin/test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../base/config.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" +config("module_private_config") { + visibility = [ ":*" ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + } +} + +ohos_unittest("cpudataplugin_ut") { + module_out_path = module_output_path + sources = [ "unittest/cpu_data_plugin_unittest.cpp" ] + deps = [ + "${OHOS_PROFILER_DIR}/device/plugins/cpu_plugin:cpudataplugin", + "${OHOS_PROFILER_DIR}/protos/types/plugins/cpu_data:cpu_data_cpp", + "//third_party/googletest:gtest_main", + "//utils/native/base:utilsecurec", + ] + include_dirs = [ + "../include", + "../../../memory_plugin/include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + "//third_party/googletest/googletest/include/gtest", + "//utils/native/base/include", + ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +group("unittest") { + testonly = true + deps = [ ":cpudataplugin_ut" ] +} diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/stat new file mode 100644 index 000000000..9b3cf5d61 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/stat @@ -0,0 +1 @@ +1872 (ibus-x11) S 1 1865 1780 1025 1780 4194304 3233 0 457 0 60 10 20 30 20 0 7 0 4394 726278144 0 18446744073709551615 1 1 0 0 0 0 0 16781312 16386 0 0 0 17 5 0 0 5 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1872/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1872/stat new file mode 100644 index 000000000..dbda24f8e --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1872/stat @@ -0,0 +1 @@ +1872 (ibus-x11) R 1 1865 1780 1025 1780 4194304 3217 0 457 0 17 5 10 10 20 0 7 0 4394 726278144 0 18446744073709551615 1 1 0 0 0 0 0 16781312 16386 0 0 0 17 5 0 0 5 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1965/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1965/stat new file mode 100644 index 000000000..3e4280e0e --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1965/stat @@ -0,0 +1 @@ +1965 (ibus-x1:disk$0) S 1 1865 1780 1025 1780 1077936192 1 0 0 0 8 1 5 8 20 0 7 0 4444 726278144 0 18446744073709551615 1 1 0 0 0 0 1073479423 16781312 16386 0 0 0 -1 5 0 5 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1966/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1966/stat new file mode 100644 index 000000000..044ac3758 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1966/stat @@ -0,0 +1 @@ +1966 (ibus-x1:disk$1) X 1 1865 1780 1025 1780 1077936192 1 0 0 0 0 0 0 0 20 0 7 0 4444 726278144 0 18446744073709551615 1 1 0 0 0 0 1073479423 16781312 16386 0 0 0 -1 5 0 5 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1967/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1967/stat new file mode 100644 index 000000000..43513c90b --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1967/stat @@ -0,0 +1 @@ +1967 (ibus-x1:disk$2) S 1 1865 1780 1025 1780 1077936192 1 0 0 0 10 1 5 8 20 0 7 0 4444 726278144 0 18446744073709551615 1 1 0 0 0 0 1073479423 16781312 16386 0 0 0 -1 5 0 5 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1968/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1968/stat new file mode 100644 index 000000000..d0240dc9e --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1968/stat @@ -0,0 +1 @@ +1968 (ibus-x1:disk$3) T 1 1865 1780 1025 1780 1077936192 1 0 0 0 7 0 0 0 20 0 7 0 4444 726278144 0 18446744073709551615 1 1 0 0 0 0 1073479423 16781312 16386 0 0 0 -1 5 0 5 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1995/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1995/stat new file mode 100644 index 000000000..fb15ba787 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1995/stat @@ -0,0 +1 @@ +1995 (gmain) S 1 1865 1780 1025 1780 4194368 1 0 0 0 15 3 0 4 20 0 7 0 4446 726278144 0 18446744073709551615 1 1 0 0 0 0 2147221247 16781312 16386 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/1872/task/1996/stat b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1996/stat new file mode 100644 index 000000000..1d2f83320 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/1872/task/1996/stat @@ -0,0 +1 @@ +1996 (gdbus) D 1 1865 1780 1025 1780 4194368 11 0 0 0 5 0 0 0 20 0 7 0 4446 726278144 0 18446744073709551615 1 1 0 0 0 0 0 16781312 16386 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/device/plugins/cpu_plugin/test/resources/proc/stat b/device/plugins/cpu_plugin/test/resources/proc/stat new file mode 100644 index 000000000..d516b7d16 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/proc/stat @@ -0,0 +1,14 @@ +cpu 24875428 3952448 11859815 1193297105 8980661 0 2607250 0 0 0 +cpu0 4165400 662862 1966195 196987024 3571925 0 817371 0 0 0 +cpu1 3861506 676578 1702753 199535158 1752008 0 401639 0 0 0 +cpu2 3549890 676286 1544630 200640747 1133743 0 205972 0 0 0 +cpu3 3336646 676939 1458898 201176432 854578 0 124812 0 0 0 +cpu4 4566158 601107 2305309 197166395 929594 0 1007959 0 0 0 +cpu5 5395826 658673 2882028 197791346 738811 0 49496 0 0 0 +intr 1770859348 7 4 0 0 0 0 0 0 1 11 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 171 59725591 981403168 19 439482 559268 457611 427943 581724 453376 45 20991 669 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +ctxt 2926398868 +btime 1620093904 +processes 18239603 +procs_running 1 +procs_blocked 0 +softirq 2254950393 2090427 450858980 2885663 985716628 59484869 0 134917257 208251538 45883 410699148 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..3eb28a61a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1018000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..fa76231d4 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +3844000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..6ccf58238 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +509000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..25e38638a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1023000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..45fa1d3d5 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +2844000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..6ccf58238 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +509000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..c8bc9652b --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1011000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..fa76231d4 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +3844000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..6ccf58238 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +509000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..bf8657409 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1518000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..fa76231d4 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +3844000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..3eb28a61a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +1018000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..d54b3aaca --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1245000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..63a1a37e4 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +1844000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..3eb28a61a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +1018000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_cur_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_cur_freq new file mode 100644 index 000000000..d3693fa4a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_cur_freq @@ -0,0 +1 @@ +1767000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_max_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_max_freq new file mode 100644 index 000000000..440d7a057 --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_max_freq @@ -0,0 +1 @@ +3044000 diff --git a/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_min_freq b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_min_freq new file mode 100644 index 000000000..3eb28a61a --- /dev/null +++ b/device/plugins/cpu_plugin/test/resources/sys/devices/system/cpu/cpu5/cpufreq/cpuinfo_min_freq @@ -0,0 +1 @@ +1018000 diff --git a/device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp b/device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp new file mode 100644 index 000000000..20b971599 --- /dev/null +++ b/device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include + +#include "cpu_data_plugin.h" +#include "plugin_module_api.h" + +using namespace testing::ext; + +namespace { +#if defined(__i386__) || defined(__x86_64__) +const std::string DEFAULT_TEST_PATH = "./resources"; +#else +const std::string DEFAULT_TEST_PATH = "/data/local/tmp/resources"; +#endif + +constexpr uint32_t BUF_SIZE = 4 * 1024 * 1024; +const std::string SO_PATH = "/system/lib/libcpudataplugin.z.so"; +constexpr int TEST_PID = 1; + +std::string g_path; +std::string g_testPath; +std::vector g_tidList = {1872, 1965, 1966, 1967, 1968, 1995, 1996}; + +constexpr int CORE_NUM = 6; +constexpr int THREAD_NUM = 7; + +struct TestSystemStat { + int32_t core; + int64_t user; + int64_t nice; + int64_t system; + int64_t idle; + int64_t iowait; + int64_t irq; + int64_t softirq; + int64_t steal; +}; + +struct TestStat { + int64_t utime; + int64_t stime; + int64_t cutime; + int64_t cstime; +}; + +struct TestTidStat { + int32_t tid; + std::string name; + ThreadState state; + TestStat stat; +}; + +struct TestFreq { + int32_t curFreq; + int32_t maxFreq; + int32_t minFreq; +}; + +TestSystemStat g_systemStat[CORE_NUM + 1] = { + {-1, 24875428, 3952448, 11859815, 1193297105, 8980661, 0, 2607250, 0}, + {0, 4165400, 662862, 1966195, 196987024, 3571925, 0, 817371, 0}, + {1, 3861506, 676578, 1702753, 199535158, 1752008, 0, 401639, 0}, + {2, 3549890, 676286, 1544630, 200640747, 1133743, 0, 205972, 0}, + {3, 3336646, 676939, 1458898, 201176432, 854578, 0, 124812, 0}, + {4, 4566158, 601107, 2305309, 197166395, 929594, 0, 1007959, 0}, + {5, 5395826, 658673, 2882028, 197791346, 738811, 0, 49496, 0}, +}; + +TestStat g_pidStat = {60, 10, 20, 30}; + +TestTidStat g_tidStat[THREAD_NUM] = { + {1872, "ibus-x11", THREAD_RUNNING, {17, 5, 10, 10}}, + {1965, "ibus-x1:disk$0", THREAD_SLEEPING, {8, 1, 5, 8}}, + {1966, "ibus-x1:disk$1", THREAD_UNSPECIFIED, {0, 0, 0, 0}}, + {1967, "ibus-x1:disk$2", THREAD_SLEEPING, {10, 1, 5, 8}}, + {1968, "ibus-x1:disk$3", THREAD_STOPPED, {7, 0, 0, 0}}, + {1995, "gmain", THREAD_SLEEPING, {15, 3, 0, 4}}, + {1996, "gdbus", THREAD_WAITING, {5, 0, 0, 0}}, +}; + +TestFreq g_Freq[CORE_NUM + 1] = { + {1018, 3844, 509}, {1023, 2844, 509}, {1011, 3844, 509}, {1518, 3844, 1018}, {1245, 1844, 1018}, {1767, 3044, 1018}, +}; + +class CpuDataPluginTest : public ::testing::Test { +public: + static void SetUpTestCase() {} + + static void TearDownTestCase() + { + if (access(g_testPath.c_str(), F_OK) == 0) { + std::string str = "rm -rf " + g_testPath; + printf("TearDown--> %s\r\n", str.c_str()); + system(str.c_str()); + } + } +}; + +string Getexepath() +{ + char buf[PATH_MAX] = ""; + std::string path = "/proc/self/exe"; + size_t rslt = readlink(path.c_str(), buf, sizeof(buf)); + if (rslt < 0 || (rslt >= sizeof(buf))) { + return ""; + } + buf[rslt] = '\0'; + for (int i = rslt; i >= 0; i--) { + if (buf[i] == '/') { + buf[i + 1] = '\0'; + break; + } + } + return buf; +} + +std::string GetFullPath(std::string path) +{ + if (path.size() > 0 && path[0] != '/') { + return Getexepath() + path; + } + return path; +} + +#if defined(__i386__) || defined(__x86_64__) +bool CreatTestResource(std::string path, std::string exepath) +{ + std::string str = "cp -r " + path + " " + exepath; + printf("CreatTestResource:%s\n", str.c_str()); + + pid_t status = system(str.c_str()); + if (-1 == status) { + printf("system error!"); + } else { + printf("exit status value = [0x%x]\n", status); + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == 0) { + return true; + } else { + printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status)); + return false; + } + } else { + printf("exit status = [%d]\n", WEXITSTATUS(status)); + return true; + } + } + return false; +} +#endif + +bool CheckTid(std::vector& tidListTmp) +{ + sort(g_tidList.begin(), g_tidList.end()); + for (size_t i = 0; i < g_tidList.size(); i++) { + if (tidListTmp.at(i) != g_tidList.at(i)) { + return false; + } + } + return true; +} + +bool PluginCpuinfoStub(CpuDataPlugin& cpuPlugin, CpuData& cpuData, int pid, bool unusualBuff) +{ + CpuConfig protoConfig; + protoConfig.set_pid(pid); + + // serialize + std::vector configData(protoConfig.ByteSizeLong()); + int ret = protoConfig.SerializeToArray(configData.data(), configData.size()); + + // start + ret = cpuPlugin.Start(configData.data(), configData.size()); + if (ret < 0) { + return false; + } + printf("ut: serialize success start plugin ret = %d\n", ret); + + // report + std::vector bufferData(BUF_SIZE); + if (unusualBuff) { // buffer异常,调整缓冲区长度为1,测试异常情况 + bufferData.resize(1, 0); + printf("ut: bufferData resize\n"); + } + + ret = cpuPlugin.Report(bufferData.data(), bufferData.size()); + if (ret > 0) { + cpuData.ParseFromArray(bufferData.data(), ret); + return true; + } + + return false; +} + +void GetSystemCpuTime(TestSystemStat& stat, int64_t Hz, int64_t& usageTime, int64_t& time) +{ + usageTime = (stat.user + stat.nice + stat.system + stat.irq + stat.softirq + stat.steal) * Hz; + time = (usageTime + stat.idle + stat.iowait) * Hz; +} + +/** + * @tc.name: cpu plugin + * @tc.desc: Test whether the path exists. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestPath, TestSize.Level1) +{ + g_path = GetFullPath(DEFAULT_TEST_PATH); + g_testPath = g_path; + printf("g_path:%s\n", g_path.c_str()); + EXPECT_NE("", g_path); + +#if defined(__i386__) || defined(__x86_64__) + if (DEFAULT_TEST_PATH != g_path) { + if ((access(g_path.c_str(), F_OK) != 0) && (access(DEFAULT_TEST_PATH.c_str(), F_OK) == 0)) { + EXPECT_TRUE(CreatTestResource(DEFAULT_TEST_PATH, g_path)); + } + } +#endif +} + +/** + * @tc.name: cpu plugin + * @tc.desc: Tid list test in a specific directory. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestTidlist, TestSize.Level1) +{ + CpuDataPlugin cpuPlugin; + std::string path = g_path + "/proc/1872/task/"; + printf("path:%s\n", path.c_str()); + DIR* dir = cpuPlugin.OpenDestDir(path); + EXPECT_NE(nullptr, dir); + + std::vector tidListTmp; + while (int32_t pid = cpuPlugin.GetValidTid(dir)) { + tidListTmp.push_back(pid); + sort(tidListTmp.begin(), tidListTmp.end()); + } + EXPECT_TRUE(CheckTid(tidListTmp)); +} + +/** + * @tc.name: cpu plugin + * @tc.desc: a part of cpu information test for specific pid. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestPluginInfo, TestSize.Level1) +{ + CpuDataPlugin cpuPlugin; + CpuData cpuData; + cpuPlugin.SetFreqPath(g_path); + g_path += "/proc/"; + cpuPlugin.SetPath(g_path); + EXPECT_TRUE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, false)); + + int64_t systemCpuTime = 0; + int64_t systemBootTime = 0; + int64_t Hz = cpuPlugin.GetUserHz(); + printf("Hz : %" PRId64 "\n", Hz); + int64_t processCpuTime = (g_pidStat.utime + g_pidStat.stime + g_pidStat.cutime + g_pidStat.cstime) * Hz; + GetSystemCpuTime(g_systemStat[0], Hz, systemCpuTime, systemBootTime); + + CpuUsageInfo cpuUsageInfo = cpuData.cpu_usage_info(); + EXPECT_EQ(cpuUsageInfo.prev_process_cpu_time_ms(), 0); + EXPECT_EQ(cpuUsageInfo.prev_system_cpu_time_ms(), 0); + EXPECT_EQ(cpuUsageInfo.prev_system_boot_time_ms(), 0); + EXPECT_EQ(cpuUsageInfo.process_cpu_time_ms(), processCpuTime); + EXPECT_EQ(cpuUsageInfo.system_cpu_time_ms(), systemCpuTime); + printf("systemCpuTime = %" PRId64 "\n", systemCpuTime); + EXPECT_EQ(cpuUsageInfo.system_boot_time_ms(), systemBootTime); + printf("systemBootTime = %" PRId64 "\n", systemBootTime); + + ASSERT_EQ(cpuUsageInfo.cores_size(), 6); + for (int i = 1; i <= CORE_NUM; i++) { + CpuCoreUsageInfo cpuCoreUsageInfo = cpuUsageInfo.cores()[i - 1]; + GetSystemCpuTime(g_systemStat[i], Hz, systemCpuTime, systemBootTime); + EXPECT_EQ(cpuCoreUsageInfo.cpu_core(), g_systemStat[i].core); + EXPECT_EQ(cpuCoreUsageInfo.prev_system_cpu_time_ms(), 0); + EXPECT_EQ(cpuCoreUsageInfo.prev_system_boot_time_ms(), 0); + EXPECT_EQ(cpuCoreUsageInfo.system_cpu_time_ms(), systemCpuTime); + EXPECT_EQ(cpuCoreUsageInfo.system_boot_time_ms(), systemBootTime); + + EXPECT_EQ(cpuCoreUsageInfo.frequency().min_frequency_khz(), g_Freq[i - 1].minFreq); + EXPECT_EQ(cpuCoreUsageInfo.frequency().max_frequency_khz(), g_Freq[i - 1].maxFreq); + EXPECT_EQ(cpuCoreUsageInfo.frequency().cur_frequency_khz(), g_Freq[i - 1].curFreq); + if (i == 1) { // cpu0为大核 + EXPECT_EQ(cpuCoreUsageInfo.is_little_core(), false); + } else { + EXPECT_EQ(cpuCoreUsageInfo.is_little_core(), true); + } + } +} + +/** + * @tc.name: cpu plugin + * @tc.desc: cpu information test for specific pid. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestPlugin, TestSize.Level1) +{ + CpuDataPlugin cpuPlugin; + CpuData cpuData; + g_path = g_testPath; + cpuPlugin.SetFreqPath(g_path); + g_path += "/proc/"; + cpuPlugin.SetPath(g_path); + EXPECT_TRUE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, false)); + + int64_t Hz = cpuPlugin.GetUserHz(); + int64_t threadCpuTime; + ASSERT_EQ(cpuData.thread_info_size(), 7); + for (int i = 0; i < THREAD_NUM; i++) { + threadCpuTime = (g_tidStat[i].stat.utime + g_tidStat[i].stat.stime + + g_tidStat[i].stat.cutime + g_tidStat[i].stat.cstime) * Hz; + ThreadInfo threadInfo = cpuData.thread_info()[i]; + EXPECT_EQ(threadInfo.tid(), g_tidStat[i].tid); + EXPECT_STREQ(threadInfo.thread_name().c_str(), g_tidStat[i].name.c_str()); + EXPECT_EQ(threadInfo.thread_state(), g_tidStat[i].state); + EXPECT_EQ(threadInfo.thread_cpu_time_ms(), threadCpuTime); + EXPECT_EQ(threadInfo.prev_thread_cpu_time_ms(), 0); + } + + EXPECT_EQ(cpuPlugin.Stop(), 0); + + // 缓冲区异常 + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, true)); + EXPECT_EQ(cpuPlugin.Stop(), 0); +} + +/** + * @tc.name: cpu plugin + * @tc.desc: cpu information test for unusual path. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestPluginBoundary, TestSize.Level1) +{ + CpuDataPlugin cpuPlugin; + CpuData cpuData; + g_path += "/proc/"; + cpuPlugin.SetPath(g_path); + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, -1, false)); + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, 12345, false)); + + CpuDataPlugin cpuPlugin2; + cpuPlugin2.SetPath("123"); + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, 1872, false)); + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, -1, false)); + EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, 12345, false)); +} + +/** + * @tc.name: cpu plugin + * @tc.desc: cpu plugin registration test. + * @tc.type: FUNC + */ +HWTEST_F(CpuDataPluginTest, TestPluginRegister, TestSize.Level1) +{ + void* handle = dlopen(SO_PATH.c_str(), RTLD_LAZY); + ASSERT_NE(handle, nullptr); + PluginModuleStruct* cpuPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); + ASSERT_NE(cpuPlugin, nullptr); + EXPECT_STREQ(cpuPlugin->name, "cpu-plugin"); + EXPECT_EQ(cpuPlugin->resultBufferSizeHint, BUF_SIZE); + + // Serialize config + CpuConfig protoConfig; + protoConfig.set_pid(TEST_PID); + int configLength = protoConfig.ByteSizeLong(); + ASSERT_GT(configLength, 0); + std::vector configBuffer(configLength); + EXPECT_TRUE(protoConfig.SerializeToArray(configBuffer.data(), configLength)); + + // run plugin + std::vector dataBuffer(cpuPlugin->resultBufferSizeHint); + EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStart(configBuffer.data(), configLength), RET_SUCC); + ASSERT_GT(cpuPlugin->callbacks->onPluginReportResult(dataBuffer.data(), cpuPlugin->resultBufferSizeHint), 0); + EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStop(), 0); + + // 反序列化失败导致的start失败 + EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStart(configBuffer.data(), configLength+1), RET_FAIL); +} +} // namespace \ No newline at end of file diff --git a/device/plugins/memory_plugin/BUILD.gn b/device/plugins/memory_plugin/BUILD.gn old mode 100755 new mode 100644 index cb3fe7330..45fcd74bf --- a/device/plugins/memory_plugin/BUILD.gn +++ b/device/plugins/memory_plugin/BUILD.gn @@ -33,7 +33,7 @@ ohos_shared_library("memdataplugin") { "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", "${OHOS_PROFILER_DIR}/protos/types/plugins/memory_data:memory_data_cpp", - "//utils/native/base:utilsbase", + "//utils/native/base:utilsecurec", ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] diff --git a/device/plugins/memory_plugin/include/buffer_splitter.h b/device/plugins/memory_plugin/include/buffer_splitter.h old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/include/memory_data_plugin.h b/device/plugins/memory_plugin/include/memory_data_plugin.h old mode 100755 new mode 100644 index 99a648d61..1966940b1 --- a/device/plugins/memory_plugin/include/memory_data_plugin.h +++ b/device/plugins/memory_plugin/include/memory_data_plugin.h @@ -135,7 +135,8 @@ private: /* data */ MemoryConfig protoConfig_; - void* buffer_; + std::unique_ptr buffer_; + int meminfoFd_; int vmstatFd_; std::map meminfoCounters_; diff --git a/device/plugins/memory_plugin/include/smaps_stats.h b/device/plugins/memory_plugin/include/smaps_stats.h old mode 100755 new mode 100644 index 09624e5d0..c91ea0255 --- a/device/plugins/memory_plugin/include/smaps_stats.h +++ b/device/plugins/memory_plugin/include/smaps_stats.h @@ -17,6 +17,7 @@ #define SMAPS_STATS_H #include "logging.h" +#include #include #include #include @@ -26,16 +27,71 @@ #include #include -struct stats_t { - int pss; - int swappablePss; - int rss; - int privateDirty; - int sharedDirty; - int privateClean; - int sharedClean; - int swappedOut; - int swappedOutPss; +struct MemUsageInfo { + uint64_t vss; + uint64_t rss; + uint64_t pss; + uint64_t uss; + + uint64_t swap; + uint64_t swapPss; + + uint64_t privateClean; + uint64_t privateDirty; + uint64_t sharedClean; + uint64_t sharedDirty; +}; + +class StatsInfo { +public: + int pss_; + int swappablePss_; + int rss_; + int privateDirty_; + int sharedDirty_; + int privateClean_; + int sharedClean_; + int swappedOut_; + int swappedOutPss_; + + StatsInfo() + : pss_(0), + swappablePss_(0), + rss_(0), + privateDirty_(0), + sharedDirty_(0), + privateClean_(0), + sharedClean_(0), + swappedOut_(0), + swappedOutPss_(0) + { + } + + StatsInfo(uint64_t swapablePss, const MemUsageInfo& usage) + : pss_(usage.pss), + swappablePss_(swapablePss), + rss_(usage.rss), + privateDirty_(usage.privateDirty), + sharedDirty_(usage.sharedDirty), + privateClean_(usage.privateClean), + sharedClean_(usage.sharedClean), + swappedOut_(usage.swap), + swappedOutPss_(usage.swapPss) + { + } + + void operator+=(const StatsInfo &S) + { + pss_ += S.pss_; + swappablePss_ += S.swappablePss_; + rss_ += S.rss_; + privateDirty_ += S.privateDirty_; + sharedDirty_ += S.sharedDirty_; + privateClean_ += S.privateClean_; + sharedClean_ += S.sharedClean_; + swappedOut_ += S.swappedOut_; + swappedOutPss_ += S.swappedOutPss_; + } }; enum NumType { @@ -44,29 +100,14 @@ enum NumType { DEC_BASE = 10, }; -struct MapPiecesInfo_t { - uint64_t start_addr; - uint64_t end_addr; +struct MapPiecesInfo { + uint64_t startAddr; + uint64_t endAddr; std::string name; }; -struct MemUsageInfo_t { - uint64_t vss; - uint64_t rss; - uint64_t pss; - uint64_t uss; - - uint64_t swap; - uint64_t swap_pss; - - uint64_t private_clean; - uint64_t private_dirty; - uint64_t shared_clean; - uint64_t shared_dirty; -}; - -enum vmemifoType { +enum VmemifoType { VMHEAP_NULL = -2, VMHEAP_NEEDFIX = -1, VMHEAP_UNKNOWN, @@ -113,9 +154,9 @@ enum vmemifoType { VMHEAP_ART_APP, VMHEAP_ART_BOOT, - _NUM_HEAP, - _NUM_EXCLUSIVE_HEAP = VMHEAP_OTHER_MEMTRACK + 1, - _NUM_CORE_HEAP = VMHEAP_NATIVE + 1 + VMHEAP_NUM_HEAP, + VMHEAP_NUM_EXCLUSIVE_HEAP = VMHEAP_OTHER_MEMTRACK + 1, + VMHEAP_NUM_CORE_HEAP = VMHEAP_NATIVE + 1 }; enum OpsType { @@ -123,86 +164,86 @@ enum OpsType { OPS_END, }; -struct vMeminfoAreaMapping { +struct VmeminfoAreaMapping { int ops; const char* heapstr; int heapid[2]; }; -constexpr vMeminfoAreaMapping vmaMemheap[] = { - {OpsType::OPS_START, "[heap]", {vmemifoType::VMHEAP_NATIVE, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "[stack", {vmemifoType::VMHEAP_STACK, vmemifoType::VMHEAP_NULL}}, +constexpr VmeminfoAreaMapping g_vmaMemHeap[] = { + {OpsType::OPS_START, "[heap]", {VmemifoType::VMHEAP_NATIVE, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "[stack", {VmemifoType::VMHEAP_STACK, VmemifoType::VMHEAP_NULL}}, }; // [anon: -constexpr vMeminfoAreaMapping vmaMemanon[] = { - {OpsType::OPS_START, "[anon:libc_malloc]", {vmemifoType::VMHEAP_NATIVE, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "[anon:scudo:", {vmemifoType::VMHEAP_NATIVE, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "[anon:GWP-ASan", {vmemifoType::VMHEAP_NATIVE, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "[anon:stack_and_tls:", {vmemifoType::VMHEAP_STACK, vmemifoType::VMHEAP_NULL}}, +constexpr VmeminfoAreaMapping g_vmaMemAnon[] = { + {OpsType::OPS_START, "[anon:libc_malloc]", {VmemifoType::VMHEAP_NATIVE, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "[anon:scudo:", {VmemifoType::VMHEAP_NATIVE, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "[anon:GWP-ASan", {VmemifoType::VMHEAP_NATIVE, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "[anon:stack_and_tls:", {VmemifoType::VMHEAP_STACK, VmemifoType::VMHEAP_NULL}}, {OpsType::OPS_START, "[anon:dalvik-LinearAlloc", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_LINEARALLOC}}, - {OpsType::OPS_START, "[anon:dalvik-alloc space", {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_NORMAL}}, - {OpsType::OPS_START, "[anon:dalvik-main space", {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_NORMAL}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_LINEARALLOC}}, + {OpsType::OPS_START, "[anon:dalvik-alloc space", {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_NORMAL}}, + {OpsType::OPS_START, "[anon:dalvik-main space", {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_NORMAL}}, {OpsType::OPS_START, "[anon:dalvik-large object space", - {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_LARGE}}, + {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_LARGE}}, {OpsType::OPS_START, "[anon:dalvik-free list large object space", - {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_LARGE}}, + {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_LARGE}}, {OpsType::OPS_START, "[anon:dalvik-non moving space", - {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_NON_MOVING}}, - {OpsType::OPS_START, "[anon:dalvik-zygote space", {vmemifoType::VMHEAP_DALVIK, vmemifoType::VMHEAP_DALVIK_ZYGOTE}}, + {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_NON_MOVING}}, + {OpsType::OPS_START, "[anon:dalvik-zygote space", {VmemifoType::VMHEAP_DALVIK, VmemifoType::VMHEAP_DALVIK_ZYGOTE}}, {OpsType::OPS_START, "[anon:dalvik-indirect ref", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE}}, {OpsType::OPS_START, "[anon:dalvik-jit-code-cache", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, {OpsType::OPS_START, "[anon:dalvik-data-code-cache", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, {OpsType::OPS_START, "[anon:dalvik-CompilerMetadata", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_COMPILER_METADATA}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_COMPILER_METADATA}}, {OpsType::OPS_START, "[anon:dalvik-", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_ACCOUNTING}}, - {OpsType::OPS_START, "[anon:", {vmemifoType::VMHEAP_UNKNOWN, vmemifoType::VMHEAP_NULL}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_ACCOUNTING}}, + {OpsType::OPS_START, "[anon:", {VmemifoType::VMHEAP_UNKNOWN, VmemifoType::VMHEAP_NULL}}, }; -constexpr vMeminfoAreaMapping vmaMemfd[] = { +constexpr VmeminfoAreaMapping g_vmaMemFd[] = { {OpsType::OPS_START, "/memfd:jit-cache", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_APP_CODE_CACHE}}, {OpsType::OPS_START, "/memfd:jit-zygote-cache", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE}}, }; // dev -constexpr vMeminfoAreaMapping vmaMemdev[] = { - {OpsType::OPS_START, "/dev/kgsl-3d0", {vmemifoType::VMHEAP_GL_DEV, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "/dev/ashmem/CursorWindow", {vmemifoType::VMHEAP_CURSOR, vmemifoType::VMHEAP_NULL}}, +constexpr VmeminfoAreaMapping g_vmaMemDev[] = { + {OpsType::OPS_START, "/dev/kgsl-3d0", {VmemifoType::VMHEAP_GL_DEV, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "/dev/ashmem/CursorWindow", {VmemifoType::VMHEAP_CURSOR, VmemifoType::VMHEAP_NULL}}, {OpsType::OPS_START, "/dev/ashmem/jit-zygote-cache", - {vmemifoType::VMHEAP_DALVIK_OTHER, vmemifoType::VMHEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE}}, - {OpsType::OPS_START, "/dev/ashmem", {vmemifoType::VMHEAP_ASHMEM, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_START, "/dev/", {vmemifoType::VMHEAP_UNKNOWN_DEV, vmemifoType::VMHEAP_NULL}}, + {VmemifoType::VMHEAP_DALVIK_OTHER, VmemifoType::VMHEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE}}, + {OpsType::OPS_START, "/dev/ashmem", {VmemifoType::VMHEAP_ASHMEM, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_START, "/dev/", {VmemifoType::VMHEAP_UNKNOWN_DEV, VmemifoType::VMHEAP_NULL}}, }; -constexpr vMeminfoAreaMapping vmaMemsuffix[] = { - {OpsType::OPS_END, ".so", {vmemifoType::VMHEAP_SO, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_END, ".jar", {vmemifoType::VMHEAP_JAR, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_END, ".ttf", {vmemifoType::VMHEAP_TTF, vmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_END, ".oat", {vmemifoType::VMHEAP_OAT, vmemifoType::VMHEAP_NULL}}, +constexpr VmeminfoAreaMapping g_vmaMemSuffix[] = { + {OpsType::OPS_END, ".so", {VmemifoType::VMHEAP_SO, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_END, ".jar", {VmemifoType::VMHEAP_JAR, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_END, ".ttf", {VmemifoType::VMHEAP_TTF, VmemifoType::VMHEAP_NULL}}, + {OpsType::OPS_END, ".oat", {VmemifoType::VMHEAP_OAT, VmemifoType::VMHEAP_NULL}}, - {OpsType::OPS_END, ".odex", {vmemifoType::VMHEAP_DEX, vmemifoType::VMHEAP_DEX_APP_DEX}}, + {OpsType::OPS_END, ".odex", {VmemifoType::VMHEAP_DEX, VmemifoType::VMHEAP_DEX_APP_DEX}}, - {OpsType::OPS_END, ".vdex", {vmemifoType::VMHEAP_DEX, vmemifoType::VMHEAP_NEEDFIX}}, - {OpsType::OPS_END, ".art", {vmemifoType::VMHEAP_ART, vmemifoType::VMHEAP_NEEDFIX}}, - {OpsType::OPS_END, ".art]", {vmemifoType::VMHEAP_ART, vmemifoType::VMHEAP_NEEDFIX}}, + {OpsType::OPS_END, ".vdex", {VmemifoType::VMHEAP_DEX, VmemifoType::VMHEAP_NEEDFIX}}, + {OpsType::OPS_END, ".art", {VmemifoType::VMHEAP_ART, VmemifoType::VMHEAP_NEEDFIX}}, + {OpsType::OPS_END, ".art]", {VmemifoType::VMHEAP_ART, VmemifoType::VMHEAP_NEEDFIX}}, }; class SmapsStats { @@ -220,7 +261,7 @@ public: int GetProcessSystem(); private: - stats_t stats_[_NUM_HEAP] = {{0}}; + std::array stats_; bool lastline_ = false; std::string testpath_; @@ -232,20 +273,20 @@ private: void ReviseStatsData(); bool ReadVmemareasFile(const std::string& path); - bool ParseMapHead(std::string& line, MapPiecesInfo_t& head); - bool SetMapAddrInfo(std::string& line, MapPiecesInfo_t& head); - bool GetMemUsageField(std::string& line, MemUsageInfo_t& memusage); - void CollectVmemAreasData(const MapPiecesInfo_t& mempic, - const MemUsageInfo_t& memusage, + bool ParseMapHead(std::string& line, MapPiecesInfo& head); + bool SetMapAddrInfo(std::string& line, MapPiecesInfo& head); + bool GetMemUsageField(std::string& line, MemUsageInfo& memusage); + void CollectVmemAreasData(const MapPiecesInfo& mempic, + const MemUsageInfo& memusage, uint64_t& prevEnd, int& prevHeap); bool GetVmaIndex(std::string name, uint32_t namesz, int32_t heapIndex[2], bool& swappable); - uint64_t GetSwapablepssValue(const MemUsageInfo_t& memusage, bool swappable); - void SetVmemAreasData(int index, uint64_t swapablePss, const MemUsageInfo_t& usage); + uint64_t GetSwapablepssValue(const MemUsageInfo& memusage, bool swappable); + void SetVmemAreasData(int index, uint64_t swapablePss, const MemUsageInfo& usage); void HeapIndexFix(std::string name, const char* key, int32_t heapIndex[2]); bool GetVMAStuId(int ops, std::string name, - const vMeminfoAreaMapping* vma, + const VmeminfoAreaMapping vma[], int count, int32_t heapIndex[2], bool& swappable); diff --git a/device/plugins/memory_plugin/src/buffer_splitter.cpp b/device/plugins/memory_plugin/src/buffer_splitter.cpp old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/src/memory_data_plugin.cpp b/device/plugins/memory_plugin/src/memory_data_plugin.cpp index 6617cb875..647673862 100644 --- a/device/plugins/memory_plugin/src/memory_data_plugin.cpp +++ b/device/plugins/memory_plugin/src/memory_data_plugin.cpp @@ -27,12 +27,8 @@ static const int BUF_MAX_LEN = 2048; } // namespace MemoryDataPlugin::MemoryDataPlugin() + : buffer_(new (std::nothrow) uint8_t[READ_BUFFER_SIZE]), meminfoFd_(-1), vmstatFd_(-1), err_(-1) { - buffer_ = nullptr; - meminfoFd_ = -1; - vmstatFd_ = -1; - testpath_ = nullptr; - err_ = -1; InitProto2StrVector(); SetPath(const_cast("/proc")); } @@ -40,10 +36,9 @@ MemoryDataPlugin::MemoryDataPlugin() MemoryDataPlugin::~MemoryDataPlugin() { HILOG_INFO(LOG_CORE, "plugin:~MemoryDataPlugin!"); - if (buffer_ != nullptr) { - free(buffer_); - buffer_ = nullptr; - } + + buffer_ = nullptr; + if (meminfoFd_ > 0) { close(meminfoFd_); meminfoFd_ = -1; @@ -78,9 +73,8 @@ void MemoryDataPlugin::InitProto2StrVector() int MemoryDataPlugin::Start(const uint8_t* configData, uint32_t configSize) { - buffer_ = malloc(READ_BUFFER_SIZE); if (buffer_ == nullptr) { - HILOG_ERROR(LOG_CORE, "plugin:malloc buffer_ fail"); + HILOG_ERROR(LOG_CORE, "buffer_ = null"); return RET_FAIL; } @@ -140,7 +134,7 @@ void MemoryDataPlugin::WriteMeminfo(MemoryData& data) HILOG_ERROR(LOG_CORE, "%s:read meminfoFd fail!", __func__); return; } - BufferSplitter totalbuffer((const char*)buffer_, readsize); + BufferSplitter totalbuffer((const char*)buffer_.get(), readsize); do { if (!totalbuffer.NextWord(':')) { @@ -195,10 +189,8 @@ bool MemoryDataPlugin::ParseMemInfo(const char* data, ProcessMemoryInfo* memoryI std::string line; while (std::getline(ss, line)) { - HILOG_INFO(LOG_CORE, "line: %s", line.c_str()); std::string s(line); if (s.find("App Summary") != s.npos) { - HILOG_INFO(LOG_CORE, "ready"); ready = true; continue; } @@ -241,15 +233,13 @@ bool MemoryDataPlugin::ParseMemInfo(const char* data, ProcessMemoryInfo* memoryI bool MemoryDataPlugin::GetMemInfoByDumpsys(uint32_t pid, ProcessMemoryInfo* memoryInfo) { std::string fullCmd = CMD_FORMAT + std::to_string(pid); - HILOG_INFO(LOG_CORE, "popen cmd = %s", fullCmd.c_str()); std::unique_ptr buffer {new (std::nothrow) uint8_t[BUF_MAX_LEN]}; std::unique_ptr fp(popen(fullCmd.c_str(), "r"), pclose); if (!fp) { - HILOG_INFO(LOG_CORE, "popen error"); + HILOG_ERROR(LOG_CORE, "popen error"); return false; } - HILOG_INFO(LOG_CORE, "popen ok"); fread(buffer.get(), 1, BUF_MAX_LEN, fp.get()); buffer.get()[BUF_MAX_LEN - 1] = '\0'; @@ -278,23 +268,17 @@ int MemoryDataPlugin::Report(uint8_t* data, uint32_t dataSize) } if (protoConfig_.pid().size() > 0) { - HILOG_DEBUG(LOG_CORE, "plugin:set pid counter, cnt = %d", protoConfig_.pid().size()); - for (int i = 0; i < protoConfig_.pid().size(); i++) { int32_t pid = protoConfig_.pid(i); - auto* processinfo = dataProto.add_processesinfo(); if (protoConfig_.report_process_mem_info()) { - HILOG_DEBUG(LOG_CORE, "plugin:need report meminfo pid(%d)", pid); WriteProcinfoByPidfds(processinfo, pid); } if (protoConfig_.report_app_mem_info()) { if (protoConfig_.report_app_mem_by_dumpsys()) { - HILOG_DEBUG(LOG_CORE, "plugin:report_app_mem_by_dumpsys"); GetMemInfoByDumpsys(pid, processinfo); } else { - HILOG_DEBUG(LOG_CORE, "plugin:need report appmeminfo pid(%d)", pid); SmapsStats smapInfo; smapInfo.ParseMaps(pid); WriteAppsummary(processinfo, smapInfo); @@ -308,7 +292,6 @@ int MemoryDataPlugin::Report(uint8_t* data, uint32_t dataSize) return -length; } if (dataProto.SerializeToArray(data, length) > 0) { - HILOG_DEBUG(LOG_CORE, "plugin:report success! length = %d", length); return length; } return 0; @@ -316,10 +299,6 @@ int MemoryDataPlugin::Report(uint8_t* data, uint32_t dataSize) int MemoryDataPlugin::Stop() { - if (buffer_ != nullptr) { - free(buffer_); - buffer_ = nullptr; - } if (meminfoFd_ > 0) { close(meminfoFd_); meminfoFd_ = -1; @@ -346,12 +325,12 @@ void MemoryDataPlugin::WriteProcinfoByPidfds(ProcessMemoryInfo* processinfo, int readSize = ReadFile(pidFds_[pid][FILE_STATUS]); if (readSize != RET_FAIL) { - WriteProcess(processinfo, (char*)buffer_, readSize, pid); + WriteProcess(processinfo, (char*)buffer_.get(), readSize, pid); } else { SetEmptyProcessInfo(processinfo); } if (ReadFile(pidFds_[pid][FILE_OOM]) != RET_FAIL) { - processinfo->set_oom_score_adj(strtol((char*)buffer_, &end, DEC_BASE)); + processinfo->set_oom_score_adj(strtol((char*)buffer_.get(), &end, DEC_BASE)); } else { processinfo->set_oom_score_adj(0); } @@ -360,11 +339,11 @@ void MemoryDataPlugin::WriteProcinfoByPidfds(ProcessMemoryInfo* processinfo, int int32_t MemoryDataPlugin::ReadFile(int fd) { - if ((buffer_ == nullptr) || (fd == -1)) { + if ((buffer_.get() == nullptr) || (fd == -1)) { HILOG_ERROR(LOG_CORE, "%s:Empty address, or invalid fd", __func__); return RET_FAIL; } - int readsize = pread(fd, buffer_, READ_BUFFER_SIZE - 1, 0); + int readsize = pread(fd, buffer_.get(), READ_BUFFER_SIZE - 1, 0); if (readsize <= 0) { HILOG_ERROR(LOG_CORE, "Failed to read(%d), errno=%d", fd, errno); err_ = errno; @@ -375,7 +354,6 @@ int32_t MemoryDataPlugin::ReadFile(int fd) std::vector MemoryDataPlugin::OpenProcPidFiles(int32_t pid) { - int fd = -1; char fileName[PATH_MAX + 1] = {0}; char realPath[PATH_MAX + 1] = {0}; int count = sizeof(procfdMapping) / sizeof(procfdMapping[0]); @@ -389,7 +367,7 @@ std::vector MemoryDataPlugin::OpenProcPidFiles(int32_t pid) if (realpath(fileName, realPath) == nullptr) { HILOG_ERROR(LOG_CORE, "plugin:realpath failed, errno=%d", errno); } - fd = open(realPath, O_RDONLY | O_CLOEXEC); + int fd = open(realPath, O_RDONLY | O_CLOEXEC); if (fd == -1) { HILOG_ERROR(LOG_CORE, "Failed to open(%s), errno=%d", fileName, errno); } @@ -431,7 +409,7 @@ int32_t MemoryDataPlugin::ReadProcPidFile(int32_t pid, const char* pFileName) char fileName[PATH_MAX + 1] = {0}; char realPath[PATH_MAX + 1] = {0}; int fd = -1; - ssize_t bytesRead; + ssize_t bytesRead = 0; if (snprintf_s(fileName, sizeof(fileName), sizeof(fileName) - 1, "%s/%d/%s", testpath_, pid, pFileName) < 0) { HILOG_ERROR(LOG_CORE, "snprintf_s error"); @@ -446,13 +424,13 @@ int32_t MemoryDataPlugin::ReadProcPidFile(int32_t pid, const char* pFileName) err_ = errno; return RET_FAIL; } - if (buffer_ == nullptr) { + if (buffer_.get() == nullptr) { HILOG_INFO(LOG_CORE, "%s:Empty address, buffer_ is NULL", __func__); err_ = RET_NULL_ADDR; close(fd); return RET_FAIL; } - bytesRead = read(fd, buffer_, READ_BUFFER_SIZE - 1); + bytesRead = read(fd, buffer_.get(), READ_BUFFER_SIZE - 1); if (bytesRead <= 0) { close(fd); HILOG_INFO(LOG_CORE, "Failed to read(%s), errno=%d", fileName, errno); @@ -490,9 +468,7 @@ bool MemoryDataPlugin::addPidBySort(int32_t pid) int MemoryDataPlugin::GetProcStatusId(const char* src, int srcLen) { - int count; - - count = sizeof(procStatusMapping) / sizeof(procStatusMapping[0]); + int count = sizeof(procStatusMapping) / sizeof(procStatusMapping[0]); for (int i = 0; i < count; i++) { if (BufnCmp(src, srcLen, procStatusMapping[i].procstr, strlen(procStatusMapping[i].procstr))) { return procStatusMapping[i].procid; @@ -506,41 +482,33 @@ void MemoryDataPlugin::SetProcessInfo(ProcessMemoryInfo* processinfo, int key, c char* end = nullptr; switch (key) { - case PRO_TGID: { + case PRO_TGID: processinfo->set_pid(strtoul(word, &end, DEC_BASE)); - } break; - case PRO_VMSIZE: { - uint64_t vm_size_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_vm_size_kb(vm_size_kb); - } break; - case PRO_VMRSS: { - uint64_t vm_rss_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_vm_rss_kb(vm_rss_kb); - } break; - case PRO_RSSANON: { - uint64_t rss_anon_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_rss_anon_kb(rss_anon_kb); - } break; - case PRO_RSSFILE: { - uint64_t rss_file_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_rss_file_kb(rss_file_kb); - } break; - case PRO_RSSSHMEM: { - uint64_t rss_shmem_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_rss_shmem_kb(rss_shmem_kb); - } break; - case PRO_VMSWAP: { - uint64_t vm_swap_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_vm_swap_kb(vm_swap_kb); - } break; - case PRO_VMLCK: { - uint64_t vm_locked_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_vm_locked_kb(vm_locked_kb); - } break; - case PRO_VMHWM: { - uint64_t vm_hwm_kb = strtoul(word, &end, DEC_BASE); - processinfo->set_vm_hwm_kb(vm_hwm_kb); - } break; + break; + case PRO_VMSIZE: + processinfo->set_vm_size_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_VMRSS: + processinfo->set_vm_rss_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_RSSANON: + processinfo->set_rss_anon_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_RSSFILE: + processinfo->set_rss_file_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_RSSSHMEM: + processinfo->set_rss_shmem_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_VMSWAP: + processinfo->set_vm_swap_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_VMLCK: + processinfo->set_vm_locked_kb(strtoul(word, &end, DEC_BASE)); + break; + case PRO_VMHWM: + processinfo->set_vm_hwm_kb(strtoul(word, &end, DEC_BASE)); + break; default: break; } @@ -570,8 +538,7 @@ void MemoryDataPlugin::WriteProcess(ProcessMemoryInfo* processinfo, const char* // update process name int32_t ret = ReadProcPidFile(pid, "cmdline"); if (ret > 0) { - processinfo->set_name(static_cast(buffer_), strlen(static_cast(buffer_))); - HILOG_ERROR(LOG_CORE, "%s:update process name=%s", __func__, processinfo->name().c_str()); + processinfo->set_name(reinterpret_cast(buffer_.get()), strlen(reinterpret_cast(buffer_.get()))); } } @@ -598,12 +565,12 @@ void MemoryDataPlugin::WriteOomInfo(ProcessMemoryInfo* processinfo, int32_t pid) processinfo->set_oom_score_adj(0); return; } - if (buffer_ == nullptr) { + if (buffer_.get() == nullptr) { processinfo->set_oom_score_adj(0); HILOG_ERROR(LOG_CORE, "%s:invalid params, read buffer_ is NULL", __func__); return; } - processinfo->set_oom_score_adj(strtol((char*)buffer_, &end, DEC_BASE)); + processinfo->set_oom_score_adj(strtol((char*)buffer_.get(), &end, DEC_BASE)); } void MemoryDataPlugin::WriteProcessInfo(MemoryData& data, int32_t pid) @@ -613,12 +580,12 @@ void MemoryDataPlugin::WriteProcessInfo(MemoryData& data, int32_t pid) SetEmptyProcessInfo(data.add_processesinfo()); return; } - if ((buffer_ == nullptr) || (ret == 0)) { + if ((buffer_.get() == nullptr) || (ret == 0)) { HILOG_ERROR(LOG_CORE, "%s:invalid params, read buffer_ is NULL", __func__); return; } auto* processinfo = data.add_processesinfo(); - WriteProcess(processinfo, (char*)buffer_, ret, pid); + WriteProcess(processinfo, (char*)buffer_.get(), ret, pid); WriteOomInfo(processinfo, pid); } diff --git a/device/plugins/memory_plugin/src/memory_module.cpp b/device/plugins/memory_plugin/src/memory_module.cpp old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/src/smaps_stats.cpp b/device/plugins/memory_plugin/src/smaps_stats.cpp old mode 100755 new mode 100644 index 4c20151d5..8a6e25af3 --- a/device/plugins/memory_plugin/src/smaps_stats.cpp +++ b/device/plugins/memory_plugin/src/smaps_stats.cpp @@ -37,7 +37,6 @@ bool SmapsStats::ParseMaps(int pid) if (testpath_.size() > 0) { smaps_path = testpath_ + std::to_string(pid) + std::string("/smaps"); } - HILOG_INFO(LOG_CORE, "smaps path:%s", smaps_path.c_str()); ReadVmemareasFile(smaps_path); ReviseStatsData(); return true; @@ -46,8 +45,8 @@ bool SmapsStats::ParseMaps(int pid) bool SmapsStats::ReadVmemareasFile(const std::string& path) { bool findMapHead = false; - MapPiecesInfo_t mappic = {0}; - MemUsageInfo_t memusage = {0}; + MapPiecesInfo mappic = {0}; + MemUsageInfo memusage = {0}; uint64_t prevEnd = 0; int prevHeap = 0; std::ifstream input(path, std::ios::in); @@ -84,7 +83,7 @@ bool SmapsStats::ReadVmemareasFile(const std::string& path) bool SmapsStats::GetVMAStuId(int ops, std::string name, - const vMeminfoAreaMapping* vma, + const VmeminfoAreaMapping vma[], int count, int32_t heapIndex[2], bool& swappable) @@ -118,34 +117,33 @@ bool SmapsStats::GetVmaIndex(std::string name, uint32_t namesz, int32_t heapInde switch (name[0]) { case '[': if (MatchHead(name, "[heap]") || MatchHead(name, "[stack")) { - int count = sizeof(vmaMemheap) / sizeof(vmaMemheap[0]); - return GetVMAStuId(OPS_START, name, vmaMemheap, count, heapIndex, swappable); + return GetVMAStuId(OPS_START, name, g_vmaMemHeap, sizeof(g_vmaMemHeap) / + sizeof(g_vmaMemHeap[0]), heapIndex, swappable); } else if (MatchHead(name, "[anon:")) { - if (MatchHead(name, "[anon:dalvik-")) { - int count = sizeof(vmaMemsuffix) / sizeof(vmaMemsuffix[0]); - if (GetVMAStuId(OPS_END, name, vmaMemsuffix, count, heapIndex, swappable)) { + if (MatchHead(name, "[anon:dalvik-") && + GetVMAStuId(OPS_END, name, g_vmaMemSuffix, sizeof(g_vmaMemSuffix) / + sizeof(g_vmaMemSuffix[0]), heapIndex, swappable)) { return true; - } } - int count = sizeof(vmaMemanon) / sizeof(vmaMemanon[0]); - return GetVMAStuId(OPS_START, name, vmaMemanon, count, heapIndex, swappable); + return GetVMAStuId(OPS_START, name, g_vmaMemAnon, sizeof(g_vmaMemAnon) / + sizeof(g_vmaMemAnon[0]), heapIndex, swappable); } break; case '/': if (MatchHead(name, "/memfd:")) { - int count = sizeof(vmaMemfd) / sizeof(vmaMemfd[0]); - return GetVMAStuId(OPS_START, name, vmaMemfd, count, heapIndex, swappable); + return GetVMAStuId(OPS_START, name, g_vmaMemFd, sizeof(g_vmaMemFd) / + sizeof(g_vmaMemFd[0]), heapIndex, swappable); } else if (MatchHead(name, "/dev/")) { - int count = sizeof(vmaMemdev) / sizeof(vmaMemdev[0]); - return GetVMAStuId(OPS_START, name, vmaMemdev, count, heapIndex, swappable); + return GetVMAStuId(OPS_START, name, g_vmaMemDev, sizeof(g_vmaMemDev) / + sizeof(g_vmaMemDev[0]), heapIndex, swappable); } else { - int count = sizeof(vmaMemsuffix) / sizeof(vmaMemsuffix[0]); - return GetVMAStuId(OPS_END, name, vmaMemsuffix, count, heapIndex, swappable); + return GetVMAStuId(OPS_END, name, g_vmaMemSuffix, sizeof(g_vmaMemSuffix) / + sizeof(g_vmaMemSuffix[0]), heapIndex, swappable); } break; default: - int count = sizeof(vmaMemsuffix) / sizeof(vmaMemsuffix[0]); - return GetVMAStuId(OPS_END, name, vmaMemsuffix, count, heapIndex, swappable); + return GetVMAStuId(OPS_END, name, g_vmaMemSuffix, sizeof(g_vmaMemSuffix) / + sizeof(g_vmaMemSuffix[0]), heapIndex, swappable); break; } if (namesz > strlen(".dex") && strstr(name.c_str(), ".dex") != nullptr) { @@ -157,8 +155,8 @@ bool SmapsStats::GetVmaIndex(std::string name, uint32_t namesz, int32_t heapInde return false; } -void SmapsStats::CollectVmemAreasData(const MapPiecesInfo_t& mempic, - const MemUsageInfo_t& memusage, +void SmapsStats::CollectVmemAreasData(const MapPiecesInfo& mempic, + const MemUsageInfo& memusage, uint64_t& prevEnd, int& prevHeap) { @@ -176,12 +174,12 @@ void SmapsStats::CollectVmemAreasData(const MapPiecesInfo_t& mempic, if (!GetVmaIndex(name, namesz, heapIndex, swappable)) { if (namesz > 0) { heapIndex[0] = VMHEAP_UNKNOWN_MAP; - } else if (mempic.start_addr == prevEnd && prevHeap == VMHEAP_SO) { + } else if (mempic.startAddr == prevEnd && prevHeap == VMHEAP_SO) { // bss section of a shared library heapIndex[0] = VMHEAP_SO; } } - prevEnd = mempic.end_addr; + prevEnd = mempic.endAddr; prevHeap = heapIndex[0]; swapablePss = GetSwapablepssValue(memusage, swappable); SetVmemAreasData(heapIndex[0], swapablePss, memusage); @@ -193,64 +191,52 @@ void SmapsStats::CollectVmemAreasData(const MapPiecesInfo_t& mempic, void SmapsStats::ReviseStatsData() { // Summary data to VMHEAP_UNKNOWN - for (int i = _NUM_CORE_HEAP; i < _NUM_EXCLUSIVE_HEAP; i++) { - stats_[VMHEAP_UNKNOWN].pss += stats_[i].pss; - stats_[VMHEAP_UNKNOWN].swappablePss += stats_[i].swappablePss; - stats_[VMHEAP_UNKNOWN].rss += stats_[i].rss; - stats_[VMHEAP_UNKNOWN].privateDirty += stats_[i].privateDirty; - stats_[VMHEAP_UNKNOWN].sharedDirty += stats_[i].sharedDirty; - stats_[VMHEAP_UNKNOWN].privateClean += stats_[i].privateClean; - stats_[VMHEAP_UNKNOWN].sharedClean += stats_[i].sharedClean; - stats_[VMHEAP_UNKNOWN].swappedOut += stats_[i].swappedOut; - stats_[VMHEAP_UNKNOWN].swappedOutPss += stats_[i].swappedOutPss; + for (int i = VMHEAP_NUM_CORE_HEAP; i < VMHEAP_NUM_EXCLUSIVE_HEAP; i++) { + stats_[VMHEAP_UNKNOWN] += stats_[i]; } } -bool SmapsStats::SetMapAddrInfo(std::string& line, MapPiecesInfo_t& head) +bool SmapsStats::SetMapAddrInfo(std::string& line, MapPiecesInfo& head) { const char* pStr = line.c_str(); char* end = nullptr; - // start_addr - head.start_addr = strtoull(pStr, &end, HEX_BASE); + head.startAddr = strtoull(pStr, &end, HEX_BASE); if (end == pStr || *end != '-') { return false; } pStr = end + 1; - // end_addr - head.end_addr = strtoull(pStr, &end, HEX_BASE); + head.endAddr = strtoull(pStr, &end, HEX_BASE); if (end == pStr) { return false; } return true; } -bool SmapsStats::ParseMapHead(std::string& line, MapPiecesInfo_t& head) +bool SmapsStats::ParseMapHead(std::string& line, MapPiecesInfo& head) { if (!SetMapAddrInfo(line, head)) { return false; } - size_t newlineops = 0; - size_t wordsz = 0; std::string newline = line; for (int i = 0; i < FIFTH_FIELD; i++) { std::string word = newline; - wordsz = word.find(" "); + size_t wordsz = word.find(" "); if (wordsz == std::string::npos) { return false; } word = newline.substr(0, wordsz); - newlineops = newline.find_first_not_of(" ", wordsz); + size_t newlineops = newline.find_first_not_of(" ", wordsz); newline = newline.substr(newlineops); } head.name = newline.substr(0, newline.size() - 1); return true; } -bool SmapsStats::GetMemUsageField(std::string& line, MemUsageInfo_t& memusage) +bool SmapsStats::GetMemUsageField(std::string& line, MemUsageInfo& memusage) { char field[64]; - int len; + int len = 0; const char* pLine = line.c_str(); int ret = sscanf_s(pLine, "%63s %n", field, sizeof(field), &len); @@ -263,11 +249,11 @@ bool SmapsStats::GetMemUsageField(std::string& line, MemUsageInfo_t& memusage) memusage.pss = strtoull(c, nullptr, DEC_BASE); } else if (MatchHead(strfield, "Private_Clean:")) { uint64_t prcl = strtoull(c, nullptr, DEC_BASE); - memusage.private_clean = prcl; + memusage.privateClean = prcl; memusage.uss += prcl; } else if (MatchHead(strfield, "Private_Dirty:")) { uint64_t prdi = strtoull(c, nullptr, DEC_BASE); - memusage.private_dirty = prdi; + memusage.privateDirty = prdi; memusage.uss += prdi; } break; @@ -275,13 +261,13 @@ bool SmapsStats::GetMemUsageField(std::string& line, MemUsageInfo_t& memusage) if (MatchHead(strfield, "Size:")) { memusage.vss = strtoull(c, nullptr, DEC_BASE); } else if (MatchHead(strfield, "Shared_Clean:")) { - memusage.shared_clean = strtoull(c, nullptr, DEC_BASE); + memusage.sharedClean = strtoull(c, nullptr, DEC_BASE); } else if (MatchHead(strfield, "Shared_Dirty:")) { - memusage.shared_dirty = strtoull(c, nullptr, DEC_BASE); + memusage.sharedDirty = strtoull(c, nullptr, DEC_BASE); } else if (MatchHead(strfield, "Swap:")) { memusage.swap = strtoull(c, nullptr, DEC_BASE); } else if (MatchHead(strfield, "SwapPss:")) { - memusage.swap_pss = strtoull(c, nullptr, DEC_BASE); + memusage.swapPss = strtoull(c, nullptr, DEC_BASE); } break; case 'R': @@ -303,32 +289,24 @@ bool SmapsStats::GetMemUsageField(std::string& line, MemUsageInfo_t& memusage) return false; } -uint64_t SmapsStats::GetSwapablepssValue(const MemUsageInfo_t& memusage, bool swappable) +uint64_t SmapsStats::GetSwapablepssValue(const MemUsageInfo& memusage, bool swappable) { - const MemUsageInfo_t& usage = memusage; - uint64_t swapablePss = 0; - - if (swappable && (usage.pss > 0)) { - float sharing_proportion = 0.0f; - if ((usage.shared_clean > 0) || (usage.shared_dirty > 0)) { - sharing_proportion = (usage.pss - usage.uss) / (usage.shared_clean + usage.shared_dirty); - } - swapablePss = (sharing_proportion * usage.shared_clean) + usage.private_clean; + if (!swappable || (memusage.pss == 0)) { + return 0; } - return swapablePss; + + if ((memusage.sharedClean == 0) && (memusage.sharedDirty == 0)) { + return memusage.privateClean; + } + float proportion = (memusage.pss - memusage.uss) / (memusage.sharedClean + memusage.sharedDirty); + + return (proportion * memusage.sharedClean) + memusage.privateClean; } -void SmapsStats::SetVmemAreasData(int index, uint64_t swapablePss, const MemUsageInfo_t& usage) +void SmapsStats::SetVmemAreasData(int index, uint64_t swapablePss, const MemUsageInfo& usage) { - stats_[index].pss += usage.pss; - stats_[index].swappablePss += swapablePss; - stats_[index].rss += usage.rss; - stats_[index].privateDirty += usage.private_dirty; - stats_[index].sharedDirty += usage.shared_dirty; - stats_[index].privateClean += usage.private_clean; - stats_[index].sharedClean += usage.shared_clean; - stats_[index].swappedOut += usage.swap; - stats_[index].swappedOutPss += usage.swap_pss; + StatsInfo oobj(swapablePss, usage); + stats_[index] += oobj; } void SmapsStats::HeapIndexFix(std::string name, const char* key, int32_t heapIndex[2]) @@ -356,12 +334,12 @@ void SmapsStats::HeapIndexFix(std::string name, const char* key, int32_t heapInd int SmapsStats::GetProcessJavaHeap() { - return stats_[VMHEAP_DALVIK].privateDirty + GetPrivate(VMHEAP_ART); + return stats_[VMHEAP_DALVIK].privateDirty_ + GetPrivate(VMHEAP_ART); } int SmapsStats::GetProcessNativeHeap() { - return stats_[VMHEAP_NATIVE].privateDirty; + return stats_[VMHEAP_NATIVE].privateDirty_; } int SmapsStats::GetProcessCode() @@ -374,7 +352,7 @@ int SmapsStats::GetProcessCode() int SmapsStats::GetProcessStack() { - return stats_[VMHEAP_STACK].privateDirty; + return stats_[VMHEAP_STACK].privateDirty_; } int SmapsStats::GetProcessGraphics() @@ -395,28 +373,29 @@ int SmapsStats::GetProcessSystem() int SmapsStats::GetTotalPrivateClean() { - return stats_[VMHEAP_UNKNOWN].privateClean + stats_[VMHEAP_NATIVE].privateClean + - stats_[VMHEAP_DALVIK].privateClean; + return stats_[VMHEAP_UNKNOWN].privateClean_ + stats_[VMHEAP_NATIVE].privateClean_ + + stats_[VMHEAP_DALVIK].privateClean_; } int SmapsStats::GetTotalPrivateDirty() { - return stats_[VMHEAP_UNKNOWN].privateDirty + stats_[VMHEAP_NATIVE].privateDirty + - stats_[VMHEAP_DALVIK].privateDirty; + return stats_[VMHEAP_UNKNOWN].privateDirty_ + stats_[VMHEAP_NATIVE].privateDirty_ + + stats_[VMHEAP_DALVIK].privateDirty_; } int SmapsStats::GetPrivate(int type) { - return stats_[type].privateDirty + stats_[type].privateClean; + return stats_[type].privateDirty_ + stats_[type].privateClean_; } int SmapsStats::GetTotalPss() { - return stats_[VMHEAP_UNKNOWN].pss + stats_[VMHEAP_NATIVE].pss + stats_[VMHEAP_DALVIK].pss + GetTotalSwappedOutPss(); + return stats_[VMHEAP_UNKNOWN].pss_ + stats_[VMHEAP_NATIVE].pss_ + stats_[VMHEAP_DALVIK].pss_ + + GetTotalSwappedOutPss(); } int SmapsStats::GetTotalSwappedOutPss() { - return stats_[VMHEAP_UNKNOWN].swappedOutPss + stats_[VMHEAP_NATIVE].swappedOutPss + - stats_[VMHEAP_DALVIK].swappedOutPss; + return stats_[VMHEAP_UNKNOWN].swappedOutPss_ + stats_[VMHEAP_NATIVE].swappedOutPss_ + + stats_[VMHEAP_DALVIK].swappedOutPss_; } diff --git a/device/plugins/memory_plugin/test/BUILD.gn b/device/plugins/memory_plugin/test/BUILD.gn index df7d17530..9d69dcec6 100644 --- a/device/plugins/memory_plugin/test/BUILD.gn +++ b/device/plugins/memory_plugin/test/BUILD.gn @@ -1,60 +1,58 @@ -# 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("//build/test.gni") -import("../../../base/config.gni") - -module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" -config("module_private_config") { - visibility = [":*"] - if (current_toolchain != host_toolchain) { - defines = [ "HAVE_HILOG" ] - } -} - -ohos_unittest("memdataplugin_ut") { - module_out_path = module_output_path - sources = [ - "unittest/buffer_splitter_unittest.cpp", - "unittest/memory_data_plugin_unittest.cpp", - ] - deps = [ - "${OHOS_PROFILER_DIR}/device/plugins/memory_plugin:memdataplugin", - "${OHOS_PROFILER_DIR}/protos/types/plugins/memory_data:memory_data_cpp", - "//third_party/googletest:gtest_main", - ] - include_dirs = [ - "../include", - "../../api/include", - "${OHOS_PROFILER_DIR}/interfaces/kits", - "${OHOS_PROFILER_DIR}/device/base/include", - "//third_party/googletest/googletest/include/gtest", - ] - cflags = [ - "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - configs = [ ":module_private_config" ] - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" - resource_config_file = get_path_info("utresources/ohos_test.xml", "abspath") -} - -group("unittest") { - testonly = true - deps = [ - ":memdataplugin_ut", - ] -} +# 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("//build/test.gni") +import("../../../base/config.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" +config("module_private_config") { + visibility = [ ":*" ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + } +} + +ohos_unittest("memdataplugin_ut") { + module_out_path = module_output_path + sources = [ + "unittest/buffer_splitter_unittest.cpp", + "unittest/memory_data_plugin_unittest.cpp", + ] + deps = [ + "${OHOS_PROFILER_DIR}/device/plugins/memory_plugin:memdataplugin", + "${OHOS_PROFILER_DIR}/protos/types/plugins/memory_data:memory_data_cpp", + "//third_party/googletest:gtest_main", + "//utils/native/base:utilsecurec", + ] + include_dirs = [ + "../include", + "../../api/include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + "//third_party/googletest/googletest/include/gtest", + "//utils/native/base/include", + ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +group("unittest") { + testonly = true + deps = [ ":memdataplugin_ut" ] +} diff --git a/device/plugins/memory_plugin/test/unittest/buffer_splitter_unittest.cpp b/device/plugins/memory_plugin/test/unittest/buffer_splitter_unittest.cpp index 9eca326b4..d3ed329a6 100644 --- a/device/plugins/memory_plugin/test/unittest/buffer_splitter_unittest.cpp +++ b/device/plugins/memory_plugin/test/unittest/buffer_splitter_unittest.cpp @@ -443,4 +443,4 @@ HWTEST_F(BufferSplitterUnittest, MemInfoBufferTEST, TestSize.Level1) EXPECT_EQ((uint64_t)counter_id, value); } while (totalbuffer.NextLine()); } -} // namespace \ No newline at end of file +} // namespace diff --git a/device/plugins/memory_plugin/test/unittest/memory_data_plugin_unittest.cpp b/device/plugins/memory_plugin/test/unittest/memory_data_plugin_unittest.cpp old mode 100755 new mode 100644 index 0b93816b1..2c80fb446 --- a/device/plugins/memory_plugin/test/unittest/memory_data_plugin_unittest.cpp +++ b/device/plugins/memory_plugin/test/unittest/memory_data_plugin_unittest.cpp @@ -1,4 +1,4 @@ -/* + /* * 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. @@ -132,53 +132,23 @@ void MyPrintfProcessMemoryInfo(MemoryData memoryData) } } -bool PluginStub(std::vector processList, MemoryDataPlugin& memoryPlugin, MemoryData& memoryData) +void SetPluginProcessConfig(std::vector processList, MemoryConfig& protoConfig) { - MemoryConfig protoConfig; - int configSize; - int ret; - - // set config if (processList.size() != 0) { + // 具体进程 protoConfig.set_report_process_mem_info(true); protoConfig.set_report_app_mem_info(true); for (size_t i = 0; i < processList.size(); i++) { protoConfig.add_pid(processList.at(i)); } } else { + // 进程树 protoConfig.set_report_process_tree(true); } - - // serialize - configSize = protoConfig.ByteSizeLong(); - std::vector configData(configSize); - ret = protoConfig.SerializeToArray(configData.data(), configData.size()); - - // start - ret = memoryPlugin.Start(configData.data(), configData.size()); - if (ret < 0) { - return false; - } - printf("ut: serialize success start plugin ret = %d\n", ret); - - // report - std::vector bufferData(BUF_SIZE); - ret = memoryPlugin.Report(bufferData.data(), bufferData.size()); - if (ret > 0) { - memoryData.ParseFromArray(bufferData.data(), ret); - MyPrintfProcessMemoryInfo(memoryData); - return true; - } - - return false; } -bool pluginMeminfoStub(MemoryDataPlugin& memoryPlugin, MemoryData& memoryData) +void SetPluginSysMemConfig(MemoryConfig &protoConfig) { - MemoryConfig protoConfig; - int configSize; - int ret; - protoConfig.set_report_sysmem_mem_info(true); protoConfig.add_sys_meminfo_counters(SysMeminfoType::MEMINFO_MEM_TOTAL); @@ -198,88 +168,34 @@ bool pluginMeminfoStub(MemoryDataPlugin& memoryPlugin, MemoryData& memoryData) protoConfig.add_sys_meminfo_counters(SysMeminfoType::MEMINFO_SWAP_TOTAL); protoConfig.add_sys_meminfo_counters(SysMeminfoType::MEMINFO_SWAP_FREE); protoConfig.add_sys_meminfo_counters(SysMeminfoType::MEMINFO_DIRTY); - - // serialize - configSize = protoConfig.ByteSizeLong(); - std::vector configData(configSize); - ret = protoConfig.SerializeToArray(configData.data(), configData.size()); - - // start - ret = memoryPlugin.Start(configData.data(), configData.size()); - if (ret < 0) { - return false; - } - printf("ut: serialize success start plugin ret = %d\n", ret); - - // report - std::vector bufferData(BUF_SIZE); - ret = memoryPlugin.Report(bufferData.data(), bufferData.size()); - if (ret > 0) { - memoryData.ParseFromArray(bufferData.data(), ret); - return true; - } - - return false; } -bool pluginWriteVmstat(MemoryDataPlugin& memoryPlugin, MemoryData& memoryData) +void SetPluginDumpsysConfig(MemoryConfig& protoConfig) { - MemoryConfig protoConfig; - int configSize; - int ret; - - protoConfig.set_report_sysmem_vmem_info(true); - - // serialize - configSize = protoConfig.ByteSizeLong(); - std::vector configData(configSize); - ret = protoConfig.SerializeToArray(configData.data(), configData.size()); - - // start - ret = memoryPlugin.Start(configData.data(), configData.size()); - if (ret < 0) { - return false; - } - printf("ut: serialize success start plugin ret = %d\n", ret); - - // report - std::vector bufferData(BUF_SIZE); - ret = memoryPlugin.Report(bufferData.data(), bufferData.size()); - if (ret > 0) { - memoryData.ParseFromArray(bufferData.data(), ret); - return true; - } - - return false; -} - -bool pluginDumpsys(MemoryDataPlugin& memoryPlugin, MemoryData& memoryData) -{ - MemoryConfig protoConfig; - int configSize; - int ret; - protoConfig.set_report_process_mem_info(true); protoConfig.set_report_app_mem_info(true); protoConfig.add_pid(1); protoConfig.set_report_app_mem_by_dumpsys(true); +} +bool PluginStub(MemoryDataPlugin& memoryPlugin, MemoryConfig& protoConfig, MemoryData& memoryData) +{ // serialize - configSize = protoConfig.ByteSizeLong(); + int configSize = protoConfig.ByteSizeLong(); std::vector configData(configSize); - ret = protoConfig.SerializeToArray(configData.data(), configData.size()); + int ret = protoConfig.SerializeToArray(configData.data(), configData.size()); + CHECK_TRUE(ret > 0, false, "PluginStub::SerializeToArray fail!!!"); // start ret = memoryPlugin.Start(configData.data(), configData.size()); - if (ret < 0) { - return false; - } + CHECK_TRUE(ret == 0, false, "PluginStub::start plugin fail!!!"); + printf("ut: serialize success start plugin ret = %d\n", ret); // report std::vector bufferData(BUF_SIZE); ret = memoryPlugin.Report(bufferData.data(), bufferData.size()); - if (ret > 0) { + if (ret >= 0) { memoryData.ParseFromArray(bufferData.data(), ret); return true; } @@ -346,7 +262,7 @@ void MemoryDataPluginTest::SetUpTestCase() * @tc.desc: Test whether the path exists. * @tc.type: FUNC */ -HWTEST_F(MemoryDataPluginTest, Testpath, TestSize.Level1) +HWTEST_F(MemoryDataPluginTest, TestUtpath, TestSize.Level1) { EXPECT_NE(g_path, ""); printf("g_path:%s\n", g_path.c_str()); @@ -385,19 +301,62 @@ HWTEST_F(MemoryDataPluginTest, Testpluginformeminfo, TestSize.Level1) { MemoryDataPlugin memoryPlugin; MemoryData memoryData; - memoryPlugin.SetPath(const_cast(g_path.c_str())); - printf("Testpluginformeminfo:setPath=%s\n", g_path.c_str()); - EXPECT_TRUE(pluginMeminfoStub(memoryPlugin, memoryData)); + MemoryConfig protoConfig; - int index = memoryData.meminfo().size(); - EXPECT_EQ(16, index); - printf("Testpluginformeminfo:index=%d\n", index); + SetPluginSysMemConfig(protoConfig); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); + + EXPECT_EQ(16, memoryData.meminfo().size()); + int index = memoryData.processesinfo_size(); for (int i = 0; i < index; ++i) { EXPECT_EQ(g_meminfo[i], memoryData.meminfo(i).value()); } - printf("\n"); - // stop + memoryPlugin.Stop(); +} + +/** + * @tc.name: memory plugin + * @tc.desc: pid list information test for process tree. + * @tc.type: FUNC + */ +HWTEST_F(MemoryDataPluginTest, Testpluginforlist, TestSize.Level1) +{ + MemoryDataPlugin memoryPlugin; + MemoryData memoryData; + MemoryConfig protoConfig; + + std::vector cmpPidList; + EXPECT_EQ((size_t)0, cmpPidList.size()); + + memoryPlugin.SetPath(const_cast(g_path.c_str())); + printf("Testpluginforlist:setPath=%s\n", g_path.c_str()); + + SetPluginProcessConfig(cmpPidList, protoConfig); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); + MyPrintfProcessMemoryInfo(memoryData); + + int index = memoryData.processesinfo_size(); + EXPECT_EQ(3, index); + printf("Testpluginforlist:index=%d", index); + for (int i = 0; i < index; ++i) { + ProcessMemoryInfo it = memoryData.processesinfo(i); + EXPECT_EQ(g_pidtarget[i].pid, it.pid()); + printf("%d:pid=%d\r\n", i, it.pid()); + EXPECT_EQ(g_pidtarget[i].name, it.name()); + EXPECT_EQ(g_pidtarget[i].vm_size_kb, it.vm_size_kb()); + EXPECT_EQ(g_pidtarget[i].vm_rss_kb, it.vm_rss_kb()); + EXPECT_EQ(g_pidtarget[i].rss_anon_kb, it.rss_anon_kb()); + EXPECT_EQ(g_pidtarget[i].rss_file_kb, it.rss_file_kb()); + EXPECT_EQ(g_pidtarget[i].rss_shmem_kb, it.rss_shmem_kb()); + EXPECT_EQ(g_pidtarget[i].vm_locked_kb, it.vm_locked_kb()); + EXPECT_EQ(g_pidtarget[i].vm_hwm_kb, it.vm_hwm_kb()); + + EXPECT_EQ(g_pidtarget[i].oom_score_adj, it.oom_score_adj()); + + EXPECT_FALSE(it.has_memsummary()); + } + memoryPlugin.Stop(); } @@ -410,11 +369,17 @@ HWTEST_F(MemoryDataPluginTest, Testpluginforsinglepid, TestSize.Level1) { MemoryDataPlugin memoryPlugin; MemoryData memoryData; - std::vector pid; - pid.push_back(5); + MemoryConfig protoConfig; + + std::vector pid = {5}; + memoryPlugin.SetPath(const_cast(g_path.c_str())); printf("Testpluginforsinglepid:setPath=%s\n", g_path.c_str()); - EXPECT_TRUE(PluginStub(pid, memoryPlugin, memoryData)); + + SetPluginProcessConfig(pid, protoConfig); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); + MyPrintfProcessMemoryInfo(memoryData); + int index = memoryData.processesinfo_size(); EXPECT_EQ(1, index); printf("Testpluginforsinglepid:index=%d\n", index); @@ -442,7 +407,6 @@ HWTEST_F(MemoryDataPluginTest, Testpluginforsinglepid, TestSize.Level1) EXPECT_EQ(g_singlepid.graphics, app.graphics()); EXPECT_EQ(g_singlepid.private_other, app.private_other()); - // stop memoryPlugin.Stop(); } @@ -453,13 +417,20 @@ HWTEST_F(MemoryDataPluginTest, Testpluginforsinglepid, TestSize.Level1) */ HWTEST_F(MemoryDataPluginTest, Testpluginforpids, TestSize.Level1) { - std::vector cmpPidList = g_expectPidList; - EXPECT_NE((size_t)0, cmpPidList.size()); MemoryDataPlugin memoryPlugin; MemoryData memoryData; + MemoryConfig protoConfig; + + std::vector cmpPidList = g_expectPidList; + EXPECT_NE((size_t)0, cmpPidList.size()); + memoryPlugin.SetPath(const_cast(g_path.c_str())); printf("Testpluginforpids:setPath=%s\n", g_path.c_str()); - EXPECT_TRUE(PluginStub(cmpPidList, memoryPlugin, memoryData)); + + SetPluginProcessConfig(cmpPidList, protoConfig); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); + MyPrintfProcessMemoryInfo(memoryData); + int index = memoryData.processesinfo_size(); EXPECT_EQ(3, index); printf("Testpluginforpids:index=%d\n", index); @@ -480,47 +451,7 @@ HWTEST_F(MemoryDataPluginTest, Testpluginforpids, TestSize.Level1) EXPECT_TRUE(it.has_memsummary()); } - // stop - memoryPlugin.Stop(); -} -/** - * @tc.name: memory plugin - * @tc.desc: pid list information test for process tree. - * @tc.type: FUNC - */ -HWTEST_F(MemoryDataPluginTest, Testpluginforlist, TestSize.Level1) -{ - std::vector cmpPidList = g_expectPidList; - EXPECT_NE((size_t)0, cmpPidList.size()); - MemoryDataPlugin memoryPlugin; - std::vector pid; - MemoryData memoryData; - memoryPlugin.SetPath(const_cast(g_path.c_str())); - printf("Testpluginforlist:setPath=%s\n", g_path.c_str()); - EXPECT_TRUE(PluginStub(pid, memoryPlugin, memoryData)); - int index = memoryData.processesinfo_size(); - EXPECT_EQ(3, index); - printf("Testpluginforlist:index=%d, pidsize=", index); - std::cout << pid.size() << std::endl; - for (int i = 0; i < index; ++i) { - ProcessMemoryInfo it = memoryData.processesinfo(i); - EXPECT_EQ(g_pidtarget[i].pid, it.pid()); - printf("%d:pid=%d\r\n", i, it.pid()); - EXPECT_EQ(g_pidtarget[i].name, it.name()); - EXPECT_EQ(g_pidtarget[i].vm_size_kb, it.vm_size_kb()); - EXPECT_EQ(g_pidtarget[i].vm_rss_kb, it.vm_rss_kb()); - EXPECT_EQ(g_pidtarget[i].rss_anon_kb, it.rss_anon_kb()); - EXPECT_EQ(g_pidtarget[i].rss_file_kb, it.rss_file_kb()); - EXPECT_EQ(g_pidtarget[i].rss_shmem_kb, it.rss_shmem_kb()); - EXPECT_EQ(g_pidtarget[i].vm_locked_kb, it.vm_locked_kb()); - EXPECT_EQ(g_pidtarget[i].vm_hwm_kb, it.vm_hwm_kb()); - - EXPECT_EQ(g_pidtarget[i].oom_score_adj, it.oom_score_adj()); - - EXPECT_TRUE(!it.has_memsummary()); - } - // stop memoryPlugin.Stop(); } @@ -552,10 +483,11 @@ HWTEST_F(MemoryDataPluginTest, TestpluginWriteVmstat, TestSize.Level1) { MemoryDataPlugin memoryPlugin; MemoryData memoryData; - memoryPlugin.SetPath(const_cast(g_path.c_str())); - printf("Testpluginformeminfo:setPath=%s\n", g_path.c_str()); - EXPECT_FALSE(pluginWriteVmstat(memoryPlugin, memoryData)); - // stop + MemoryConfig protoConfig; + + protoConfig.set_report_sysmem_vmem_info(true); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); + memoryPlugin.Stop(); } @@ -568,12 +500,23 @@ HWTEST_F(MemoryDataPluginTest, TestpluginDumpsys, TestSize.Level1) { MemoryDataPlugin memoryPlugin; MemoryData memoryData; - memoryPlugin.SetPath(const_cast(g_path.c_str())); - printf("Testpluginformeminfo:setPath=%s\n", g_path.c_str()); - EXPECT_TRUE(pluginDumpsys(memoryPlugin, memoryData)); + MemoryConfig protoConfig; + + SetPluginDumpsysConfig(protoConfig); + EXPECT_TRUE(PluginStub(memoryPlugin, protoConfig, memoryData)); std::string line = "01234567890"; memoryPlugin.ParseNumber(line); - // stop + + ProcessMemoryInfo it = memoryData.processesinfo(0); + EXPECT_FALSE(it.has_memsummary()); + AppSummary app = it.memsummary(); + EXPECT_EQ((uint64_t)0, app.java_heap()); + EXPECT_EQ((uint64_t)0, app.native_heap()); + EXPECT_EQ((uint64_t)0, app.code()); + EXPECT_EQ((uint64_t)0, app.stack()); + EXPECT_EQ((uint64_t)0, app.graphics()); + EXPECT_EQ((uint64_t)0, app.private_other()); + memoryPlugin.Stop(); } } // namespace diff --git a/device/plugins/memory_plugin/test/utresources/ohos_test.xml b/device/plugins/memory_plugin/test/utresources/ohos_test.xml deleted file mode 100644 index defafe9b7..000000000 --- a/device/plugins/memory_plugin/test/utresources/ohos_test.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - diff --git a/device/plugins/memory_plugin/test/utresources/proc/1/oom_score_adj b/device/plugins/memory_plugin/test/utresources/proc/1/oom_score_adj old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/1/smaps b/device/plugins/memory_plugin/test/utresources/proc/1/smaps old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/1/status b/device/plugins/memory_plugin/test/utresources/proc/1/status old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/11/oom_score_adj b/device/plugins/memory_plugin/test/utresources/proc/11/oom_score_adj old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/11/smaps b/device/plugins/memory_plugin/test/utresources/proc/11/smaps old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/11/status b/device/plugins/memory_plugin/test/utresources/proc/11/status old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/2/oom_score_adj b/device/plugins/memory_plugin/test/utresources/proc/2/oom_score_adj old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/2/smaps b/device/plugins/memory_plugin/test/utresources/proc/2/smaps old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/2/status b/device/plugins/memory_plugin/test/utresources/proc/2/status old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/cmdline b/device/plugins/memory_plugin/test/utresources/proc/cmdline old mode 100755 new mode 100644 diff --git a/device/plugins/memory_plugin/test/utresources/proc/meminfo b/device/plugins/memory_plugin/test/utresources/proc/meminfo old mode 100755 new mode 100644 diff --git a/device/plugins/sample_plugin/BUILD.gn b/device/plugins/sample_plugin/BUILD.gn new file mode 100644 index 000000000..10d14fd89 --- /dev/null +++ b/device/plugins/sample_plugin/BUILD.gn @@ -0,0 +1,46 @@ +# 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("//build/ohos.gni") +import("../../base/config.gni") + +ohos_shared_library("sampleplugin") { + output_name = "sampleplugin" + sources = [ + "src/sample_module.cpp", + "src/sample_plugin.cpp", + ] + include_dirs = [ + "include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + "//utils/native/base/include", + ] + deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", + "${OHOS_PROFILER_DIR}/protos/types/plugins/sample_data:sample_data_cpp", + "//utils/native/base:utilsecurec", + ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + if (build_l2) { + external_deps = [ "shared_library:libhilog" ] + } else { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } + } + public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] + install_enable = true + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" +} diff --git a/device/plugins/sample_plugin/include/sample_plugin.h b/device/plugins/sample_plugin/include/sample_plugin.h new file mode 100644 index 000000000..9b352ba17 --- /dev/null +++ b/device/plugins/sample_plugin/include/sample_plugin.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 SAMPLE_PLUGIN_H +#define SAMPLE_PLUGIN_H + +#include "logging.h" +#include "sample_plugin_config.pb.h" +#include "sample_plugin_result.pb.h" + +class SamplePlugin { +public: + SamplePlugin(); + ~SamplePlugin(); + int Start(const uint8_t* configData, uint32_t configSize); + int Report(uint8_t* configData, uint32_t configSize); + int Stop(); + uint64_t GetTimeMS(); + +private: + SampleConfig protoConfig_; +}; + +#endif // SAMPLE_PLUGIN_H \ No newline at end of file diff --git a/device/plugins/sample_plugin/src/sample_module.cpp b/device/plugins/sample_plugin/src/sample_module.cpp new file mode 100644 index 000000000..723d42a5e --- /dev/null +++ b/device/plugins/sample_plugin/src/sample_module.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "plugin_module_api.h" +#include "sample_plugin.h" + +namespace { +constexpr uint32_t MAX_BUFFER_SIZE = 4 * 1024 * 1024; +std::unique_ptr g_plugin = nullptr; +std::mutex g_taskMutex; +} // namespace + +static int SamplePluginSessionStart(const uint8_t* configData, uint32_t configSize) +{ + std::lock_guard guard(g_taskMutex); + g_plugin = std::make_unique(); + return g_plugin->Start(configData, configSize); +} + +static int SamplePluginReportResult(uint8_t* bufferData, uint32_t bufferSize) +{ + std::lock_guard guard(g_taskMutex); + return g_plugin->Report(bufferData, bufferSize); +} + +static int SamplePluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + g_plugin->Stop(); + g_plugin = nullptr; + return 0; +} + +static int SampleRegisterWriterStruct(const WriterStruct* writer) +{ + return 0; +} + +static PluginModuleCallbacks g_callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + SampleRegisterWriterStruct, +}; + +PluginModuleStruct g_pluginModule = {&g_callbacks, "sample-plugin", MAX_BUFFER_SIZE}; \ No newline at end of file diff --git a/device/plugins/sample_plugin/src/sample_plugin.cpp b/device/plugins/sample_plugin/src/sample_plugin.cpp new file mode 100644 index 000000000..e089ab5d6 --- /dev/null +++ b/device/plugins/sample_plugin/src/sample_plugin.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sample_plugin.h" +#include "securec.h" + +SamplePlugin::SamplePlugin() {} + +SamplePlugin::~SamplePlugin() {} + +uint64_t SamplePlugin::GetTimeMS() +{ + const int MS_PER_S = 1000; + const int NS_PER_MS = 1000000; + struct timespec ts; + clock_gettime(CLOCK_BOOTTIME, &ts); + return ts.tv_sec * MS_PER_S + ts.tv_nsec / NS_PER_MS; +} + +int SamplePlugin::Start(const uint8_t* configData, uint32_t configSize) +{ + HILOG_INFO(LOG_CORE, "SamplePlugin: config data -->configSize=%d", configSize); + CHECK_TRUE(configData != nullptr, -1, "SamplePlugin: param invalid!!!"); + for (uint32_t i = 0; i < configSize; i++) { + HILOG_INFO(LOG_CORE, "0x%02x", configData[i]); + } + + // 反序列化 + if (protoConfig_.ParseFromArray(configData, configSize) <= 0) { + HILOG_ERROR(LOG_CORE, "SamplePlugin: ParseFromArray failed"); + return -1; + } + HILOG_INFO(LOG_CORE, "ParseFromArray --> %d", protoConfig_.pid()); + // 插件准备工作 + + return 0; +} + +int SamplePlugin::Report(uint8_t* data, uint32_t dataSize) +{ + SampleData dataProto; + + // 回填数据 + dataProto.set_time_ms(GetTimeMS()); + + uint32_t length = dataProto.ByteSizeLong(); + if (length > dataSize) { + return -length; + } + // 序列化 + if (dataProto.SerializeToArray(data, length) > 0) { + HILOG_DEBUG(LOG_CORE, "SamplePlugin: report success! length = %d", length); + return length; + } + return 0; +} + +int SamplePlugin::Stop() +{ + HILOG_INFO(LOG_CORE, "SamplePlugin: stop success!"); + return 0; +} \ No newline at end of file diff --git a/device/plugins/stream_plugin/BUILD.gn b/device/plugins/stream_plugin/BUILD.gn new file mode 100644 index 000000000..c55b465c1 --- /dev/null +++ b/device/plugins/stream_plugin/BUILD.gn @@ -0,0 +1,46 @@ +# 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("//build/ohos.gni") +import("../../base/config.gni") + +ohos_shared_library("streamplugin") { + output_name = "streamplugin" + sources = [ + "src/stream_module.cpp", + "src/stream_plugin.cpp", + ] + include_dirs = [ + "include", + "${OHOS_PROFILER_DIR}/interfaces/kits", + "${OHOS_PROFILER_DIR}/device/base/include", + "//utils/native/base/include", + ] + deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc_lib", + "${OHOS_PROFILER_DIR}/protos/types/plugins/stream_data:stream_data_cpp", + "//utils/native/base:utilsecurec", + ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + if (build_l2) { + external_deps = [ "shared_library:libhilog" ] + } else { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } + } + public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] + install_enable = true + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" +} diff --git a/device/plugins/stream_plugin/include/stream_plugin.h b/device/plugins/stream_plugin/include/stream_plugin.h new file mode 100644 index 000000000..9451db6c9 --- /dev/null +++ b/device/plugins/stream_plugin/include/stream_plugin.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STREAM_PLUGIN_H +#define STREAM_PLUGIN_H + +#include "logging.h" +#include "plugin_module_api.h" +#include "stream_plugin_config.pb.h" +#include "stream_plugin_result.pb.h" + +#include +#include +#include +#include + +class StreamPlugin { +public: + StreamPlugin(); + ~StreamPlugin(); + int Start(const uint8_t* configData, uint32_t configSize); + int Stop(); + + int SetWriter(WriterStruct* writer); + void Loop(void); + uint64_t GetTimeMS(); + +private: + StreamConfig protoConfig_; + std::vector buffer_; + WriterStruct* resultWriter_ = nullptr; + + std::mutex mutex_; + std::thread writeThread_; + std::atomic running_ = true; + + int32_t nbyte_ = 0; +}; + +#endif // STREAM_PLUGIN_H \ No newline at end of file diff --git a/device/plugins/stream_plugin/src/stream_module.cpp b/device/plugins/stream_plugin/src/stream_module.cpp new file mode 100644 index 000000000..9cf335cd8 --- /dev/null +++ b/device/plugins/stream_plugin/src/stream_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "plugin_module_api.h" +#include "stream_plugin.h" + +namespace { +constexpr uint32_t MAX_BUFFER_SIZE = 4 * 1024 * 1024; +std::unique_ptr g_plugin = nullptr; +std::mutex g_taskMutex; +} // namespace + +static int StreamPluginSessionStart(const uint8_t* configData, uint32_t configSize) +{ + std::lock_guard guard(g_taskMutex); + return g_plugin->Start(configData, configSize); +} + +static int StreamPluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + g_plugin->Stop(); + g_plugin = nullptr; + return 0; +} + +static int StreamRegisterWriterStruct(WriterStruct* writer) +{ + std::lock_guard guard(g_taskMutex); + g_plugin = std::make_unique(); + g_plugin->SetWriter(writer); + return 0; +} + +static PluginModuleCallbacks g_callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, +}; + +PluginModuleStruct g_pluginModule = {&g_callbacks, "stream-plugin", MAX_BUFFER_SIZE}; \ No newline at end of file diff --git a/device/plugins/stream_plugin/src/stream_plugin.cpp b/device/plugins/stream_plugin/src/stream_plugin.cpp new file mode 100644 index 000000000..a87ca3110 --- /dev/null +++ b/device/plugins/stream_plugin/src/stream_plugin.cpp @@ -0,0 +1,108 @@ +/* + * 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 "stream_plugin.h" +#include "securec.h" + +#include +#include +#include + +namespace { +constexpr int INTERVAL_TIME_BASE = 10000; // 间隔时间base +constexpr int INTERVAL_TIME_MAX = 9; // 最大间隔 +constexpr int INTERVAL_TIME_STEP = 2; // 间隔步长 +constexpr int BYTE_BUFFER_SIZE = 128; +constexpr int MS_PER_S = 1000; +constexpr int NS_PER_MS = 1000000; +}//namespace + +StreamPlugin::StreamPlugin() {} + +StreamPlugin::~StreamPlugin() {} + +int StreamPlugin::Start(const uint8_t* configData, uint32_t configSize) +{ + // 反序列化 + if (protoConfig_.ParseFromArray(configData, configSize) <= 0) { + HILOG_ERROR(LOG_CORE, "StreamPlugin: ParseFromArray failed"); + return -1; + } + // 启动线程写数据 + std::unique_lock locker(mutex_); + running_ = true; + writeThread_ = std::thread(&StreamPlugin::Loop, this); + + return 0; +} + +int StreamPlugin::Stop() +{ + std::unique_lock locker(mutex_); + running_ = false; + locker.unlock(); + if (writeThread_.joinable()) { + writeThread_.join(); + } + HILOG_INFO(LOG_CORE, "StreamPlugin: stop success!"); + return 0; +} + +int StreamPlugin::SetWriter(WriterStruct* writer) +{ + resultWriter_ = writer; + return 0; +} + +uint64_t StreamPlugin::GetTimeMS() +{ + struct timespec ts; + clock_gettime(CLOCK_BOOTTIME, &ts); + return ts.tv_sec * MS_PER_S + ts.tv_nsec / NS_PER_MS; +} + +void StreamPlugin::Loop(void) +{ + HILOG_INFO(LOG_CORE, "StreamPlugin thread %{public}d start !!!!!", gettid()); + uint32_t i = 1; + while (running_) { + StreamData dataProto; + uint64_t tm = GetTimeMS(); + dataProto.set_time_ms(tm); + + // 序列化 + buffer_.resize(dataProto.ByteSizeLong()); + dataProto.SerializeToArray(buffer_.data(), buffer_.size()); + + usleep(i * INTERVAL_TIME_BASE); // 间隔时间不固定 + + if (i < INTERVAL_TIME_MAX) { + i += INTERVAL_TIME_STEP; + } else { + i = 1; + } + + if (resultWriter_->write != nullptr) { + resultWriter_->write(resultWriter_, buffer_.data(), buffer_.size()); + } + + nbyte_ += buffer_.size(); + if (nbyte_ >= BYTE_BUFFER_SIZE) { + resultWriter_->flush(resultWriter_); + nbyte_ = 0; + } + } + resultWriter_->flush(resultWriter_); + HILOG_INFO(LOG_CORE, "Transporter thread %{public}d exit !!!!!", gettid()); +} \ No newline at end of file diff --git a/device/services/ipc/BUILD.gn b/device/services/ipc/BUILD.gn old mode 100755 new mode 100644 index 9c0b54e9c..0962873ab --- a/device/services/ipc/BUILD.gn +++ b/device/services/ipc/BUILD.gn @@ -39,7 +39,7 @@ ohos_source_set("ipc") { deps = [ "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf", "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", - "//utils/native/base:utilsbase", + "//utils/native/base:utilsecurec", ] public_configs = [ "../../base:hiprofiler_test_config" ] } diff --git a/device/services/ipc/include/client_connection.h b/device/services/ipc/include/client_connection.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/client_map.h b/device/services/ipc/include/client_map.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/ipc_generator.h b/device/services/ipc/include/ipc_generator.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/service_base.h b/device/services/ipc/include/service_base.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/service_entry.h b/device/services/ipc/include/service_entry.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/socket_context.h b/device/services/ipc/include/socket_context.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/unix_socket_client.h b/device/services/ipc/include/unix_socket_client.h old mode 100755 new mode 100644 diff --git a/device/services/ipc/include/unix_socket_server.h b/device/services/ipc/include/unix_socket_server.h old mode 100755 new mode 100644 index 897a46a50..00c19d1d1 --- a/device/services/ipc/include/unix_socket_server.h +++ b/device/services/ipc/include/unix_socket_server.h @@ -35,8 +35,9 @@ public: ServiceEntry* serviceEntry_; private: + void UnixSocketAccept(); + std::thread acceptThread_; - static void* UnixSocketAccept(void* p); }; #endif \ No newline at end of file diff --git a/device/services/ipc/src/client_connection.cpp b/device/services/ipc/src/client_connection.cpp old mode 100755 new mode 100644 diff --git a/device/services/ipc/src/client_map.cpp b/device/services/ipc/src/client_map.cpp old mode 100755 new mode 100644 diff --git a/device/services/ipc/src/ipc_generator.cpp b/device/services/ipc/src/ipc_generator.cpp old mode 100755 new mode 100644 diff --git a/device/services/ipc/src/ipc_generator_impl.cpp b/device/services/ipc/src/ipc_generator_impl.cpp index 5f69776db..b9f09cf51 100644 --- a/device/services/ipc/src/ipc_generator_impl.cpp +++ b/device/services/ipc/src/ipc_generator_impl.cpp @@ -238,7 +238,7 @@ void IpcGeneratorImpl::GenerateHeader(std::string& header_str) std::string IpcGeneratorImpl::GenHeader() { std::string header_str = BASE_HEADER_STRING; - std::string tmp1, tmp2; + std::string tmp1; header_str = ReplaceStr(header_str, "#HEAD_FILE_NAME#", headFileName_); if (serviceCount_ > 0) { diff --git a/device/services/ipc/src/main.cpp b/device/services/ipc/src/main.cpp old mode 100755 new mode 100644 diff --git a/device/services/ipc/src/service_entry.cpp b/device/services/ipc/src/service_entry.cpp old mode 100755 new mode 100644 diff --git a/device/services/ipc/src/socket_context.cpp b/device/services/ipc/src/socket_context.cpp old mode 100755 new mode 100644 index 316da08d0..f2a7ef817 --- a/device/services/ipc/src/socket_context.cpp +++ b/device/services/ipc/src/socket_context.cpp @@ -136,9 +136,7 @@ bool SocketContext::CreateRecvThread() bool SocketContext::SendRaw(uint32_t pnum, const int8_t* data, uint32_t size, int sockfd) { - if (data == nullptr) { - return false; - } + CHECK_NOTNULL(data, false, "SendRaw data null"); if (sockfd == -1) { sockfd = socketHandle_; } diff --git a/device/services/ipc/src/unix_socket_client.cpp b/device/services/ipc/src/unix_socket_client.cpp old mode 100755 new mode 100644 index f7ec59141..2b88ed4f0 --- a/device/services/ipc/src/unix_socket_client.cpp +++ b/device/services/ipc/src/unix_socket_client.cpp @@ -45,7 +45,7 @@ bool UnixSocketClient::Connect(const std::string addrname, ServiceBase& serviceB HILOG_ERROR(LOG_CORE, "memset_s error!"); } addr.sun_family = AF_UNIX; - if (strncpy_s(addr.sun_path, UNIX_PATH_MAX, addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) { + if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) { HILOG_ERROR(LOG_CORE, "strncpy_s error!"); } diff --git a/device/services/ipc/src/unix_socket_server.cpp b/device/services/ipc/src/unix_socket_server.cpp old mode 100755 new mode 100644 index bb7e43e05..f24100477 --- a/device/services/ipc/src/unix_socket_server.cpp +++ b/device/services/ipc/src/unix_socket_server.cpp @@ -45,34 +45,25 @@ UnixSocketServer::~UnixSocketServer() } } -void* UnixSocketServer::UnixSocketAccept(void* p) +void UnixSocketServer::UnixSocketAccept() { - if (p == nullptr) { - return nullptr; - } pthread_setname_np(pthread_self(), "UnixSocketAccept"); - UnixSocketServer* puss = (UnixSocketServer*)p; - if (puss == nullptr) { - return nullptr; - } - CHECK_TRUE(puss->socketHandle_ != -1, nullptr, "Unix Socket Accept socketHandle_ == -1"); + CHECK_TRUE(socketHandle_ != -1, NO_RETVAL, "Unix Socket Accept socketHandle_ == -1"); int epfd = epoll_create(1); struct epoll_event evt; - evt.data.fd = puss->socketHandle_; + evt.data.fd = socketHandle_; evt.events = EPOLLIN | EPOLLET; - CHECK_TRUE(epoll_ctl(epfd, EPOLL_CTL_ADD, puss->socketHandle_, &evt) != -1, nullptr, "Unix Socket Server Exit"); - int nfds; - while (puss->socketHandle_ != -1) { - nfds = epoll_wait(epfd, &evt, 1, 1000); // timeout value set 1000. + CHECK_TRUE(epoll_ctl(epfd, EPOLL_CTL_ADD, socketHandle_, &evt) != -1, NO_RETVAL, "Unix Socket Server Exit"); + while (socketHandle_ != -1) { + int nfds = epoll_wait(epfd, &evt, 1, 1000); // timeout value set 1000. if (nfds > 0) { - int clientSocket = accept(puss->socketHandle_, nullptr, nullptr); + int clientSocket = accept(socketHandle_, nullptr, nullptr); HILOG_INFO(LOG_CORE, "Accept A Client %d", clientSocket); - ClientMap::GetInstance().PutClientSocket(clientSocket, *puss->serviceEntry_); + ClientMap::GetInstance().PutClientSocket(clientSocket, *serviceEntry_); } } close(epfd); - return nullptr; } namespace { @@ -90,7 +81,7 @@ bool UnixSocketServer::StartServer(const std::string& addrname, ServiceEntry& p) HILOG_ERROR(LOG_CORE, "memset_s error!"); } addr.sun_family = AF_UNIX; - if (strncpy_s(addr.sun_path, UNIX_PATH_MAX, addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) { + if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) { HILOG_ERROR(LOG_CORE, "strncpy_s error!"); } unlink(addrname.c_str()); diff --git a/device/services/ipc/test/BUILD.gn b/device/services/ipc/test/BUILD.gn old mode 100755 new mode 100644 index b5f9a4669..fe757d712 --- a/device/services/ipc/test/BUILD.gn +++ b/device/services/ipc/test/BUILD.gn @@ -1,62 +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 +# 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("//build/test.gni") -import("../../../base/config.gni") - -module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" -config("module_private_config") { - visibility = [":*"] -} - -ohos_unittest("ipc_ut") { - module_out_path = module_output_path - sources = [ - "../src/ipc_generator_impl.cpp", - "unittest/client_connection_test.cpp", - "unittest/client_map_test.cpp", - "unittest/ipc_generator_impl_test.cpp", - "unittest/service_base_test.cpp", - "unittest/service_entry_test.cpp", - "unittest/socket_context_test.cpp", - "unittest/unix_socket_client_test.cpp", - "unittest/unix_socket_server_test.cpp", - ] - include_dirs = [ - "${OHOS_PROFILER_DIR}/device/services/ipc/include", - "//third_party/googletest/googletest/include/gtest", - ] - deps = [ - "../:ipc", - "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", - "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", - "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", - "//third_party/googletest:gtest", - ] - cflags = [ - "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - "-Dprotected=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" -} - -group("unittest") { - testonly = true - deps = [ - ":ipc_ut", - ] -} + +import("//build/test.gni") +import("../../../base/config.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" +config("module_private_config") { + visibility = [ ":*" ] +} + +ohos_unittest("ipc_ut") { + module_out_path = module_output_path + sources = [ + "../src/ipc_generator_impl.cpp", + "unittest/client_connection_test.cpp", + "unittest/client_map_test.cpp", + "unittest/ipc_generator_impl_test.cpp", + "unittest/service_base_test.cpp", + "unittest/service_entry_test.cpp", + "unittest/socket_context_test.cpp", + "unittest/unix_socket_client_test.cpp", + "unittest/unix_socket_server_test.cpp", + ] + include_dirs = [ + "${OHOS_PROFILER_DIR}/device/services/ipc/include", + "//third_party/googletest/googletest/include/gtest", + ] + deps = [ + "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", + "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", + "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", + "../:ipc", + "//third_party/googletest:gtest", + ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + "-Dprotected=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +group("unittest") { + testonly = true + deps = [ ":ipc_ut" ] +} diff --git a/device/services/ipc/test/unittest/client_connection_test.cpp b/device/services/ipc/test/unittest/client_connection_test.cpp old mode 100755 new mode 100644 index 42fa7dcca..15368c074 --- a/device/services/ipc/test/unittest/client_connection_test.cpp +++ b/device/services/ipc/test/unittest/client_connection_test.cpp @@ -38,8 +38,13 @@ public: */ HWTEST_F(ClientConnectionTest, RawProtocolProc, TestSize.Level1) { + std::string serviceName="test_service_name"; + struct RawPointToService rpts; + std::copy(serviceName.begin(), serviceName.end(), rpts.serviceName_); + ServiceEntry serviceEntry; ClientConnection* clientConnection = new ClientConnection(0, serviceEntry); - ASSERT_EQ(clientConnection->RawProtocolProc(-1, nullptr, 0), -1); + ASSERT_EQ(clientConnection->RawProtocolProc(RAW_PROTOCOL_POINTTO_SERVICE, + (int8_t *)&rpts, sizeof(struct RawPointToService)), 1); } } // namespace \ No newline at end of file diff --git a/device/services/ipc/test/unittest/client_map_test.cpp b/device/services/ipc/test/unittest/client_map_test.cpp old mode 100755 new mode 100644 index b0bbc66b3..3a06f78eb --- a/device/services/ipc/test/unittest/client_map_test.cpp +++ b/device/services/ipc/test/unittest/client_map_test.cpp @@ -39,8 +39,7 @@ public: HWTEST_F(ClientMapTest, ClientSocket, TestSize.Level1) { ServiceEntry serviceEntry; - ClientMap::GetInstance(); - ClientMap::GetInstance().PutClientSocket(0, serviceEntry); + ASSERT_EQ(ClientMap::GetInstance().PutClientSocket(1, serviceEntry), 1); ASSERT_EQ(ClientMap::GetInstance().AutoRelease(), 1); } } // namespace \ No newline at end of file diff --git a/device/services/ipc/test/unittest/service_base_test.cpp b/device/services/ipc/test/unittest/service_base_test.cpp old mode 100755 new mode 100644 index 418acb816..5deb735f0 --- a/device/services/ipc/test/unittest/service_base_test.cpp +++ b/device/services/ipc/test/unittest/service_base_test.cpp @@ -37,8 +37,9 @@ public: */ HWTEST_F(ServiceBaseTest, ProtocolProc, TestSize.Level1) { + std::string s="asdf"; ServiceBase serviceBase; SocketContext socketContext; - ASSERT_FALSE(serviceBase.ProtocolProc(socketContext, 0, nullptr, 0)); + ASSERT_FALSE(serviceBase.ProtocolProc(socketContext, 0, (const int8_t *)s.c_str(), s.size())); } } // namespace \ No newline at end of file diff --git a/device/services/ipc/test/unittest/service_entry_test.cpp b/device/services/ipc/test/unittest/service_entry_test.cpp old mode 100755 new mode 100644 index 5578d9da1..29f1b247c --- a/device/services/ipc/test/unittest/service_entry_test.cpp +++ b/device/services/ipc/test/unittest/service_entry_test.cpp @@ -30,6 +30,15 @@ public: void TearDown() {} }; +namespace { +const int MS_PER_S = 1000; +const int US_PER_S = 1000000; +const int NS_PER_US = 1000; +const int NS_PER_S = 1000000000; +const int NS_PER_MS = 1000000; +const int SLEEP_TIME = 30000; +} // namespace + /** * @tc.name: Service * @tc.desc: Server process monitoring. @@ -43,12 +52,12 @@ HWTEST_F(ServiceEntryTest, AllCase, TestSize.Level1) serviceEntry.RegisterService(pluginService); serviceEntry.FindServiceByName(pluginService.serviceName_); - usleep(30000); + usleep(SLEEP_TIME); IPluginServiceClient pluginClient; - ASSERT_FALSE(pluginClient.Connect("")); + ASSERT_TRUE(pluginClient.Connect("test_unix_socket_service_entry")); - usleep(30000); + usleep(SLEEP_TIME); } /** @@ -58,7 +67,12 @@ HWTEST_F(ServiceEntryTest, AllCase, TestSize.Level1) */ HWTEST_F(ServiceEntryTest, GetTimeMS, TestSize.Level1) { - GetTimeMS(); + struct timespec ts; + clock_gettime(CLOCK_BOOTTIME, &ts); + long t1= ts.tv_sec * MS_PER_S + ts.tv_nsec / NS_PER_MS; + long t2=GetTimeMS(); + + ASSERT_TRUE(t2-t1>=0); } /** @@ -68,7 +82,12 @@ HWTEST_F(ServiceEntryTest, GetTimeMS, TestSize.Level1) */ HWTEST_F(ServiceEntryTest, GetTimeUS, TestSize.Level1) { - GetTimeUS(); + struct timespec ts; + clock_gettime(CLOCK_BOOTTIME, &ts); + long t1= ts.tv_sec * US_PER_S + ts.tv_nsec / NS_PER_US; + long t2 = GetTimeUS(); + + ASSERT_TRUE(t2-t1>=0); } /** @@ -78,6 +97,10 @@ HWTEST_F(ServiceEntryTest, GetTimeUS, TestSize.Level1) */ HWTEST_F(ServiceEntryTest, GetTimeNS, TestSize.Level1) { - GetTimeNS(); + struct timespec ts; + clock_gettime(CLOCK_BOOTTIME, &ts); + long t1 = ts.tv_sec * NS_PER_S + ts.tv_nsec; + long t2 = GetTimeNS(); + ASSERT_TRUE(t2-t1>=0); } } // namespace \ No newline at end of file diff --git a/device/services/ipc/test/unittest/socket_context_test.cpp b/device/services/ipc/test/unittest/socket_context_test.cpp old mode 100755 new mode 100644 index 274bd72e9..e9f228fe4 --- a/device/services/ipc/test/unittest/socket_context_test.cpp +++ b/device/services/ipc/test/unittest/socket_context_test.cpp @@ -39,6 +39,7 @@ HWTEST_F(SocketContextTest, SendFileDescriptor, TestSize.Level1) { SocketContext socketContext; ASSERT_TRUE(!socketContext.SendFileDescriptor(-1)); + ASSERT_TRUE(!socketContext.SendFileDescriptor(1)); } /** @@ -48,8 +49,9 @@ HWTEST_F(SocketContextTest, SendFileDescriptor, TestSize.Level1) */ HWTEST_F(SocketContextTest, RawProtocolProc, TestSize.Level1) { + std::string s="abc"; SocketContext socketContext; - ASSERT_EQ(socketContext.RawProtocolProc(-1, nullptr, -1), -1); + ASSERT_EQ(socketContext.RawProtocolProc(2, (const int8_t *)s.c_str(), s.size()), -1); } /** @@ -59,8 +61,14 @@ HWTEST_F(SocketContextTest, RawProtocolProc, TestSize.Level1) */ HWTEST_F(SocketContextTest, SendRaw, TestSize.Level1) { + std::string s="abc"; SocketContext socketContext; - ASSERT_TRUE(!socketContext.SendRaw(-1, nullptr, 0, 0)); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), 0)); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), -1)); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), 1)); + ASSERT_TRUE(!socketContext.SendRaw(1, (const int8_t *)s.c_str(), s.size(), 1)); + ASSERT_TRUE(!socketContext.SendFileDescriptor(-1)); + ASSERT_TRUE(!socketContext.SendFileDescriptor(1)); } /** diff --git a/device/services/ipc/test/unittest/unix_socket_server_test.cpp b/device/services/ipc/test/unittest/unix_socket_server_test.cpp index a107ff15c..86cba9a84 100644 --- a/device/services/ipc/test/unittest/unix_socket_server_test.cpp +++ b/device/services/ipc/test/unittest/unix_socket_server_test.cpp @@ -17,6 +17,7 @@ #include #include "service_entry.h" +#include "unix_socket_client.h" #include "unix_socket_server.h" using namespace testing::ext; @@ -31,17 +32,6 @@ public: void TearDown() {} }; -/** - * @tc.name: Service - * @tc.desc: Socket server receives client connection. - * @tc.type: FUNC - */ -HWTEST_F(UnixSocketServerTest, UnixSocketAccept, TestSize.Level1) -{ - UnixSocketServer unixSocketServer; - unixSocketServer.UnixSocketAccept(nullptr); -} - /** * @tc.name: Service * @tc.desc: Start socket server. @@ -51,6 +41,10 @@ HWTEST_F(UnixSocketServerTest, StartServer, TestSize.Level1) { UnixSocketServer unixSocketServer; ServiceEntry serviceEntry; - ASSERT_TRUE(unixSocketServer.StartServer("", serviceEntry)); + ASSERT_TRUE(unixSocketServer.StartServer("server_name", serviceEntry)); + + UnixSocketClient unixSocketClient; + ServiceBase serviceBase; + ASSERT_TRUE(unixSocketClient.Connect("server_name", serviceBase)); } } // namespace \ No newline at end of file diff --git a/device/services/plugin_service/BUILD.gn b/device/services/plugin_service/BUILD.gn old mode 100755 new mode 100644 index d9389c973..7c4d1ab2d --- a/device/services/plugin_service/BUILD.gn +++ b/device/services/plugin_service/BUILD.gn @@ -32,6 +32,7 @@ ohos_source_set("hiprofiler_plugin_service") { "src/plugin_service.cpp", "src/plugin_service_impl.cpp", ] + deps = [ "../../base:hiprofiler_base" ] if (current_toolchain != host_toolchain) { if (build_l2) { external_deps = [ "shared_library:libhilog" ] diff --git a/device/services/plugin_service/include/plugin_service.h b/device/services/plugin_service/include/plugin_service.h old mode 100755 new mode 100644 index 89b19ee50..9cae343da --- a/device/services/plugin_service/include/plugin_service.h +++ b/device/services/plugin_service/include/plugin_service.h @@ -16,6 +16,7 @@ #ifndef PLUGIN_SERVICE_H #define PLUGIN_SERVICE_H +#include #include #include #include @@ -23,6 +24,9 @@ #include #include "common_types.pb.h" +#include "epoll_event_poller.h" +#include "event_notifier.h" +#include "i_semaphore.h" #include "logging.h" #include "plugin_service_types.pb.h" #include "profiler_service_types.pb.h" @@ -47,14 +51,16 @@ struct PluginInfo { }; struct PluginContext { + std::string name; std::string path; + std::string sha256; + uint32_t bufferSizeHint; SocketContext* context; ProfilerPluginConfig config; ProfilerDataRepeaterPtr profilerDataRepeater; std::shared_ptr shareMemoryBlock; + EventNotifierPtr eventNotifier; ProfilerPluginStatePtr profilerPluginState; - std::string sha256; - uint32_t bufferSizeHint; }; class PluginService { @@ -65,13 +71,13 @@ public: bool CreatePluginSession(const ProfilerPluginConfig& pluginConfig, const ProfilerSessionConfig::BufferConfig& bufferConfig, const ProfilerDataRepeaterPtr& dataRepeater); - bool CreatePluginSession(const ProfilerPluginConfig& pluginConfig, - const ProfilerDataRepeaterPtr& dataRepeater); + bool CreatePluginSession(const ProfilerPluginConfig& pluginConfig, const ProfilerDataRepeaterPtr& dataRepeater); bool StartPluginSession(const ProfilerPluginConfig& config); bool StopPluginSession(const std::string& pluginName); bool DestroyPluginSession(const std::string& pluginName); bool AddPluginInfo(const PluginInfo& pluginInfo); + bool GetPluginInfo(const std::string& pluginName, PluginInfo& pluginInfo); bool RemovePluginInfo(const PluginInfo& pluginInfo); bool AppendResult(NotifyResultRequest& request); @@ -80,32 +86,21 @@ public: uint32_t GetPluginIdByName(std::string name); private: - std::map pluginContext_; bool StartService(const std::string& unixSocketName); + SemaphorePtr GetSemaphore(uint32_t) const; + void ReadShareMemory(PluginContext&); + + mutable std::mutex mutex_; + std::map pluginContext_; + std::map waitSemphores_; std::map nameIndex_; - uint32_t pluginIdAutoIncrease_; + std::atomic pluginIdCounter_; std::shared_ptr serviceEntry_; std::shared_ptr pluginServiceImpl_; std::shared_ptr pluginCommandBuilder_; - - std::mutex readShareMemory_; - void ReadShareMemoryOneTime(); - - enum ReadShareMemoryStatus { - READ_SHARE_MEMORY_FREE, - READ_SHARE_MEMORY_WORKING, - READ_SHARE_MEMORY_EXIT, - READ_SHARE_MEMORY_UNSPECIFIED, - }; - ReadShareMemoryStatus readShareMemoryThreadStatus_; // 0空闲等待,1工作中,2线程退出 - std::timed_mutex readShareMemoryThreadSleep_; - static void* ReadShareMemoryThread(void* p); - std::thread readShareMemoryThread_; - - uint32_t waitForCommandId_; - std::timed_mutex waitStopSession_; + std::unique_ptr eventPoller_; }; #endif // PLUGIN_SERVICE_H \ No newline at end of file diff --git a/device/services/plugin_service/src/plugin_service.cpp b/device/services/plugin_service/src/plugin_service.cpp old mode 100755 new mode 100644 index dd3a4ba1c..8d28244b8 --- a/device/services/plugin_service/src/plugin_service.cpp +++ b/device/services/plugin_service/src/plugin_service.cpp @@ -15,6 +15,7 @@ #include "plugin_service.h" +#include #include #include #include @@ -27,34 +28,40 @@ #include "share_memory_allocator.h" #include "socket_context.h" - namespace { const int PAGE_BYTES = 4096; -} +const int DEFAULT_EVENT_POLLING_INTERVAL = 5000; +} // namespace PluginService::PluginService() { - pluginIdAutoIncrease_ = 0; - waitForCommandId_ = 0; + pluginIdCounter_ = 0; StartService(DEFAULT_UNIX_SOCKET_PATH); pluginCommandBuilder_ = std::make_shared(); - waitStopSession_.lock(); + eventPoller_ = std::make_unique(DEFAULT_EVENT_POLLING_INTERVAL); + CHECK_NOTNULL(eventPoller_, NO_RETVAL, "create event poller FAILED!"); - readShareMemoryThreadStatus_ = READ_SHARE_MEMORY_FREE; - readShareMemoryThreadSleep_.lock(); - - readShareMemoryThread_ = std::thread(&PluginService::ReadShareMemoryThread, this); - if (readShareMemoryThread_.get_id() == std::thread::id()) { - HILOG_ERROR(LOG_CORE, "CreateReadShareMemoryThread FAIL"); - } + eventPoller_->Init(); + eventPoller_->Start(); } PluginService::~PluginService() { - readShareMemoryThreadStatus_ = READ_SHARE_MEMORY_EXIT; - readShareMemoryThreadSleep_.unlock(); - readShareMemoryThread_.join(); + if (eventPoller_) { + eventPoller_->Stop(); + eventPoller_->Finalize(); + } +} + +SemaphorePtr PluginService::GetSemaphore(uint32_t id) const +{ + std::unique_lock lock(mutex_); + auto it = waitSemphores_.find(id); + if (it != waitSemphores_.end()) { + return it->second; + } + return nullptr; } bool PluginService::StartService(const std::string& unixSocketName) @@ -71,6 +78,14 @@ bool PluginService::StartService(const std::string& unixSocketName) return true; } +static ShareMemoryBlock::ReusePolicy GetReusePolicy(const ProfilerSessionConfig::BufferConfig& bufferConfig) +{ + if (bufferConfig.policy() == ProfilerSessionConfig::BufferConfig::RECYCLE) { + return ShareMemoryBlock::DROP_OLD; + } + return ShareMemoryBlock::DROP_NONE; +} + bool PluginService::CreatePluginSession(const ProfilerPluginConfig& pluginConfig, const ProfilerSessionConfig::BufferConfig& bufferConfig, const ProfilerDataRepeaterPtr& dataRepeater) @@ -81,21 +96,33 @@ bool PluginService::CreatePluginSession(const ProfilerPluginConfig& pluginConfig uint32_t idx = nameIndex_[pluginConfig.name()]; pluginContext_[idx].profilerDataRepeater = dataRepeater; - auto gcr = pluginCommandBuilder_->BuildCreateSessionCmd(pluginConfig, bufferConfig.pages() * PAGE_BYTES); - CHECK_TRUE(gcr != nullptr, false, "CreatePluginSession BuildCreateSessionCmd FAIL %s", pluginConfig.name().c_str()); + auto cmd = pluginCommandBuilder_->BuildCreateSessionCmd(pluginConfig, bufferConfig.pages() * PAGE_BYTES); + CHECK_TRUE(cmd != nullptr, false, "CreatePluginSession BuildCreateSessionCmd FAIL %s", pluginConfig.name().c_str()); auto smb = ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal(pluginConfig.name(), bufferConfig.pages() * PAGE_BYTES); CHECK_TRUE(smb != nullptr, false, "CreateMemoryBlockLocal FAIL %s", pluginConfig.name().c_str()); + auto policy = GetReusePolicy(bufferConfig); + HILOG_DEBUG(LOG_CORE, "CreatePluginSession policy = %d", (int)policy); + smb->SetReusePolicy(policy); + + auto notifier = EventNotifier::Create(0, EventNotifier::NONBLOCK); + CHECK_NOTNULL(notifier, false, "create EventNotifier for %s failed!", pluginConfig.name().c_str()); + pluginContext_[idx].shareMemoryBlock = smb; + pluginContext_[idx].eventNotifier = notifier; pluginContext_[idx].profilerPluginState->set_state(ProfilerPluginState::LOADED); - pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, gcr); - pluginContext_[idx].context->SendFileDescriptor(pluginContext_[idx].shareMemoryBlock->GetfileDescriptor()); + pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, cmd); + pluginContext_[idx].context->SendFileDescriptor(smb->GetfileDescriptor()); + pluginContext_[idx].context->SendFileDescriptor(notifier->GetFd()); + + eventPoller_->AddFileDescriptor(notifier->GetFd(), + std::bind(&PluginService::ReadShareMemory, this, pluginContext_[idx])); HILOG_DEBUG(LOG_CORE, "pluginContext_[idx].shareMemoryBlock->GetfileDescriptor = %d", - pluginContext_[idx].shareMemoryBlock->GetfileDescriptor()); + pluginContext_[idx].shareMemoryBlock->GetfileDescriptor()); return true; } bool PluginService::CreatePluginSession(const ProfilerPluginConfig& pluginConfig, @@ -110,12 +137,12 @@ bool PluginService::CreatePluginSession(const ProfilerPluginConfig& pluginConfig pluginContext_[idx].shareMemoryBlock = nullptr; - auto gcr = pluginCommandBuilder_->BuildCreateSessionCmd(pluginConfig, 0); - CHECK_TRUE(gcr != nullptr, false, "CreatePluginSession BuildCreateSessionCmd FAIL %s", pluginConfig.name().c_str()); + auto cmd = pluginCommandBuilder_->BuildCreateSessionCmd(pluginConfig, 0); + CHECK_TRUE(cmd != nullptr, false, "CreatePluginSession BuildCreateSessionCmd FAIL %s", pluginConfig.name().c_str()); pluginContext_[idx].profilerPluginState->set_state(ProfilerPluginState::LOADED); - pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, gcr); + pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, cmd); return true; } @@ -125,16 +152,11 @@ bool PluginService::StartPluginSession(const ProfilerPluginConfig& config) "StartPluginSession can't find plugin name %s", config.name().c_str()); uint32_t idx = nameIndex_[config.name()]; - auto gcr = pluginCommandBuilder_->BuildStartSessionCmd(config, idx); - CHECK_TRUE(gcr != nullptr, false, "StartPluginSession BuildStartSessionCmd FAIL %s", config.name().c_str()); + auto cmd = pluginCommandBuilder_->BuildStartSessionCmd(config, idx); + CHECK_TRUE(cmd != nullptr, false, "StartPluginSession BuildStartSessionCmd FAIL %s", config.name().c_str()); pluginContext_[idx].profilerPluginState->set_state(ProfilerPluginState::IN_SESSION); - pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, gcr); - - if (readShareMemoryThreadStatus_ == READ_SHARE_MEMORY_FREE) { // Start the thread that reads shared memory - readShareMemoryThreadStatus_ = READ_SHARE_MEMORY_WORKING; - readShareMemoryThreadSleep_.unlock(); - } + pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, cmd); return true; } bool PluginService::StopPluginSession(const std::string& pluginName) @@ -143,28 +165,26 @@ bool PluginService::StopPluginSession(const std::string& pluginName) pluginName.c_str()); uint32_t idx = nameIndex_[pluginName]; - auto gcr = pluginCommandBuilder_->BuildStopSessionCmd(idx); - CHECK_TRUE(gcr != nullptr, false, "StopPluginSession BuildStopSessionCmd FAIL %s", pluginName.c_str()); + auto cmd = pluginCommandBuilder_->BuildStopSessionCmd(idx); + CHECK_TRUE(cmd != nullptr, false, "StopPluginSession BuildStopSessionCmd FAIL %s", pluginName.c_str()); pluginContext_[idx].profilerPluginState->set_state(ProfilerPluginState::LOADED); - pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, gcr); + pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, cmd); - waitForCommandId_ = gcr->command_id(); + auto sem = GetSemaphoreFactory().Create(0); + CHECK_NOTNULL(sem, false, "create Semaphore for stop %s FAILED!", pluginName.c_str()); + + waitSemphores_[cmd->command_id()] = sem; HILOG_DEBUG(LOG_CORE, "=== StopPluginSession Waiting ... ==="); // try lock for 30000 ms. - if (waitStopSession_.try_lock_for(std::chrono::milliseconds(30000))) { // Received command reply,and stopsession, - ReadShareMemoryOneTime(); // Read the shared memory data again before exiting to avoid losing it + if (sem->TimedWait(30)) { + ReadShareMemory(pluginContext_[idx]); HILOG_DEBUG(LOG_CORE, "=== ShareMemory Clear ==="); } else { HILOG_DEBUG(LOG_CORE, "=== StopPluginSession Waiting FAIL ==="); return false; } HILOG_DEBUG(LOG_CORE, "=== StopPluginSession Waiting OK ==="); - - if (readShareMemoryThreadStatus_ == READ_SHARE_MEMORY_WORKING) { // Stop the thread reading shared memory - readShareMemoryThreadStatus_ = READ_SHARE_MEMORY_FREE; - } - return true; } bool PluginService::DestroyPluginSession(const std::string& pluginName) @@ -174,25 +194,30 @@ bool PluginService::DestroyPluginSession(const std::string& pluginName) uint32_t idx = nameIndex_[pluginName]; - auto gcr = pluginCommandBuilder_->BuildDestroySessionCmd(idx); - CHECK_TRUE(gcr != nullptr, false, "DestroyPluginSession BuildDestroySessionCmd FAIL %s", pluginName.c_str()); + auto cmd = pluginCommandBuilder_->BuildDestroySessionCmd(idx); + CHECK_TRUE(cmd != nullptr, false, "DestroyPluginSession BuildDestroySessionCmd FAIL %s", pluginName.c_str()); if (pluginContext_[idx].shareMemoryBlock != nullptr) { ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal(pluginName); pluginContext_[idx].shareMemoryBlock = nullptr; } + if (pluginContext_[idx].eventNotifier) { + eventPoller_->RemoveFileDescriptor(pluginContext_[idx].eventNotifier->GetFd()); + pluginContext_[idx].eventNotifier = nullptr; + } + pluginContext_[idx].profilerPluginState->set_state(ProfilerPluginState::REGISTERED); - pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, gcr); + pluginServiceImpl_->PushCommand(*pluginContext_[idx].context, cmd); return true; } bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) { if (nameIndex_.find(pluginInfo.name) == nameIndex_.end()) { // add new plugin - while (pluginContext_.find(pluginIdAutoIncrease_) != pluginContext_.end()) { - pluginIdAutoIncrease_++; + while (pluginContext_.find(pluginIdCounter_) != pluginContext_.end()) { + pluginIdCounter_++; } ProfilerPluginCapability capability; @@ -201,19 +226,20 @@ bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) CHECK_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(capability), false, "AddPluginInfo AddCapability FAIL"); - pluginContext_[pluginIdAutoIncrease_].path = pluginInfo.path; - pluginContext_[pluginIdAutoIncrease_].context = pluginInfo.context; - pluginContext_[pluginIdAutoIncrease_].config.set_name(pluginInfo.name); - pluginContext_[pluginIdAutoIncrease_].config.set_plugin_sha256(pluginInfo.sha256); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState = std::make_shared(); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState->set_name(pluginInfo.name); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState->set_state(ProfilerPluginState::REGISTERED); + pluginContext_[pluginIdCounter_].name = pluginInfo.name; + pluginContext_[pluginIdCounter_].path = pluginInfo.path; + pluginContext_[pluginIdCounter_].context = pluginInfo.context; + pluginContext_[pluginIdCounter_].config.set_name(pluginInfo.name); + pluginContext_[pluginIdCounter_].config.set_plugin_sha256(pluginInfo.sha256); + pluginContext_[pluginIdCounter_].profilerPluginState = std::make_shared(); + pluginContext_[pluginIdCounter_].profilerPluginState->set_name(pluginInfo.name); + pluginContext_[pluginIdCounter_].profilerPluginState->set_state(ProfilerPluginState::REGISTERED); - pluginContext_[pluginIdAutoIncrease_].sha256 = pluginInfo.sha256; - pluginContext_[pluginIdAutoIncrease_].bufferSizeHint = pluginInfo.bufferSizeHint; + pluginContext_[pluginIdCounter_].sha256 = pluginInfo.sha256; + pluginContext_[pluginIdCounter_].bufferSizeHint = pluginInfo.bufferSizeHint; - nameIndex_[pluginInfo.name] = pluginIdAutoIncrease_; - pluginIdAutoIncrease_++; + nameIndex_[pluginInfo.name] = pluginIdCounter_; + pluginIdCounter_++; } else { // update sha256 or bufferSizeHint uint32_t idx = nameIndex_[pluginInfo.name]; @@ -224,10 +250,29 @@ bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) pluginContext_[idx].bufferSizeHint = pluginInfo.bufferSizeHint; } } + HILOG_DEBUG(LOG_CORE, "AddPluginInfo for %s done!", pluginInfo.name.c_str()); return true; } +bool PluginService::GetPluginInfo(const std::string& pluginName, PluginInfo& pluginInfo) +{ + uint32_t pluginId = 0; + auto itId = nameIndex_.find(pluginName); + CHECK_TRUE(itId != nameIndex_.end(), false, "plugin name %s not found!", pluginName.c_str()); + pluginId = itId->second; + + auto it = pluginContext_.find(pluginId); + CHECK_TRUE(it != pluginContext_.end(), false, "plugin id %d not found!", pluginId); + + pluginInfo.id = pluginId; + pluginInfo.name = it->second.name; + pluginInfo.path = it->second.path; + pluginInfo.sha256 = it->second.sha256; + pluginInfo.bufferSizeHint = it->second.bufferSizeHint; + return true; +} + bool PluginService::RemovePluginInfo(const PluginInfo& pluginInfo) { CHECK_TRUE(pluginContext_.find(pluginInfo.id) != pluginContext_.end(), false, @@ -238,73 +283,52 @@ bool PluginService::RemovePluginInfo(const PluginInfo& pluginInfo) nameIndex_.erase(pluginContext_[pluginInfo.id].config.name()); pluginContext_.erase(pluginInfo.id); + HILOG_DEBUG(LOG_CORE, "RemovePluginInfo for %s done!", pluginInfo.name.c_str()); return true; } -void PluginService::ReadShareMemoryOneTime() +void PluginService::ReadShareMemory(PluginContext& context) { - readShareMemory_.lock(); - for (auto it = pluginContext_.begin(); it != pluginContext_.end(); it++) { - PluginContext* pluginContext = &it->second; - if (pluginContext->shareMemoryBlock == nullptr) { - continue; + CHECK_NOTNULL(context.shareMemoryBlock, NO_RETVAL, "smb of %s is null!", context.path.c_str()); + uint64_t value = 0; + if (context.eventNotifier) { + value = context.eventNotifier->Take(); + } + HILOG_DEBUG(LOG_CORE, "ReadShareMemory for %s %" PRIu64, context.path.c_str(), value); + while (true) { + auto pluginData = std::make_shared(); + bool ret = context.shareMemoryBlock->TakeData([&](const int8_t data[], uint32_t size) -> bool { + int retval = pluginData->ParseFromArray(reinterpret_cast(data), size); + CHECK_TRUE(retval, false, "parse %d bytes failed!", size); + return true; + }); + if (!ret) { + break; } - do { - uint32_t size = pluginContext->shareMemoryBlock->GetDataSize(); - if (size == 0) { - break; - } - - int8_t* p = const_cast(pluginContext->shareMemoryBlock->GetDataPoint()); - auto pluginData = std::make_shared(); - pluginData->ParseFromArray(reinterpret_cast(p), size); - HILOG_DEBUG(LOG_CORE, "Read ShareMemory %d", size); - if (!pluginContext->profilerDataRepeater->PutPluginData(pluginData)) { - } - if (!pluginContext->shareMemoryBlock->Next()) { - break; - } - } while (true); - } - readShareMemory_.unlock(); -} - -void* PluginService::ReadShareMemoryThread(void* p) -{ - pthread_setname_np(pthread_self(), "ReadMemThread"); - - PluginService* pluginService = (PluginService*)p; - if (pluginService == nullptr) { - return nullptr; - } - while (pluginService->readShareMemoryThreadStatus_ != READ_SHARE_MEMORY_EXIT) { - // try lock for 60000000 ms. - if (pluginService->readShareMemoryThreadSleep_.try_lock_for(std::chrono::milliseconds(60000000))) { - while (pluginService->readShareMemoryThreadStatus_ == READ_SHARE_MEMORY_WORKING) { - pluginService->ReadShareMemoryOneTime(); - usleep(10000); // sleep for 10000 us. - } + if (!context.profilerDataRepeater->PutPluginData(pluginData)) { + break; } } - return nullptr; } + bool PluginService::AppendResult(NotifyResultRequest& request) { pluginCommandBuilder_->GetedCommandResponse(request.command_id()); - if (request.command_id() == waitForCommandId_) { - waitStopSession_.unlock(); + auto sem = GetSemaphore(request.command_id()); + if (sem) { + sem->Post(); } int size = request.result_size(); - HILOG_DEBUG(LOG_CORE, "AppendResult size:%d,cmdid:%d,waitid:%d", size, request.command_id(), waitForCommandId_); + HILOG_DEBUG(LOG_CORE, "AppendResult size:%d, cmd id:%d", size, request.command_id()); for (int i = 0; i < size; i++) { PluginResult pr = request.result(i); if (pr.data().size() > 0) { HILOG_DEBUG(LOG_CORE, "AppendResult Size : %zu", pr.data().size()); uint32_t pluginId = pr.plugin_id(); if (pluginContext_[pluginId].profilerDataRepeater == nullptr) { - HILOG_DEBUG(LOG_CORE, "AppendResult profilerDataRepeater==nullptr %s %d", - pr.status().name().c_str(), pluginId); + HILOG_DEBUG(LOG_CORE, "AppendResult profilerDataRepeater==nullptr %s %d", pr.status().name().c_str(), + pluginId); return false; } auto pluginData = std::make_shared(); @@ -325,7 +349,7 @@ std::vector PluginService::GetPluginStatus() { std::vector ret; std::map::iterator iter; - for (iter = pluginContext_.begin(); iter != pluginContext_.end(); iter++) { + for (iter = pluginContext_.begin(); iter != pluginContext_.end(); ++iter) { ret.push_back(iter->second.profilerPluginState); } return ret; diff --git a/device/services/plugin_service/src/plugin_service_impl.cpp b/device/services/plugin_service/src/plugin_service_impl.cpp old mode 100755 new mode 100644 diff --git a/device/services/plugin_service/src/plugin_service_impl.h b/device/services/plugin_service/src/plugin_service_impl.h old mode 100755 new mode 100644 index 14349c538..c5a98d0f0 --- a/device/services/plugin_service/src/plugin_service_impl.h +++ b/device/services/plugin_service/src/plugin_service_impl.h @@ -25,7 +25,7 @@ using GetCommandResponsePtr = STD_PTR(shared, ::GetCommandResponse); class PluginServiceImpl final : public IPluginServiceServer { public: - PluginServiceImpl(PluginService& p); + explicit PluginServiceImpl(PluginService& p); ~PluginServiceImpl(); bool RegisterPlugin(SocketContext& context, ::RegisterPluginRequest& request, diff --git a/device/services/plugin_service/test/BUILD.gn b/device/services/plugin_service/test/BUILD.gn old mode 100755 new mode 100644 index 58f3be584..e0bf1dcb6 --- a/device/services/plugin_service/test/BUILD.gn +++ b/device/services/plugin_service/test/BUILD.gn @@ -1,83 +1,80 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("../../../base/config.gni") - -module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" -config("module_private_config") { - visibility = [":*"] -} - -ohos_unittest("plugin_service_ut") { - module_out_path = module_output_path - sources = [ - "unittest/plugin_service_test.cpp", - "unittest/services_ipc_test.cpp", - ] - public_deps = [ - "${OHOS_PROFILER_DIR}/device/services/plugin_service:hiprofiler_plugin_service", - "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", - "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", - "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", - ] - deps = [ - "//third_party/googletest:gtest_main", - "//third_party/googletest:gtest", - ] - include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] - cflags = [ - "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - "-Dprotected=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" -} - -ohos_unittest("plugin_service_module_test") { - module_out_path = module_output_path - sources = [ - "moduletest/plugin_service_test.cpp", - "moduletest/services_ipc_test.cpp", - ] - public_deps = [ - "${OHOS_PROFILER_DIR}/device/services/plugin_service:hiprofiler_plugin_service", - "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", - "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", - "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", - ] - deps = [ - "//third_party/googletest:gtest", - ] - include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] - cflags = [ - "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - "-Dprotected=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" -} - -group("unittest") { - testonly = true - deps = [ - ":plugin_service_ut", - ":plugin_service_module_test" - ] -} +# 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("//build/test.gni") +import("../../../base/config.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" +config("module_private_config") { + visibility = [ ":*" ] +} + +ohos_unittest("plugin_service_ut") { + module_out_path = module_output_path + sources = [ + "unittest/plugin_service_test.cpp", + "unittest/services_ipc_test.cpp", + ] + public_deps = [ + "${OHOS_PROFILER_DIR}/device/services/plugin_service:hiprofiler_plugin_service", + "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", + "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", + "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", + ] + deps = [ + "../../../base:hiprofiler_base", + "//third_party/googletest:gtest", + "//third_party/googletest:gtest_main", + ] + include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + "-Dprotected=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +ohos_unittest("plugin_service_module_test") { + module_out_path = module_output_path + sources = [ + "moduletest/plugin_service_test.cpp", + "moduletest/services_ipc_test.cpp", + ] + public_deps = [ + "${OHOS_PROFILER_DIR}/device/services/plugin_service:hiprofiler_plugin_service", + "${OHOS_PROFILER_DIR}/device/services/shared_memory:shared_memory", + "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", + "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", + ] + deps = [ "//third_party/googletest:gtest" ] + include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + "-Dprotected=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +group("unittest") { + testonly = true + deps = [ + ":plugin_service_module_test", + ":plugin_service_ut", + ] +} diff --git a/device/services/plugin_service/test/moduletest/services_ipc_test.cpp b/device/services/plugin_service/test/moduletest/services_ipc_test.cpp index 95d4287e9..497644ee9 100644 --- a/device/services/plugin_service/test/moduletest/services_ipc_test.cpp +++ b/device/services/plugin_service/test/moduletest/services_ipc_test.cpp @@ -65,7 +65,7 @@ HWTEST_F(ServicesIpcTest, UnixSocketServer, TestSize.Level1) { UnixSocketServer unixSocketServer; - unixSocketServer.UnixSocketAccept(nullptr); + unixSocketServer.UnixSocketAccept(); ServiceEntry serviceEntry; ASSERT_TRUE(unixSocketServer.StartServer("", serviceEntry)); diff --git a/device/services/plugin_service/test/unittest/plugin_service_test.cpp b/device/services/plugin_service/test/unittest/plugin_service_test.cpp index dfcf36148..2820d1b46 100644 --- a/device/services/plugin_service/test/unittest/plugin_service_test.cpp +++ b/device/services/plugin_service/test/unittest/plugin_service_test.cpp @@ -26,9 +26,6 @@ using namespace testing::ext; namespace { -std::unique_ptr g_pluginService; -uint32_t g_pluginId; - class PluginClientTest final : public IPluginServiceClient { public: bool OnGetCommandResponse(SocketContext& context, ::GetCommandResponse& response) override @@ -37,24 +34,27 @@ public: } }; -std::unique_ptr g_pluginClient; class UnitTestPluginService : public testing::Test { public: - static void SetUpTestCase() + static void SetUpTestCase() {} + static void TearDownTestCase() {} + + void SetUp() { - g_pluginService = std::make_unique(); + pluginService_ = std::make_unique(); usleep(100000); // sleep for 100000 us. - g_pluginClient = std::make_unique(); - ASSERT_FALSE(g_pluginClient->Connect("")); + pluginClient_ = std::make_unique(); } - static void TearDownTestCase() + void TearDown() { - g_pluginClient = nullptr; - g_pluginService = nullptr; + pluginClient_ = nullptr; + pluginService_ = nullptr; } - void SetUp() {} - void TearDown() {} +public: + std::unique_ptr pluginService_ = nullptr; + std::unique_ptr pluginClient_ = nullptr; + uint32_t pluginId_; }; /** @@ -66,13 +66,19 @@ HWTEST_F(UnitTestPluginService, AddPluginInfo, TestSize.Level1) { RegisterPluginRequest request; RegisterPluginResponse response; + PluginInfo plugin; request.set_request_id(1); request.set_path("abc.so"); request.set_sha256("asdfasdfasdfasfd"); request.set_name("abc.so"); ASSERT_TRUE(response.status() == 0); - g_pluginId = response.plugin_id(); + pluginId_ = response.plugin_id(); + + plugin.name = "abc.so"; + plugin.bufferSizeHint = 0; + plugin.sha256 = ""; + ASSERT_TRUE(pluginService_->AddPluginInfo(plugin)); } /** @@ -87,7 +93,7 @@ HWTEST_F(UnitTestPluginService, CreatePluginSession1, TestSize.Level1) ppc.set_plugin_sha256("ASDFAADSF"); ppc.set_sample_interval(20); - g_pluginService->CreatePluginSession(ppc, std::make_shared(4096)); + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, std::make_shared(4096))); } /** @@ -106,7 +112,7 @@ HWTEST_F(UnitTestPluginService, CreatePluginSession2, TestSize.Level1) bc.set_pages(1); bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); - g_pluginService->CreatePluginSession(ppc, bc, std::make_shared(4096)); + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, bc, std::make_shared(4096))); } /** @@ -121,7 +127,7 @@ HWTEST_F(UnitTestPluginService, StartPluginSession, TestSize.Level1) ppc.set_plugin_sha256("ASDFAADSF"); ppc.set_sample_interval(20); - g_pluginService->StartPluginSession(ppc); + ASSERT_FALSE(pluginService_->StartPluginSession(ppc)); } /** @@ -131,7 +137,7 @@ HWTEST_F(UnitTestPluginService, StartPluginSession, TestSize.Level1) */ HWTEST_F(UnitTestPluginService, StopPluginSession, TestSize.Level1) { - g_pluginService->StopPluginSession("abc.so"); + ASSERT_FALSE(pluginService_->StopPluginSession("abc.so")); } /** @@ -141,7 +147,7 @@ HWTEST_F(UnitTestPluginService, StopPluginSession, TestSize.Level1) */ HWTEST_F(UnitTestPluginService, DestroyPluginSession, TestSize.Level1) { - g_pluginService->DestroyPluginSession("abc.so"); + ASSERT_FALSE(pluginService_->DestroyPluginSession("abc.so")); } /** @@ -157,7 +163,7 @@ HWTEST_F(UnitTestPluginService, RemovePluginInfo, TestSize.Level1) pi.name = "abc.so"; pi.path = "abc.so"; pi.sha256 = "asdfasdf"; - g_pluginService->RemovePluginInfo(pi); + ASSERT_FALSE(pluginService_->RemovePluginInfo(pi)); } /** @@ -170,6 +176,7 @@ HWTEST_F(UnitTestPluginService, AppendResult, TestSize.Level1) NotifyResultRequest nrr; nrr.set_request_id(1); nrr.set_command_id(1); + ASSERT_TRUE(pluginService_->AppendResult(nrr)); } /** @@ -179,7 +186,8 @@ HWTEST_F(UnitTestPluginService, AppendResult, TestSize.Level1) */ HWTEST_F(UnitTestPluginService, GetPluginStatus, TestSize.Level1) { - auto status = g_pluginService->GetPluginStatus(); + auto status = pluginService_->GetPluginStatus(); + ASSERT_TRUE(status.size()==0); } /** @@ -189,6 +197,578 @@ HWTEST_F(UnitTestPluginService, GetPluginStatus, TestSize.Level1) */ HWTEST_F(UnitTestPluginService, GetPluginIdByName, TestSize.Level1) { - g_pluginService->GetPluginIdByName("abc.so"); + ASSERT_TRUE(pluginService_->GetPluginIdByName("abc.so")==0); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin registration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AddPluginInfo2, TestSize.Level1) +{ + RegisterPluginRequest request; + RegisterPluginResponse response; + PluginInfo plugin; + + request.set_request_id(2); + request.set_path("mem.so"); + request.set_sha256("asdfasdfasdfasfd"); + request.set_name("mem.so"); + ASSERT_TRUE(response.status() == 0); + pluginId_ = response.plugin_id(); + + plugin.name = "mem.so"; + plugin.bufferSizeHint = 0; + plugin.sha256 = ""; + EXPECT_TRUE(pluginService_->AddPluginInfo(plugin)); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin configuration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession12, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("mem.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Set session configuration. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession22, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("mem.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ProfilerSessionConfig::BufferConfig bc; + bc.set_pages(1); + bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, bc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Start plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StartPluginSession2, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("mem.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->StartPluginSession(ppc)); +} + +/** + * @tc.name: Service + * @tc.desc: Stop plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StopPluginSession2, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->StopPluginSession("mem.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Destroy receiving test. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, DestroyPluginSession2, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->DestroyPluginSession("mem.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Remove the specified plugin. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, RemovePluginInfo2, TestSize.Level1) +{ + UnregisterPluginRequest request; + PluginInfo pi; + pi.id = 0; + pi.name = "mem.so"; + pi.path = "mem.so"; + pi.sha256 = "asdfasdf"; + ASSERT_FALSE(pluginService_->RemovePluginInfo(pi)); +} + +/** + * @tc.name: Service + * @tc.desc: Setting report results. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AppendResult2, TestSize.Level1) +{ + NotifyResultRequest nrr; + nrr.set_request_id(2); + nrr.set_command_id(2); + ASSERT_TRUE(pluginService_->AppendResult(nrr)); +} + +/** + * @tc.name: Service + * @tc.desc: Get plugin status. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginStatus2, TestSize.Level1) +{ + auto status = pluginService_->GetPluginStatus(); + ASSERT_TRUE(status.size() == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Gets the plugin with the specified name. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginIdByName2, TestSize.Level1) +{ + ASSERT_TRUE(pluginService_->GetPluginIdByName("mem.so") == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin registration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AddPluginInfo3, TestSize.Level1) +{ + RegisterPluginRequest request; + RegisterPluginResponse response; + PluginInfo plugin; + + request.set_request_id(3); + request.set_path("cpu.so"); + request.set_sha256("asdfasdfasdfasfd"); + request.set_name("cpu.so"); + ASSERT_TRUE(response.status() == 0); + pluginId_ = response.plugin_id(); + + plugin.name = "cpu.so"; + plugin.bufferSizeHint = 0; + plugin.sha256 = ""; + EXPECT_TRUE(pluginService_->AddPluginInfo(plugin)); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin configuration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession13, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("cpu.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Set session configuration. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession23, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("cpu.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ProfilerSessionConfig::BufferConfig bc; + bc.set_pages(1); + bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, bc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Start plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StartPluginSession3, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("cpu.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->StartPluginSession(ppc)); +} + +/** + * @tc.name: Service + * @tc.desc: Stop plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StopPluginSession3, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->StopPluginSession("cpu.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Destroy receiving test. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, DestroyPluginSession3, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->DestroyPluginSession("cpu.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Remove the specified plugin. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, RemovePluginInfo3, TestSize.Level1) +{ + UnregisterPluginRequest request; + PluginInfo pi; + pi.id = 0; + pi.name = "cpu.so"; + pi.path = "cpu.so"; + pi.sha256 = "asdfasdf"; + ASSERT_FALSE(pluginService_->RemovePluginInfo(pi)); +} + +/** + * @tc.name: Service + * @tc.desc: Setting report results. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AppendResult3, TestSize.Level1) +{ + NotifyResultRequest nrr; + nrr.set_request_id(3); + nrr.set_command_id(3); + ASSERT_TRUE(pluginService_->AppendResult(nrr)); +} + +/** + * @tc.name: Service + * @tc.desc: Get plugin status. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginStatus3, TestSize.Level1) +{ + auto status = pluginService_->GetPluginStatus(); + ASSERT_TRUE(status.size() == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Gets the plugin with the specified name. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginIdByName3, TestSize.Level1) +{ + ASSERT_TRUE(pluginService_->GetPluginIdByName("cpu.so") == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin registration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AddPluginInfo4, TestSize.Level1) +{ + RegisterPluginRequest request; + RegisterPluginResponse response; + PluginInfo plugin; + + request.set_request_id(4); + request.set_path("stream.so"); + request.set_sha256("asdfasdfasdfasfd"); + request.set_name("stream.so"); + ASSERT_TRUE(response.status() == 0); + pluginId_ = response.plugin_id(); + + plugin.name = "stream.so"; + plugin.bufferSizeHint = 0; + plugin.sha256 = ""; + EXPECT_TRUE(pluginService_->AddPluginInfo(plugin)); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin configuration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession14, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("stream.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Set session configuration. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession24, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("stream.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ProfilerSessionConfig::BufferConfig bc; + bc.set_pages(1); + bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, bc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Start plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StartPluginSession4, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("stream.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->StartPluginSession(ppc)); +} + +/** + * @tc.name: Service + * @tc.desc: Stop plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StopPluginSession4, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->StopPluginSession("stream.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Destroy receiving test. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, DestroyPluginSession4, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->DestroyPluginSession("stream.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Remove the specified plugin. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, RemovePluginInfo4, TestSize.Level1) +{ + UnregisterPluginRequest request; + PluginInfo pi; + pi.id = 0; + pi.name = "stream.so"; + pi.path = "stream.so"; + pi.sha256 = "asdfasdf"; + ASSERT_FALSE(pluginService_->RemovePluginInfo(pi)); +} + +/** + * @tc.name: Service + * @tc.desc: Setting report results. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AppendResult4, TestSize.Level1) +{ + NotifyResultRequest nrr; + nrr.set_request_id(4); + nrr.set_command_id(4); + ASSERT_TRUE(pluginService_->AppendResult(nrr)); +} + +/** + * @tc.name: Service + * @tc.desc: Get plugin status. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginStatus4, TestSize.Level1) +{ + auto status = pluginService_->GetPluginStatus(); + ASSERT_TRUE(status.size() == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Gets the plugin with the specified name. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginIdByName4, TestSize.Level1) +{ + ASSERT_TRUE(pluginService_->GetPluginIdByName("stream.so") == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin registration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AddPluginInfo5, TestSize.Level1) +{ + RegisterPluginRequest request; + RegisterPluginResponse response; + PluginInfo plugin; + + request.set_request_id(5); + request.set_path("sample.so"); + request.set_sha256("asdfasdfasdfasfd"); + request.set_name("sample.so"); + ASSERT_TRUE(response.status() == 0); + pluginId_ = response.plugin_id(); + + plugin.name = "sample.so"; + plugin.bufferSizeHint = 0; + plugin.sha256 = ""; + EXPECT_TRUE(pluginService_->AddPluginInfo(plugin)); +} + +/** + * @tc.name: Service + * @tc.desc: Set plugin configuration information. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession15, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("sample.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Set session configuration. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, CreatePluginSession25, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("sample.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ProfilerSessionConfig::BufferConfig bc; + bc.set_pages(1); + bc.set_policy(ProfilerSessionConfig_BufferConfig_Policy_RECYCLE); + + ASSERT_FALSE(pluginService_->CreatePluginSession(ppc, bc, std::make_shared(4096))); +} + +/** + * @tc.name: Service + * @tc.desc: Start plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StartPluginSession5, TestSize.Level1) +{ + ProfilerPluginConfig ppc; + ppc.set_name("sample.so"); + ppc.set_plugin_sha256("ASDFAADSF"); + ppc.set_sample_interval(20); + + ASSERT_FALSE(pluginService_->StartPluginSession(ppc)); +} + +/** + * @tc.name: Service + * @tc.desc: Stop plugin session. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, StopPluginSession5, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->StopPluginSession("sample.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Destroy receiving test. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, DestroyPluginSession5, TestSize.Level1) +{ + ASSERT_FALSE(pluginService_->DestroyPluginSession("sample.so")); +} + +/** + * @tc.name: Service + * @tc.desc: Remove the specified plugin. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, RemovePluginInfo5, TestSize.Level1) +{ + UnregisterPluginRequest request; + PluginInfo pi; + pi.id = 0; + pi.name = "sample.so"; + pi.path = "sample.so"; + pi.sha256 = "asdfasdf"; + ASSERT_FALSE(pluginService_->RemovePluginInfo(pi)); +} + +/** + * @tc.name: Service + * @tc.desc: Setting report results. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, AppendResult5, TestSize.Level1) +{ + NotifyResultRequest nrr; + nrr.set_request_id(5); + nrr.set_command_id(5); + ASSERT_TRUE(pluginService_->AppendResult(nrr)); +} + +/** + * @tc.name: Service + * @tc.desc: Get plugin status. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginStatus5, TestSize.Level1) +{ + auto status = pluginService_->GetPluginStatus(); + ASSERT_TRUE(status.size() == 0); +} + +/** + * @tc.name: Service + * @tc.desc: Gets the plugin with the specified name. + * @tc.type: FUNC + */ +HWTEST_F(UnitTestPluginService, GetPluginIdByName5, TestSize.Level1) +{ + ASSERT_TRUE(pluginService_->GetPluginIdByName("sample.so") == 0); } } // namespace \ No newline at end of file diff --git a/device/services/plugin_service/test/unittest/services_ipc_test.cpp b/device/services/plugin_service/test/unittest/services_ipc_test.cpp index 34c37eb93..73ce24f85 100644 --- a/device/services/plugin_service/test/unittest/services_ipc_test.cpp +++ b/device/services/plugin_service/test/unittest/services_ipc_test.cpp @@ -14,13 +14,9 @@ */ #include -#include -#include -#include "client_map.h" #include "plugin_service.ipc.h" #include "service_entry.h" -#include "socket_context.h" #include "unix_socket_client.h" #include "unix_socket_server.h" @@ -40,28 +36,18 @@ protected: */ HWTEST_F(ServicesIpcTest, ProtocolProc, TestSize.Level1) { + std::string s="abc"; ServiceBase serviceBase; SocketContext socketContext; - ASSERT_FALSE(serviceBase.ProtocolProc(socketContext, 0, nullptr, 0)); - ASSERT_TRUE(!socketContext.SendRaw(-1, nullptr, 0, 0)); + ASSERT_FALSE(serviceBase.ProtocolProc(socketContext, 0, (const int8_t *)s.c_str(), s.size())); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), 0)); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), -1)); + ASSERT_TRUE(!socketContext.SendRaw(-1, (const int8_t *)s.c_str(), s.size(), 1)); + ASSERT_TRUE(!socketContext.SendRaw(1, (const int8_t *)s.c_str(), s.size(), 1)); ASSERT_TRUE(!socketContext.SendFileDescriptor(-1)); + ASSERT_TRUE(!socketContext.SendFileDescriptor(1)); ASSERT_EQ(socketContext.ReceiveFileDiscriptor(), -1); - ASSERT_EQ(socketContext.RawProtocolProc(-1, nullptr, -1), -1); -} - -/** - * @tc.name: Service - * @tc.desc: Client link. - * @tc.type: FUNC - */ -HWTEST_F(ServicesIpcTest, ClientSocket, TestSize.Level1) -{ - ServiceEntry serviceEntry; - ClientMap::GetInstance().PutClientSocket(0, serviceEntry); - ASSERT_EQ(ClientMap::GetInstance().AutoRelease(), 1); - - ClientConnection* clientConnection = new ClientConnection(0, serviceEntry); - ASSERT_EQ(clientConnection->RawProtocolProc(-1, nullptr, 0), -1); + ASSERT_EQ(socketContext.RawProtocolProc(1, (const int8_t *)s.c_str(), s.size()), -1); } /** @@ -85,12 +71,16 @@ HWTEST_F(ServicesIpcTest, UnixSocketServer, TestSize.Level1) { UnixSocketServer unixSocketServer; - unixSocketServer.UnixSocketAccept(nullptr); + unixSocketServer.UnixSocketAccept(); ServiceEntry serviceEntry; - ASSERT_TRUE(unixSocketServer.StartServer("", serviceEntry)); + ASSERT_TRUE(unixSocketServer.StartServer("test_server_name", serviceEntry)); } +namespace { +const int SLEEP_TIME = 30000; +} // namespace + /** * @tc.name: Service * @tc.desc: Server process monitoring. @@ -104,14 +94,11 @@ HWTEST_F(ServicesIpcTest, ServiceEntry, TestSize.Level1) serviceEntry.RegisterService(pluginService); serviceEntry.FindServiceByName(pluginService.serviceName_); - usleep(30000); - - GetTimeMS(); - GetTimeUS(); - GetTimeNS(); + usleep(SLEEP_TIME); IPluginServiceClient pluginClient; - ASSERT_FALSE(pluginClient.Connect("")); - usleep(30000); + ASSERT_FALSE(pluginClient.Connect("invalid_name")); + ASSERT_TRUE(pluginClient.Connect("test_unix_socket_service_entry")); + usleep(SLEEP_TIME); } } // namespace \ No newline at end of file diff --git a/device/services/profiler_service/BUILD.gn b/device/services/profiler_service/BUILD.gn old mode 100755 new mode 100644 index 16ccfc8db..307f45338 --- a/device/services/profiler_service/BUILD.gn +++ b/device/services/profiler_service/BUILD.gn @@ -36,6 +36,7 @@ ohos_source_set("profiler_service") { "src/profiler_data_repeater.cpp", "src/profiler_service.cpp", "src/result_demuxer.cpp", + "src/trace_file_helper.cpp", "src/trace_file_reader.cpp", "src/trace_file_writer.cpp", ] @@ -57,11 +58,10 @@ ohos_source_set("profiler_service") { } ohos_executable("hiprofilerd") { - sources = [ - "src/main.cpp", - ] + sources = [ "src/main.cpp" ] deps = [ ":profiler_service", + "../../base:hiprofiler_base", "../plugin_service:hiprofiler_plugin_service", ] if (current_toolchain != host_toolchain) { diff --git a/device/services/profiler_service/include/profiler_capability_manager.h b/device/services/profiler_service/include/profiler_capability_manager.h old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/include/profiler_data_repeater.h b/device/services/profiler_service/include/profiler_data_repeater.h old mode 100755 new mode 100644 index a8afa67ca..3c5d00178 --- a/device/services/profiler_service/include/profiler_data_repeater.h +++ b/device/services/profiler_service/include/profiler_data_repeater.h @@ -31,7 +31,9 @@ public: ~ProfilerDataRepeater(); bool PutPluginData(const ProfilerPluginDataPtr& pluginData); + ProfilerPluginDataPtr TakePluginData(); + int TakePluginData(std::vector& pluginDataVec); void Close(); diff --git a/device/services/profiler_service/include/profiler_service.h b/device/services/profiler_service/include/profiler_service.h old mode 100755 new mode 100644 index 08942927e..efade4c42 --- a/device/services/profiler_service/include/profiler_service.h +++ b/device/services/profiler_service/include/profiler_service.h @@ -15,10 +15,11 @@ #ifndef PROFILER_SERVICE_H #define PROFILER_SERVICE_H +#include +#include #include "logging.h" #include "nocopyable.h" #include "profiler_service.grpc.pb.h" -#include class PluginService; @@ -66,20 +67,30 @@ public: const ::DestroySessionRequest* request, ::DestroySessionResponse* response) override; + // keep tracing session alive. + ::grpc::Status KeepSession(::grpc::ServerContext* context, + const ::KeepSessionRequest* request, + ::KeepSessionResponse* response) override; + + // only used in main, for service control. bool StartService(const std::string& listenUri); - void WaitServiceDone(); - void StopService(); private: - static constexpr size_t DEFAULT_REPEATER_BUFFER_SIZE = 100; + static constexpr size_t DEFAULT_REPEATER_BUFFER_SIZE = 2000; - struct SessionContext { - uint32_t id; - std::mutex mutex; + using BufferConfig = ProfilerSessionConfig::BufferConfig; + + struct SessionContext : public std::enable_shared_from_this { + uint32_t id = 0; + std::string name; + std::string offlineTask; // offline sample task name + std::string timeoutTask; // session timeout task name + ProfilerService* service = nullptr; + std::mutex sessionMutex; ProfilerSessionConfig sessionConfig; - std::vector bufferConfigs; + std::vector bufferConfigs; std::vector pluginConfigs; std::vector pluginStatus; std::map pluginSessions; @@ -88,23 +99,30 @@ private: std::shared_ptr resultDemuxer; PluginSessionPtr CreatePluginSession(const PluginServicePtr& pluginService, - const ProfilerPluginConfig& pluginConfig); + const ProfilerPluginConfig& pluginConfig); PluginSessionPtr CreatePluginSession(const PluginServicePtr& pluginService, - const ProfilerPluginConfig& pluginConfig, - const ProfilerSessionConfig::BufferConfig& bufferConfig); + const ProfilerPluginConfig& pluginConfig, + const BufferConfig& bufferConfig); - bool CheckBufferConfig(const ProfilerSessionConfig::BufferConfig& bufferConfig); + bool CheckPluginSha256(const ProfilerPluginConfig& pluginConfig); + + bool CheckBufferConfig(const BufferConfig& bufferConfig); bool CreatePluginSessions(const PluginServicePtr& pluginService); bool RemovePluginSessions(const std::vector& nameList); - bool UpdatePluginSessions(const PluginServicePtr& pluginService, - const std::vector& configIndexes); + bool UpdatePluginSessions(const PluginServicePtr& pluginService, const std::vector& configIndexes); std::vector UpdatePluginConfigs(const std::vector& configList); SessionContext() = default; ~SessionContext(); + bool StartPluginSessions(); + bool StopPluginSessions(); + + void SetKeepAliveTime(uint32_t timeout); + void StartSessionExpireTask(); + void StopSessionExpireTask(); DISALLOW_COPY_AND_MOVE(SessionContext); }; @@ -117,12 +135,12 @@ private: bool RemoveSessionContext(uint32_t sessionId); private: - mutable std::mutex sessionContextMutex_; - PluginServicePtr pluginService_; - std::atomic sessionIdCounter_ {0}; - std::atomic responseIdCounter_ {0}; - std::map sessionContext_; - std::unique_ptr server_; + mutable std::mutex sessionContextMutex_ = {}; + PluginServicePtr pluginService_ = nullptr; + std::atomic sessionIdCounter_ = 0; + std::atomic responseIdCounter_ = 0; + std::map sessionContext_ = {}; + std::unique_ptr server_ = nullptr; DISALLOW_COPY_AND_MOVE(ProfilerService); }; diff --git a/device/services/profiler_service/src/main.cpp b/device/services/profiler_service/src/main.cpp old mode 100755 new mode 100644 index 1830ec704..aa4026eaf --- a/device/services/profiler_service/src/main.cpp +++ b/device/services/profiler_service/src/main.cpp @@ -15,7 +15,7 @@ #include #include "grpc/impl/codegen/log.h" -#include +#include "grpcpp/health_check_service_interface.h" #include "logging.h" #include "plugin_service.h" #include "profiler_service.h" diff --git a/device/services/profiler_service/src/plugin_session.cpp b/device/services/profiler_service/src/plugin_session.cpp old mode 100755 new mode 100644 index 2490634d0..2a05076c9 --- a/device/services/profiler_service/src/plugin_session.cpp +++ b/device/services/profiler_service/src/plugin_session.cpp @@ -45,7 +45,9 @@ PluginSession::PluginSession(const ProfilerPluginConfig& pluginConfig, PluginSession::~PluginSession() { - Destroy(); + if (state_ != INITIAL) { + Destroy(); + } } bool PluginSession::Create() @@ -55,7 +57,7 @@ bool PluginSession::Create() CHECK_TRUE(state_ == INITIAL, false, "plugin state %d invalid!", state_); auto pluginService = pluginService_.lock(); // promote to shared_ptr - CHECK_NOTNULL(pluginService, false, "PluginSession::Create pluginService null!"); + CHECK_NOTNULL(pluginService, false, "PluginSession::%s pluginService promote failed!", __func__); bool retval = false; if (withBufferConfig_) { @@ -80,7 +82,12 @@ bool PluginSession::Destroy() CHECK_TRUE(state_ == CREATED || state_ == STARTED, false, "plugin state %d invalid!", state_); auto pluginService = pluginService_.lock(); - CHECK_NOTNULL(pluginService, false, "PluginSession::Create pluginService null!"); + CHECK_NOTNULL(pluginService, false, "PluginSession::%s pluginService promote failed!", __func__); + + if (state_ == STARTED) { + HILOG_INFO(LOG_CORE, "PluginSession::Destroy state is STARED, need stop!"); + StopLocked(); + } bool retval = pluginService->DestroyPluginSession(pluginConfig_.name()); HILOG_INFO(LOG_CORE, "DestroyPluginSession for %s %s!", pluginConfig_.name().c_str(), retval ? "OK" : "FAIL"); @@ -109,7 +116,7 @@ bool PluginSession::Start() CHECK_TRUE(state_ == CREATED, false, "plugin state %d invalid!", state_); auto pluginService = pluginService_.lock(); - CHECK_NOTNULL(pluginService, false, "PluginSession::Create pluginService null!"); + CHECK_NOTNULL(pluginService, false, "PluginSession::%s pluginService promote failed!", __func__); bool retval = pluginService->StartPluginSession(pluginConfig_); HILOG_INFO(LOG_CORE, "StartPluginSession for %s %s!", pluginConfig_.name().c_str(), retval ? "OK" : "FAIL"); @@ -122,11 +129,16 @@ bool PluginSession::Start() bool PluginSession::Stop() { std::unique_lock lock(mutex_); + return StopLocked(); +} + +bool PluginSession::StopLocked() +{ HILOG_INFO(LOG_CORE, "StopPluginSession for %s...", pluginConfig_.name().c_str()); CHECK_TRUE(state_ == STARTED, false, "plugin state %d invalid!", state_); auto pluginService = pluginService_.lock(); - CHECK_NOTNULL(pluginService, false, "PluginSession::Create pluginService null!"); + CHECK_NOTNULL(pluginService, false, "PluginSession::%s pluginService promote failed!", __func__); bool retval = pluginService->StopPluginSession(pluginConfig_.name()); HILOG_INFO(LOG_CORE, "StopPluginSession for %s %s!", pluginConfig_.name().c_str(), retval ? "OK" : "FAIL"); diff --git a/device/services/profiler_service/src/plugin_session.h b/device/services/profiler_service/src/plugin_session.h old mode 100755 new mode 100644 index 3291f775b..66f71a63f --- a/device/services/profiler_service/src/plugin_session.h +++ b/device/services/profiler_service/src/plugin_session.h @@ -41,7 +41,6 @@ public: bool Start(); bool Stop(); - bool Destroy(); bool IsAvailable() const; @@ -54,6 +53,8 @@ public: private: bool Create(); + bool StopLocked(); + bool Destroy(); private: mutable std::mutex mutex_; diff --git a/device/services/profiler_service/src/profiler_capability_manager.cpp b/device/services/profiler_service/src/profiler_capability_manager.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/src/profiler_data_repeater.cpp b/device/services/profiler_service/src/profiler_data_repeater.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/src/profiler_service.cpp b/device/services/profiler_service/src/profiler_service.cpp old mode 100755 new mode 100644 index 04d72cb34..a64237968 --- a/device/services/profiler_service/src/profiler_service.cpp +++ b/device/services/profiler_service/src/profiler_service.cpp @@ -20,29 +20,32 @@ #include "profiler_capability_manager.h" #include "profiler_data_repeater.h" #include "result_demuxer.h" +#include "schedule_task_manager.h" #include "trace_file_writer.h" -#include - using namespace ::grpc; -#define CHECK_REQUEST_RESPONSE(arg, response) \ - if (request == nullptr || response == nullptr) { \ - HILOG_WARN(LOG_CORE, "%s: FAILED, %s", __func__, "request or response invalid!"); \ - return {StatusCode::INVALID_ARGUMENT, "request or response invalid!"}; \ +#define CHECK_REQUEST_RESPONSE(context, requst, response) \ + CHECK_POINTER_NOTNULL(context, "context ptr invalid!"); \ + CHECK_POINTER_NOTNULL(requst, "request ptr invalid!"); \ + CHECK_POINTER_NOTNULL(response, "response ptr invalid!") + +#define CHECK_POINTER_NOTNULL(ptr, errorMessage) \ + if (ptr == nullptr) { \ + HILOG_ERROR(LOG_CORE, "%s: FAILED, %s is null!", __func__, #ptr); \ + return {StatusCode::INTERNAL, errorMessage}; \ } -#define CHECK_POINTER_NOTNULL(ptr, errorMessage) \ - if (ptr == nullptr) { \ - HILOG_WARN(LOG_CORE, "%s: FAILED, %s is null!", __func__, #ptr); \ - return {StatusCode::INTERNAL, errorMessage}; \ +#define CHECK_EXPRESSION_TRUE(expr, errorMessage) \ + if (!(expr)) { \ + HILOG_ERROR(LOG_CORE, "%s: FAILED, %s", __func__, errorMessage); \ + return {StatusCode::INTERNAL, (errorMessage)}; \ } -#define CHECK_EXPRESSION_TRUE(expr, errorMessage) \ - if (!(expr)) { \ - HILOG_WARN(LOG_CORE, "%s: FAILED, %s", __func__, errorMessage); \ - return {StatusCode::INTERNAL, (errorMessage)}; \ - } +namespace { +constexpr int MIN_SESSION_TIMEOUT_MS = 1000; +constexpr int MAX_SESSION_TIMEOUT_MS = 1000 * 600; +} // namespace ProfilerService::ProfilerService(const PluginServicePtr& pluginService) : pluginService_(pluginService) {} @@ -51,14 +54,18 @@ ProfilerService::~ProfilerService() {} ProfilerService::SessionContext::~SessionContext() { HILOG_INFO(LOG_CORE, "~SessionContext id = %d", id); + if (offlineTask.size() > 0) { + ScheduleTaskManager::GetInstance().UnscheduleTask(offlineTask); + } + StopSessionExpireTask(); } Status ProfilerService::GetCapabilities(ServerContext* context, const ::GetCapabilitiesRequest* request, ::GetCapabilitiesResponse* response) { + CHECK_REQUEST_RESPONSE(context, request, response); HILOG_INFO(LOG_CORE, "GetCapabilities from '%s'", context->peer().c_str()); - CHECK_REQUEST_RESPONSE(request, response); HILOG_INFO(LOG_CORE, "GetCapabilities %d start", request->request_id()); std::vector capabilities = ProfilerCapabilityManager::GetInstance().GetCapabilities(); @@ -71,11 +78,12 @@ Status ProfilerService::GetCapabilities(ServerContext* context, return Status::OK; } -PluginSessionPtr ProfilerService::SessionContext::CreatePluginSession( - const PluginServicePtr& pluginService, const ProfilerPluginConfig& pluginConfig) +PluginSessionPtr ProfilerService::SessionContext::CreatePluginSession(const PluginServicePtr& pluginService, + const ProfilerPluginConfig& pluginConfig) { auto name = pluginConfig.name(); CHECK_TRUE(pluginSessions.count(name) == 0, nullptr, "plugin name %s exists!", name.c_str()); + CHECK_TRUE(CheckPluginSha256(pluginConfig), nullptr, "SHA256 check failed!"); auto session = std::make_shared(pluginConfig, pluginService, dataRepeater); CHECK_NOTNULL(session, nullptr, "allocate plugin session for %s failed!", name.c_str()); @@ -87,22 +95,40 @@ namespace { constexpr uint32_t MAX_BUFFER_PAGES = 512 * 1024 * 1024 / 4096; } -bool ProfilerService::SessionContext::CheckBufferConfig(const ProfilerSessionConfig::BufferConfig& bufferConfig) +bool ProfilerService::SessionContext::CheckPluginSha256(const ProfilerPluginConfig& pluginConfig) +{ + std::string reqSha = pluginConfig.plugin_sha256(); + if (reqSha.size() > 0) { // only check when SHA256 provided in request + CHECK_NOTNULL(service, false, "profiler service null!"); + auto pluginSvc = service->pluginService_; + CHECK_NOTNULL(pluginSvc, false, "plugin service null!"); + + PluginInfo info = {}; + std::string name = pluginConfig.name(); + CHECK_TRUE(pluginSvc->GetPluginInfo(name, info), false, "get plugin info %s failed!", name.c_str()); + + std::string devSha = info.sha256; + CHECK_TRUE(devSha == reqSha, false, "SHA256 mismatch: %s, %s!", devSha.c_str(), reqSha.c_str()); + } + return true; +} + +bool ProfilerService::SessionContext::CheckBufferConfig(const BufferConfig& bufferConfig) { const uint32_t pages = bufferConfig.pages(); const auto policy = bufferConfig.policy(); - return (pages > 0 && pages <= MAX_BUFFER_PAGES) && (policy == ProfilerSessionConfig::BufferConfig::RECYCLE || - policy == ProfilerSessionConfig::BufferConfig::FLATTEN); + return (pages > 0 && pages <= MAX_BUFFER_PAGES) && + (policy == BufferConfig::RECYCLE || policy == BufferConfig::FLATTEN); } -PluginSessionPtr ProfilerService::SessionContext::CreatePluginSession( - const PluginServicePtr& pluginService, - const ProfilerPluginConfig& pluginConfig, - const ProfilerSessionConfig::BufferConfig& bufferConfig) +PluginSessionPtr ProfilerService::SessionContext::CreatePluginSession(const PluginServicePtr& pluginService, + const ProfilerPluginConfig& pluginConfig, + const BufferConfig& bufferConfig) { auto name = pluginConfig.name(); CHECK_TRUE(pluginSessions.count(name) == 0, nullptr, "plugin name %s exists!", name.c_str()); CHECK_TRUE(CheckBufferConfig(bufferConfig), nullptr, "buffer config invalid!"); + CHECK_TRUE(CheckPluginSha256(pluginConfig), nullptr, "SHA256 check failed!"); auto session = std::make_shared(pluginConfig, bufferConfig, pluginService, dataRepeater); CHECK_NOTNULL(session, nullptr, "allocate plugin session for %s failed!", name.c_str()); @@ -171,24 +197,128 @@ std::vector ProfilerService::SessionContext::UpdatePluginConfigs( return updates; } +bool ProfilerService::SessionContext::StartPluginSessions() +{ + std::unique_lock lock(sessionMutex); + + // if dataRepeater exists, reset it to usable state. + if (dataRepeater) { + dataRepeater->Reset(); + } + + // start demuxer take result thread + if (resultDemuxer != nullptr && sessionConfig.session_mode() == ProfilerSessionConfig::OFFLINE) { + resultDemuxer->StartTakeResults(); // start write file thread + uint32_t sampleDuration = sessionConfig.sample_duration(); + if (sampleDuration > 0) { + offlineTask = "stop-session-" + std::to_string(id); + std::weak_ptr weakCtx(shared_from_this()); + // start offline trace timeout task + ScheduleTaskManager::GetInstance().ScheduleTask( + offlineTask, + [weakCtx]() { + if (auto ctx = weakCtx.lock(); ctx != nullptr) { + ctx->StopPluginSessions(); + } + }, + std::chrono::milliseconds(0), // do not repeat + std::chrono::milliseconds(sampleDuration)); + + // keep_alive_time not set by client, but the sample_duration setted + if (sessionConfig.keep_alive_time() == 0) { + // use sample_duration add a little time to set keep_alive_time + SetKeepAliveTime(sampleDuration + MIN_SESSION_TIMEOUT_MS); + StartSessionExpireTask(); + } + } + } + + // start each plugin sessions + for (auto sessionEntry : pluginSessions) { + if (sessionEntry.second) { + sessionEntry.second->Start(); + } + } + return true; +} + +bool ProfilerService::SessionContext::StopPluginSessions() +{ + std::unique_lock lock(sessionMutex); + // stop each plugin sessions + for (auto sessionEntry : pluginSessions) { + if (sessionEntry.second) { + sessionEntry.second->Stop(); + } + } + + // stop demuxer take result thread + if (resultDemuxer && sessionConfig.session_mode() == ProfilerSessionConfig::OFFLINE) { + if (offlineTask.size() > 0) { + ScheduleTaskManager::GetInstance().UnscheduleTask(offlineTask); + } + resultDemuxer->StopTakeResults(); // stop write file thread + } + + // make sure FetchData thread exit + if (dataRepeater) { + dataRepeater->Close(); + } + return true; +} + +void ProfilerService::SessionContext::SetKeepAliveTime(uint32_t timeout) +{ + if (timeout > 0) { + timeoutTask = "timeout-session-" + std::to_string(id); + if (timeout < MIN_SESSION_TIMEOUT_MS) { + timeout = MIN_SESSION_TIMEOUT_MS; + } else if (timeout > MAX_SESSION_TIMEOUT_MS) { + timeout = MAX_SESSION_TIMEOUT_MS; + } + sessionConfig.set_keep_alive_time(timeout); + } +} + +void ProfilerService::SessionContext::StartSessionExpireTask() +{ + if (timeoutTask.size() > 0) { + ScheduleTaskManager::GetInstance().ScheduleTask(timeoutTask, + std::bind(&ProfilerService::RemoveSessionContext, service, id), + std::chrono::milliseconds(0), // do not repeat + std::chrono::milliseconds(sessionConfig.keep_alive_time())); + } +} + +void ProfilerService::SessionContext::StopSessionExpireTask() +{ + if (timeoutTask.size() > 0) { + ScheduleTaskManager::GetInstance().UnscheduleTask(timeoutTask); + } +} + Status ProfilerService::CreateSession(ServerContext* context, const ::CreateSessionRequest* request, ::CreateSessionResponse* response) { + CHECK_REQUEST_RESPONSE(context, request, response); HILOG_INFO(LOG_CORE, "CreateSession from '%s'", context->peer().c_str()); - CHECK_REQUEST_RESPONSE(request, response); CHECK_POINTER_NOTNULL(pluginService_, "plugin service not ready!"); + // check plugin configs HILOG_INFO(LOG_CORE, "CreateSession %d start", request->request_id()); const int nConfigs = request->plugin_configs_size(); CHECK_EXPRESSION_TRUE(nConfigs > 0, "no plugin configs!"); + // check buffer configs ProfilerSessionConfig sessionConfig = request->session_config(); const int nBuffers = sessionConfig.buffers_size(); CHECK_EXPRESSION_TRUE(nBuffers == 0 || nBuffers == 1 || nBuffers == nConfigs, "buffers config invalid!"); - std::vector bufferConfigs; + // copy buffer configs + std::vector bufferConfigs; if (nBuffers == 1) { + // if only one buffer config provided, all plugin use the same buffer config bufferConfigs.resize(nConfigs, sessionConfig.buffers(0)); } else if (nBuffers > 0) { bufferConfigs.assign(sessionConfig.buffers().begin(), sessionConfig.buffers().end()); @@ -220,11 +350,12 @@ Status ProfilerService::CreateSession(ServerContext* context, resultDemuxer->SetTraceWriter(traceWriter); } - // start prepare session context + // create session context auto ctx = std::make_shared(); CHECK_POINTER_NOTNULL(ctx, "alloc SessionContext failed!"); // fill fields of SessionContext + ctx->service = this; ctx->dataRepeater = dataRepeater; ctx->resultDemuxer = resultDemuxer; ctx->traceFileWriter = traceWriter; @@ -236,15 +367,22 @@ Status ProfilerService::CreateSession(ServerContext* context, // alloc new session id uint32_t sessionId = ++sessionIdCounter_; ctx->id = sessionId; + ctx->name = "session-" + std::to_string(sessionId); // add {sessionId, ctx} to map CHECK_EXPRESSION_TRUE(AddSessionContext(sessionId, ctx), "sessionId conflict!"); + if (sessionConfig.keep_alive_time()) { + // create schedule task for session timeout feature + ctx->SetKeepAliveTime(sessionConfig.keep_alive_time()); + ctx->StartSessionExpireTask(); + } + // prepare response data fields response->set_status(0); response->set_session_id(sessionId); - HILOG_INFO(LOG_CORE, "CreateSession %d done!", request->request_id()); + HILOG_INFO(LOG_CORE, "CreateSession %d %{public}u done!", request->request_id(), sessionId); return Status::OK; } @@ -264,8 +402,9 @@ ProfilerService::SessionContextPtr ProfilerService::GetSessionContext(uint32_t s std::unique_lock lock(sessionContextMutex_); auto it = sessionContext_.find(sessionId); if (it != sessionContext_.end()) { - HILOG_INFO(LOG_CORE, "use_count: %ld", it->second.use_count()); - return it->second; + auto ptr = it->second; + HILOG_INFO(LOG_CORE, "GetCtx %p use_count: %ld", ptr.get(), ptr.use_count()); + return ptr; } return nullptr; } @@ -275,7 +414,8 @@ bool ProfilerService::RemoveSessionContext(uint32_t sessionId) std::unique_lock lock(sessionContextMutex_); auto it = sessionContext_.find(sessionId); if (it != sessionContext_.end()) { - HILOG_INFO(LOG_CORE, "use_count: %ld", it->second.use_count()); + auto ptr = it->second; + HILOG_INFO(LOG_CORE, "DelCtx %p use_count: %ld", ptr.get(), ptr.use_count()); sessionContext_.erase(it); return true; } @@ -286,11 +426,11 @@ Status ProfilerService::StartSession(ServerContext* context, const ::StartSessionRequest* request, ::StartSessionResponse* response) { + CHECK_REQUEST_RESPONSE(context, request, response); HILOG_INFO(LOG_CORE, "StartSession from '%s'", context->peer().c_str()); - CHECK_REQUEST_RESPONSE(request, response); uint32_t sessionId = request->session_id(); - HILOG_INFO(LOG_CORE, "StartSession %d start", request->request_id()); + HILOG_INFO(LOG_CORE, "StartSession %d %{public}u start", request->request_id(), sessionId); // copy plugin configs from request std::vector pluginConfigsList; @@ -301,9 +441,8 @@ Status ProfilerService::StartSession(ServerContext* context, } std::vector nameList; - for (auto& config : pluginConfigsList) { - nameList.push_back(config.name()); - } + std::transform(pluginConfigsList.begin(), pluginConfigsList.end(), std::back_inserter(nameList), + [](auto& config) { return config.name(); }); auto ctx = GetSessionContext(sessionId); CHECK_POINTER_NOTNULL(ctx, "session_id invalid!"); @@ -317,26 +456,9 @@ Status ProfilerService::StartSession(ServerContext* context, // update plugin sessions CHECK_EXPRESSION_TRUE(ctx->UpdatePluginSessions(pluginService_, updates), "update sessions failed!"); - // if dataRepeater exists, reset it to usable state. - if (ctx->dataRepeater) { - ctx->dataRepeater->Reset(); - } - - // start demuxer take result thread - if (ctx->resultDemuxer) { - if (ctx->sessionConfig.session_mode() == ProfilerSessionConfig::OFFLINE) { - ctx->resultDemuxer->StartTakeResults(); - } - } - - // start each plugin sessions - for (auto sessionEntry : ctx->pluginSessions) { - if (sessionEntry.second) { - sessionEntry.second->Start(); - } - } - - HILOG_INFO(LOG_CORE, "StartSession %d done!", request->request_id()); + // start plugin sessions with configs + CHECK_EXPRESSION_TRUE(ctx->StartPluginSessions(), "start plugin sessions failed!"); + HILOG_INFO(LOG_CORE, "StartSession %d %{public}u done!", request->request_id(), sessionId); return Status::OK; } @@ -344,12 +466,16 @@ Status ProfilerService::FetchData(ServerContext* context, const ::FetchDataRequest* request, ServerWriter<::FetchDataResponse>* writer) { + CHECK_POINTER_NOTNULL(context, "context ptr invalid!"); + CHECK_POINTER_NOTNULL(request, "request ptr invalid!"); + CHECK_POINTER_NOTNULL(writer, "writer ptr invalid!"); + HILOG_INFO(LOG_CORE, "FetchData from '%s'", context->peer().c_str()); CHECK_POINTER_NOTNULL(request, "request invalid!"); CHECK_POINTER_NOTNULL(writer, "writer invalid!"); uint32_t sessionId = request->session_id(); - HILOG_INFO(LOG_CORE, "FetchData %d start", request->request_id()); + HILOG_INFO(LOG_CORE, "FetchData %d %{public}u start", request->request_id(), sessionId); auto ctx = GetSessionContext(sessionId); CHECK_POINTER_NOTNULL(ctx, "session_id invalid!"); @@ -367,7 +493,6 @@ Status ProfilerService::FetchData(ServerContext* context, auto dataRepeater = ctx->dataRepeater; CHECK_POINTER_NOTNULL(dataRepeater, "repeater invalid!"); - bool sendSuccess = false; while (1) { FetchDataResponse response; response.set_status(StatusCode::OK); @@ -390,7 +515,7 @@ Status ProfilerService::FetchData(ServerContext* context, HILOG_INFO(LOG_CORE, "no more data need to fill to response!"); } - sendSuccess = writer->Write(response); + bool sendSuccess = writer->Write(response); if (count <= 0 || !sendSuccess) { HILOG_INFO(LOG_CORE, "count = %d, sendSuccess = %d", count, sendSuccess); break; @@ -398,7 +523,7 @@ Status ProfilerService::FetchData(ServerContext* context, } } - HILOG_INFO(LOG_CORE, "FetchData %d done!", request->request_id()); + HILOG_INFO(LOG_CORE, "FetchData %d %{public}u done!", request->request_id(), sessionId); return Status::OK; } @@ -406,35 +531,17 @@ Status ProfilerService::StopSession(ServerContext* context, const ::StopSessionRequest* request, ::StopSessionResponse* response) { + CHECK_REQUEST_RESPONSE(context, request, response); HILOG_INFO(LOG_CORE, "StopSession from '%s'", context->peer().c_str()); - CHECK_REQUEST_RESPONSE(request, response); uint32_t sessionId = request->session_id(); - HILOG_INFO(LOG_CORE, "StopSession %d start", request->request_id()); + HILOG_INFO(LOG_CORE, "StopSession %d %{public}u start", request->request_id(), sessionId); auto ctx = GetSessionContext(sessionId); CHECK_POINTER_NOTNULL(ctx, "session_id invalid!"); - // stop each plugin sessions - for (auto sessionEntry : ctx->pluginSessions) { - if (sessionEntry.second) { - sessionEntry.second->Stop(); - } - } - - // stop demuxer take result thread - if (ctx->resultDemuxer) { - if (ctx->sessionConfig.session_mode() == ProfilerSessionConfig::OFFLINE) { - ctx->resultDemuxer->StopTakeResults(); - } - } - - // make sure FetchData thread exit - if (ctx->dataRepeater) { - ctx->dataRepeater->Close(); - } - - HILOG_INFO(LOG_CORE, "StopSession %d done!", request->request_id()); + CHECK_EXPRESSION_TRUE(ctx->StopPluginSessions(), "stop plugin sessions failed!"); + HILOG_INFO(LOG_CORE, "StopSession %d %{public}u done!", request->request_id(), sessionId); return Status::OK; } @@ -442,38 +549,103 @@ Status ProfilerService::DestroySession(ServerContext* context, const ::DestroySessionRequest* request, ::DestroySessionResponse* response) { + CHECK_REQUEST_RESPONSE(context, request, response); HILOG_INFO(LOG_CORE, "DestroySession from '%s'", context->peer().c_str()); - CHECK_REQUEST_RESPONSE(request, response); uint32_t sessionId = request->session_id(); - HILOG_INFO(LOG_CORE, "DestroySession %d start", request->request_id()); + HILOG_INFO(LOG_CORE, "DestroySession %d %{public}u start", request->request_id(), sessionId); - CHECK_EXPRESSION_TRUE(RemoveSessionContext(sessionId), "session_id invalid!"); - HILOG_INFO(LOG_CORE, "DestroySession %d done!", request->request_id()); + auto ctx = GetSessionContext(sessionId); + CHECK_POINTER_NOTNULL(ctx, "session_id invalid!"); + + CHECK_EXPRESSION_TRUE(RemoveSessionContext(sessionId), "remove session FAILED!"); + HILOG_INFO(LOG_CORE, "DestroySession %d %{public}u done!", request->request_id(), sessionId); return Status::OK; } +::grpc::Status ProfilerService::KeepSession(::grpc::ServerContext* context, + const ::KeepSessionRequest* request, + ::KeepSessionResponse* response) +{ + CHECK_REQUEST_RESPONSE(context, request, response); + HILOG_INFO(LOG_CORE, "KeepSession from '%s'", context->peer().c_str()); + + uint32_t sessionId = request->session_id(); + HILOG_INFO(LOG_CORE, "KeepSession %d %{public}u start", request->request_id(), sessionId); + + auto ctx = GetSessionContext(sessionId); + CHECK_POINTER_NOTNULL(ctx, "session_id invalid!"); + + // update keep alive time if keep_alive_time parameter provided + if (request->keep_alive_time()) { + ctx->SetKeepAliveTime(request->keep_alive_time()); + } + + // reschedule session timeout task + if (ctx->timeoutTask.size() > 0) { + ctx->StopSessionExpireTask(); + ctx->StartSessionExpireTask(); + } + HILOG_INFO(LOG_CORE, "KeepSession %d %{public}u done!", request->request_id(), sessionId); + return Status::OK; +} + +class LoggingInterceptor : public grpc::experimental::Interceptor { +public: + explicit LoggingInterceptor(grpc::experimental::ServerRpcInfo* info) : info_(info) {} + + void Intercept(experimental::InterceptorBatchMethods* methods) override + { + const char* method = info_->method(); + if (methods->QueryInterceptionHookPoint(experimental::InterceptionHookPoints::POST_SEND_MESSAGE)) { + HILOG_DEBUG(LOG_CORE, "POST_SEND_MESSAGE method: %s", method); + } else if (methods->QueryInterceptionHookPoint(experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) { + HILOG_DEBUG(LOG_CORE, "POST_RECV_MESSAGE method: %s", method); + } + methods->Proceed(); + } + +private: + grpc::experimental::ServerRpcInfo* info_ = nullptr; +}; + +struct InterceptorFactory : public grpc::experimental::ServerInterceptorFactoryInterface { +protected: + grpc::experimental::Interceptor* CreateServerInterceptor(grpc::experimental::ServerRpcInfo* info) override + { + return new LoggingInterceptor(info); + } +}; + bool ProfilerService::StartService(const std::string& listenUri) { if (listenUri == "") { + HILOG_WARN(LOG_CORE, "listenUri empty!"); return false; } + std::vector> interceptorFactories; + interceptorFactories.emplace_back(std::make_unique()); + ServerBuilder builder; + builder.experimental().SetInterceptorCreators(std::move(interceptorFactories)); builder.AddListeningPort(listenUri, grpc::InsecureServerCredentials()); builder.RegisterService(this); - server_ = builder.BuildAndStart(); - CHECK_NOTNULL(server_, false, "start service on %s failed!", listenUri.c_str()); + auto server = builder.BuildAndStart(); + CHECK_NOTNULL(server, false, "start service on %s failed!", listenUri.c_str()); HILOG_INFO(LOG_CORE, "Server listening on %s", listenUri.c_str()); + server_ = std::move(server); return true; } void ProfilerService::WaitServiceDone() { if (server_) { + HILOG_INFO(LOG_CORE, "waiting Server..."); server_->Wait(); + HILOG_INFO(LOG_CORE, "Server done!"); } } @@ -481,5 +653,6 @@ void ProfilerService::StopService() { if (server_) { server_->Shutdown(); + HILOG_INFO(LOG_CORE, "Server stop done!"); } } diff --git a/device/services/profiler_service/src/result_demuxer.cpp b/device/services/profiler_service/src/result_demuxer.cpp index 9cb734d7d..7e6f48188 100644 --- a/device/services/profiler_service/src/result_demuxer.cpp +++ b/device/services/profiler_service/src/result_demuxer.cpp @@ -17,21 +17,25 @@ #include #include "logging.h" -#define CHECK_POINTER_NOTNULL(ptr) \ - if (ptr == nullptr) { \ +#define CHECK_POINTER_NOTNULL(ptr) \ + if (ptr == nullptr) { \ HILOG_WARN(LOG_CORE, "%s: FAILED, %s is null!", __func__, #ptr); \ - return false; \ + return false; \ } -#define CHECK_THREAD_ID_VALID(t) \ - if (t.get_id() == std::thread::id()) { \ +#define CHECK_THREAD_ID_VALID(t) \ + if (t.get_id() == std::thread::id()) { \ HILOG_WARN(LOG_CORE, "%s: FAILED, %s id invalid!", __func__, #t); \ - return false; \ + return false; \ } +namespace { +constexpr auto DEFAULT_FLUSH_INTERVAL = std::chrono::milliseconds(1000); +} // namespace + ResultDemuxer::ResultDemuxer(const ProfilerDataRepeaterPtr& dataRepeater) + : dataRepeater_(dataRepeater), flushInterval_(DEFAULT_FLUSH_INTERVAL) { - dataRepeater_ = dataRepeater; } ResultDemuxer::~ResultDemuxer() @@ -49,6 +53,11 @@ void ResultDemuxer::SetTraceWriter(const TraceFileWriterPtr& traceWriter) traceWriter_ = traceWriter; } +void ResultDemuxer::SetFlushInterval(std::chrono::milliseconds interval) +{ + flushInterval_ = interval; +} + bool ResultDemuxer::StartTakeResults() { CHECK_POINTER_NOTNULL(dataRepeater_); @@ -65,6 +74,10 @@ bool ResultDemuxer::StopTakeResults() CHECK_POINTER_NOTNULL(dataRepeater_); CHECK_THREAD_ID_VALID(demuxerThread_); + if (traceWriter_) { + traceWriter_->Flush(); + } + dataRepeater_->PutPluginData(nullptr); if (demuxerThread_.joinable()) { demuxerThread_.join(); @@ -79,6 +92,7 @@ void ResultDemuxer::TakeResults() } HILOG_INFO(LOG_CORE, "TakeResults thread %d, start!", gettid()); + lastFlushTime_ = std::chrono::steady_clock::now(); while (1) { auto pluginData = dataRepeater_->TakePluginData(); if (!pluginData) { @@ -87,9 +101,17 @@ void ResultDemuxer::TakeResults() if (traceWriter_) { traceWriter_->Write(*pluginData); + auto currentTime = std::chrono::steady_clock::now(); + auto elapsedTime = std::chrono::duration_cast(currentTime - lastFlushTime_); + if (elapsedTime >= flushInterval_) { + traceWriter_->Flush(); + lastFlushTime_ = currentTime; + } } else { HILOG_WARN(LOG_CORE, "no writer, drop data!"); } } + traceWriter_->Flush(); + traceWriter_->Finish(); HILOG_INFO(LOG_CORE, "TakeResults thread %d, exit!", gettid()); } diff --git a/device/services/profiler_service/src/result_demuxer.h b/device/services/profiler_service/src/result_demuxer.h old mode 100755 new mode 100644 index 5e22e3151..a4bfc9fe2 --- a/device/services/profiler_service/src/result_demuxer.h +++ b/device/services/profiler_service/src/result_demuxer.h @@ -15,6 +15,7 @@ #ifndef RESULT_DEMUXER_H #define RESULT_DEMUXER_H +#include #include #include "logging.h" @@ -31,6 +32,8 @@ public: void SetTraceWriter(const TraceFileWriterPtr& traceWriter); + void SetFlushInterval(std::chrono::milliseconds interval); + bool StartTakeResults(); bool StopTakeResults(); @@ -41,7 +44,9 @@ private: private: TraceFileWriterPtr traceWriter_ = nullptr; ProfilerDataRepeaterPtr dataRepeater_ = nullptr; - std::thread demuxerThread_; + std::chrono::milliseconds flushInterval_ {}; + std::chrono::steady_clock::time_point lastFlushTime_ {}; + std::thread demuxerThread_ {}; DISALLOW_COPY_AND_MOVE(ResultDemuxer); }; diff --git a/device/services/profiler_service/src/trace_file_header.h b/device/services/profiler_service/src/trace_file_header.h new file mode 100644 index 000000000..637b1e892 --- /dev/null +++ b/device/services/profiler_service/src/trace_file_header.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef TRACE_FILE_HEADER_H +#define TRACE_FILE_HEADER_H + +#include + +struct TraceFileHeader { + static constexpr uint32_t HEADER_SIZE = 1024; // 预留了一些空间,方便后续在头部添加字段 + static constexpr uint32_t SHA256_SIZE = 256 / 8; + static constexpr uint64_t HEADER_MAGIC = 0x464F5250534F484FuLL; + static constexpr uint32_t V_MAJOR = 0x0001; + static constexpr uint32_t V_MAJOR_BITS = 16; + static constexpr uint32_t V_MINOR = 0x0000; + static constexpr uint32_t TRACE_VERSION = (V_MAJOR << V_MAJOR_BITS) | V_MINOR; + + struct HeaderData { + uint64_t magic_ = HEADER_MAGIC; // 魔数,用于区分离线文件 + uint64_t length_ = HEADER_SIZE; // 总长度,可用于检验文件是否被截断; + uint32_t version_ = TRACE_VERSION; + uint32_t segments_ = 0; // 载荷数据中的段个数, 段个数为偶数,一个描述长度 L,一个描述接下来的数据 V + uint8_t sha256_[SHA256_SIZE] = {}; // 载荷数据 的 SHA256 ,用于校验 载荷数据是否完整; + } __attribute__((packed)); + HeaderData data_ = {}; + uint8_t padding_[HEADER_SIZE - sizeof(data_)] = {}; +}; + +#endif // TRACE_FILE_HEADER_H \ No newline at end of file diff --git a/device/services/profiler_service/src/trace_file_helper.cpp b/device/services/profiler_service/src/trace_file_helper.cpp new file mode 100644 index 000000000..b5f027fb6 --- /dev/null +++ b/device/services/profiler_service/src/trace_file_helper.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "trace_file_helper.h" + +#include +#include +#include +#include +#include "logging.h" + +TraceFileHelper::TraceFileHelper() + : shaCtx_(std::make_shared()) +{ + SHA256_Init(shaCtx_.get()); +} + +TraceFileHelper::~TraceFileHelper() +{ +} + +bool TraceFileHelper::AddSegment(const uint8_t data[], uint32_t size) +{ + if (size > std::numeric_limits::max() - header_.data_.length_ - sizeof(size)) { + return false; + } + int retval = 0; + header_.data_.segments_ += 1; + + header_.data_.length_ += size; + retval = SHA256_Update(shaCtx_.get(), data, size); + CHECK_TRUE(retval, false, "[%u] SHA256_Update FAILED, s:%u, d:%p!", header_.data_.segments_, size, data); + return true; +} + +bool TraceFileHelper::Finish() +{ + int retval = 0; + retval = SHA256_Final(header_.data_.sha256_, shaCtx_.get()); + CHECK_TRUE(retval, false, "[%u] SHA256_Final FAILED!", header_.data_.segments_); + return true; +} + +bool TraceFileHelper::Update(TraceFileHeader& header) +{ + CHECK_TRUE(Finish(), false, "Finish FAILED!"); + if (memcpy_s(&header, sizeof(header), &header_, sizeof(header)) != 0) { + return false; + } + return true; +} + +bool TraceFileHelper::Validate(const TraceFileHeader& header) +{ + CHECK_TRUE(Finish(), false, "Finish FAILED!"); + return memcmp(&header_, &header, sizeof(header_)) == 0; +} diff --git a/device/services/profiler_service/src/trace_file_helper.h b/device/services/profiler_service/src/trace_file_helper.h new file mode 100644 index 000000000..eacd6efc3 --- /dev/null +++ b/device/services/profiler_service/src/trace_file_helper.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 TRACE_FILER_HELPER_H +#define TRACE_FILER_HELPER_H + +#include +#include +#include "openssl/sha.h" +#include "trace_file_header.h" + +class TraceFileHelper { +public: + TraceFileHelper(); + ~TraceFileHelper(); + + bool AddSegment(const uint8_t data[], uint32_t size); + + bool Update(TraceFileHeader& header); + + bool Validate(const TraceFileHeader& header); + +private: + bool Finish(); + +private: + TraceFileHeader header_ = {}; + std::shared_ptr shaCtx_ = nullptr; +}; + +#endif // TRACE_FILER_HELPER_H \ No newline at end of file diff --git a/device/services/profiler_service/src/trace_file_reader.cpp b/device/services/profiler_service/src/trace_file_reader.cpp index e5440dd51..6ea882d47 100644 --- a/device/services/profiler_service/src/trace_file_reader.cpp +++ b/device/services/profiler_service/src/trace_file_reader.cpp @@ -27,14 +27,33 @@ TraceFileReader::~TraceFileReader() } } +TraceFileHeader TraceFileReader::GetHeader() const +{ + return header_; +} + +bool TraceFileReader::ValidateHeader() +{ + return helper_.Validate(header_); +} + bool TraceFileReader::Open(const std::string& path) { stream_.open(path, std::ios_base::in | std::ios_base::binary); CHECK_TRUE(stream_.is_open(), false, "open %s failed, %s!", path.c_str(), strerror(errno)); + + stream_.read(reinterpret_cast(&header_), sizeof(header_)); + CHECK_TRUE(stream_, false, "read header from %s failed!", path_.c_str()); + path_ = path; return true; } +static size_t GetReadPos(std::ifstream& stream) +{ + return static_cast(stream.tellg()); +} + long TraceFileReader::Read(MessageLite& message) { CHECK_TRUE(stream_.is_open(), 0, "binary file %s not open or open failed!", path_.c_str()); @@ -42,21 +61,34 @@ long TraceFileReader::Read(MessageLite& message) uint32_t msgLen = 0; stream_.read(reinterpret_cast(&msgLen), sizeof(msgLen)); - CHECK_TRUE(stream_, 0, "read msg head failed!"); + CHECK_TRUE(stream_, 0, "read msg length from %s (offset %zu) failed!", path_.c_str(), GetReadPos(stream_)); + CHECK_TRUE(helper_.AddSegment(reinterpret_cast(&msgLen), sizeof(msgLen)), + 0, "Add payload for message length failed!"); std::vector msgData(msgLen); stream_.read(msgData.data(), msgData.size()); - CHECK_TRUE(stream_, 0, "read msg body failed!"); + CHECK_TRUE(stream_, 0, "read msg bytes from %s (offset %zu) failed!", path_.c_str(), GetReadPos(stream_)); + CHECK_TRUE(helper_.AddSegment(reinterpret_cast(msgData.data()), msgData.size()), + 0, "Add payload for message bytes failed!"); CHECK_TRUE(message.ParseFromArray(msgData.data(), msgData.size()), 0, "ParseFromArray failed!"); return sizeof(msgLen) + msgData.size(); } -long TraceFileReader::Read(BytePtr data, long size) +long TraceFileReader::Read(uint8_t buffer[], uint32_t bufferSize) { CHECK_TRUE(stream_.is_open(), 0, "binary file %s not open or open failed!", path_.c_str()); CHECK_TRUE(!stream_.eof(), 0, "no more data in file %s stream", path_.c_str()); - CHECK_TRUE(stream_.read(reinterpret_cast(data), size), 0, "binary file %s write raw buffer data failed!", - path_.c_str()); - return size; + + uint32_t dataLen = 0; + stream_.read(reinterpret_cast(&dataLen), sizeof(dataLen)); + CHECK_TRUE(stream_, 0, "read data length from file %s (offset %zu) failed!", path_.c_str(), GetReadPos(stream_)); + CHECK_TRUE(bufferSize >= dataLen, 0, "buffer size does not enough to read data bytes!"); + CHECK_TRUE(helper_.AddSegment(reinterpret_cast(&dataLen), sizeof(dataLen)), + 0, "Add payload for data length failed!"); + + stream_.read(reinterpret_cast(buffer), dataLen); + CHECK_TRUE(stream_, 0, "read data bytes from %s (offset %zu) failed!", path_.c_str(), GetReadPos(stream_)); + CHECK_TRUE(helper_.AddSegment(buffer, dataLen), 0, "Add payload for data bytes failed!"); + return dataLen; } diff --git a/device/services/profiler_service/src/trace_file_reader.h b/device/services/profiler_service/src/trace_file_reader.h index 9247cd1f4..ea1c47a11 100644 --- a/device/services/profiler_service/src/trace_file_reader.h +++ b/device/services/profiler_service/src/trace_file_reader.h @@ -17,7 +17,7 @@ #include "logging.h" #include "nocopyable.h" -#include "writer.h" +#include "trace_file_helper.h" #include #include @@ -36,13 +36,17 @@ public: long Read(MessageLite& message); - using BytePtr = int8_t *; + long Read(uint8_t buffer[], uint32_t bufferSize); - long Read(BytePtr data, long size); + bool ValidateHeader(); + + TraceFileHeader GetHeader() const; private: - std::string path_; - std::ifstream stream_; + std::string path_ {}; + std::ifstream stream_ {}; + TraceFileHeader header_ {}; + TraceFileHelper helper_ {}; DISALLOW_COPY_AND_MOVE(TraceFileReader); }; diff --git a/device/services/profiler_service/src/trace_file_writer.cpp b/device/services/profiler_service/src/trace_file_writer.cpp index 590895ae8..687fecec2 100644 --- a/device/services/profiler_service/src/trace_file_writer.cpp +++ b/device/services/profiler_service/src/trace_file_writer.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ #include "trace_file_writer.h" + +#include #include #include "logging.h" @@ -20,7 +22,7 @@ using CharPtr = std::unique_ptr::pointer; using ConstCharPtr = std::unique_ptr::pointer; -TraceFileWriter::TraceFileWriter(const std::string& path) : path_(path) +TraceFileWriter::TraceFileWriter(const std::string& path) : path_(path), writeBytes_(0) { Open(path); } @@ -33,46 +35,74 @@ TraceFileWriter::~TraceFileWriter() } } +std::string TraceFileWriter::Path() const +{ + return path_; +} + bool TraceFileWriter::Open(const std::string& path) { stream_.open(path, std::ios_base::out | std::ios_base::binary); CHECK_TRUE(stream_.is_open(), false, "open %s failed, %s!", path.c_str(), strerror(errno)); + + // write initial header, makes file write position move forward + stream_.write(reinterpret_cast(&header_), sizeof(header_)); + CHECK_TRUE(stream_, 0, "write initial header to %s failed!", path_.c_str()); path_ = path; return true; } long TraceFileWriter::Write(const void* data, size_t size) { + uint32_t dataLen = size; CHECK_TRUE(stream_.is_open(), 0, "binary file %s not open or open failed!", path_.c_str()); - uint32_t dataLen = size; + // write 4B data length. stream_.write(reinterpret_cast(&dataLen), sizeof(dataLen)); CHECK_TRUE(stream_, 0, "binary file %s write raw buffer size failed!", path_.c_str()); + CHECK_TRUE(helper_.AddSegment(reinterpret_cast(&size), sizeof(size)), + 0, "Add payload for size %u FAILED!", dataLen); + // write data bytes stream_.write(reinterpret_cast(data), size); CHECK_TRUE(stream_, 0, "binary file %s write raw buffer data failed!", path_.c_str()); - return sizeof(dataLen) + size; + CHECK_TRUE(helper_.AddSegment(reinterpret_cast(const_cast(data)), size), + 0, "Add payload for data bytes %zu FAILED!", size); + + long nbytes = sizeof(dataLen) + size; + writeBytes_ += nbytes; + ++writeCount_; + return nbytes; } long TraceFileWriter::Write(const MessageLite& message) { - CHECK_TRUE(stream_.is_open(), 0, "binary file %s not open or open failed!", path_.c_str()); - uint32_t msgLen = message.ByteSizeLong(); - stream_.write(reinterpret_cast(&msgLen), sizeof(msgLen)); - CHECK_TRUE(stream_, 0, "write msg head failed!"); - + // serialize message to bytes array std::vector msgData(message.ByteSizeLong()); CHECK_TRUE(message.SerializeToArray(msgData.data(), msgData.size()), 0, "SerializeToArray failed!"); - stream_.write(msgData.data(), msgData.size()); - CHECK_TRUE(stream_, 0, "write msg body failed!"); - HILOG_DEBUG(LOG_CORE, "write %zu bytes to file %s", sizeof(msgLen) + msgLen, path_.c_str()); - return sizeof(msgLen) + message.ByteSizeLong(); + return Write(msgData.data(), msgData.size()); +} + +bool TraceFileWriter::Finish() +{ + // update header info + helper_.Update(header_); + + // move write position to begin of file + stream_.seekp(0); + CHECK_TRUE(stream_, 0, "seek write position to head for %s failed!", path_.c_str()); + + // write final header + stream_.write(reinterpret_cast(&header_), sizeof(header_)); + CHECK_TRUE(stream_, 0, "write final header to %s failed!", path_.c_str()); + return true; } bool TraceFileWriter::Flush() { CHECK_TRUE(stream_.is_open(), false, "binary file %s not open or open failed!", path_.c_str()); CHECK_TRUE(stream_.flush(), false, "binary file %s flush failed!", path_.c_str()); + HILOG_INFO(LOG_CORE, "flush: %s, bytes: %" PRIu64 ", count: %" PRIu64, path_.c_str(), writeBytes_, writeCount_); return true; } diff --git a/device/services/profiler_service/src/trace_file_writer.h b/device/services/profiler_service/src/trace_file_writer.h old mode 100755 new mode 100644 index 732874ad4..ee6858cba --- a/device/services/profiler_service/src/trace_file_writer.h +++ b/device/services/profiler_service/src/trace_file_writer.h @@ -15,14 +15,16 @@ #ifndef TRANCE_FILE_WRITER_H #define TRANCE_FILE_WRITER_H -#include "logging.h" -#include "nocopyable.h" -#include "writer.h" - +#include #include #include #include +#include "logging.h" +#include "nocopyable.h" +#include "trace_file_helper.h" +#include "writer.h" + using google::protobuf::MessageLite; class TraceFileWriter : public Writer { @@ -31,6 +33,8 @@ public: ~TraceFileWriter(); + std::string Path() const; + bool Open(const std::string& path); long Write(const MessageLite& message); @@ -39,9 +43,15 @@ public: bool Flush() override; + bool Finish(); + private: - std::string path_; - std::ofstream stream_; + std::string path_ {}; + std::ofstream stream_ {}; + uint64_t writeBytes_ = 0; + uint64_t writeCount_ = 0; + TraceFileHeader header_ {}; + TraceFileHelper helper_ {}; DISALLOW_COPY_AND_MOVE(TraceFileWriter); }; diff --git a/device/services/profiler_service/test/BUILD.gn b/device/services/profiler_service/test/BUILD.gn old mode 100755 new mode 100644 index 5166fd3dc..e5115a195 --- a/device/services/profiler_service/test/BUILD.gn +++ b/device/services/profiler_service/test/BUILD.gn @@ -16,14 +16,14 @@ import("../../../base/config.gni") module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" config("module_private_config") { - visibility = [":*"] + visibility = [ ":*" ] } config("cflags_config") { cflags = [ "-Wno-sign-compare", "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members + "-Dprivate=public", #allow test code access private members ] } @@ -41,24 +41,18 @@ ohos_unittest("profiler_service_ut") { ] deps = [ "../:profiler_service", + "../../../base:hiprofiler_base", "//third_party/googletest:gtest", ] include_dirs = [ "//third_party/googletest/googletest/include/gtest" ] configs = [ ":cflags_config" ] - #cflags = [ - # "-Wno-sign-compare", - # "-Wno-inconsistent-missing-override", - # "-Dprivate=public", #allow test code access private members - #] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" } group("unittest") { testonly = true - deps = [ - ":profiler_service_ut", - ] + deps = [ ":profiler_service_ut" ] } diff --git a/device/services/profiler_service/test/moduletest/profiler_service_test.cpp b/device/services/profiler_service/test/moduletest/profiler_service_test.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/test/unittest/plugin_service_stubs.cpp b/device/services/profiler_service/test/unittest/plugin_service_stubs.cpp old mode 100755 new mode 100644 index 534856aeb..ea134bd9a --- a/device/services/profiler_service/test/unittest/plugin_service_stubs.cpp +++ b/device/services/profiler_service/test/unittest/plugin_service_stubs.cpp @@ -110,12 +110,10 @@ bool PluginServiceStub::GetRemoveResult() PluginService::PluginService() { - pluginIdAutoIncrease_ = 0; + pluginIdCounter_ = 0; serviceEntry_ = NULL; pluginServiceImpl_ = NULL; pluginCommandBuilder_ = NULL; - readShareMemoryThreadStatus_ = READ_SHARE_MEMORY_UNSPECIFIED; - waitForCommandId_ = 0; } PluginService::~PluginService() {} @@ -181,8 +179,8 @@ bool PluginService::DestroyPluginSession(const std::string& pluginName) bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) { if (nameIndex_.find(pluginInfo.name) == nameIndex_.end()) { // add new plugin - while (pluginContext_.find(pluginIdAutoIncrease_) != pluginContext_.end()) { - pluginIdAutoIncrease_++; + while (pluginContext_.find(pluginIdCounter_) != pluginContext_.end()) { + pluginIdCounter_++; } ProfilerPluginCapability capability; @@ -193,19 +191,19 @@ bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) return false; } - pluginContext_[pluginIdAutoIncrease_].path = pluginInfo.path; - pluginContext_[pluginIdAutoIncrease_].context = pluginInfo.context; - pluginContext_[pluginIdAutoIncrease_].config.set_name(pluginInfo.name); - pluginContext_[pluginIdAutoIncrease_].config.set_plugin_sha256(pluginInfo.sha256); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState = std::make_shared(); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState->set_name(pluginInfo.name); - pluginContext_[pluginIdAutoIncrease_].profilerPluginState->set_state(ProfilerPluginState::REGISTERED); + pluginContext_[pluginIdCounter_].path = pluginInfo.path; + pluginContext_[pluginIdCounter_].context = pluginInfo.context; + pluginContext_[pluginIdCounter_].config.set_name(pluginInfo.name); + pluginContext_[pluginIdCounter_].config.set_plugin_sha256(pluginInfo.sha256); + pluginContext_[pluginIdCounter_].profilerPluginState = std::make_shared(); + pluginContext_[pluginIdCounter_].profilerPluginState->set_name(pluginInfo.name); + pluginContext_[pluginIdCounter_].profilerPluginState->set_state(ProfilerPluginState::REGISTERED); - pluginContext_[pluginIdAutoIncrease_].sha256 = pluginInfo.sha256; - pluginContext_[pluginIdAutoIncrease_].bufferSizeHint = pluginInfo.bufferSizeHint; + pluginContext_[pluginIdCounter_].sha256 = pluginInfo.sha256; + pluginContext_[pluginIdCounter_].bufferSizeHint = pluginInfo.bufferSizeHint; - nameIndex_[pluginInfo.name] = pluginIdAutoIncrease_; - pluginIdAutoIncrease_++; + nameIndex_[pluginInfo.name] = pluginIdCounter_; + pluginIdCounter_++; } else { // update sha256 or bufferSizeHint uint32_t idx = nameIndex_[pluginInfo.name]; @@ -221,6 +219,25 @@ bool PluginService::AddPluginInfo(const PluginInfo& pluginInfo) return true; } +bool PluginService::GetPluginInfo(const std::string& pluginName, PluginInfo& pluginInfo) +{ + uint32_t pluginId = 0; + + auto itName = nameIndex_.find(pluginName); + CHECK_TRUE(itName != nameIndex_.end(), false, "plugin name %s not found!", pluginName.c_str()); + pluginId = itName->second; + + auto itId = pluginContext_.find(pluginId); + CHECK_TRUE(itId != pluginContext_.end(), false, "plugin id %d not found!", pluginId); + + pluginInfo.id = pluginId; + pluginInfo.name = itId->second.name; + pluginInfo.path = itId->second.path; + pluginInfo.sha256 = itId->second.sha256; + pluginInfo.bufferSizeHint = itId->second.bufferSizeHint; + return true; +} + bool PluginService::RemovePluginInfo(const PluginInfo& pluginInfo) { if (pluginContext_.find(pluginInfo.id) == pluginContext_.end()) { diff --git a/device/services/profiler_service/test/unittest/plugin_service_stubs.h b/device/services/profiler_service/test/unittest/plugin_service_stubs.h old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/test/unittest/plugin_session_test.cpp b/device/services/profiler_service/test/unittest/plugin_session_test.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/test/unittest/profiler_capability_manager_test.cpp b/device/services/profiler_service/test/unittest/profiler_capability_manager_test.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/test/unittest/profiler_data_repeater_test.cpp b/device/services/profiler_service/test/unittest/profiler_data_repeater_test.cpp old mode 100755 new mode 100644 diff --git a/device/services/profiler_service/test/unittest/profiler_service_test.cpp b/device/services/profiler_service/test/unittest/profiler_service_test.cpp index 8ac2d8196..c009cee03 100644 --- a/device/services/profiler_service/test/unittest/profiler_service_test.cpp +++ b/device/services/profiler_service/test/unittest/profiler_service_test.cpp @@ -16,6 +16,8 @@ #define final // disable final keyword #define LOG_TAG "ProfilerServiceTest" +#include +#include #include #include #include @@ -25,10 +27,53 @@ #include "profiler_capability_manager.h" #include "profiler_data_repeater.h" #include "profiler_service.h" +#include "schedule_task_manager.h" using namespace testing::ext; using ProfilerServicePtr = STD_PTR(shared, ProfilerService); + +namespace { +constexpr int BATCH_SIZE = 100; +constexpr int ROUND_COUNT = 200; +constexpr int FETCH_DATA_DELAY_US = 100 * 1000; +constexpr int TEST_SESSION_TIMEOUT_MS = 100; + +class Timer { +public: + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + + Timer() + : startTime_(Now()) + { + } + + ~Timer() + { + } + + long ElapsedUs() + { + auto currentTime = Now(); + return std::chrono::duration_cast(currentTime - startTime_).count(); + } + + void Reset() + { + startTime_ = Now(); + } + +protected: + TimePoint Now() + { + return Clock::now(); + } + +private: + TimePoint startTime_; +}; + class ProfilerServiceTest : public ::testing::Test { protected: PluginServicePtr pluginService_; @@ -36,7 +81,7 @@ protected: PluginInfo pluginInfo; std::unique_ptr context_; - std::atomic requestCounter{0}; + std::atomic requestCounter = 0; static void SetUpTestCase() {} static void TearDownTestCase() {} @@ -63,6 +108,15 @@ protected: ProfilerCapabilityManager::GetInstance().pluginCapabilities_.clear(); } + void AddPlugin(const std::string& pluginName) + { + PluginInfo pluginInfo; + pluginInfo.name = pluginName; + if (pluginService_) { + pluginService_->AddPluginInfo(pluginInfo); + } + } + grpc::Status StartSession(uint32_t sessionId) { StartSessionRequest request; @@ -93,7 +147,46 @@ protected: return service_->DestroySession(context_.get(), &request, &response); } - void FetchDataOnlineSet(uint32_t& sessionId); + uint32_t CreateOnlineSession() + { + CreateSessionRequest request; + CreateSessionResponse response; + + auto sessionConfig = request.mutable_session_config(); + CHECK_NOTNULL(sessionConfig, 0, "request.mutable_session_config() return nullptr!"); + + sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); + auto pluginConfig = request.add_plugin_configs(); + CHECK_NOTNULL(pluginConfig, 0, "request.add_plugin_configs() return nullptr!"); + + pluginConfig->set_name(pluginInfo.name); + request.set_request_id(++requestCounter); + auto status = service_->CreateSession(context_.get(), &request, &response); + CHECK_TRUE(status.error_code() == grpc::StatusCode::OK, 0, "create session FAILED!"); + + return response.session_id(); + } + + uint32_t CreateOfflineSession() + { + CreateSessionRequest request; + CreateSessionResponse response; + + auto sessionConfig = request.mutable_session_config(); + CHECK_NOTNULL(sessionConfig, 0, "request.mutable_session_config() return nullptr!"); + + sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); + sessionConfig->set_result_file("trace.bin"); + auto pluginConfig = request.add_plugin_configs(); + CHECK_NOTNULL(pluginConfig, 0, "request.add_plugin_configs() return nullptr!"); + + pluginConfig->set_name(pluginInfo.name); + request.set_request_id(++requestCounter); + auto status = service_->CreateSession(context_.get(), &request, &response); + CHECK_TRUE(status.error_code() == grpc::StatusCode::OK, 0, "create session FAILED!"); + + return response.session_id(); + } }; /** @@ -108,7 +201,7 @@ HWTEST_F(ProfilerServiceTest, CtorDtor, TestSize.Level1) /** * @tc.name: server - * @tc.desc: get plugin capabilities. + * @tc.desc: get plugin capabilities normal. * @tc.type: FUNC */ HWTEST_F(ProfilerServiceTest, GetCapabilities, TestSize.Level1) @@ -117,25 +210,152 @@ HWTEST_F(ProfilerServiceTest, GetCapabilities, TestSize.Level1) ASSERT_NE(context_, nullptr); GetCapabilitiesRequest request; - GetCapabilitiesResponse response; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); ProfilerPluginCapability cap; cap.set_name("cap1"); - ProfilerCapabilityManager::GetInstance().AddCapability(cap); request.set_request_id(++requestCounter); - auto status = service_->GetCapabilities(context_.get(), &request, &response); + auto status = service_->GetCapabilities(context_.get(), &request, response.get()); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - EXPECT_GT(response.capabilities_size(), 0); - HILOG_DEBUG(LOG_CORE, "GetCapabilities, capabilities_size = %d", response.capabilities_size()); + EXPECT_EQ(response->capabilities_size(), ProfilerCapabilityManager::GetInstance().GetCapabilities().size()); + + int capSize = response->capabilities_size(); + EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(cap)); + + request.set_request_id(++requestCounter); + response = std::make_unique(); + status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + EXPECT_EQ(response->capabilities_size(), ProfilerCapabilityManager::GetInstance().GetCapabilities().size()); + EXPECT_EQ(response->capabilities_size(), capSize + 1); } /** * @tc.name: server - * @tc.desc: create session. + * @tc.desc: get plugin capabilities normal. * @tc.type: FUNC */ -HWTEST_F(ProfilerServiceTest, CreateSession, TestSize.Level1) +HWTEST_F(ProfilerServiceTest, GetCapabilitiesAfterRemove, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + GetCapabilitiesRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + ProfilerPluginCapability cap; + cap.set_name("cap1"); + + request.set_request_id(++requestCounter); + auto status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + EXPECT_EQ(response->capabilities_size(), ProfilerCapabilityManager::GetInstance().GetCapabilities().size()); + + int capSize = response->capabilities_size(); + EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(cap)); + + request.set_request_id(++requestCounter); + response = std::make_unique(); + status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + EXPECT_EQ(response->capabilities_size(), capSize + 1); + + EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().RemoveCapability(cap.name())); + response = std::make_unique(); + status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + EXPECT_EQ(response->capabilities_size(), ProfilerCapabilityManager::GetInstance().GetCapabilities().size()); + EXPECT_EQ(response->capabilities_size(), capSize); +} + + +/** + * @tc.name: server + * @tc.desc: get plugin capabilities batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, GetCapabilitiesBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + GetCapabilitiesRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + request.set_request_id(++requestCounter); + auto status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + EXPECT_EQ(response->capabilities_size(), ProfilerCapabilityManager::GetInstance().GetCapabilities().size()); + + for (int i = 0; i < BATCH_SIZE; i++) { + ProfilerPluginCapability cap; + cap.set_name("cap_" + std::to_string(i)); + EXPECT_TRUE(ProfilerCapabilityManager::GetInstance().AddCapability(cap)); + } + + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { + request.set_request_id(++requestCounter); + response = std::make_unique(); + status = service_->GetCapabilities(context_.get(), &request, response.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + } + auto timeCost = timer.ElapsedUs(); + printf("GetCapabilities %d time cost %ldus.\n", ROUND_COUNT, timeCost); +} + +/** + * @tc.name: server + * @tc.desc: get plugin capabilities with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, GetCapabilitiesWithInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + GetCapabilitiesRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->GetCapabilities(nullptr, &request, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: get plugin capabilities with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, GetCapabilitiesWithInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + GetCapabilitiesRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->GetCapabilities(context_.get(), nullptr, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->GetCapabilities(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->GetCapabilities(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: create session without plugin config. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, CreateSessionNoPluginConfig, TestSize.Level1) { ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); @@ -145,6 +365,20 @@ HWTEST_F(ProfilerServiceTest, CreateSession, TestSize.Level1) auto status = service_->CreateSession(context_.get(), &request, &response); EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: create session offline test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, CreateSessionOffline, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + CreateSessionRequest request; + CreateSessionResponse response; auto sessionConfig = request.mutable_session_config(); ASSERT_NE(sessionConfig, nullptr); @@ -156,13 +390,13 @@ HWTEST_F(ProfilerServiceTest, CreateSession, TestSize.Level1) pluginConfig->set_name(pluginInfo.name); request.set_request_id(++requestCounter); - status = service_->CreateSession(context_.get(), &request, &response); + auto status = service_->CreateSession(context_.get(), &request, &response); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); } /** * @tc.name: server - * @tc.desc: create session online. + * @tc.desc: create session online test. * @tc.type: FUNC */ HWTEST_F(ProfilerServiceTest, CreateSessionOnline, TestSize.Level1) @@ -189,78 +423,262 @@ HWTEST_F(ProfilerServiceTest, CreateSessionOnline, TestSize.Level1) /** * @tc.name: server - * @tc.desc: destroy session. + * @tc.desc: create session batch test. * @tc.type: FUNC */ -HWTEST_F(ProfilerServiceTest, DestroySession, TestSize.Level1) +HWTEST_F(ProfilerServiceTest, CreateSessionBatchTest, TestSize.Level1) { ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); - EXPECT_NE(DestroySession(0).error_code(), grpc::StatusCode::OK); + CreateSessionRequest request; + CreateSessionResponse response; - uint32_t sessionId = 0; - { - CreateSessionRequest request; - CreateSessionResponse response; - - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); - sessionConfig->set_result_file("trace.bin"); + auto sessionConfig = request.mutable_session_config(); + ASSERT_NE(sessionConfig, nullptr); + sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); + sessionConfig->clear_result_file(); + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { auto pluginConfig = request.add_plugin_configs(); ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); + std::string pluginName = "create_session_batch_test_" + std::to_string(i); + AddPlugin(pluginName); + pluginConfig->set_name(pluginName); request.set_request_id(++requestCounter); auto status = service_->CreateSession(context_.get(), &request, &response); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - sessionId = response.session_id(); } + printf("CreateSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); +} + +/** + * @tc.name: server + * @tc.desc: create session with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, CreateSessionInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + CreateSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->CreateSession(context_.get(), nullptr, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->CreateSession(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->CreateSession(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: create session with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, CreateSessionWithInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + CreateSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->CreateSession(nullptr, &request, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + + +/** + * @tc.name: server + * @tc.desc: destroy session with invalid session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, DestroySessionInvalidSessionId, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + + EXPECT_NE(DestroySession(0).error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: destroy session with offline session. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, DestroySessionOffline, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); } /** * @tc.name: server - * @tc.desc: start session. + * @tc.desc: destroy session with online session. * @tc.type: FUNC */ -HWTEST_F(ProfilerServiceTest, StartSession, TestSize.Level1) +HWTEST_F(ProfilerServiceTest, DestroySessionOnline, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: destroy session batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, DestroySessionBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + std::vector sessionIds; + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { + uint32_t sessionId = 0; + { + CreateSessionRequest request; + CreateSessionResponse response; + + auto sessionConfig = request.mutable_session_config(); + ASSERT_NE(sessionConfig, nullptr); + sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); + + auto pluginConfig = request.add_plugin_configs(); + ASSERT_NE(pluginConfig, nullptr); + + std::string pluginName = "create_session_batch_test_" + std::to_string(i); + AddPlugin(pluginName); + pluginConfig->set_name(pluginName); + + request.set_request_id(++requestCounter); + auto status = service_->CreateSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + sessionId = response.session_id(); + } + if (sessionId) { + sessionIds.push_back(sessionId); + } + } + printf("CreateSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); + + timer.Reset(); + for (auto sessionId : sessionIds) { + EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); + } + printf("DestroySession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); +} + +/** + * @tc.name: server + * @tc.desc: destroy session with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, DestroySessionInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + DestroySessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->DestroySession(context_.get(), nullptr, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->DestroySession(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->DestroySession(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: destroy session with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, DestroySessionWithInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + DestroySessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->DestroySession(nullptr, &request, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: start session with invalid session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StartSessionInvalidSessionId, TestSize.Level1) { ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); auto status = StartSession(0); EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} - uint32_t sessionId = 0; - { - CreateSessionRequest request; - CreateSessionResponse response; +/** + * @tc.name: server + * @tc.desc: start session with valid offline session. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StartSessionOffline, TestSize.Level1) +{ + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); - sessionConfig->set_result_file("trace.bin"); - - auto pluginConfig = request.add_plugin_configs(); - ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); - - request.set_request_id(++requestCounter); - auto status = service_->CreateSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - sessionId = response.session_id(); - } - - status = StartSession(sessionId); + auto status = StartSession(sessionId); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); } /** * @tc.name: server - * @tc.desc: start session by update config. + * @tc.desc: start session with valid online session. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StartSessionOnline, TestSize.Level1) +{ + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + auto status = StartSession(sessionId); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: start session and update configs. * @tc.type: FUNC */ HWTEST_F(ProfilerServiceTest, StartSessionUpdateConfigs, TestSize.Level1) @@ -268,25 +686,8 @@ HWTEST_F(ProfilerServiceTest, StartSessionUpdateConfigs, TestSize.Level1) ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); - uint32_t sessionId = 0; - { - CreateSessionRequest request; - CreateSessionResponse response; - - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); - sessionConfig->set_result_file("trace.bin"); - - auto pluginConfig = request.add_plugin_configs(); - ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); - - request.set_request_id(++requestCounter); - auto status = service_->CreateSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - sessionId = response.session_id(); - } + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); StartSessionRequest request; StartSessionResponse response; @@ -302,54 +703,250 @@ HWTEST_F(ProfilerServiceTest, StartSessionUpdateConfigs, TestSize.Level1) EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); } +/** + * @tc.name: server + * @tc.desc: start session batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StartSessionBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + std::vector sessionIds; + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { + uint32_t sessionId = 0; + { + CreateSessionRequest request; + CreateSessionResponse response; + + auto sessionConfig = request.mutable_session_config(); + ASSERT_NE(sessionConfig, nullptr); + sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); + + auto pluginConfig = request.add_plugin_configs(); + ASSERT_NE(pluginConfig, nullptr); + + std::string pluginName = "create_session_batch_test_" + std::to_string(i); + AddPlugin(pluginName); + pluginConfig->set_name(pluginName); + + request.set_request_id(++requestCounter); + auto status = service_->CreateSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + sessionId = response.session_id(); + } + if (sessionId) { + sessionIds.push_back(sessionId); + } + } + printf("CreateSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); + + timer.Reset(); + for (auto sessionId : sessionIds) { + EXPECT_EQ(StartSession(sessionId).error_code(), grpc::StatusCode::OK); + } + printf("StartSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); +} /** * @tc.name: server - * @tc.desc: stop session. + * @tc.desc: start session with invalid arguments. * @tc.type: FUNC */ -HWTEST_F(ProfilerServiceTest, StopSession, TestSize.Level1) +HWTEST_F(ProfilerServiceTest, StartSessionInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + StartSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->StartSession(context_.get(), nullptr, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->StartSession(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->StartSession(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: start session with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StartSessionWithInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + + StartSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->StartSession(nullptr, &request, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: stop session with invalid session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionInvalidSessionId, TestSize.Level1) { ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); auto status = StopSession(0); EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} - uint32_t sessionId = 0; +/** + * @tc.name: server + * @tc.desc: stop session with offline session. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionOffline, TestSize.Level1) +{ + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + auto status = StopSession(sessionId); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: stop session with online session. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionOnline, TestSize.Level1) +{ + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); { - CreateSessionRequest request; - CreateSessionResponse response; - - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); - sessionConfig->set_result_file("trace.bin"); - - auto pluginConfig = request.add_plugin_configs(); - ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); - - request.set_request_id(++requestCounter); - auto status = service_->CreateSession(context_.get(), &request, &response); + auto status = StartSession(sessionId); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - - sessionId = response.session_id(); - { - StartSessionRequest request; - StartSessionResponse response; - - request.set_session_id(sessionId); - request.set_request_id(++requestCounter); - auto status = service_->StartSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - } } - status = StopSession(sessionId); + auto status = StopSession(sessionId); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); } +/** + * @tc.name: server + * @tc.desc: stop session batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + std::vector sessionIds; + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { + uint32_t sessionId = 0; + { + CreateSessionRequest request; + CreateSessionResponse response; + + auto sessionConfig = request.mutable_session_config(); + ASSERT_NE(sessionConfig, nullptr); + sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); + + auto pluginConfig = request.add_plugin_configs(); + ASSERT_NE(pluginConfig, nullptr); + + std::string pluginName = "create_session_batch_test_" + std::to_string(i); + AddPlugin(pluginName); + pluginConfig->set_name(pluginName); + + request.set_request_id(++requestCounter); + auto status = service_->CreateSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + sessionId = response.session_id(); + } + if (sessionId) { + sessionIds.push_back(sessionId); + } + } + printf("CreateSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); + + timer.Reset(); + for (auto sessionId : sessionIds) { + EXPECT_EQ(StartSession(sessionId).error_code(), grpc::StatusCode::OK); + } + printf("StartSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); + + timer.Reset(); + for (auto sessionId : sessionIds) { + EXPECT_EQ(StopSession(sessionId).error_code(), grpc::StatusCode::OK); + } + printf("StopSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); +} + +/** + * @tc.name: server + * @tc.desc: stop session with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + EXPECT_EQ(StartSession(sessionId).error_code(), grpc::StatusCode::OK); + + StopSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->StopSession(context_.get(), nullptr, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->StopSession(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->StopSession(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: stop session with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, StopSessionWithInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOnlineSession(); + EXPECT_NE(sessionId, 0); + EXPECT_EQ(StartSession(sessionId).error_code(), grpc::StatusCode::OK); + + StopSessionRequest request; + auto response = std::make_unique(); + ASSERT_NE(response, nullptr); + + auto status = service_->StopSession(nullptr, &request, response.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + class FakeServerWriter : public ::grpc::ServerWriter<::FetchDataResponse> { public: FakeServerWriter(::grpc::internal::Call* call, grpc::ServerContext* ctx) @@ -357,100 +954,76 @@ public: { } ~FakeServerWriter() = default; + + uint32_t GetDataCount() const + { + return dataCount_; + } + using grpc::internal::WriterInterface<::FetchDataResponse>::Write; bool Write(const ::FetchDataResponse& msg, ::grpc::WriteOptions options) override { - HILOG_DEBUG(LOG_CORE, "FakeServerWriter::Write %zu bytes!", msg.ByteSizeLong()); + if (msg.plugin_data_size() > 0) { + printf("ServerWriter recv %d data!\n",msg.plugin_data_size()); + for (int i = 0; i < msg.plugin_data_size(); i++) { + printf("data[%d] size = %zu\n", i, msg.plugin_data(i).ByteSizeLong()); + } + dataCount_ += msg.plugin_data_size(); + } return true; } + +private: + std::atomic dataCount_ = 0; }; /** * @tc.name: server - * @tc.desc: fetch data. + * @tc.desc: fetch data with invalid session id. * @tc.type: FUNC */ -HWTEST_F(ProfilerServiceTest, FetchData, TestSize.Level1) +HWTEST_F(ProfilerServiceTest, FetchDataInvalidSessionId, TestSize.Level1) { ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); FetchDataRequest request; - auto writer = std::make_unique(nullptr, context_.get()); + request.set_session_id(0); // invalid session id request.set_request_id(++requestCounter); auto status = service_->FetchData(context_.get(), &request, writer.get()); EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} - uint32_t sessionId = 0; +/** + * @tc.name: server + * @tc.desc: fetch data with offline. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, FetchDataOffline, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); { - CreateSessionRequest request; - CreateSessionResponse response; - - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::OFFLINE); - sessionConfig->set_result_file("trace.bin"); - - auto pluginConfig = request.add_plugin_configs(); - ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); - - request.set_request_id(++requestCounter); - auto status = service_->CreateSession(context_.get(), &request, &response); + auto status = StartSession(sessionId); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - - sessionId = response.session_id(); - { - StartSessionRequest request; - StartSessionResponse response; - - request.set_session_id(sessionId); - request.set_request_id(++requestCounter); - auto status = service_->StartSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - } } + FetchDataRequest request; request.set_session_id(sessionId); request.set_request_id(++requestCounter); - status = service_->FetchData(context_.get(), &request, writer.get()); + auto writer = std::make_unique(nullptr, context_.get()); + auto status = service_->FetchData(context_.get(), &request, writer.get()); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); EXPECT_EQ(StopSession(sessionId).error_code(), grpc::StatusCode::OK); EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); } -void ProfilerServiceTest::FetchDataOnlineSet(uint32_t& sessionId) -{ - CreateSessionRequest request; - CreateSessionResponse response; - - auto sessionConfig = request.mutable_session_config(); - ASSERT_NE(sessionConfig, nullptr); - sessionConfig->set_session_mode(ProfilerSessionConfig::ONLINE); - - auto pluginConfig = request.add_plugin_configs(); - ASSERT_NE(pluginConfig, nullptr); - pluginConfig->set_name(pluginInfo.name); - - request.set_request_id(++requestCounter); - auto status = service_->CreateSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - - sessionId = response.session_id(); - { - StartSessionRequest request; - StartSessionResponse response; - - request.set_session_id(sessionId); - request.set_request_id(++requestCounter); - auto status = service_->StartSession(context_.get(), &request, &response); - EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); - } -} - /** * @tc.name: server * @tc.desc: fetch data online. @@ -461,23 +1034,57 @@ HWTEST_F(ProfilerServiceTest, FetchDataOnline, TestSize.Level1) ASSERT_NE(service_, nullptr); ASSERT_NE(context_, nullptr); + uint32_t sessionId = CreateOnlineSession(); + StartSession(sessionId); + + auto sessionCtx = service_->GetSessionContext(sessionId); + ASSERT_NE(sessionCtx->dataRepeater, nullptr); + { + auto data = std::make_shared(); + ASSERT_NE(data, nullptr); + data->set_name(pluginInfo.name); + sessionCtx->dataRepeater->PutPluginData(data); + } + FetchDataRequest request; + auto writer = std::make_unique(nullptr, context_.get()); + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + std::thread bgThread([&] { + auto status = service_->FetchData(context_.get(), &request, writer.get()); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + }); + + usleep(FETCH_DATA_DELAY_US); + sessionCtx->dataRepeater->Close(); + bgThread.join(); + + EXPECT_EQ(StopSession(sessionId).error_code(), grpc::StatusCode::OK); + EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); + + EXPECT_EQ(writer->GetDataCount(), 1); +} + +/** + * @tc.name: server + * @tc.desc: fetch data online batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, FetchDataBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); auto writer = std::make_unique(nullptr, context_.get()); - request.set_request_id(++requestCounter); - auto status = service_->FetchData(context_.get(), &request, writer.get()); - EXPECT_NE(status.error_code(), grpc::StatusCode::OK); - - uint32_t sessionId = 0; - FetchDataOnlineSet(sessionId); + uint32_t sessionId = CreateOnlineSession(); + StartSession(sessionId); auto sessionCtx = service_->GetSessionContext(sessionId); ASSERT_NE(sessionCtx->dataRepeater, nullptr); - const int pluginDataCount = 10; std::thread dataProducer([&]() { - for (int i = 0; i < pluginDataCount; i++) { + for (int i = 0; i < BATCH_SIZE; i++) { auto data = std::make_shared(); ASSERT_NE(data, nullptr); data->set_name(pluginInfo.name); @@ -486,22 +1093,243 @@ HWTEST_F(ProfilerServiceTest, FetchDataOnline, TestSize.Level1) } }); - request.set_session_id(sessionId); - request.set_request_id(++requestCounter); - std::thread dataConsumer([&]() { - status = service_->FetchData(context_.get(), &request, writer.get()); + FetchDataRequest request; + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + auto status = service_->FetchData(context_.get(), &request, writer.get()); EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); }); dataProducer.join(); - - usleep(100 * 1000); // wait for reader take done! - sessionCtx->dataRepeater->Close(); + sleep(1); + sessionCtx->dataRepeater->Close(); // make sure FetchData thread exit dataConsumer.join(); EXPECT_EQ(StopSession(sessionId).error_code(), grpc::StatusCode::OK); EXPECT_EQ(DestroySession(sessionId).error_code(), grpc::StatusCode::OK); + + EXPECT_EQ(writer->GetDataCount(), BATCH_SIZE); +} + +/** + * @tc.name: server + * @tc.desc: fetch data with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, FetchDataInvalidArguments, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + FetchDataRequest request; + auto writer = std::make_unique(nullptr, context_.get()); + request.set_request_id(++requestCounter); + auto status = service_->FetchData(context_.get(), &request, writer.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + uint32_t sessionId = CreateOnlineSession(); + + auto sessionCtx = service_->GetSessionContext(sessionId); + ASSERT_NE(sessionCtx->dataRepeater, nullptr); + { + auto data = std::make_shared(); + ASSERT_NE(data, nullptr); + data->set_name(pluginInfo.name); + sessionCtx->dataRepeater->PutPluginData(data); + } + + status = service_->FetchData(context_.get(), nullptr, writer.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->FetchData(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->FetchData(context_.get(), nullptr, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: fetch data with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, FetchDataInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + FetchDataRequest request; + auto writer = std::make_unique(nullptr, context_.get()); + request.set_request_id(++requestCounter); + auto status = service_->FetchData(context_.get(), &request, writer.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + uint32_t sessionId = CreateOnlineSession(); + + auto sessionCtx = service_->GetSessionContext(sessionId); + ASSERT_NE(sessionCtx->dataRepeater, nullptr); + { + auto data = std::make_shared(); + ASSERT_NE(data, nullptr); + data->set_name(pluginInfo.name); + sessionCtx->dataRepeater->PutPluginData(data); + } + + status = service_->FetchData(nullptr, &request, writer.get()); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with invalid session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionInvalidSessionId, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(0); + request.set_request_id(++requestCounter); + auto status = service_->KeepSession(context_.get(), &request, &response); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with offline session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionWithoutAliveTime, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + auto status = service_->KeepSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with offline session id. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionOffline, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + request.set_keep_alive_time(TEST_SESSION_TIMEOUT_MS); + auto status = service_->KeepSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + + // make sure session expired by backgroud task + std::this_thread::sleep_for(std::chrono::milliseconds(TEST_SESSION_TIMEOUT_MS)); + std::this_thread::sleep_for(std::chrono::milliseconds(TEST_SESSION_TIMEOUT_MS)); + + status = DestroySession(sessionId); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with batch test. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionBatchTest, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + Timer timer = {}; + for (int i = 0; i < ROUND_COUNT; i++) { + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + request.set_keep_alive_time(TEST_SESSION_TIMEOUT_MS); + auto status = service_->KeepSession(context_.get(), &request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); + } + printf("KeepSession %d time, cost %ldus.\n", ROUND_COUNT, timer.ElapsedUs()); + + std::this_thread::sleep_for(std::chrono::milliseconds(TEST_SESSION_TIMEOUT_MS)); + std::this_thread::sleep_for(std::chrono::milliseconds(TEST_SESSION_TIMEOUT_MS)); + auto status = DestroySession(sessionId); + EXPECT_EQ(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with invalid arguments. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionInvalidArgs, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + request.set_keep_alive_time(TEST_SESSION_TIMEOUT_MS); + auto status = service_->KeepSession(context_.get(), nullptr, &response); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); + + status = service_->KeepSession(context_.get(), &request, nullptr); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); +} + +/** + * @tc.name: server + * @tc.desc: keep session with invalid context. + * @tc.type: FUNC + */ +HWTEST_F(ProfilerServiceTest, KeepSessionInvalidContext, TestSize.Level1) +{ + ASSERT_NE(service_, nullptr); + ASSERT_NE(context_, nullptr); + + uint32_t sessionId = CreateOfflineSession(); + EXPECT_NE(sessionId, 0); + + KeepSessionRequest request; + KeepSessionResponse response; + + request.set_session_id(sessionId); + request.set_request_id(++requestCounter); + request.set_keep_alive_time(TEST_SESSION_TIMEOUT_MS); + auto status = service_->KeepSession(nullptr, &request, &response); + EXPECT_NE(status.error_code(), grpc::StatusCode::OK); } /** @@ -521,3 +1349,4 @@ HWTEST_F(ProfilerServiceTest, StartService, TestSize.Level1) service->StopService(); waiterThread.join(); } +} diff --git a/device/services/profiler_service/test/unittest/trace_file_reader_test.cpp b/device/services/profiler_service/test/unittest/trace_file_reader_test.cpp index 56b617377..e498a6456 100644 --- a/device/services/profiler_service/test/unittest/trace_file_reader_test.cpp +++ b/device/services/profiler_service/test/unittest/trace_file_reader_test.cpp @@ -40,7 +40,15 @@ protected: std::string path = "trace.bin"; static void SetUpTestCase() {} - static void TearDownTestCase() {} + static void TearDownTestCase() + { + std::string name = "325.ht"; + std::string path = DEFAULT_TEST_PATH + name; + + if (access(path.c_str(), F_OK) == 0) { + system(std::string("rm " + path).c_str()); + } + } void SetUp() override {} @@ -129,7 +137,9 @@ HWTEST_F(TraceFileReaderTest, Read, TestSize.Level1) std::string path = DEFAULT_TEST_PATH + name; if (access(path.c_str(), F_OK) != 0) { - system(std::string("touch " + path).c_str()); + std::unique_ptr fptr(fopen(path.c_str(), "wb+"), fclose); + TraceFileHeader header = {}; // default header data + fwrite(&header, sizeof(char), sizeof(header), fptr.get()); } auto reader = std::make_shared(); ASSERT_NE(reader, nullptr); diff --git a/device/services/profiler_service/test/unittest/trace_file_writer_test.cpp b/device/services/profiler_service/test/unittest/trace_file_writer_test.cpp old mode 100755 new mode 100644 index 486ec6ade..899383941 --- a/device/services/profiler_service/test/unittest/trace_file_writer_test.cpp +++ b/device/services/profiler_service/test/unittest/trace_file_writer_test.cpp @@ -91,10 +91,10 @@ HWTEST_F(TraceFileWriterTest, Flush, TestSize.Level1) // check file length fin.seekg(0, std::ios_base::end); - EXPECT_EQ(fin.tellg(), sizeof(msgLen) + testData.size()); + EXPECT_EQ(fin.tellg(), TraceFileHeader::HEADER_SIZE + sizeof(msgLen) + testData.size()); // check msg length - fin.seekg(0, std::ios_base::beg); + fin.seekg(TraceFileHeader::HEADER_SIZE, std::ios_base::beg); // skip file header fin.read(reinterpret_cast(&msgLen), sizeof(msgLen)); EXPECT_EQ(msgLen, testData.size()); diff --git a/device/services/shared_memory/BUILD.gn b/device/services/shared_memory/BUILD.gn old mode 100755 new mode 100644 index d86e175c3..2088cc506 --- a/device/services/shared_memory/BUILD.gn +++ b/device/services/shared_memory/BUILD.gn @@ -21,10 +21,6 @@ config("shared_memory_config") { "${OHOS_PROFILER_DIR}/interfaces/innerkits", "//utils/native/base/include", ] - if (current_toolchain == host_toolchain) { - cflags += [ "-DHAVE_PTHREAD" ] - } else { - } } ohos_shared_library("shared_memory") { @@ -40,7 +36,7 @@ ohos_shared_library("shared_memory") { public_deps = [ "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf", "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", - "//utils/native/base:utilsbase", + "//utils/native/base:utilsecurec", ] install_enable = true subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" diff --git a/device/services/shared_memory/include/share_memory_allocator.h b/device/services/shared_memory/include/share_memory_allocator.h index e374a961b..9de96efd1 100644 --- a/device/services/shared_memory/include/share_memory_allocator.h +++ b/device/services/shared_memory/include/share_memory_allocator.h @@ -31,7 +31,7 @@ public: bool ReleaseMemoryBlockLocal(std::string name); bool ReleaseMemoryBlockRemote(std::string name); - ShareMemoryBlockPtr FindMBByName(std::string name); + ShareMemoryBlockPtr FindMemoryBlockByName(std::string name); private: ShareMemoryAllocator(); diff --git a/device/services/shared_memory/include/share_memory_block.h b/device/services/shared_memory/include/share_memory_block.h old mode 100755 new mode 100644 index c6ca15df9..43ebfbf8f --- a/device/services/shared_memory/include/share_memory_block.h +++ b/device/services/shared_memory/include/share_memory_block.h @@ -18,61 +18,69 @@ #include "google/protobuf/message.h" #include - -#define SHARE_MEMORY_HEAD_SIZE 64 - -struct ShareMemoryStruct { - struct alignas(SHARE_MEMORY_HEAD_SIZE) { - uint32_t writeOffset; - uint32_t readOffset; - uint32_t memorySize_; - } head; - int8_t data[0]; -}; +#include class ShareMemoryBlock { public: - ShareMemoryBlock(); - ~ShareMemoryBlock() {} + ShareMemoryBlock(const std::string& name, uint32_t size); + ShareMemoryBlock(const std::string& name, uint32_t size, int fd); + ~ShareMemoryBlock(); - bool CreateBlock(std::string name, uint32_t size); - bool ReleaseBlock(); - bool CreateBlockByFd(std::string name, uint32_t size, int fd); - bool ReleaseBlockRemote(); - - int8_t* GetFreeMemory(uint32_t size); - bool UseFreeMemory(int8_t* pmem, uint32_t size); bool PutRaw(const int8_t* data, uint32_t size); - bool PutProtobuf(google::protobuf::Message& pmsg); + bool PutMessage(const google::protobuf::Message& pmsg); - uint32_t GetDataSize(); - const int8_t* GetDataPoint(); - bool Next(); + using DataHandler = std::function; + bool TakeData(const DataHandler& func); std::string GetName(); uint32_t GetSize(); int GetfileDescriptor(); - enum DropType { - DROP_OLD, // buffer满时,丢弃最老的数据 + bool Valid() const; + + enum ReusePolicy { DROP_NONE, // buffer满时,不丢弃老数据,不放入新数据 + DROP_OLD, // buffer满时,丢弃最老的数据 }; - void SetDropType(enum DropType dt) + void SetReusePolicy(enum ReusePolicy dt) { - dropType_ = dt; + reusePloicy_ = dt; } private: + int8_t* GetFreeMemory(uint32_t size); + bool UseFreeMemory(int8_t* pmem, uint32_t size); + + uint32_t GetDataSize(); + const int8_t* GetDataPoint(); + bool Next(); + + struct BlockHeader { + struct alignas(sizeof(uintptr_t)) { + uint32_t writeOffset_; + uint32_t readOffset_; + uint32_t memorySize_; + pthread_mutex_t mutex_; + uint32_t bytesCount_; + uint32_t chunkCount_; + } info; + int8_t data[0]; + }; + + ShareMemoryBlock(); int8_t* GetCurrentFreeMemory(uint32_t size); - std::string memoryName_; - uint32_t memorySize_; + bool CreateBlock(std::string name, uint32_t size); + bool CreateBlockWithFd(std::string name, uint32_t size, int fd); + bool ReleaseBlock(); + int fileDescriptor_; - void* memoryPoint_; - struct ShareMemoryStruct* pMemory_; + uint32_t memorySize_; + std::string memoryName_; - DropType dropType_; + BlockHeader* header_; + ReusePolicy reusePloicy_; }; -#endif \ No newline at end of file +#endif diff --git a/device/services/shared_memory/src/share_memory_allocator.cpp b/device/services/shared_memory/src/share_memory_allocator.cpp index 16e9be992..c431bcc68 100644 --- a/device/services/shared_memory/src/share_memory_allocator.cpp +++ b/device/services/shared_memory/src/share_memory_allocator.cpp @@ -37,22 +37,20 @@ ShareMemoryAllocator::~ShareMemoryAllocator() {} bool ShareMemoryAllocator::ReleaseMemoryBlockLocal(std::string name) { - auto pmb = FindMBByName(name); + auto pmb = FindMemoryBlockByName(name); CHECK_NOTNULL(pmb, false, "FAIL %s", name.c_str()); - pmb->ReleaseBlock(); memoryBlocks.erase(name); return true; } bool ShareMemoryAllocator::ReleaseMemoryBlockRemote(std::string name) { - auto pmb = FindMBByName(name); + auto pmb = FindMemoryBlockByName(name); CHECK_NOTNULL(pmb, false, "FAIL %s", name.c_str()); - pmb->ReleaseBlockRemote(); memoryBlocks.erase(name); return true; } @@ -60,28 +58,36 @@ bool ShareMemoryAllocator::ReleaseMemoryBlockRemote(std::string name) ShareMemoryBlockPtr ShareMemoryAllocator::CreateMemoryBlockLocal(std::string name, uint32_t size) { CHECK_TRUE(memoryBlocks.find(name) == memoryBlocks.end(), nullptr, "%s already used", name.c_str()); - CHECK_TRUE(size >= MIN_SHARE_MEMORY_SIZE, NULL, "%s %d size less than %d", name.c_str(), size, MIN_SHARE_MEMORY_SIZE); - memoryBlocks[name] = std::make_shared(); - memoryBlocks[name]->CreateBlock(name, size); - return memoryBlocks[name]; + auto block = std::make_shared(name, size); + if (!block->Valid()) { + HILOG_INFO(LOG_CORE, "CreateMemoryBlockLocal FAIL"); + return nullptr; + } + memoryBlocks[name] = block; + return block; } ShareMemoryBlockPtr ShareMemoryAllocator::CreateMemoryBlockRemote(std::string name, uint32_t size, int fd) { - memoryBlocks[name] = std::make_shared(); - if (memoryBlocks[name]->CreateBlockByFd(name, size, fd)) { - return memoryBlocks[name]; + CHECK_TRUE(memoryBlocks.find(name) == memoryBlocks.end(), nullptr, "%s already used", name.c_str()); + CHECK_TRUE(size >= MIN_SHARE_MEMORY_SIZE, NULL, "%s %d size less than %d", name.c_str(), size, + MIN_SHARE_MEMORY_SIZE); + + auto block = std::make_shared(name, size, fd); + if (!block->Valid()) { + HILOG_INFO(LOG_CORE, "CreateMemoryBlockRemote FAIL"); + return nullptr; } - memoryBlocks.erase(name); - HILOG_INFO(LOG_CORE, "CreateMemoryBlockRemote FAIL"); - return nullptr; + memoryBlocks[name] = block; + return block; } -ShareMemoryBlockPtr ShareMemoryAllocator::FindMBByName(std::string name) +ShareMemoryBlockPtr ShareMemoryAllocator::FindMemoryBlockByName(std::string name) { - CHECK_TRUE(memoryBlocks.find(name) != memoryBlocks.end(), nullptr, "FAIL"); - return memoryBlocks[name]; + auto it = memoryBlocks.find(name); + CHECK_TRUE(it != memoryBlocks.end(), nullptr, "FAIL"); + return it->second; } diff --git a/device/services/shared_memory/src/share_memory_block.cpp b/device/services/shared_memory/src/share_memory_block.cpp old mode 100755 new mode 100644 index f7f0f2d4a..82bb980e6 --- a/device/services/shared_memory/src/share_memory_block.cpp +++ b/device/services/shared_memory/src/share_memory_block.cpp @@ -28,88 +28,119 @@ namespace { const int HEAD_OFFSET_LEN = 4; +#ifndef PAGE_SIZE +constexpr uint32_t PAGE_SIZE = 4096; +#endif } +struct PthreadLocker { + explicit PthreadLocker(pthread_mutex_t& mutex) : mutex_(mutex) + { + pthread_mutex_lock(&mutex_); + } + + ~PthreadLocker() + { + pthread_mutex_unlock(&mutex_); + } + +private: + pthread_mutex_t& mutex_; +}; + ShareMemoryBlock::ShareMemoryBlock() + : fileDescriptor_(-1), + memoryPoint_(nullptr), + memorySize_(0), + memoryName_(), + header_(nullptr), + reusePloicy_(ReusePolicy::DROP_NONE) { - memoryPoint_ = nullptr; - memorySize_ = 0; - fileDescriptor_ = -1; - dropType_ = DropType::DROP_NONE; - pMemory_ = nullptr; - memoryName_ = ""; } -std::string ReplaceStr(std::string base, std::string _from, std::string _to) +bool ShareMemoryBlock::CreateBlockWithFd(std::string name, uint32_t size, int fd) { - while (true) { - size_t pos = base.find(_from, 0); - if (pos == std::string::npos) { - break; - } - base.replace(pos, _from.length(), _to); - } - return base; -} + CHECK_TRUE(fd >= 0, false, "CreateBlock FAIL SYS_memfd_create"); -bool ShareMemoryBlock::CreateBlockByFd(std::string name, uint32_t size, int fd) -{ - CHECK_TRUE(memorySize_ == 0, false, "%s already allocated memory", name.c_str()); - - fileDescriptor_ = fd; - - CHECK_TRUE(fileDescriptor_ >= 0, false, "CreateBlock FAIL SYS_memfd_create"); - - memoryPoint_ = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor_, 0); - if (memoryPoint_ == MAP_FAILED) { - ReleaseBlockRemote(); - - HILOG_ERROR(LOG_CORE, "CreateBlockByFd mmap ERR : %s", strerror(errno)); + auto ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + HILOG_ERROR(LOG_CORE, "CreateBlockWithFd mmap ERR : %s", strerror(errno)); return false; } + fileDescriptor_ = fd; + memoryPoint_ = ptr; memorySize_ = size; memoryName_ = name; - pMemory_ = (struct ShareMemoryStruct*)memoryPoint_; + header_ = reinterpret_cast(ptr); return true; } bool ShareMemoryBlock::CreateBlock(std::string name, uint32_t size) { HILOG_INFO(LOG_CORE, "CreateBlock %s %d", name.c_str(), size); + CHECK_TRUE(size > sizeof(BlockHeader), false, "size %u too less!", size); + CHECK_TRUE(size % PAGE_SIZE == 0, false, "size %u not times of %d!", size, PAGE_SIZE); - CHECK_TRUE(memorySize_ == 0, false, "%s already allocated memory", name.c_str()); + int fd = syscall(SYS_memfd_create, name.c_str(), 0); + CHECK_TRUE(fd >= 0, false, "CreateBlock FAIL SYS_memfd_create"); - fileDescriptor_ = syscall(SYS_memfd_create, name.c_str(), 0); - - CHECK_TRUE(fileDescriptor_ >= 0, false, "CreateBlock FAIL SYS_memfd_create"); - - int check = ftruncate(fileDescriptor_, size); + int check = ftruncate(fd, size); if (check < 0) { - ReleaseBlock(); - + close(fd); HILOG_ERROR(LOG_CORE, "CreateBlock ftruncate ERR : %s", strerror(errno)); return false; } - memoryPoint_ = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor_, 0); - if (memoryPoint_ == MAP_FAILED) { - ReleaseBlock(); + auto ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + close(fd); HILOG_ERROR(LOG_CORE, "CreateBlock mmap ERR : %s", strerror(errno)); - return false; } + + fileDescriptor_ = fd; + memoryPoint_ = ptr; memorySize_ = size; memoryName_ = name; - pMemory_ = (struct ShareMemoryStruct*)memoryPoint_; - pMemory_->head.readOffset = 0; - pMemory_->head.writeOffset = 0; - pMemory_->head.memorySize_ = size - SHARE_MEMORY_HEAD_SIZE; + header_ = reinterpret_cast(ptr); + + // initialize header infos + header_->info.readOffset_ = 0; + header_->info.writeOffset_ = 0; + header_->info.memorySize_ = size - sizeof(BlockHeader); + header_->info.bytesCount_ = 0; + header_->info.chunkCount_ = 0; + + pthread_mutexattr_t muAttr; + pthread_mutexattr_init(&muAttr); + pthread_mutexattr_setpshared(&muAttr, PTHREAD_PROCESS_SHARED); + pthread_mutex_init(&header_->info.mutex_, &muAttr); return true; } +bool ShareMemoryBlock::Valid() const +{ + return header_ != nullptr; +} + +ShareMemoryBlock::ShareMemoryBlock(const std::string& name, uint32_t size) : ShareMemoryBlock() +{ + CreateBlock(name, size); +} + +ShareMemoryBlock::ShareMemoryBlock(const std::string& name, uint32_t size, int fd) : ShareMemoryBlock() +{ + CreateBlockWithFd(name, size, fd); +} + +ShareMemoryBlock::~ShareMemoryBlock() +{ + ReleaseBlock(); +} + bool ShareMemoryBlock::ReleaseBlock() { if (memorySize_ > 0) { @@ -124,32 +155,30 @@ bool ShareMemoryBlock::ReleaseBlock() } return true; } -bool ShareMemoryBlock::ReleaseBlockRemote() -{ - return ReleaseBlock(); -} int8_t* ShareMemoryBlock::GetCurrentFreeMemory(uint32_t size) { + CHECK_NOTNULL(header_, nullptr, "header not ready!"); uint32_t realSize = size + sizeof(uint32_t) + HEAD_OFFSET_LEN; - uint32_t wp = pMemory_->head.writeOffset; - if (wp + realSize > pMemory_->head.memorySize_) { // 后面部分放不下,从头开始放 - if (pMemory_->head.readOffset == 0) { + + uint32_t wp = header_->info.writeOffset_; + if (wp + realSize > header_->info.memorySize_) { // 后面部分放不下,从头开始放 + if (header_->info.readOffset_ == 0) { return nullptr; } - *((uint32_t*)(&pMemory_->data[wp])) = 0xffffffff; + *((uint32_t*)(&header_->data[wp])) = 0xffffffff; wp = 0; } - if (wp < pMemory_->head.readOffset && pMemory_->head.readOffset < wp + realSize) { // + if (wp < header_->info.readOffset_ && header_->info.readOffset_ < wp + realSize) { // return nullptr; } - return &pMemory_->data[wp + sizeof(uint32_t)]; + return &header_->data[wp + sizeof(uint32_t)]; } int8_t* ShareMemoryBlock::GetFreeMemory(uint32_t size) { - if (dropType_ == DropType::DROP_NONE) { + if (reusePloicy_ == ReusePolicy::DROP_NONE) { return GetCurrentFreeMemory(size); } int8_t* ret = nullptr; @@ -167,14 +196,17 @@ int8_t* ShareMemoryBlock::GetFreeMemory(uint32_t size) bool ShareMemoryBlock::UseFreeMemory(int8_t* pmem, uint32_t size) { - uint32_t wp = pmem - sizeof(uint32_t) - pMemory_->data; - *((int*)(&pMemory_->data[wp])) = size; - pMemory_->head.writeOffset = wp + sizeof(uint32_t) + size; + uint32_t wp = pmem - sizeof(uint32_t) - header_->data; + *((int*)(&header_->data[wp])) = size; + + header_->info.writeOffset_ = wp + sizeof(uint32_t) + size; return true; } bool ShareMemoryBlock::PutRaw(const int8_t* data, uint32_t size) { + CHECK_NOTNULL(header_, false, "header not ready!"); + PthreadLocker locker(header_->info.mutex_); int8_t* rawMemory = GetFreeMemory(size); if (rawMemory == nullptr) { HILOG_INFO(LOG_CORE, "_PutRaw not enough space [%d]", size); @@ -182,57 +214,81 @@ bool ShareMemoryBlock::PutRaw(const int8_t* data, uint32_t size) } if (memcpy_s(rawMemory, size, data, size) != EOK) { HILOG_ERROR(LOG_CORE, "memcpy_s error"); + return false; } UseFreeMemory(rawMemory, size); + HILOG_INFO(LOG_CORE, "ShareMemoryBlock::%s %d %d", __func__, header_->info.bytesCount_, header_->info.chunkCount_); return true; } -bool ShareMemoryBlock::PutProtobuf(google::protobuf::Message& pmsg) +bool ShareMemoryBlock::PutMessage(const google::protobuf::Message& pmsg) { size_t size = pmsg.ByteSizeLong(); + CHECK_NOTNULL(header_, false, "header not ready!"); + PthreadLocker locker(header_->info.mutex_); int8_t* rawMemory = GetFreeMemory(size); if (rawMemory == nullptr) { - HILOG_INFO(LOG_CORE, "PutProtobuf not enough space [%zu]", size); + HILOG_INFO(LOG_CORE, "PutMessage not enough space [%zu]", size); return false; } pmsg.SerializeToArray(rawMemory, size); UseFreeMemory(rawMemory, size); + ++header_->info.bytesCount_; + ++header_->info.chunkCount_; + return true; +} + +bool ShareMemoryBlock::TakeData(const DataHandler& func) +{ + CHECK_NOTNULL(header_, false, "header not ready!"); + CHECK_TRUE(static_cast(func), false, "func invalid!"); + + PthreadLocker locker(header_->info.mutex_); + auto size = GetDataSize(); + if (size == 0) { + return false; + } + auto ptr = GetDataPoint(); + CHECK_TRUE(func(ptr, size), false, "call func FAILED!"); + CHECK_TRUE(Next(), false, "move read pointer FAILED!"); + --header_->info.chunkCount_; return true; } uint32_t ShareMemoryBlock::GetDataSize() { - if (pMemory_->head.readOffset == pMemory_->head.writeOffset) { + if (header_->info.readOffset_ == header_->info.writeOffset_) { return 0; } - uint32_t ret = *((uint32_t*)(&pMemory_->data[pMemory_->head.readOffset])); + uint32_t ret = *((uint32_t*)(&header_->data[header_->info.readOffset_])); if (ret == 0xffffffff) { - ret = *((uint32_t*)(&pMemory_->data[0])); + ret = *((uint32_t*)(&header_->data[0])); } return ret; } const int8_t* ShareMemoryBlock::GetDataPoint() { - if (*((uint32_t*)(&pMemory_->data[pMemory_->head.readOffset])) == 0xffffffff) { - return &pMemory_->data[HEAD_OFFSET_LEN]; + if (*((uint32_t*)(&header_->data[header_->info.readOffset_])) == 0xffffffff) { + return &header_->data[HEAD_OFFSET_LEN]; } - return &pMemory_->data[pMemory_->head.readOffset + HEAD_OFFSET_LEN]; + return &header_->data[header_->info.readOffset_ + HEAD_OFFSET_LEN]; } + bool ShareMemoryBlock::Next() { - if (pMemory_->head.readOffset == pMemory_->head.writeOffset) { + if (header_->info.readOffset_ == header_->info.writeOffset_) { return false; } - uint32_t size = *((uint32_t*)(&pMemory_->data[pMemory_->head.readOffset])); + uint32_t size = *((uint32_t*)(&header_->data[header_->info.readOffset_])); if (size == 0xffffffff) { - size = *((uint32_t*)(&pMemory_->data[0])); - pMemory_->head.readOffset = size + sizeof(uint32_t); + size = *((uint32_t*)(&header_->data[0])); + header_->info.readOffset_ = size + sizeof(uint32_t); } else { - pMemory_->head.readOffset += size + sizeof(uint32_t); + header_->info.readOffset_ += size + sizeof(uint32_t); } return true; } diff --git a/device/services/shared_memory/test/BUILD.gn b/device/services/shared_memory/test/BUILD.gn old mode 100755 new mode 100644 index 37e00da8b..cbf423e41 --- a/device/services/shared_memory/test/BUILD.gn +++ b/device/services/shared_memory/test/BUILD.gn @@ -1,59 +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. - -import("//build/test.gni") -import("../../../base/config.gni") - -module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" -config("module_private_config") { - visibility = [":*"] - if (current_toolchain != host_toolchain) { - defines = [ "HAVE_HILOG" ] - } -} - -ohos_unittest("shared_memory_ut") { - module_out_path = module_output_path - sources = [ - "unittest/shared_memory_allocator_test.cpp", - "unittest/shared_memory_block_test.cpp", - ] - include_dirs = [ - "${OHOS_PROFILER_DIR}/device/services/ipc/include", - "//third_party/googletest/googletest/include/gtest", - ] - configs = [ ":module_private_config" ] - deps = [ - "../:shared_memory", - "${OHOS_PROFILER_DIR}/device/services/ipc:ipc", - "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", - "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", - "//third_party/googletest:gtest", - ] - cflags = [ - "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - "-Dprotected=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" -} - -group("unittest") { - testonly = true - deps = [ - ":shared_memory_ut", - ] -} +# 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("//build/test.gni") +import("../../../base/config.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" +config("module_private_config") { + visibility = [ ":*" ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + } +} + +ohos_unittest("shared_memory_ut") { + module_out_path = module_output_path + sources = [ + "unittest/shared_memory_allocator_test.cpp", + "unittest/shared_memory_block_test.cpp", + ] + include_dirs = [ + "${OHOS_PROFILER_DIR}/device/services/ipc/include", + "//third_party/googletest/googletest/include/gtest", + ] + configs = [ ":module_private_config" ] + deps = [ + "${OHOS_PROFILER_DIR}/device/services/ipc:ipc", + "${OHOS_PROFILER_DIR}/protos/services:plugin_services_proto", + "${OHOS_PROFILER_DIR}/protos/services:service_types_proto", + "../:shared_memory", + "//third_party/googletest:gtest", + ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + "-Dprotected=public", #allow test code access private members + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" +} + +group("unittest") { + testonly = true + deps = [ ":shared_memory_ut" ] +} diff --git a/device/services/shared_memory/test/unittest/shared_memory_allocator_test.cpp b/device/services/shared_memory/test/unittest/shared_memory_allocator_test.cpp index 6beb1371f..4661d7744 100644 --- a/device/services/shared_memory/test/unittest/shared_memory_allocator_test.cpp +++ b/device/services/shared_memory/test/unittest/shared_memory_allocator_test.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "client_map.h" #include "plugin_service.ipc.h" @@ -67,19 +68,17 @@ public: */ HWTEST_F(SharedMemoryAllocatorTest, CreateMemoryBlockLocal, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 0) == + nullptr); // 创建大小为0的内存块,返回空 + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1) == - nullptr); // 创建内存块大小<1024,返回空 - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1024) != nullptr); // 成功创建 - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1024) == + nullptr); // 创建内存块大小<4096,返回空 + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 4096) != nullptr); // 成功创建 + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 4096) == nullptr); // 创建同名内存块返回空 - exit(0); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); } /** @@ -87,37 +86,41 @@ HWTEST_F(SharedMemoryAllocatorTest, CreateMemoryBlockLocal, TestSize.Level1) * @tc.desc: Find memory block by name. * @tc.type: FUNC */ -HWTEST_F(SharedMemoryAllocatorTest, FindMBByName, TestSize.Level1) +HWTEST_F(SharedMemoryAllocatorTest, FindMemoryBlockByName, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().FindMBByName("err") == nullptr); // 查找不存在的内存块返回空 - - exit(0); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().FindMemoryBlockByName("err") == nullptr); // 查找不存在的内存块返回空 } /** * @tc.name: Service - * @tc.desc: Create a memory block with a nonexistent file descriptor. + * @tc.desc: Shared memory MemoryBlockRemote test. * @tc.type: FUNC */ -HWTEST_F(SharedMemoryAllocatorTest, CreateMemoryBlockRemote, TestSize.Level1) +HWTEST_F(SharedMemoryAllocatorTest, MemoryBlockRemote, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("err", 1024, 99) == + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("err", 4096, 99) == nullptr); // 使用不存在的文件描述符映射内存块返回空 - exit(0); + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("err")); + + int fd = syscall(SYS_memfd_create, "testnameremote", 0); + EXPECT_GE(fd, 0); + int check = ftruncate(fd, 4096); + EXPECT_GE(check, 0); + + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("testnameremote", 0, fd) == + nullptr); // 创建大小为0的内存块,返回空 + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("testnameremote")); + + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("testnameremote", 1, fd) == + nullptr); // 创建内存块大小<4096,返回空 + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("testnameremote")); + + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("testnameremote", 4096, fd) == + nullptr); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote("testnameremote", 4096, fd) == + nullptr); // 创建正确fd的重复内存块 + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("testnameremote")); + ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("testnameremote")); // 重复释放内存块返回-1 } /** @@ -127,17 +130,9 @@ HWTEST_F(SharedMemoryAllocatorTest, CreateMemoryBlockRemote, TestSize.Level1) */ HWTEST_F(SharedMemoryAllocatorTest, GetDataSize, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 1024) != nullptr); // 成功创建 - ASSERT_TRUE(ShareMemoryAllocator::GetInstance().FindMBByName("testname")->GetDataSize() == 0); - - exit(0); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().CreateMemoryBlockLocal("testname", 4096) != nullptr); // 成功创建 + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().FindMemoryBlockByName("testname")->GetDataSize() == 0); + ASSERT_TRUE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("testname")); } /** @@ -147,15 +142,7 @@ HWTEST_F(SharedMemoryAllocatorTest, GetDataSize, TestSize.Level1) */ HWTEST_F(SharedMemoryAllocatorTest, ReleaseMemoryBlockLocal, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockLocal("or")); // 释放不存在的内存块返回-1 - exit(0); } /** @@ -165,15 +152,7 @@ HWTEST_F(SharedMemoryAllocatorTest, ReleaseMemoryBlockLocal, TestSize.Level1) */ HWTEST_F(SharedMemoryAllocatorTest, ReleaseMemoryBlockRemote, TestSize.Level1) { - pid_t pid1 = fork(); - ASSERT_TRUE(pid1 >= 0); - if (pid1 > 0) { - waitpid(pid1, nullptr, 0); - return; - } - ASSERT_FALSE(ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote("or")); // 释放不存在的内存块返回-1 - exit(0); } /** @@ -251,8 +230,7 @@ HWTEST_F(SharedMemoryAllocatorTest, unixSocketClient, TestSize.Level1) HWTEST_F(SharedMemoryAllocatorTest, UnixSocketServer, TestSize.Level1) { UnixSocketServer unixSocketServer; - - unixSocketServer.UnixSocketAccept(nullptr); + unixSocketServer.UnixSocketAccept(); ServiceEntry serviceEntry; ASSERT_TRUE(unixSocketServer.StartServer("", serviceEntry)); diff --git a/device/services/shared_memory/test/unittest/shared_memory_block_test.cpp b/device/services/shared_memory/test/unittest/shared_memory_block_test.cpp old mode 100755 new mode 100644 index f87327e90..4f8d6a1b0 --- a/device/services/shared_memory/test/unittest/shared_memory_block_test.cpp +++ b/device/services/shared_memory/test/unittest/shared_memory_block_test.cpp @@ -23,7 +23,7 @@ using namespace testing::ext; namespace { -constexpr size_t ARRAYSIZE = 100; +constexpr size_t ARRAYSIZE = 1024; class SharedMemoryBlockTest : public testing::Test { public: @@ -41,8 +41,8 @@ public: */ HWTEST_F(SharedMemoryBlockTest, ReadLock, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); } @@ -54,8 +54,8 @@ HWTEST_F(SharedMemoryBlockTest, ReadLock, TestSize.Level1) */ HWTEST_F(SharedMemoryBlockTest, GetName, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); shareMemoryBlock.GetName(); @@ -69,8 +69,8 @@ HWTEST_F(SharedMemoryBlockTest, GetName, TestSize.Level1) */ HWTEST_F(SharedMemoryBlockTest, GetSize, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); shareMemoryBlock.GetSize(); @@ -84,8 +84,8 @@ HWTEST_F(SharedMemoryBlockTest, GetSize, TestSize.Level1) */ HWTEST_F(SharedMemoryBlockTest, GetfileDescriptor, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); shareMemoryBlock.GetfileDescriptor(); @@ -99,13 +99,13 @@ HWTEST_F(SharedMemoryBlockTest, GetfileDescriptor, TestSize.Level1) */ HWTEST_F(SharedMemoryBlockTest, DROP_NONE, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); - shareMemoryBlock.SetDropType(ShareMemoryBlock::DropType::DROP_NONE); + shareMemoryBlock.SetReusePolicy(ShareMemoryBlock::ReusePolicy::DROP_NONE); int8_t data[ARRAYSIZE]; - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 5; i++) { *((uint32_t*)data) = i; shareMemoryBlock.PutRaw(data, ARRAYSIZE); } @@ -126,13 +126,13 @@ HWTEST_F(SharedMemoryBlockTest, DROP_NONE, TestSize.Level1) */ HWTEST_F(SharedMemoryBlockTest, DROP_OLD, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); - shareMemoryBlock.SetDropType(ShareMemoryBlock::DropType::DROP_OLD); + shareMemoryBlock.SetReusePolicy(ShareMemoryBlock::ReusePolicy::DROP_OLD); int8_t data[ARRAYSIZE]; - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 5; i++) { *((uint32_t*)data) = i; shareMemoryBlock.PutRaw(data, ARRAYSIZE); } @@ -151,18 +151,148 @@ HWTEST_F(SharedMemoryBlockTest, DROP_OLD, TestSize.Level1) * @tc.desc: put protobuf. * @tc.type: FUNC */ -HWTEST_F(SharedMemoryBlockTest, PutProtobuf, TestSize.Level1) +HWTEST_F(SharedMemoryBlockTest, PutMessage, TestSize.Level1) { - ShareMemoryBlock shareMemoryBlock; - ASSERT_TRUE(shareMemoryBlock.CreateBlock("testname", 1024)); + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); + ASSERT_TRUE(shareMemoryBlock.GetDataSize() == 0); NotifyResultResponse response; response.set_status(123); - ASSERT_TRUE(shareMemoryBlock.PutProtobuf(response)); - ASSERT_TRUE(shareMemoryBlock.GetDataSize() > 0); + ASSERT_TRUE(shareMemoryBlock.PutMessage(response)); + EXPECT_EQ(shareMemoryBlock.GetDataSize(), response.ByteSizeLong()); response.ParseFromArray(shareMemoryBlock.GetDataPoint(), shareMemoryBlock.GetDataSize()); ASSERT_TRUE(response.status() == 123); + // 调用next移动指针,取值正常 + shareMemoryBlock.Next(); + NotifyResultResponse response2; + response2.set_status(2345); + ASSERT_TRUE(shareMemoryBlock.PutMessage(response2)); + EXPECT_EQ(shareMemoryBlock.GetDataSize(), response2.ByteSizeLong()); + response2.ParseFromArray(shareMemoryBlock.GetDataPoint(), shareMemoryBlock.GetDataSize()); + EXPECT_TRUE(response2.status() == 2345); + + // 调用next,设置空message + shareMemoryBlock.Next(); + NotifyResultRequest request; + ASSERT_TRUE(shareMemoryBlock.PutMessage(request)); + EXPECT_EQ(shareMemoryBlock.GetDataSize(), request.ByteSizeLong()); + + ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); +} + +/** + * @tc.name: share memory + * @tc.desc: Shared memory PutMessage abnormal test. + * @tc.type: FUNC + */ +HWTEST_F(SharedMemoryBlockTest, PutMessageAbnormal, TestSize.Level1) +{ + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); + ASSERT_TRUE(shareMemoryBlock.GetDataSize() == 0); + + NotifyResultResponse response; + response.set_status(123); + ASSERT_TRUE(shareMemoryBlock.PutMessage(response)); + EXPECT_EQ(shareMemoryBlock.GetDataSize(), response.ByteSizeLong()); + response.ParseFromArray(shareMemoryBlock.GetDataPoint(), shareMemoryBlock.GetDataSize()); + ASSERT_TRUE(response.status() == 123); + + // 不调用next无法移动指针,取值出错 + NotifyResultResponse response2; + response2.set_status(2345); + ASSERT_TRUE(shareMemoryBlock.PutMessage(response2)); + EXPECT_NE(shareMemoryBlock.GetDataSize(), response2.ByteSizeLong()); + EXPECT_EQ(shareMemoryBlock.GetDataSize(), response.ByteSizeLong()); + response2.ParseFromArray(shareMemoryBlock.GetDataPoint(), shareMemoryBlock.GetDataSize()); + EXPECT_FALSE(response2.status() == 2345); + EXPECT_TRUE(response2.status() == 123); + + ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); +} + +/** + * @tc.name: share memory + * @tc.desc: Shared memory PutRaw abnormal test. + * @tc.type: FUNC + */ +HWTEST_F(SharedMemoryBlockTest, PutRawAbnormal, TestSize.Level1) +{ + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); + + ASSERT_FALSE(shareMemoryBlock.PutRaw(nullptr, ARRAYSIZE)); + ASSERT_NE(shareMemoryBlock.GetFreeMemory(ARRAYSIZE), nullptr); + + int8_t data[ARRAYSIZE]; + ASSERT_FALSE(shareMemoryBlock.PutRaw(data, 0)); + ASSERT_NE(shareMemoryBlock.GetFreeMemory(0), nullptr); + + ASSERT_FALSE(shareMemoryBlock.PutRaw(data, 4096+1)); + ASSERT_EQ(shareMemoryBlock.GetFreeMemory(4096+1), nullptr); + + ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); +} + +bool function(const int8_t data[], uint32_t size) +{ + auto pluginData = std::make_shared(); + return pluginData->ParseFromArray(reinterpret_cast(data), 6); +} + +bool functionErr(const int8_t data[], uint32_t size) +{ + auto pluginData = std::make_shared(); + return pluginData->ParseFromArray(reinterpret_cast(data), 4096); +} + +/** + * @tc.name: share memory + * @tc.desc: Shared memory TakeData test. + * @tc.type: FUNC + */ +HWTEST_F(SharedMemoryBlockTest, TakeData, TestSize.Level1) +{ + ShareMemoryBlock shareMemoryBlock("testname", 4096); + ASSERT_TRUE(shareMemoryBlock.Valid()); + + // 不匹配的空message + NotifyResultRequest request; + ASSERT_TRUE(shareMemoryBlock.PutMessage(request)); + ASSERT_TRUE(shareMemoryBlock.GetDataSize() == 0); + EXPECT_FALSE(shareMemoryBlock.TakeData(function)); + + // 不匹配的非空message + shareMemoryBlock.Next(); + NotifyResultResponse response; + response.set_status(123); + ASSERT_TRUE(shareMemoryBlock.PutMessage(response)); + EXPECT_FALSE(shareMemoryBlock.GetDataSize() == 0); + EXPECT_FALSE(shareMemoryBlock.TakeData(function)); + + // 匹配的空message + shareMemoryBlock.Next(); + ProfilerPluginData data; + ASSERT_TRUE(shareMemoryBlock.PutMessage(data)); + ASSERT_TRUE(shareMemoryBlock.GetDataSize() == 0); + EXPECT_FALSE(shareMemoryBlock.TakeData(function)); + + // 匹配的非空message, 但DataSize设置为大值 + shareMemoryBlock.Next(); + data.set_name("test"); + ASSERT_TRUE(shareMemoryBlock.PutMessage(data)); + EXPECT_FALSE(shareMemoryBlock.GetDataSize() == 0); + EXPECT_FALSE(shareMemoryBlock.TakeData(functionErr)); + + // 匹配的非空message,正确的DataSize + shareMemoryBlock.Next(); + data.set_name("test"); + ASSERT_TRUE(shareMemoryBlock.PutMessage(data)); + EXPECT_FALSE(shareMemoryBlock.GetDataSize() == 0); + EXPECT_TRUE(shareMemoryBlock.TakeData(function)); + ASSERT_TRUE(shareMemoryBlock.ReleaseBlock()); } } // namespace diff --git a/host/ohosprofiler/LICENSE b/host/ohosprofiler/LICENSE index e454a5258..f91efc558 100644 --- a/host/ohosprofiler/LICENSE +++ b/host/ohosprofiler/LICENSE @@ -1,178 +1,178 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + diff --git a/host/ohosprofiler/README.md b/host/ohosprofiler/README.md index c0d94acc3..a01c68dd4 100644 --- a/host/ohosprofiler/README.md +++ b/host/ohosprofiler/README.md @@ -1,66 +1,66 @@ -# Host Subsystem - -## Brief Introduction - -The tool chain consistency platform is divided into two parts: Host subsystem and equipment terminal system. -The final component of host subsystem is ide tool software,It is divided into UI drawing, device management, -process management, plug-in management, data import, data storage, data analysis, session management, configuration management and other modules. - - -## 目录 - -``` -ohos.devtools/ -├── views #GUI module -│   ├── layout #Layout module -│   ├── charts #Chart module -│   ├── common #Common module -│   └── resource #Resource module -├── services #Services module -│   ├── memory #Memory module -│   ├── diskio #diskio module -│   ├── network #network module -│   ├── ftrace #ftrace module -│   ├── bytrace #bytrace module -│   ├── hiperf #hiperf module -│   └── power #power module -├── database #database module -│   ├── transport #transport module -│   └── utils #utils module -├── -``` - -## USE - -1.To prepare development tools, you can use IntelliJ idea Community Edition or IntelliJ idea Ultimate Edition - -2.Using the development tool to import a project, if you are using it for the first time, you need to load ideaic. -In fact, this file is IntelliJ idea community version, when debugging plug-ins, idea will synchronously start a -community version of idea with plug-ins installed, which is relatively large and time-consuming - -3.Local packaging: after entering the main interface, select gradle in the right column and click build plug under IntelliJ. -If the execution is successful, the build file will be created in the root directory of the project by default, -and the packaged plug-ins will be in the directory of build / distributions.The plug-in without dependency is jar package, -and the plug-in with dependency is ZIP format. Either one can be installed directly in idea plug. -Open file ➡ Settings ➡ Plugins, select the gear button, and select Install plug from disk - -For issues related to idea platform, see -https://plugins.jetbrains.com/docs/intellij/welcome.html?from=jetbrains.org - - -## License - -``` -# 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. -``` +# Host Subsystem + +## Brief Introduction + +The tool chain consistency platform is divided into two parts: Host subsystem and equipment terminal system. +The final component of host subsystem is ide tool software,It is divided into UI drawing, device management, +process management, plug-in management, data import, data storage, data analysis, session management, configuration management and other modules. + + +## 目录 + +``` +ohos.devtools/ +├── views #GUI module +│   ├── layout #Layout module +│   ├── charts #Chart module +│   ├── common #Common module +│   └── resource #Resource module +├── services #Services module +│   ├── memory #Memory module +│   ├── diskio #diskio module +│   ├── network #network module +│   ├── ftrace #ftrace module +│   ├── bytrace #bytrace module +│   ├── hiperf #hiperf module +│   └── power #power module +├── database #database module +│   ├── transport #transport module +│   └── utils #utils module +├── +``` + +## USE + +1.To prepare development tools, you can use IntelliJ idea Community Edition or IntelliJ idea Ultimate Edition + +2.Using the development tool to import a project, if you are using it for the first time, you need to load ideaic. +In fact, this file is IntelliJ idea community version, when debugging plug-ins, idea will synchronously start a +community version of idea with plug-ins installed, which is relatively large and time-consuming + +3.Local packaging: after entering the main interface, select gradle in the right column and click build plug under IntelliJ. +If the execution is successful, the build file will be created in the root directory of the project by default, +and the packaged plug-ins will be in the directory of build / distributions.The plug-in without dependency is jar package, +and the plug-in with dependency is ZIP format. Either one can be installed directly in idea plug. +Open file ➡ Settings ➡ Plugins, select the gear button, and select Install plug from disk + +For issues related to idea platform, see +https://plugins.jetbrains.com/docs/intellij/welcome.html?from=jetbrains.org + + +## License + +``` +# 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. +``` diff --git a/host/ohosprofiler/README_zh.md b/host/ohosprofiler/README_zh.md index 6eb87fe9e..51dd678f8 100644 --- a/host/ohosprofiler/README_zh.md +++ b/host/ohosprofiler/README_zh.md @@ -1,64 +1,64 @@ -# HOST子系统 - -## 简介 - -工具链一致性平台整体分为HOST子系统和设备端子系统两部分。HOST子系统最终组件为IDE工具软件, -内部又分为UI绘制、设备管理、进程管理、插件管理、数据导入、数据存储、 数据分析、Session管理、配置管理等模块。 - - - -## 目录 - -``` -ohos.devtools/ -├── views #GUI视图管理模块 -│   ├── layout #UI布局框架 -│   ├── charts #Chart绘制模块 -│   ├── common #UI公共模块 -│   └── resource #UI资源模块 -├── services #业务管理模块 -│   ├── memory #Memory业务模块 -│   ├── diskio #diskio业务模块 -│   ├── network #network业务模块 -│   ├── ftrace #ftrace业务模块 -│   ├── bytrace #bytrace业务模块 -│   ├── hiperf #hiperf业务模块 -│   └── power #power业务模块 -├── database #数据管理模块 -│   ├── transport #数据通信模块 -│   └── utils #工具类模块 -├── -``` - -## 使用 - -1.准备开发工具,可以使用【IntelliJ IDEA社区版】或者【IntelliJ IDEA旗舰版】 - -2.使用开发工具导入项目,如果你是第一次使用是需要加载ideaIC的,这个文件其实就是 -IntelliJ Idea社区版,在插件调试时Idea会同步启动一个安装了插件的社区版Idea,由于比较大,会比较耗时 - -3.本地打包:进入主界面后,选择右边栏Gradle,在intellij下点击buildPlugin。 -执行成功默认会在项目根目录创建build文件,打包后的插件就在\build\distributions目录下。 -无依赖的插件是JAR包,带有依赖的插件是ZIP格式。无论哪种都可以直接在IDEA Plugin中安装。 -打开File➡Settings➡Plugins,选择齿轮按钮,选择Install Plugin from Disk(从本地磁盘中安装) - -IDEA Platform相关问题请参见: -https://plugins.jetbrains.com/docs/intellij/welcome.html?from=jetbrains.org - - -## 版权声明 - -``` -# 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. -``` +# HOST子系统 + +## 简介 + +工具链一致性平台整体分为HOST子系统和设备端子系统两部分。HOST子系统最终组件为IDE工具软件, +内部又分为UI绘制、设备管理、进程管理、插件管理、数据导入、数据存储、 数据分析、Session管理、配置管理等模块。 + + + +## 目录 + +``` +ohos.devtools/ +├── views #GUI视图管理模块 +│   ├── layout #UI布局框架 +│   ├── charts #Chart绘制模块 +│   ├── common #UI公共模块 +│   └── resource #UI资源模块 +├── services #业务管理模块 +│   ├── memory #Memory业务模块 +│   ├── diskio #diskio业务模块 +│   ├── network #network业务模块 +│   ├── ftrace #ftrace业务模块 +│   ├── bytrace #bytrace业务模块 +│   ├── hiperf #hiperf业务模块 +│   └── power #power业务模块 +├── database #数据管理模块 +│   ├── transport #数据通信模块 +│   └── utils #工具类模块 +├── +``` + +## 使用 + +1.准备开发工具,可以使用【IntelliJ IDEA社区版】或者【IntelliJ IDEA旗舰版】 + +2.使用开发工具导入项目,如果你是第一次使用是需要加载ideaIC的,这个文件其实就是 +IntelliJ Idea社区版,在插件调试时Idea会同步启动一个安装了插件的社区版Idea,由于比较大,会比较耗时 + +3.本地打包:进入主界面后,选择右边栏Gradle,在intellij下点击buildPlugin。 +执行成功默认会在项目根目录创建build文件,打包后的插件就在\build\distributions目录下。 +无依赖的插件是JAR包,带有依赖的插件是ZIP格式。无论哪种都可以直接在IDEA Plugin中安装。 +打开File➡Settings➡Plugins,选择齿轮按钮,选择Install Plugin from Disk(从本地磁盘中安装) + +IDEA Platform相关问题请参见: +https://plugins.jetbrains.com/docs/intellij/welcome.html?from=jetbrains.org + + +## 版权声明 + +``` +# 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. +``` diff --git a/host/ohosprofiler/build.gradle b/host/ohosprofiler/build.gradle index 9369a7602..e818d85ba 100644 --- a/host/ohosprofiler/build.gradle +++ b/host/ohosprofiler/build.gradle @@ -1,107 +1,107 @@ -/* - * 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 org.jetbrains.intellij.tasks.PrepareSandboxTask - - -plugins { - id 'java' - id 'org.jetbrains.intellij' version '0.7.2' - id 'com.google.protobuf' version '0.8.15' -} - -group 'ohos.devtools' -version '1.06.210428_Ia06bb6beaf4128368ddb697bde7dd59de608ae9a' - -project.sourceCompatibility=1.11 -project.targetCompatibility=1.11 - -repositories { - mavenCentral() -} - -dependencies { - compile "org.xerial:sqlite-jdbc:3.34.0" - implementation 'io.grpc:grpc-netty-shaded:1.36.0' - implementation 'io.grpc:grpc-protobuf:1.36.0' - implementation 'io.grpc:grpc-stub:1.36.0' - implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.11' - implementation group: 'org.xerial', name: 'sqlite-jdbc', version: '3.7.2' - implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.75' - implementation group: 'com.alibaba', name: 'druid', version: '1.1.6' - implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.14.0' - implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.14.0' - implementation group: 'org.easytesting', name: 'fest-swing', version: '1.2' - testImplementation group: 'io.grpc', name: 'grpc-testing', version: '1.36.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' - testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9' - testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9' -} - -// See https://github.com/JetBrains/gradle-intellij-plugin/ -intellij { - version '2020.3.2' - pluginName 'ohosprofiler' -} - -patchPluginXml { - changeNotes """ - Add change notes here.
- most HTML tags may be used""" -} -test { - useJUnitPlatform() -} -tasks.withType(JavaCompile) { - options.encoding = "UTF-8" -} - - -tasks.withType(PrepareSandboxTask) { - from("src/main/resources/ohos") { - into("ohosprofiler/ohos") - include("**") - } -} - -protobuf { - protoc { - artifact = "com.google.protobuf:protoc:3.12.0" - } - plugins { - grpc { - artifact = 'io.grpc:protoc-gen-grpc-java:1.36.0' - } - } - generateProtoTasks { - all()*.plugins { - grpc {} - } - } -} - -buildSearchableOptions { - enabled = false -} - -patchPluginXml { - changeNotes """ - Add change notes here.
- most HTML tags may be used""" - version = project.version - sinceBuild = '202' - untilBuild = '203.*' +/* + * 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 org.jetbrains.intellij.tasks.PrepareSandboxTask + + +plugins { + id 'java' + id 'org.jetbrains.intellij' version '0.7.2' + id 'com.google.protobuf' version '0.8.15' +} + +group 'ohos.devtools' +version '1.06.210603_I57402e91b3ca31a5e5d458a8c65d5a0a0e8e62e8' + +project.sourceCompatibility=1.11 +project.targetCompatibility=1.11 + +repositories { + mavenCentral() +} + +dependencies { + compile "org.xerial:sqlite-jdbc:3.34.0" + implementation 'io.grpc:grpc-netty-shaded:1.36.0' + implementation 'io.grpc:grpc-protobuf:1.36.0' + implementation 'io.grpc:grpc-stub:1.36.0' + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.11' + implementation group: 'org.xerial', name: 'sqlite-jdbc', version: '3.7.2' + implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.75' + implementation group: 'com.alibaba', name: 'druid', version: '1.1.6' + implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.14.0' + implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.14.0' + implementation group: 'org.easytesting', name: 'fest-swing', version: '1.2' + testImplementation group: 'io.grpc', name: 'grpc-testing', version: '1.36.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' + testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9' + testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9' +} + +// See https://github.com/JetBrains/gradle-intellij-plugin/ +intellij { + version '2020.3.2' + pluginName 'ohosprofiler' +} + +patchPluginXml { + changeNotes """ + Add change notes here.
+ most HTML tags may be used""" +} +test { + useJUnitPlatform() +} +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + + +tasks.withType(PrepareSandboxTask) { + from("src/main/resources/ohos") { + into("ohosprofiler/ohos") + include("**") + } +} + +protobuf { + protoc { + artifact = "com.google.protobuf:protoc:3.12.0" + } + plugins { + grpc { + artifact = 'io.grpc:protoc-gen-grpc-java:1.36.0' + } + } + generateProtoTasks { + all()*.plugins { + grpc {} + } + } +} + +buildSearchableOptions { + enabled = false +} + +patchPluginXml { + changeNotes """ + Add change notes here.
+ most HTML tags may be used""" + version = project.version + sinceBuild = '202' + untilBuild = '203.*' } \ No newline at end of file diff --git a/host/ohosprofiler/gradlew b/host/ohosprofiler/gradlew index c72947139..e83c8a2d6 100644 --- a/host/ohosprofiler/gradlew +++ b/host/ohosprofiler/gradlew @@ -1,185 +1,185 @@ -#!/usr/bin/env sh - -# -# 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 -# -# https://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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" +#!/usr/bin/env sh + +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/host/ohosprofiler/gradlew.bat b/host/ohosprofiler/gradlew.bat index 93118596d..bc4de66f1 100644 --- a/host/ohosprofiler/gradlew.bat +++ b/host/ohosprofiler/gradlew.bat @@ -1,89 +1,104 @@ -@rem -@rem Copyright (c) 2021 Huawei Device Co., Ltd. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright (c) 2021 Huawei Device Co., Ltd. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/host/ohosprofiler/settings.gradle b/host/ohosprofiler/settings.gradle index 0fdaf31d2..63eb3bd40 100644 --- a/host/ohosprofiler/settings.gradle +++ b/host/ohosprofiler/settings.gradle @@ -1,2 +1,2 @@ -rootProject.name = 'ohosprofilerplugin' - +rootProject.name = 'ohosprofilerplugin' + diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerApplication.java b/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerApplication.java deleted file mode 100644 index 063e7ba14..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerApplication.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.views.layout.swing.LayoutView; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * @Description IDE Application startup class - * @Date 2021/2/9 14:35 - **/ -public class ProfilerApplication { - private ProfilerApplication() { - } - - private static final Logger LOGGER = LogManager.getLogger(ProfilerApplication.class); - - /** - * main - * - * @param args args - */ - public static void main(String[] args) { - // print ohos Profiler Start the system used - LOGGER.error("ohos Profiler Start OS is {}", System.getProperty("os.name")); - // Application initialization Step1 Initialize the data center - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - LOGGER.info("start init {}", "init"); - DataBaseApi apo = DataBaseApi.getInstance(); - LOGGER.info("end init {}", "init"); - apo.initDataSourceManager(); - // Start the device discovery service - QuartzManager instance = QuartzManager.getInstance(); - String name = MultiDeviceManager.class.getName(); - MultiDeviceManager manager = MultiDeviceManager.getInstance(); - instance.addExecutor(name, manager); - instance.startExecutor(name, QuartzManager.DELAY, QuartzManager.PERIOD); - // Launch the main page - LayoutView.init(); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerToolWindowFactory.java b/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerToolWindowFactory.java index c76b980c8..8e02d8db2 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerToolWindowFactory.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/ProfilerToolWindowFactory.java @@ -1,63 +1,79 @@ -/* - * 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. - */ - -package ohos.devtools; - -import com.intellij.openapi.project.Project; -import com.intellij.openapi.wm.ToolWindow; -import com.intellij.openapi.wm.ToolWindowFactory; -import com.intellij.ui.content.ContentFactory; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.views.layout.swing.HomeWindow; -import ohos.devtools.views.layout.swing.LayoutView; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; - -/** - * Profiler Tool Window Factory - * - * @version 1.0 - * @Date 2021/3/31 14:38 - **/ -public class ProfilerToolWindowFactory implements ToolWindowFactory { - private static final Logger LOGGER = LogManager.getLogger(ProfilerToolWindowFactory.class); - - /** - * createToolWindowContent - * - * @param project project - * @param toolWindow toolWindow - */ - @Override - public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { - LOGGER.error("ohos Profiler Start OS is {}", System.getProperty("os.name")); - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - QuartzManager instance = QuartzManager.getInstance(); - String name = MultiDeviceManager.class.getName(); - MultiDeviceManager manager = MultiDeviceManager.getInstance(); - instance.addExecutor(name, manager); - instance.startExecutor(name, QuartzManager.DELAY, QuartzManager.PERIOD); - HomeWindow homeWindow = LayoutView.init(); - toolWindow.getContentManager() - .addContent(ContentFactory.SERVICE.getInstance().createContent(homeWindow, "", false)); - } -} +/* + * 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. + */ + +package ohos.devtools; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.wm.ToolWindow; +import com.intellij.openapi.wm.ToolWindowFactory; +import com.intellij.ui.content.ContentFactory; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.pluginconfig.AgentConfig; +import ohos.devtools.pluginconfig.BytraceConfig; +import ohos.devtools.pluginconfig.CpuConfig; +import ohos.devtools.pluginconfig.FtraceConfig; +import ohos.devtools.pluginconfig.MemoryConfig; +import ohos.devtools.views.layout.HomePanel; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; + +/** + * Profiler Tool Window Factory + */ +public class ProfilerToolWindowFactory implements ToolWindowFactory { + private static final Logger LOGGER = LogManager.getLogger(ProfilerToolWindowFactory.class); + + /** + * createToolWindowContent + * + * @param project project + * @param toolWindow toolWindow + */ + @Override + public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { + LOGGER.error("ohos Profiler Start OS is {}", System.getProperty("os.name")); + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi.getInstance().initDataSourceManager(); + MultiDeviceManager.getInstance().start(); + List> plugConfigList = new ArrayList(); + plugConfigList.add(AgentConfig.class); + plugConfigList.add(BytraceConfig.class); + // plugConfigList.add(FtraceConfig.class); + plugConfigList.add(CpuConfig.class); + plugConfigList.add(MemoryConfig.class); + PlugManager.getInstance().loadingPlugs(plugConfigList); + toolWindow.getContentManager() + .addContent(ContentFactory.SERVICE.getInstance().createContent(new HomePanel(), "", false)); + // hook the Runtime thread + Runtime.getRuntime().addShutdownHook(new WindowShutdownHook()); + } + + private class WindowShutdownHook extends Thread { + @Override + public void run() { + SessionManager.getInstance().stopAllSession(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApi.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApi.java index 48e073c51..a8e79bb40 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApi.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApi.java @@ -1,402 +1,411 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databaseapi; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import ohos.devtools.datasources.databases.databasemanager.DataBaseManager; -import ohos.devtools.datasources.databases.databasepool.DataBase; -import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; -import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; -import ohos.devtools.datasources.utils.common.util.CommonUtil; - -import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; - -/** - * @Description Provides database related operations - * @Date 2021/1/25 13:15 - **/ -public class DataBaseApi { - private static final Logger LOGGER = LogManager.getLogger(DataBaseApi.class); - - /** - * System main library name - */ - public static final String DEFAULT_DATABASE_DBNAME = "defaultDB"; - - /** - * Correspondence between storage database name and database connection pool - */ - private static Map dataSourcePooleMap = new ConcurrentHashMap(CommonUtil.collectionSize(0)); - - /** - * Correspondence between storage database name and database connection pool - */ - private static List tableIndex = new ArrayList<>(CommonUtil.collectionSize(0)); - - /** - * Correspondence between storage table name and database name - */ - private static Map groupTables = new ConcurrentHashMap(CommonUtil.collectionSize(0)); - - private static class SingletonClassInstance { - private static final DataBaseApi INSTANCE = new DataBaseApi(); - } - - /** - * getInstance - * - * @return DataBaseApi - */ - public static DataBaseApi getInstance() { - return DataBaseApi.SingletonClassInstance.INSTANCE; - } - - private DataBaseApi() { - } - - /** - * Initialize the data source manager, which is called when the system is started, and only called once. - * - * @return boolean - */ - public boolean initDataSourceManager() { - return createDataBase(null, true); - } - - /** - * Create a database. If it is a system main library, create a data table in the main library. - * - * @param dbName data storage name - * @param appStart Whether the application just started - * @return boolean - */ - private boolean createDataBase(String dbName, boolean appStart) { - if (appStart) { - if (StringUtils.isBlank(dbName) || DEFAULT_DATABASE_DBNAME.equals(dbName)) { - DataBaseManager dataBaseManager = DataBaseManager.getInstance(); - DataBase dataBase = DataBaseHelper.createDefaultDataBase(); - dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); - boolean result = dataBaseManager.initDefaultDataBase(dataBase); - if (result) { - return dataBaseManager.initDefaultSql(dataBase); - } - } else { - if (StringUtils.isBlank(dbName) || appStart) { - return false; - } - if (dataSourcePooleMap.get(dbName) != null) { - return true; - } - return DataBaseManager.getInstance().createDataBase(dbName); - } - } else { - if (StringUtils.isBlank(dbName)) { - return false; - } - if (dataSourcePooleMap.get(dbName) != null) { - return true; - } - return DataBaseManager.getInstance().createDataBase(dbName); - } - return false; - } - - /** - * Get the database connection of the main library of the system - * - * @return Optional - */ - public Optional getDefaultDataBaseConnect() { - try { - return Optional.of(getPoolByDataBaseName(DEFAULT_DATABASE_DBNAME).getConnection()); - } catch (SQLException sqlException) { - LOGGER.info("getConnectByTable Exception {}", sqlException.getMessage()); - return Optional.empty(); - } - } - - /** - * Get database connection based on table name - * - * @param tableName tableName - * @return Optional - */ - public Optional getConnectByTable(String tableName) { - if (StringUtils.isBlank(tableName)) { - return Optional.empty(); - } - String dbName = groupTables.get(tableName.toUpperCase(Locale.ENGLISH)); - if (StringUtils.isNotBlank(dbName)) { - try { - Connection conn = getPoolByDataBaseName(dbName).getConnection(); - return Optional.of(conn); - } catch (SQLException throwAbles) { - LOGGER.info("getConnectByTable Exception {}", throwAbles.getMessage()); - } - } - return Optional.empty(); - } - - /** - * Get database connection based on database name - * - * @param dataBaseName dataBaseName - * @return Optional - */ - public Optional getConnectBydbname(String dataBaseName) { - Connection connection; - try { - connection = getPoolByDataBaseName(dataBaseName).getConnection(); - return Optional.of(connection); - } catch (SQLException throwAbles) { - LOGGER.info("getConnectByTable Exception {}", throwAbles.getMessage()); - } - return Optional.empty(); - } - - /** - * Get the database connection pool object according to the database name - * - * @param dataBaseName dataBaseName - * @return DataSource - */ - public DataSource getPoolByDataBaseName(String dataBaseName) { - DataSource dataSource; - if (StringUtils.isBlank(dataBaseName)) { - dataSource = dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); - if (dataSource == null) { - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName(dataBaseName)); - DataSource dataPool = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - registerDataSource(DEFAULT_DATABASE_DBNAME, dataPool); - return dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); - } - return dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); - } else { - dataSource = dataSourcePooleMap.get(dataBaseName); - if (dataSource == null) { - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName(dataBaseName)); - DataSource dataPool = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - registerDataSource(dataBaseName, dataPool); - return dataSourcePooleMap.get(dataBaseName); - } - return dataSourcePooleMap.get(dataBaseName); - } - } - - /** - * Correspondence between registered data table and database - * - * @param tableName tableName - * @param dbName dbName - */ - public void registerTable(String tableName, String dbName) { - if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(dbName)) { - groupTables.put(tableName.toUpperCase(Locale.ENGLISH), dbName); - } - } - - /** - * Correspondence between registered data table and database - * - * @param tableName tableName - * @return String - */ - public String checkTableRegister(String tableName) { - if (StringUtils.isNotBlank(tableName)) { - return groupTables.get(tableName.toUpperCase(Locale.ENGLISH)); - } - return ""; - } - - /** - * Correspondence between registered data table and database - * - * @param tableName tableName - * @return String - */ - public boolean checkIndexRegister(String tableName) { - if (StringUtils.isNotBlank(tableName)) { - return tableIndex.contains(tableName); - } - return false; - } - - /** - * Correspondence between registered database name and database connection pool - * - * @param dataBaseName dataBaseName - * @param dataSource dataSource - */ - public void registerDataSource(String dataBaseName, DataSource dataSource) { - if (StringUtils.isNotBlank(dataBaseName) && dataSource != null) { - dataSourcePooleMap.put(dataBaseName, dataSource); - } - } - - /** - * Index of the registry. - * - * @param tableName tableName - */ - public void registerCreateIndex(String tableName) { - if (StringUtils.isNotBlank(tableName)) { - tableIndex.add(tableName); - } - } - - /** - * Create a database, which is used to dynamically create a database during system operation - * - * @param dbName dbName - * @return boolean - */ - public boolean createDataBase(String dbName) { - return createDataBase(dbName, false); - } - - /** - * Create table - * - * @param dbName dbName - * @param tableName tableName - * @param params params - * @return boolean - */ - public boolean createTable(String dbName, String tableName, List params) { - if (StringUtils.isBlank(tableName) || StringUtils.isBlank(dbName)) { - return false; - } - if (params == null && params.isEmpty()) { - return false; - } - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(String.format(Locale.ENGLISH, "CREATE TABLE if not exists %s", tableName)); - Optional optionalConnection = getConnectBydbname(dbName); - if (optionalConnection.isPresent()) { - Connection conn = optionalConnection.get(); - String value = params.stream().collect(Collectors.joining(",")); - Statement statement = null; - try { - String db = DataBaseApi.getInstance().checkTableRegister(tableName); - if (tableName.equals(db)) { - return true; - } - statement = conn.createStatement(); - statement.execute(String.format(Locale.ENGLISH, "%s ( %s )", stringBuffer, value)); - registerTable(tableName, dbName); - return true; - } catch (SQLException throwAbles) { - LOGGER.info("SQLException Error {}: ", throwAbles.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, null, statement); - } - } - return false; - } - - /** - * createTable - * - * @param dbName dbName - * @param tableName tableName - * @param sql sql - * @return boolean - */ - public boolean createTable(String dbName, String tableName, String sql) { - if (StringUtils.isBlank(tableName) || StringUtils.isBlank(dbName) || StringUtils.isBlank(sql)) { - return false; - } - Optional connect = getConnectBydbname(dbName); - if (connect.isPresent()) { - Connection conn = connect.get(); - Statement statm = null; - try { - String db = DataBaseApi.getInstance().checkTableRegister(tableName); - if (dbName.equals(db)) { - return true; - } - statm = conn.createStatement(); - statm.execute(sql); - registerTable(tableName, dbName); - return true; - } catch (SQLException throwAbles) { - LOGGER.info("create Table Error {}", throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, null, statm); - } - } - return false; - } - - /** - * Create table index - * - * @param tableName tableName - * @param indexName indexName - * @param columnName columnName - * @return boolean - */ - public boolean createIndex(String tableName, String indexName, List columnName) { - if (StringUtils.isBlank(tableName) || StringUtils.isBlank(indexName)) { - return false; - } - if (columnName == null || columnName.isEmpty()) { - return false; - } - if (checkIndexRegister(tableName)) { - return true; - } - StringBuffer stringBuffer = new StringBuffer("CREATE INDEX IF NOT EXISTS ").append(indexName).append(" ON "); - stringBuffer.append(tableName).append("("); - String value = columnName.stream().collect(Collectors.joining(",")); - stringBuffer.append(value).append(")"); - Optional optionalConnection = getConnectByTable(tableName); - if (optionalConnection.isPresent()) { - Connection conn = optionalConnection.get(); - Statement statement = null; - try { - statement = conn.createStatement(); - statement.execute(stringBuffer.toString()); - registerCreateIndex(tableName); - return true; - } catch (SQLException throwAbles) { - LOGGER.info("SQLException Error {}: ", throwAbles.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, null, statement); - } - } - return false; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databaseapi; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import ohos.devtools.datasources.databases.databasemanager.DataBaseManager; +import ohos.devtools.datasources.databases.databasepool.DataBase; +import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.datasources.utils.common.util.CommonUtil; + +import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; + +/** + * Provides database related operations + */ +public class DataBaseApi { + private static final Logger LOGGER = LogManager.getLogger(DataBaseApi.class); + + /** + * System main library name + */ + public static final String DEFAULT_DATABASE_DBNAME = "defaultDB"; + + /** + * CREATE TABLE sql + */ + private static final String CREATE_TABLE = "CREATE TABLE if not exists %s"; + + /** + * CREATE TABLE INDEX sql + */ + private static final String CREATE_TABLE_INDEX = "CREATE INDEX IF NOT EXISTS "; + + /** + * Correspondence between storage database name and database connection pool + */ + private static Map dataSourcePooleMap = new ConcurrentHashMap(CommonUtil.collectionSize(0)); + + /** + * Correspondence between storage database name and database connection pool + */ + private static List tableIndex = new ArrayList<>(CommonUtil.collectionSize(0)); + + /** + * Correspondence between storage table name and database name + */ + private static Map groupTables = new ConcurrentHashMap(CommonUtil.collectionSize(0)); + + private static class SingletonClassInstance { + private static final DataBaseApi INSTANCE = new DataBaseApi(); + } + + /** + * getInstance + * + * @return DataBaseApi + */ + public static DataBaseApi getInstance() { + return DataBaseApi.SingletonClassInstance.INSTANCE; + } + + private DataBaseApi() { + } + + /** + * Initialize the data source manager, which is called when the system is started, and only called once. + * + * @return boolean + */ + public boolean initDataSourceManager() { + return createDataBase(null, true); + } + + /** + * Create a database. If it is a system main library, create a data table in the main library. + * + * @param dbName data storage name + * @param appStart Whether the application just started + * @return boolean + */ + private boolean createDataBase(String dbName, boolean appStart) { + if (appStart) { + if (StringUtils.isBlank(dbName) || DEFAULT_DATABASE_DBNAME.equals(dbName)) { + DataBaseManager dataBaseManager = DataBaseManager.getInstance(); + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); + boolean result = dataBaseManager.initDefaultDataBase(dataBase); + if (result) { + return dataBaseManager.initDefaultSql(dataBase); + } + } else { + if (StringUtils.isBlank(dbName) || appStart) { + return false; + } + if (dataSourcePooleMap.get(dbName) != null) { + return true; + } + return DataBaseManager.getInstance().createDataBase(dbName); + } + } else { + if (StringUtils.isBlank(dbName)) { + return false; + } + if (dataSourcePooleMap.get(dbName) != null) { + return true; + } + return DataBaseManager.getInstance().createDataBase(dbName); + } + return false; + } + + /** + * Get the database connection of the main library of the system + * + * @return Optional + */ + public Optional getDefaultDataBaseConnect() { + try { + return Optional.of(getPoolByDataBaseName(DEFAULT_DATABASE_DBNAME).getConnection()); + } catch (SQLException sqlException) { + LOGGER.info("getConnectByTable Exception ", sqlException); + return Optional.empty(); + } + } + + /** + * Get database connection based on table name + * + * @param tableName tableName + * @return Optional + */ + public Optional getConnectByTable(String tableName) { + if (StringUtils.isBlank(tableName)) { + return Optional.empty(); + } + String dbName = groupTables.get(tableName.toUpperCase(Locale.ENGLISH)); + if (StringUtils.isNotBlank(dbName)) { + try { + Connection conn = getPoolByDataBaseName(dbName).getConnection(); + return Optional.of(conn); + } catch (SQLException throwAbles) { + LOGGER.info("getConnectByTable Exception ", throwAbles); + } + } + return Optional.empty(); + } + + /** + * Get database connection based on database name + * + * @param dataBaseName dataBaseName + * @return Optional + */ + public Optional getConnectBydbname(String dataBaseName) { + Connection connection; + try { + connection = getPoolByDataBaseName(dataBaseName).getConnection(); + return Optional.of(connection); + } catch (SQLException throwAbles) { + LOGGER.info("getConnectByTable Exception ", throwAbles); + } + return Optional.empty(); + } + + /** + * Get the database connection pool object according to the database name + * + * @param dataBaseName dataBaseName + * @return DataSource + */ + public DataSource getPoolByDataBaseName(String dataBaseName) { + DataSource dataSource; + if (StringUtils.isBlank(dataBaseName)) { + dataSource = dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); + if (dataSource == null) { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName(dataBaseName)); + DataSource dataPool = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + registerDataSource(DEFAULT_DATABASE_DBNAME, dataPool); + return dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); + } + return dataSourcePooleMap.get(DEFAULT_DATABASE_DBNAME); + } else { + dataSource = dataSourcePooleMap.get(dataBaseName); + if (dataSource == null) { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName(dataBaseName)); + DataSource dataPool = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + registerDataSource(dataBaseName, dataPool); + return dataSourcePooleMap.get(dataBaseName); + } + return dataSourcePooleMap.get(dataBaseName); + } + } + + /** + * Correspondence between registered data table and database + * + * @param tableName tableName + * @param dbName dbName + */ + public void registerTable(String tableName, String dbName) { + if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(dbName)) { + groupTables.put(tableName.toUpperCase(Locale.ENGLISH), dbName); + } + } + + /** + * Correspondence between registered data table and database + * + * @param tableName tableName + * @return String + */ + public String checkTableRegister(String tableName) { + if (StringUtils.isNotBlank(tableName)) { + return groupTables.get(tableName.toUpperCase(Locale.ENGLISH)); + } + return ""; + } + + /** + * Correspondence between registered data table and database + * + * @param tableName tableName + * @return String + */ + public boolean checkIndexRegister(String tableName) { + if (StringUtils.isNotBlank(tableName)) { + return tableIndex.contains(tableName); + } + return false; + } + + /** + * Correspondence between registered database name and database connection pool + * + * @param dataBaseName dataBaseName + * @param dataSource dataSource + */ + public void registerDataSource(String dataBaseName, DataSource dataSource) { + if (StringUtils.isNotBlank(dataBaseName) && dataSource != null) { + dataSourcePooleMap.put(dataBaseName, dataSource); + } + } + + /** + * Index of the registry. + * + * @param tableName tableName + */ + public void registerCreateIndex(String tableName) { + if (StringUtils.isNotBlank(tableName)) { + tableIndex.add(tableName); + } + } + + /** + * Create a database, which is used to dynamically create a database during system operation + * + * @param dbName dbName + * @return boolean + */ + public boolean createDataBase(String dbName) { + return createDataBase(dbName, false); + } + + /** + * Create table + * + * @param dbName dbName + * @param tableName tableName + * @param params params + * @return boolean + */ + public boolean createTable(String dbName, String tableName, List params) { + if (StringUtils.isBlank(tableName) || StringUtils.isBlank(dbName)) { + return false; + } + if (params == null && params.isEmpty()) { + return false; + } + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append(String.format(Locale.ENGLISH, CREATE_TABLE, tableName)); + Optional optionalConnection = getConnectBydbname(dbName); + if (optionalConnection.isPresent()) { + Connection conn = optionalConnection.get(); + String value = params.stream().collect(Collectors.joining(",")); + Statement statement = null; + try { + String db = DataBaseApi.getInstance().checkTableRegister(tableName); + if (tableName.equals(db)) { + return true; + } + statement = conn.createStatement(); + statement.execute(String.format(Locale.ENGLISH, "%s ( %s )", stringBuffer, value)); + registerTable(tableName, dbName); + return true; + } catch (SQLException throwAbles) { + LOGGER.info("SQLException Error : ", throwAbles); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, null, statement); + } + } + return false; + } + + /** + * createTable + * + * @param dbName dbName + * @param tableName tableName + * @param sql sql + * @return boolean + */ + public boolean createTable(String dbName, String tableName, String sql) { + if (StringUtils.isBlank(tableName) || StringUtils.isBlank(dbName) || StringUtils.isBlank(sql)) { + return false; + } + Optional connect = getConnectBydbname(dbName); + if (connect.isPresent()) { + Connection conn = connect.get(); + Statement statm = null; + try { + String db = DataBaseApi.getInstance().checkTableRegister(tableName); + if (dbName.equals(db)) { + return true; + } + statm = conn.createStatement(); + statm.execute(sql); + registerTable(tableName, dbName); + return true; + } catch (SQLException throwAbles) { + LOGGER.info("create Table Error ", throwAbles); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, null, statm); + } + } + return false; + } + + /** + * Create table index + * + * @param tableName tableName + * @param indexName indexName + * @param columnName columnName + * @return boolean + */ + public boolean createIndex(String tableName, String indexName, List columnName) { + if (StringUtils.isBlank(tableName) || StringUtils.isBlank(indexName)) { + return false; + } + if (columnName == null || columnName.isEmpty()) { + return false; + } + if (checkIndexRegister(tableName)) { + return true; + } + StringBuffer stringBuffer = new StringBuffer(CREATE_TABLE_INDEX).append(indexName).append(" ON "); + stringBuffer.append(tableName).append("("); + String value = columnName.stream().collect(Collectors.joining(",")); + stringBuffer.append(value).append(")"); + Optional optionalConnection = getConnectByTable(tableName); + if (optionalConnection.isPresent()) { + Connection conn = optionalConnection.get(); + Statement statement = null; + try { + statement = conn.createStatement(); + statement.execute(stringBuffer.toString()); + registerCreateIndex(tableName); + return true; + } catch (SQLException throwAbles) { + LOGGER.info("SQLException Error : ", throwAbles); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, null, statement); + } + } + return false; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManager.java index 145542899..d2d941471 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManager.java @@ -1,213 +1,216 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasemanager; - -import com.alibaba.druid.pool.DruidDataSource; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.DataBase; -import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.sql.DataSource; -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import static ohos.devtools.datasources.databases.databaseapi.DataBaseApi.DEFAULT_DATABASE_DBNAME; -import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getFilePath; -import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; -import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.loadSqlFileToList; -import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.getTableNameBySql; - -/** - * @Description Database creation class - * @Date 2021/2/2 11:28 - **/ -public class DataBaseManager { - private static final Logger LOGGER = LogManager.getLogger(DataBaseManager.class); - - private static Set dbLists = new HashSet<>(); - - private static class SingletonClassInstance { - private static final DataBaseManager INSTANCE = new DataBaseManager(); - } - - /** - * getInstance - * - * @return DataBaseApi - */ - public static DataBaseManager getInstance() { - return DataBaseManager.SingletonClassInstance.INSTANCE; - } - - private DataBaseManager() { - } - - /** - * Initialize the main database of the project - * - * @param dataBase DataBase - * @return boolean - */ - public boolean initDefaultDataBase(DataBase dataBase) { - return createDataBase(dataBase); - } - - /** - * Create a data table in the main database of the database, - * and the table creation statement is stored in the path configured by default Sql - * - * @param dataBase DataBase - * @return boolean - */ - public boolean initDefaultSql(DataBase dataBase) { - Properties properties = new Properties(); - Statement statement = null; - Connection connection = null; - try { - properties.load(DataBaseManager.class.getClassLoader().getResourceAsStream("db.properties")); - String initPath = properties.getProperty("defaultSql"); - if (StringUtils.isNotBlank(initPath)) { - String sqlConfigPath = SessionManager.getInstance().getPluginPath() + initPath; - List sqlList = loadSqlFileToList(sqlConfigPath); - DataSource dataSource = createDruidConnectionPool(dataBase); - DataBaseApi.getInstance().registerDataSource(DEFAULT_DATABASE_DBNAME, dataSource); - connection = dataSource.getConnection(); - statement = connection.createStatement(); - for (String sql : sqlList) { - String tableName = getTableNameBySql(sql); - String dbName = DataBaseApi.getInstance().checkTableRegister(tableName); - if (DEFAULT_DATABASE_DBNAME.equals(dbName)) { - continue; - } - statement.execute(sql); - DataBaseApi.getInstance().registerTable(tableName, DEFAULT_DATABASE_DBNAME); - } - return true; - } - } catch (IOException | SQLException exception) { - LOGGER.error("create Table Exception {}", exception.getMessage()); - return false; - } finally { - if (statement != null) { - try { - statement.close(); - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - if (connection != null) { - try { - connection.close(); - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - } - return false; - } - - /** - * Create database - * - * @param dbName dbName - * @return boolean - */ - public boolean createDataBase(String dbName) { - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName(dbName)); - return createDataBase(dataBase); - } - - /** - * Create database - * - * @param dataBase dataBase - * @return boolean - */ - private boolean createDataBase(DataBase dataBase) { - if (dataBase.getUrl() == null || StringUtils.isBlank(dataBase.getUrl())) { - return false; - } - String dbPath = getFilePath(dataBase.getUrl()); - if (dbLists.contains(dataBase.getUrl())) { - return true; - } - File dbFile = new File(dbPath); - if (dbFile.exists()) { - boolean deletResult = dbFile.delete(); - if (!deletResult) { - LOGGER.error("delete Error"); - } - } else { - LOGGER.error("File Error"); - } - File parent = dbFile.getParentFile(); - if (parent == null) { - parent.mkdirs(); - } - try { - Class.forName("org.sqlite.JDBC"); - DriverManager.getConnection(dataBase.getUrl()); - dbLists.add(dataBase.getUrl()); - return true; - } catch (SQLException | ClassNotFoundException throwAbles) { - LOGGER.error("create DataBase failed {}", throwAbles.getMessage()); - return false; - } - } - - /** - * Create a database connection pool - * - * @param dataBase dataBase - * @return DataSource - */ - public DataSource createDruidConnectionPool(DataBase dataBase) { - boolean base = createDataBase(dataBase); - if (!base) { - return null; - } - DruidDataSource dataSource = new DruidDataSource(); - dataSource.setUrl(dataBase.getUrl()); - dataSource.setInitialSize(dataBase.getInitialSize()); - dataSource.setMaxActive(dataBase.getMaxActive()); - dataSource.setMinIdle(dataBase.getMinIdle()); - try { - dataSource.setFilters(dataBase.getFilters()); - dataSource.setMaxWait(dataBase.getMaxWait()); - dataSource.setTimeBetweenEvictionRunsMillis(dataBase.getTimeBetweenEvictionRunsMillis()); - dataSource.setValidationQuery(dataBase.getValidationQuery()); - dataSource.setTestWhileIdle(dataBase.isTestWhileIdle()); - dataSource.setTestOnBorrow(dataBase.isTestOnBorrow()); - dataSource.setTestOnReturn(dataBase.isTestOnReturn()); - } catch (SQLException throwAbles) { - LOGGER.error("create ConnectPoll {}", throwAbles.getMessage()); - } - return dataSource; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasemanager; + +import com.alibaba.druid.pool.DruidDataSource; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.DataBase; +import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.sql.DataSource; +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import static ohos.devtools.datasources.databases.databaseapi.DataBaseApi.DEFAULT_DATABASE_DBNAME; +import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getFilePath; +import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; +import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.loadSqlFileToList; +import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.getTableNameBySql; + +/** + * Database creation class + */ +public class DataBaseManager { + private static final Logger LOGGER = LogManager.getLogger(DataBaseManager.class); + private static final String DEFAULT_SQL = "defaultSql"; + private static final String DEFAULT_DB_PROPER = "db.properties"; + private static final String DEFAULT_DB_DRIVER = "org.sqlite.JDBC"; + private static Set dbLists = new HashSet<>(); + + private static class SingletonClassInstance { + private static final DataBaseManager INSTANCE = new DataBaseManager(); + } + + /** + * getInstance + * + * @return DataBaseApi + */ + public static DataBaseManager getInstance() { + return DataBaseManager.SingletonClassInstance.INSTANCE; + } + + private DataBaseManager() { + } + + /** + * Initialize the main database of the project + * + * @param dataBase DataBase + * @return boolean + */ + public boolean initDefaultDataBase(DataBase dataBase) { + return createDataBase(dataBase); + } + + /** + * Create a data table in the main database of the database, + * and the table creation statement is stored in the path configured by default Sql + * + * @param dataBase DataBase + * @return boolean + */ + public boolean initDefaultSql(DataBase dataBase) { + Properties properties = new Properties(); + Statement statement = null; + Connection connection = null; + try { + properties.load(DataBaseManager.class.getClassLoader().getResourceAsStream(DEFAULT_DB_PROPER)); + String initPath = properties.getProperty(DEFAULT_SQL); + if (StringUtils.isNotBlank(initPath)) { + String sqlConfigPath = SessionManager.getInstance().getPluginPath() + initPath; + List sqlList = loadSqlFileToList(sqlConfigPath); + DataSource dataSource = createDruidConnectionPool(dataBase); + if (dataSource != null) { + DataBaseApi.getInstance().registerDataSource(DEFAULT_DATABASE_DBNAME, dataSource); + connection = dataSource.getConnection(); + statement = connection.createStatement(); + for (String sql : sqlList) { + String tableName = getTableNameBySql(sql); + String dbName = DataBaseApi.getInstance().checkTableRegister(tableName); + if (DEFAULT_DATABASE_DBNAME.equals(dbName)) { + continue; + } + statement.execute(sql); + DataBaseApi.getInstance().registerTable(tableName, DEFAULT_DATABASE_DBNAME); + } + return true; + } + } + } catch (IOException | SQLException exception) { + LOGGER.error("create Table Exception ", exception); + return false; + } finally { + if (statement != null) { + try { + statement.close(); + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + } + return false; + } + + /** + * Create database + * + * @param dbName dbName + * @return boolean + */ + public boolean createDataBase(String dbName) { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName(dbName)); + return createDataBase(dataBase); + } + + /** + * Create database + * + * @param dataBase dataBase + * @return boolean + */ + private boolean createDataBase(DataBase dataBase) { + if (dataBase == null || dataBase.getUrl() == null || StringUtils.isBlank(dataBase.getUrl())) { + return false; + } + String dbPath = getFilePath(dataBase.getUrl()); + if (dbLists.contains(dataBase.getUrl())) { + return true; + } + File dbFile = new File(dbPath); + if (dbFile.exists()) { + boolean deletResult = dbFile.delete(); + if (!deletResult) { + LOGGER.error("delete Error"); + } + } else { + LOGGER.error("DB file not exit"); + } + File parent = dbFile.getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + try { + Class.forName(DEFAULT_DB_DRIVER); + DriverManager.getConnection(dataBase.getUrl()); + dbLists.add(dataBase.getUrl()); + return true; + } catch (SQLException | ClassNotFoundException throwAbles) { + LOGGER.error("create DataBase failed {}", throwAbles.getMessage()); + return false; + } + } + + /** + * Create a database connection pool + * + * @param dataBase dataBase + * @return DataSource + */ + public DataSource createDruidConnectionPool(DataBase dataBase) { + boolean base = createDataBase(dataBase); + if (!base) { + return null; + } + DruidDataSource dataSource = new DruidDataSource(); + dataSource.setUrl(dataBase.getUrl()); + dataSource.setInitialSize(dataBase.getInitialSize()); + dataSource.setMaxActive(dataBase.getMaxActive()); + dataSource.setMinIdle(dataBase.getMinIdle()); + try { + dataSource.setFilters(dataBase.getFilters()); + dataSource.setMaxWait(dataBase.getMaxWait()); + dataSource.setTimeBetweenEvictionRunsMillis(dataBase.getTimeBetweenEvictionRunsMillis()); + dataSource.setValidationQuery(dataBase.getValidationQuery()); + dataSource.setTestWhileIdle(dataBase.isTestWhileIdle()); + dataSource.setTestOnBorrow(dataBase.isTestOnBorrow()); + dataSource.setTestOnReturn(dataBase.isTestOnReturn()); + } catch (SQLException throwAbles) { + LOGGER.error("create ConnectPoll {}", throwAbles.getMessage()); + } + return dataSource; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/AbstractDataStore.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/AbstractDataStore.java index 57317055f..7ec62dffe 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/AbstractDataStore.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/AbstractDataStore.java @@ -1,283 +1,281 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.common.util.BeanUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.getDeleteCondition; -import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.mapToString; -import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.sqlPlaceholder; - -/** - * @param - * @Description Provides common data table operations - * @Date 2021/1/26 13:15 - **/ -public abstract class AbstractDataStore extends SqlRunnable { - private static final Logger LOGGER = LogManager.getLogger(AbstractDataStore.class); - private static final String TYPE = "type"; - private static final String STRING = "String"; - - /** - * Data insertion - * - * @param dataObject dataObject - * @param - * @return boolean - */ - @SuppressWarnings("checkstyle:JavadocMethod") - public boolean insert(T dataObject) { - if (dataObject instanceof List) { - return insertInDateBaseBatch((List) dataObject); - } - return insertInDataBase(dataObject); - } - - /** - * Get database connection - * - * @param tableName tableName - * @return Optional - */ - protected Optional getConnectByTable(String tableName) { - Optional connection = DataBaseApi.getInstance().getConnectByTable(tableName); - return connection; - } - - /** - * Get database connection - * - * @param dbName dbName - * @return Optional - */ - protected Optional getConnectBydbName(String dbName) { - Optional connection = DataBaseApi.getInstance().getConnectBydbname(dbName); - return connection; - } - - /** - * Insert data in bulk - * - * @param dataObject dataObject - * @return boolean - */ - private boolean insertInDateBaseBatch(List dataObject) { - Object obj = dataObject.get(0); - String tableName = BeanUtil.getObjectName(obj); - Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); - StringBuffer insertSql = new StringBuffer("INSERT OR IGNORE INTO "); - List attrs = BeanUtil.getObjectAttributeNames(obj); - String value = attrs.stream().collect(Collectors.joining(",")); - insertSql.append(tableName).append("(").append(value).append(") VALUES (").append(sqlPlaceholder(attrs.size())) - .append(")"); - try { - PreparedStatement psmt = connection.prepareStatement(insertSql.toString()); - for (Object data : dataObject) { - applyParams(psmt, data); - psmt.addBatch(); - } - return executeBatch(connection, psmt); - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } - return false; - } - - private void applyParams(PreparedStatement statement, T data) { - List list = BeanUtil.getFieldsInfo(data); - try { - for (int index = 0; index < list.size(); index++) { - Map objMap = list.get(index); - Object objValue = objMap.get("value"); - if (String.valueOf(objMap.get(TYPE)).contains(STRING)) { - if (objValue instanceof String) { - statement.setString(index + 1, (String) objValue); - } - } else if (String.valueOf(objMap.get(TYPE)).contains("Integer")) { - if (objValue instanceof Integer) { - statement.setLong(index + 1, (int) objValue); - } - } else if (String.valueOf(objMap.get(TYPE)).contains("Long")) { - if (objValue instanceof Long) { - statement.setLong(index + 1, (long) objValue); - } - } else if (String.valueOf(objMap.get(TYPE)).contains("byte")) { - if (objValue instanceof byte[]) { - statement.setBytes(index + 1, (byte[]) objValue); - } - } else if (String.valueOf(objMap.get(TYPE)).contains("Boolean")) { - if (objValue instanceof Boolean) { - statement.setBoolean(index + 1, (boolean) objValue); - } - } else { - continue; - } - } - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - - private boolean insertInDataBase(T dataObject) { - String tableName = BeanUtil.getObjectName(dataObject); - StringBuffer insertSql = new StringBuffer("INSERT OR IGNORE INTO "); - List> objectInfos = BeanUtil.getFields(dataObject); - StringBuffer attrs = new StringBuffer(); - StringBuffer values = new StringBuffer(); - objectInfos.forEach(objectMap -> { - attrs.append(objectMap.get("name")).append(","); - if (String.valueOf(objectMap.get(TYPE)).contains(STRING)) { - values.append("'").append(objectMap.get("value")).append("',"); - } else { - values.append(objectMap.get("value")).append(","); - } - }); - insertSql.append(tableName).append("(").append(attrs.deleteCharAt(attrs.length() - 1).toString()) - .append(") VALUES (").append(values.deleteCharAt(values.length() - 1).toString()).append(")"); - Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); - return execute(connection, insertSql.toString()); - } - - /** - * Delete database - * - * @param dataObject dataObject - * @return boolean - */ - public boolean delete(T dataObject) { - return deleteInDataBase(dataObject); - } - - private boolean deleteInDataBase(T dataObject) { - String tableName = BeanUtil.getObjectName(dataObject); - StringBuffer deleteSql = new StringBuffer("DELETE FROM "); - Map beanMap = BeanUtil.getFiledsInfos(dataObject); - deleteSql.append(tableName).append("WHERE ").append(getDeleteCondition(beanMap)).append("1 = 1"); - Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); - return execute(connection, deleteSql.toString()); - } - - /** - * update - * - * @param clazz clazz - * @param condition condition - * @param setValue setValue - * @param - * @return boolean - */ - public boolean update(Class clazz, Map condition, Map setValue) { - StringBuffer updateSql = new StringBuffer("UPDATE "); - String tableName = clazz.getSimpleName(); - updateSql.append(tableName).append("SET").append(mapToString(setValue)).append("WHERE ").append(condition); - Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); - return execute(connection, updateSql.toString()); - } - - /** - * Inquire - * - * @param clazz clazz - * @param value value - * @param condition condition - * @param - * @return List - */ - public List select(Class clazz, Map value, Map condition) { - StringBuffer selectSql = new StringBuffer("SELECT "); - if (value == null || value.isEmpty()) { - selectSql.append("*"); - } - String tableName = clazz.getSimpleName(); - if (condition == null || condition.isEmpty()) { - selectSql.append(" FROM ").append(tableName); - } else { - selectSql.append(" FROM ").append(tableName).append(" WHERE ").append(getDeleteCondition(condition)); - } - Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); - Statement stmt = null; - ResultSet rs = null; - try { - stmt = connection.createStatement(); - rs = executeQuery(stmt, selectSql.toString()); - return new DataBaseRsHelp().util(clazz.newInstance(), rs); - } catch (SQLException exe) { - LOGGER.error("SQLException: " + exe.getMessage()); - } catch (IllegalAccessException exception) { - LOGGER.error("IllegalAccessException: " + exception.getMessage()); - } catch (InstantiationException exception) { - LOGGER.error("InstantiationException: " + exception.getMessage()); - } catch (NoSuchFieldException exception) { - LOGGER.error("NoSuchFieldException: " + exception.getMessage()); - } finally { - close(rs, connection); - } - return new ArrayList<>(); - } - - /** - * Create a table in the specified database - * - * @param dbName db Name - * @param tableName table Name - * @param params params - * @return boolean - */ - public boolean createTable(String dbName, String tableName, List params) { - DataBaseApi dataSource = DataBaseApi.getInstance(); - return dataSource.createTable(dbName, tableName, params); - } - - /** - * Create a table in the specified database - * - * @param dbName db Name - * @param tableName table Name - * @param sql sql - * @return boolean - */ - public boolean createTable(String dbName, String tableName, String sql) { - DataBaseApi dataSource = DataBaseApi.getInstance(); - return dataSource.createTable(dbName, tableName, sql); - } - - /** - * Create an index on the specified data table - * - * @param tableName table Name - * @param indexName index Name - * @param params params - * @return boolean - */ - public boolean createIndex(String tableName, String indexName, List params) { - DataBaseApi dataSource = DataBaseApi.getInstance(); - return dataSource.createIndex(tableName, indexName, params); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.common.util.BeanUtil; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.getDeleteCondition; +import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.mapToString; +import static ohos.devtools.datasources.databases.databasepool.DataTableHelper.sqlPlaceholder; + +/** + * Provides common data table operations + */ +public abstract class AbstractDataStore extends SqlRunnable { + private static final Logger LOGGER = LogManager.getLogger(AbstractDataStore.class); + private static final String TYPE = "type"; + private static final String STRING = "String"; + + /** + * Data insertion + * + * @param dataObject dataObject + * @param + * @return boolean + */ + @SuppressWarnings("checkstyle:JavadocMethod") + public boolean insert(T dataObject) { + if (dataObject instanceof List) { + return insertInDateBaseBatch((List) dataObject); + } + return insertInDataBase(dataObject); + } + + /** + * Get database connection + * + * @param tableName tableName + * @return Optional + */ + protected Optional getConnectByTable(String tableName) { + Optional connection = DataBaseApi.getInstance().getConnectByTable(tableName); + return connection; + } + + /** + * Get database connection + * + * @param dbName dbName + * @return Optional + */ + protected Optional getConnectBydbName(String dbName) { + Optional connection = DataBaseApi.getInstance().getConnectBydbname(dbName); + return connection; + } + + /** + * Insert data in bulk + * + * @param dataObject dataObject + * @return boolean + */ + private boolean insertInDateBaseBatch(List dataObject) { + Object obj = dataObject.get(0); + String tableName = BeanUtil.getObjectName(obj); + Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); + StringBuffer insertSql = new StringBuffer("INSERT OR IGNORE INTO "); + List attrs = BeanUtil.getObjectAttributeNames(obj); + String value = attrs.stream().collect(Collectors.joining(",")); + insertSql.append(tableName).append("(").append(value).append(") VALUES (").append(sqlPlaceholder(attrs.size())) + .append(")"); + try { + PreparedStatement psmt = connection.prepareStatement(insertSql.toString()); + for (Object data : dataObject) { + applyParams(psmt, data); + psmt.addBatch(); + } + return executeBatch(connection, psmt); + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } + return false; + } + + private void applyParams(PreparedStatement statement, T data) { + List list = BeanUtil.getFieldsInfo(data); + try { + for (int index = 0; index < list.size(); index++) { + Map objMap = list.get(index); + Object objValue = objMap.get("value"); + if (String.valueOf(objMap.get(TYPE)).contains(STRING)) { + if (objValue instanceof String) { + statement.setString(index + 1, (String) objValue); + } + } else if (String.valueOf(objMap.get(TYPE)).contains("Integer")) { + if (objValue instanceof Integer) { + statement.setLong(index + 1, (int) objValue); + } + } else if (String.valueOf(objMap.get(TYPE)).contains("Long")) { + if (objValue instanceof Long) { + statement.setLong(index + 1, (long) objValue); + } + } else if (String.valueOf(objMap.get(TYPE)).contains("byte")) { + if (objValue instanceof byte[]) { + statement.setBytes(index + 1, (byte[]) objValue); + } + } else if (String.valueOf(objMap.get(TYPE)).contains("Boolean")) { + if (objValue instanceof Boolean) { + statement.setBoolean(index + 1, (boolean) objValue); + } + } else { + continue; + } + } + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + + private boolean insertInDataBase(T dataObject) { + String tableName = BeanUtil.getObjectName(dataObject); + StringBuffer insertSql = new StringBuffer("INSERT OR IGNORE INTO "); + List> objectInfos = BeanUtil.getFields(dataObject); + StringBuffer attrs = new StringBuffer(); + StringBuffer values = new StringBuffer(); + objectInfos.forEach(objectMap -> { + attrs.append(objectMap.get("name")).append(","); + if (String.valueOf(objectMap.get(TYPE)).contains(STRING)) { + values.append("'").append(objectMap.get("value")).append("',"); + } else { + values.append(objectMap.get("value")).append(","); + } + }); + insertSql.append(tableName).append("(").append(attrs.deleteCharAt(attrs.length() - 1).toString()) + .append(") VALUES (").append(values.deleteCharAt(values.length() - 1).toString()).append(")"); + Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); + return execute(connection, insertSql.toString()); + } + + /** + * Delete database + * + * @param dataObject dataObject + * @return boolean + */ + public boolean delete(T dataObject) { + return deleteInDataBase(dataObject); + } + + private boolean deleteInDataBase(T dataObject) { + String tableName = BeanUtil.getObjectName(dataObject); + StringBuffer deleteSql = new StringBuffer("DELETE FROM "); + Map beanMap = BeanUtil.getFiledsInfos(dataObject); + deleteSql.append(tableName).append("WHERE ").append(getDeleteCondition(beanMap)).append("1 = 1"); + Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); + return execute(connection, deleteSql.toString()); + } + + /** + * update + * + * @param clazz clazz + * @param condition condition + * @param setValue setValue + * @param + * @return boolean + */ + public boolean update(Class clazz, Map condition, Map setValue) { + StringBuffer updateSql = new StringBuffer("UPDATE "); + String tableName = clazz.getSimpleName(); + updateSql.append(tableName).append("SET").append(mapToString(setValue)).append("WHERE ").append(condition); + Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); + return execute(connection, updateSql.toString()); + } + + /** + * Inquire + * + * @param clazz clazz + * @param value value + * @param condition condition + * @param + * @return List + */ + public List select(Class clazz, Map value, Map condition) { + StringBuffer selectSql = new StringBuffer("SELECT "); + if (value == null || value.isEmpty()) { + selectSql.append("*"); + } + String tableName = clazz.getSimpleName(); + if (condition == null || condition.isEmpty()) { + selectSql.append(" FROM ").append(tableName); + } else { + selectSql.append(" FROM ").append(tableName).append(" WHERE ").append(getDeleteCondition(condition)); + } + Connection connection = DataBaseApi.getInstance().getConnectByTable(tableName).get(); + Statement stmt = null; + ResultSet rs = null; + try { + stmt = connection.createStatement(); + rs = executeQuery(stmt, selectSql.toString()); + return new DataBaseRsHelp().util(clazz.newInstance(), rs); + } catch (SQLException exe) { + LOGGER.error("SQLException: ", exe); + } catch (IllegalAccessException exception) { + LOGGER.error("IllegalAccessException: ", exception); + } catch (InstantiationException exception) { + LOGGER.error("InstantiationException: ", exception); + } catch (NoSuchFieldException exception) { + LOGGER.error("NoSuchFieldException: ", exception); + } finally { + close(rs, connection); + } + return new ArrayList<>(); + } + + /** + * Create a table in the specified database + * + * @param dbName db Name + * @param tableName table Name + * @param params params + * @return boolean + */ + public boolean createTable(String dbName, String tableName, List params) { + DataBaseApi dataSource = DataBaseApi.getInstance(); + return dataSource.createTable(dbName, tableName, params); + } + + /** + * Create a table in the specified database + * + * @param dbName db Name + * @param tableName table Name + * @param sql sql + * @return boolean + */ + public boolean createTable(String dbName, String tableName, String sql) { + DataBaseApi dataSource = DataBaseApi.getInstance(); + return dataSource.createTable(dbName, tableName, sql); + } + + /** + * Create an index on the specified data table + * + * @param tableName table Name + * @param indexName index Name + * @param params params + * @return boolean + */ + public boolean createIndex(String tableName, String indexName, List params) { + DataBaseApi dataSource = DataBaseApi.getInstance(); + return dataSource.createIndex(tableName, indexName, params); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBase.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBase.java index 3296bfc5f..f7bfe7fe5 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBase.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBase.java @@ -1,366 +1,360 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -/** - * database objects - * - * @version 1.0 - * @date 2021/1/23 16:31 - **/ -public class DataBase { - private String driver; - private String url; - private Integer initialSize; - private Integer maxActive; - private Integer minIdle; - private Integer maxWait; - private String filters; - private Integer timeBetweenEvictionRunsMillis; - private Integer minEvictableIdleTimeMillis; - private String validationQuery; - private boolean testWhileIdle; - private boolean testOnBorrow; - private boolean testOnReturn; - - private DataBase(Builder builder) { - driver = builder.driver; - url = builder.url; - initialSize = builder.initialSize; - maxActive = builder.maxActive; - minIdle = builder.minIdle; - maxWait = builder.maxWait; - filters = builder.filters; - timeBetweenEvictionRunsMillis = builder.timeBetweenEvictionRunsMillis; - minEvictableIdleTimeMillis = builder.minEvictableIdleTimeMillis; - validationQuery = builder.validationQuery; - testWhileIdle = builder.testWhileIdle; - testOnBorrow = builder.testOnBorrow; - testOnReturn = builder.testOnReturn; - } - - /** - * set Url - * - * @param url url - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * builder - * - * @return Builder - */ - public static Builder builder() { - return new Builder(); - } - - /** - * get Driver - * - * @return String - */ - public String getDriver() { - return driver; - } - - /** - * get Url - * - * @return String - */ - public String getUrl() { - return url; - } - - /** - * get Initial Size - * - * @return Integer - */ - public Integer getInitialSize() { - return initialSize; - } - - /** - * get Max Active - * - * @return Integer - */ - public Integer getMaxActive() { - return maxActive; - } - - /** - * getMinIdle - * - * @return Integer - */ - public Integer getMinIdle() { - return minIdle; - } - - /** - * getMaxWait - * - * @return Integer - */ - public Integer getMaxWait() { - return maxWait; - } - - /** - * getFilters - * - * @return String - */ - public String getFilters() { - return filters; - } - - /** - * getTimeBetweenEvictionRunsMillis - * - * @return Integer - */ - public Integer getTimeBetweenEvictionRunsMillis() { - return timeBetweenEvictionRunsMillis; - } - - /** - * getMinEvictableIdleTimeMillis - * - * @return Integer - */ - public Integer getMinEvictableIdleTimeMillis() { - return minEvictableIdleTimeMillis; - } - - /** - * getValidationQuery - * - * @return String - */ - public String getValidationQuery() { - return validationQuery; - } - - /** - * isTestWhileIdle - * - * @return boolean - */ - public boolean isTestWhileIdle() { - return testWhileIdle; - } - - /** - * isTestOnBorrow - * - * @return boolean - */ - public boolean isTestOnBorrow() { - return testOnBorrow; - } - - /** - * isTestOnReturn - * - * @return boolean - */ - public boolean isTestOnReturn() { - return testOnReturn; - } - - /** - * Builder - * - * @version 1.0 - * @date 2021/1/23 16:31 - **/ - public static class Builder { - private String driver; - private String url; - private Integer initialSize; - private Integer maxActive; - private Integer minIdle; - private String filters; - private Integer timeBetweenEvictionRunsMillis; - private Integer minEvictableIdleTimeMillis; - private String validationQuery; - private boolean testWhileIdle; - private boolean testOnBorrow; - private boolean testOnReturn; - private Integer maxWait; - - private Builder() { - } - - /** - * drive - * - * @param driver driver - * @return Builder - */ - public Builder driver(String driver) { - this.driver = driver; - return this; - } - - /** - * URL path - * - * @param url url - * @return Builder - */ - public Builder url(String url) { - this.url = url; - return this; - } - - /** - * initialSize - * - * @param initialSize initialSize - * @return Builder - */ - public Builder initialSize(Integer initialSize) { - this.initialSize = initialSize; - return this; - } - - /** - * Biggest activity - * - * @param maxActive maxActive - * @return Builder - */ - public Builder maxActive(Integer maxActive) { - this.maxActive = maxActive; - return this; - } - - /** - * minIdle - * - * @param minIdle minIdle - * @return Builder - */ - public Builder minIdle(Integer minIdle) { - this.minIdle = minIdle; - return this; - } - - /** - * maxWait - * - * @param maxWait maxWait - * @return Builder - */ - public Builder maxWait(Integer maxWait) { - this.maxWait = maxWait; - return this; - } - - /** - * filters - * - * @param filters filters - * @return Builder - */ - public Builder filters(String filters) { - this.filters = filters; - return this; - } - - /** - * timeBetweenEvictionRunsMillis - * - * @param timeBetweenEvictionRunsMillis timeBetweenEvictionRunsMillis - * @return Builder - */ - public Builder timeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) { - this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; - return this; - } - - /** - * time - * - * @param minEvictableIdleTimeMillis minEvictableIdleTimeMillis - * @return Builder - */ - public Builder minEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - return this; - } - - /** - * validationQuery - * - * @param validationQuery validationQuery - * @return Builder - */ - public Builder validationQuery(String validationQuery) { - this.validationQuery = validationQuery; - return this; - } - - /** - * testWhileIdle - * - * @param testWhileIdle testWhileIdle - * @return Builder - */ - public Builder testWhileIdle(boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - return this; - } - - /** - * test - * - * @param testOnBorrow testOnBorrow - * @return Builder - */ - public Builder testOnBorrow(boolean testOnBorrow) { - this.testOnBorrow = testOnBorrow; - return this; - } - - /** - * testOnReturn - * - * @param testOnReturn testOnReturn - * @return Builder - */ - public Builder testOnReturn(boolean testOnReturn) { - this.testOnReturn = testOnReturn; - return this; - } - - /** - * build - * - * @return DataBase - */ - public DataBase build() { - return new DataBase(this); - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +/** + * database objects + */ +public class DataBase { + private String driver; + private String url; + private Integer initialSize; + private Integer maxActive; + private Integer minIdle; + private Integer maxWait; + private String filters; + private Integer timeBetweenEvictionRunsMillis; + private Integer minEvictableIdleTimeMillis; + private String validationQuery; + private boolean testWhileIdle; + private boolean testOnBorrow; + private boolean testOnReturn; + + private DataBase(Builder builder) { + driver = builder.driver; + url = builder.url; + initialSize = builder.initialSize; + maxActive = builder.maxActive; + minIdle = builder.minIdle; + maxWait = builder.maxWait; + filters = builder.filters; + timeBetweenEvictionRunsMillis = builder.timeBetweenEvictionRunsMillis; + minEvictableIdleTimeMillis = builder.minEvictableIdleTimeMillis; + validationQuery = builder.validationQuery; + testWhileIdle = builder.testWhileIdle; + testOnBorrow = builder.testOnBorrow; + testOnReturn = builder.testOnReturn; + } + + /** + * set Url + * + * @param url url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * builder + * + * @return Builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * get Driver + * + * @return String + */ + public String getDriver() { + return driver; + } + + /** + * get Url + * + * @return String + */ + public String getUrl() { + return url; + } + + /** + * get Initial Size + * + * @return Integer + */ + public Integer getInitialSize() { + return initialSize; + } + + /** + * get Max Active + * + * @return Integer + */ + public Integer getMaxActive() { + return maxActive; + } + + /** + * getMinIdle + * + * @return Integer + */ + public Integer getMinIdle() { + return minIdle; + } + + /** + * getMaxWait + * + * @return Integer + */ + public Integer getMaxWait() { + return maxWait; + } + + /** + * getFilters + * + * @return String + */ + public String getFilters() { + return filters; + } + + /** + * getTimeBetweenEvictionRunsMillis + * + * @return Integer + */ + public Integer getTimeBetweenEvictionRunsMillis() { + return timeBetweenEvictionRunsMillis; + } + + /** + * getMinEvictableIdleTimeMillis + * + * @return Integer + */ + public Integer getMinEvictableIdleTimeMillis() { + return minEvictableIdleTimeMillis; + } + + /** + * getValidationQuery + * + * @return String + */ + public String getValidationQuery() { + return validationQuery; + } + + /** + * isTestWhileIdle + * + * @return boolean + */ + public boolean isTestWhileIdle() { + return testWhileIdle; + } + + /** + * isTestOnBorrow + * + * @return boolean + */ + public boolean isTestOnBorrow() { + return testOnBorrow; + } + + /** + * isTestOnReturn + * + * @return boolean + */ + public boolean isTestOnReturn() { + return testOnReturn; + } + + /** + * Builder + */ + public static class Builder { + private String driver; + private String url; + private Integer initialSize; + private Integer maxActive; + private Integer minIdle; + private String filters; + private Integer timeBetweenEvictionRunsMillis; + private Integer minEvictableIdleTimeMillis; + private String validationQuery; + private boolean testWhileIdle; + private boolean testOnBorrow; + private boolean testOnReturn; + private Integer maxWait; + + private Builder() { + } + + /** + * drive + * + * @param driver driver + * @return Builder + */ + public Builder driver(String driver) { + this.driver = driver; + return this; + } + + /** + * URL path + * + * @param url url + * @return Builder + */ + public Builder url(String url) { + this.url = url; + return this; + } + + /** + * initialSize + * + * @param initialSize initialSize + * @return Builder + */ + public Builder initialSize(Integer initialSize) { + this.initialSize = initialSize; + return this; + } + + /** + * Biggest activity + * + * @param maxActive maxActive + * @return Builder + */ + public Builder maxActive(Integer maxActive) { + this.maxActive = maxActive; + return this; + } + + /** + * minIdle + * + * @param minIdle minIdle + * @return Builder + */ + public Builder minIdle(Integer minIdle) { + this.minIdle = minIdle; + return this; + } + + /** + * maxWait + * + * @param maxWait maxWait + * @return Builder + */ + public Builder maxWait(Integer maxWait) { + this.maxWait = maxWait; + return this; + } + + /** + * filters + * + * @param filters filters + * @return Builder + */ + public Builder filters(String filters) { + this.filters = filters; + return this; + } + + /** + * timeBetweenEvictionRunsMillis + * + * @param timeBetweenEvictionRunsMillis timeBetweenEvictionRunsMillis + * @return Builder + */ + public Builder timeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) { + this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + return this; + } + + /** + * time + * + * @param minEvictableIdleTimeMillis minEvictableIdleTimeMillis + * @return Builder + */ + public Builder minEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) { + this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + return this; + } + + /** + * validationQuery + * + * @param validationQuery validationQuery + * @return Builder + */ + public Builder validationQuery(String validationQuery) { + this.validationQuery = validationQuery; + return this; + } + + /** + * testWhileIdle + * + * @param testWhileIdle testWhileIdle + * @return Builder + */ + public Builder testWhileIdle(boolean testWhileIdle) { + this.testWhileIdle = testWhileIdle; + return this; + } + + /** + * test + * + * @param testOnBorrow testOnBorrow + * @return Builder + */ + public Builder testOnBorrow(boolean testOnBorrow) { + this.testOnBorrow = testOnBorrow; + return this; + } + + /** + * testOnReturn + * + * @param testOnReturn testOnReturn + * @return Builder + */ + public Builder testOnReturn(boolean testOnReturn) { + this.testOnReturn = testOnReturn; + return this; + } + + /** + * build + * + * @return DataBase + */ + public DataBase build() { + return new DataBase(this); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelper.java index b0e96bf91..98974bcf7 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelper.java @@ -1,180 +1,190 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; -import static ohos.devtools.views.common.LayoutConstants.THOUSAND_TWENTY_FOUR; - -/** - * Used for database creation in the project, default table creation - * - * @version 1.0 - * @date 2021/1/25 9:45 - **/ -public class DataBaseHelper { - private DataBaseHelper() { - } - - private static final Logger LOGGER = LogManager.getLogger(DataBaseHelper.class); - private static final String SQL_START_FLAG = "##"; - - /** - * Check whether the specified database exists. - * - * @param dataBaseUrl dataBaseUrl - * @return Returns true if the database exists; returns false otherwise. - */ - public static boolean checkDataBaseExists(String dataBaseUrl) { - String dbPath = getFilePath(dataBaseUrl); - File dbFile = new File(dbPath); - return dbFile.exists(); - } - - /** - * Enter a specific path - * - * @param sqlPath sqlPath - * @return List - * @throws IOException IOException - */ - public static List loadSqlFileToList(String sqlPath) throws IOException { - File file = new File(sqlPath); - if (!file.exists() || file.isDirectory()) { - return new ArrayList<>(); - } - InputStream sqlFileIn = new FileInputStream(sqlPath); - StringBuffer sqlSb = new StringBuffer(); - byte[] buff = new byte[THOUSAND_TWENTY_FOUR]; - int byteRead = 0; - while (true) { - byteRead = sqlFileIn.read(buff); - if (byteRead == NEGATIVE_ONE) { - break; - } - sqlSb.append(new String(buff, 0, byteRead, Charset.defaultCharset())); - } - sqlFileIn.close(); - String[] sqlArr = sqlSb.toString().split("(\\r\\n)|(\\n)"); - List sqlList = new ArrayList(); - List sqlLists = Arrays.asList(sqlArr); - StringBuilder createTableSql = new StringBuilder(); - for (String sql : sqlLists) { - if (StringUtils.isNotBlank(sql) && sql.startsWith(SQL_START_FLAG)) { - continue; - } - if ((!sql.contains("*"))) { - createTableSql.append(sql); - if (sql.endsWith(");")) { - sqlList.add(createTableSql.toString()); - createTableSql = new StringBuilder(); - } - } - } - return sqlList; - } - - /** - * Get database file path through JDBC URL - * - * @param url url - * @return String - */ - public static String getFilePath(String url) { - String filePath = url.replace("jdbc:sqlite:", ""); - return filePath; - } - - /** - * getUrlByDataBaseName - * - * @param dbName dbName - * @return String String - */ - public static String getUrlByDataBaseName(String dbName) { - String dbPath = SessionManager.getInstance().getPluginPath(); - if (StringUtils.isBlank(dbName)) { - return "jdbc:sqlite:" + dbPath + "defaultDB"; - } - return "jdbc:sqlite:" + dbPath + dbName; - } - - /** - * createDataBase - * - * @return DataBase - */ - public static DataBase createDataBase() { - Properties pop = new Properties(); - try { - pop.load(DataBaseHelper.class.getClassLoader().getResourceAsStream("db.properties")); - return DataBase.builder().driver(pop.getProperty("driver")) - .initialSize(Integer.parseInt(pop.getProperty("initialSize"))) - .maxActive(Integer.parseInt(pop.getProperty("maxActive"))) - .minIdle(Integer.parseInt(pop.getProperty("minIdle"))).filters(pop.getProperty("filters")) - .maxWait(Integer.parseInt(pop.getProperty("maxWait"))) - .timeBetweenEvictionRunsMillis(Integer.parseInt(pop.getProperty("timeBetweenEvictionRunsMillis"))) - .minEvictableIdleTimeMillis(Integer.parseInt(pop.getProperty("minEvictableIdleTimeMillis"))) - .validationQuery(pop.getProperty("validationQuery")) - .testWhileIdle(Boolean.parseBoolean(pop.getProperty("testWhileIdle"))) - .testOnBorrow(Boolean.parseBoolean(pop.getProperty("testOnBorrow"))) - .testOnReturn(Boolean.parseBoolean(pop.getProperty("testOnReturn"))).build(); - } catch (IOException exception) { - LOGGER.error("createDataBase" + exception.getMessage()); - } - return DataBase.builder().build(); - } - - /** - * Create default database - * - * @return DataBase - */ - public static DataBase createDefaultDataBase() { - Properties pop = new Properties(); - try { - pop.load(DataBaseHelper.class.getClassLoader().getResourceAsStream("db.properties")); - return DataBase.builder().driver(pop.getProperty("driver")) - .initialSize(Integer.parseInt(pop.getProperty("initialSize"))) - .maxActive(Integer.parseInt(pop.getProperty("maxActive"))) - .minIdle(Integer.parseInt(pop.getProperty("minIdle"))).filters(pop.getProperty("filters")) - .maxWait(Integer.parseInt(pop.getProperty("maxWait"))) - .timeBetweenEvictionRunsMillis(Integer.parseInt(pop.getProperty("timeBetweenEvictionRunsMillis"))) - .minEvictableIdleTimeMillis(Integer.parseInt(pop.getProperty("minEvictableIdleTimeMillis"))) - .validationQuery(pop.getProperty("validationQuery")) - .testWhileIdle(Boolean.parseBoolean(pop.getProperty("testWhileIdle"))) - .testOnBorrow(Boolean.parseBoolean(pop.getProperty("testOnBorrow"))) - .testOnReturn(Boolean.parseBoolean(pop.getProperty("testOnReturn"))).build(); - } catch (IOException exception) { - LOGGER.error("createDefaultDataBase" + exception.getMessage()); - } - return DataBase.builder().build(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; +import static ohos.devtools.views.common.LayoutConstants.THOUSAND_TWENTY_FOUR; + +/** + * Used for database creation in the project, default table creation + */ +public class DataBaseHelper { + private DataBaseHelper() { + } + + private static final Logger LOGGER = LogManager.getLogger(DataBaseHelper.class); + private static final String SQL_START_FLAG = "##"; + private static final String DB_DRIVER = "driver"; + private static final String DB_INIT_SIZE = "initialSize"; + private static final String DB_MAX_ACTIVE = "maxActive"; + private static final String DB_MIN_IDLE = "minIdle"; + private static final String DB_FILTERS = "filters"; + private static final String DB_MAX_WAIT = "maxWait"; + private static final String DB_RUN_MILLIS = "timeBetweenEvictionRunsMillis"; + private static final String DB_IDLE_MILLIS = "minEvictableIdleTimeMillis"; + private static final String DB_QUERY = "validationQuery"; + private static final String DB_TEST_IDLE = "testWhileIdle"; + private static final String DB_TEST_BORROW = "testOnBorrow"; + private static final String DB_TEST_RETURN = "testOnReturn"; + private static final String JDBC_SQLITE = "jdbc:sqlite:"; + + /** + * Check whether the specified database exists. + * + * @param dataBaseUrl dataBaseUrl + * @return Returns true if the database exists; false otherwise. + */ + public static boolean checkDataBaseExists(String dataBaseUrl) { + String dbPath = getFilePath(dataBaseUrl); + File dbFile = new File(dbPath); + return dbFile.exists(); + } + + /** + * Enter a specific path + * + * @param sqlPath sqlPath + * @return List + * @throws IOException IOException + */ + public static List loadSqlFileToList(String sqlPath) throws IOException { + File file = new File(sqlPath); + if (!file.exists() || file.isDirectory()) { + return new ArrayList<>(); + } + InputStream sqlFileIn = new FileInputStream(sqlPath); + StringBuffer sqlSb = new StringBuffer(); + byte[] buff = new byte[THOUSAND_TWENTY_FOUR]; + int byteRead = 0; + while (true) { + byteRead = sqlFileIn.read(buff); + if (byteRead == NEGATIVE_ONE) { + break; + } + sqlSb.append(new String(buff, 0, byteRead, Charset.defaultCharset())); + } + sqlFileIn.close(); + String[] sqlArr = sqlSb.toString().split("(\\r\\n)|(\\n)"); + List sqlList = new ArrayList(); + List sqlLists = Arrays.asList(sqlArr); + StringBuilder createTableSql = new StringBuilder(); + for (String sql : sqlLists) { + if (StringUtils.isNotBlank(sql) && sql.startsWith(SQL_START_FLAG)) { + continue; + } + if ((!sql.contains("*"))) { + createTableSql.append(sql); + if (sql.endsWith(");")) { + sqlList.add(createTableSql.toString()); + createTableSql = new StringBuilder(); + } + } + } + return sqlList; + } + + /** + * Get database file path through JDBC URL + * + * @param url url + * @return String + */ + public static String getFilePath(String url) { + String filePath = url.replace("jdbc:sqlite:", ""); + return filePath; + } + + /** + * getUrlByDataBaseName + * + * @param dbName dbName + * @return String String + */ + public static String getUrlByDataBaseName(String dbName) { + String dbPath = SessionManager.getInstance().tempPath(); + if (StringUtils.isBlank(dbName)) { + return JDBC_SQLITE + dbPath + "defaultDB"; + } + return JDBC_SQLITE + dbPath + dbName; + } + + /** + * createDataBase + * + * @return DataBase + */ + public static DataBase createDataBase() { + Properties pop = new Properties(); + try { + pop.load(DataBaseHelper.class.getClassLoader().getResourceAsStream("db.properties")); + return DataBase.builder().driver(pop.getProperty(DB_DRIVER)) + .initialSize(Integer.parseInt(pop.getProperty(DB_INIT_SIZE))) + .maxActive(Integer.parseInt(pop.getProperty(DB_MAX_ACTIVE))) + .minIdle(Integer.parseInt(pop.getProperty(DB_MIN_IDLE))).filters(pop.getProperty(DB_FILTERS)) + .maxWait(Integer.parseInt(pop.getProperty(DB_MAX_WAIT))) + .timeBetweenEvictionRunsMillis(Integer.parseInt(pop.getProperty(DB_RUN_MILLIS))) + .minEvictableIdleTimeMillis(Integer.parseInt(pop.getProperty(DB_IDLE_MILLIS))) + .validationQuery(pop.getProperty(DB_QUERY)) + .testWhileIdle(Boolean.parseBoolean(pop.getProperty(DB_TEST_IDLE))) + .testOnBorrow(Boolean.parseBoolean(pop.getProperty(DB_TEST_BORROW))) + .testOnReturn(Boolean.parseBoolean(pop.getProperty(DB_TEST_RETURN))).build(); + } catch (IOException exception) { + LOGGER.error("createDataBase ", exception); + } + return DataBase.builder().build(); + } + + /** + * Create default database + * + * @return DataBase + */ + public static DataBase createDefaultDataBase() { + Properties pop = new Properties(); + try { + pop.load(DataBaseHelper.class.getClassLoader().getResourceAsStream("db.properties")); + return DataBase.builder().driver(pop.getProperty(DB_DRIVER)) + .initialSize(Integer.parseInt(pop.getProperty(DB_INIT_SIZE))) + .maxActive(Integer.parseInt(pop.getProperty(DB_MAX_ACTIVE))) + .minIdle(Integer.parseInt(pop.getProperty(DB_MIN_IDLE))).filters(pop.getProperty(DB_FILTERS)) + .maxWait(Integer.parseInt(pop.getProperty(DB_MAX_WAIT))) + .timeBetweenEvictionRunsMillis(Integer.parseInt(pop.getProperty(DB_RUN_MILLIS))) + .minEvictableIdleTimeMillis(Integer.parseInt(pop.getProperty(DB_IDLE_MILLIS))) + .validationQuery(pop.getProperty(DB_QUERY)) + .testWhileIdle(Boolean.parseBoolean(pop.getProperty(DB_TEST_IDLE))) + .testOnBorrow(Boolean.parseBoolean(pop.getProperty(DB_TEST_BORROW))) + .testOnReturn(Boolean.parseBoolean(pop.getProperty(DB_TEST_RETURN))).build(); + } catch (IOException exception) { + LOGGER.error("createDefaultDataBase ", exception); + } + return DataBase.builder().build(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseRsHelp.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseRsHelp.java index e5246b200..dd1c57d3c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseRsHelp.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataBaseRsHelp.java @@ -1,79 +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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import java.lang.reflect.Field; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * Data results help - * - * @version 1.0 - * @date 2021/1/23 16:31 - **/ -public class DataBaseRsHelp { - private static final Logger LOGGER = LogManager.getLogger(DataBaseRsHelp.class); - - /** - * Get the database table name by SQL. - * - * @param instanceClass generic paradigm - * @param rs result set - * @return List - * @throws IllegalAccessException IllegalAccessException - * @throws InstantiationException InstantiationException - * @throws NoSuchFieldException NoSuchFieldException - */ - public List util(T instanceClass, ResultSet rs) - throws IllegalAccessException, InstantiationException, NoSuchFieldException { - List list = new ArrayList(); - Class aClass = instanceClass.getClass(); - Field[] fs = aClass.getDeclaredFields(); - if (rs != null) { - while (true) { - try { - if (!rs.next()) { - break; - } - T instance = (T) aClass.newInstance(); - for (int index = 0; index < fs.length; index++) { - Field declaredField = instance.getClass().getDeclaredField(fs[index].getName()); - declaredField.setAccessible(true); - if (declaredField.getType().getName().equals(String.class.getName())) { - declaredField.set(instance, rs.getString(fs[index].getName())); - } else if (declaredField.getType().getName().equals(int.class.getName())) { - declaredField.set(instance, rs.getInt(fs[index].getName())); - } else { - continue; - } - } - list.add(instance); - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } - } - } - // Return results - return list; - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Field; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * Data results help + */ +public class DataBaseRsHelp { + private static final Logger LOGGER = LogManager.getLogger(DataBaseRsHelp.class); + + /** + * Get the database table name by SQL. + * + * @param instanceClass generic paradigm + * @param rs result set + * @return List + * @throws IllegalAccessException IllegalAccessException + * @throws InstantiationException InstantiationException + * @throws NoSuchFieldException NoSuchFieldException + */ + public List util(T instanceClass, ResultSet rs) + throws IllegalAccessException, InstantiationException, NoSuchFieldException { + List list = new ArrayList(); + Class aClass = instanceClass.getClass(); + Field[] fs = aClass.getDeclaredFields(); + if (rs != null) { + while (true) { + try { + if (!rs.next()) { + break; + } + T instance = (T) aClass.newInstance(); + for (int index = 0; index < fs.length; index++) { + Field declaredField = instance.getClass().getDeclaredField(fs[index].getName()); + declaredField.setAccessible(true); + if (declaredField.getType().getName().equals(String.class.getName())) { + declaredField.set(instance, rs.getString(fs[index].getName())); + } else if (declaredField.getType().getName().equals(int.class.getName())) { + declaredField.set(instance, rs.getInt(fs[index].getName())); + } else { + continue; + } + } + list.add(instance); + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } + } + } + // Return results + return list; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataTableHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataTableHelper.java index cd20638d4..24f995f21 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataTableHelper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/DataTableHelper.java @@ -1,131 +1,128 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Arrays; -import java.util.Map; -import java.util.Set; - -import static ohos.devtools.views.common.LayoutConstants.INDEX_FIVE; -import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; - -/** - * Database table structure maintenance - * - * @version 1.0 - * @date 2021/01/27 17:11 - **/ -public class DataTableHelper { - private DataTableHelper() { - } - - private static final Logger LOGGER = LogManager.getLogger(DataTableHelper.class); - - /** - * Get the database table name by SQL. - * - * @param sql sql - * @return String - */ - public static String getTableNameBySql(String sql) { - int tableIndex = sql.indexOf("TABLE"); - if (tableIndex != NEGATIVE_ONE) { - String tableName = sql.substring(tableIndex + INDEX_FIVE, sql.indexOf("(")); - return tableName.trim(); - } - return ""; - } - - /** - * sql Placeholder - * - * @param size size - * @return String - */ - public static String sqlPlaceholder(int size) { - StringBuffer stringBuffer = new StringBuffer(); - for (int i = 0; i < size; i++) { - if (i == (size - 1)) { - stringBuffer.append("?"); - } else { - stringBuffer.append("?,"); - } - } - return stringBuffer.toString(); - } - - /** - * Map to String - * - * @param map map - * @return String - */ - public static String getDeleteCondition(Map map) { - Set keySet = map.keySet(); - // Convert set collection to array - String[] keyArray = keySet.toArray(new String[keySet.size()]); - // Sort the array (ascending order) - Arrays.sort(keyArray); - // Because String splicing efficiency will be very low, so switch to String Builder - StringBuilder stringBuffer = new StringBuilder(); - for (int i = 0; i < keyArray.length; i++) { - // If the parameter value is empty, it does not participate in the signature. - // This method trim() removes spaces - if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) { - stringBuffer.append(keyArray[i]); - if (map.get(keyArray[i]) instanceof String) { - stringBuffer.append(" = '").append(String.valueOf(map.get(keyArray[i])).trim()).append("'"); - } else { - stringBuffer.append(" = `").append(String.valueOf(map.get(keyArray[i])).trim()).append("`"); - } - } - if (i != keyArray.length - 1) { - stringBuffer.append(" and "); - } - } - return stringBuffer.toString(); - } - - /** - * Map to String - * - * @param map map - * @return String - */ - public static String mapToString(Map map) { - Set keySet = map.keySet(); - // Convert set collection to array - String[] keyArray = keySet.toArray(new String[keySet.size()]); - // Sort the array (ascending order) - Arrays.sort(keyArray); - StringBuilder stringBuffer = new StringBuilder(); - for (int i = 0; i < keyArray.length; i++) { - // If the parameter value is empty, it does not participate in the signature. - // This method trim() removes spaces - if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) { - stringBuffer.append(keyArray[i]).append(" = '").append(String.valueOf(map.get(keyArray[i])).trim()) - .append("'"); - } - if (i != keyArray.length - 1) { - stringBuffer.append("="); - } - } - return stringBuffer.toString(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Arrays; +import java.util.Map; +import java.util.Set; + +import static ohos.devtools.views.common.LayoutConstants.INDEX_FIVE; +import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; + +/** + * Database table structure maintenance + */ +public class DataTableHelper { + private static final Logger LOGGER = LogManager.getLogger(DataTableHelper.class); + + private DataTableHelper() { + } + + /** + * Get the database table name by SQL. + * + * @param sql sql + * @return String + */ + public static String getTableNameBySql(String sql) { + int tableIndex = sql.indexOf("TABLE"); + if (tableIndex != NEGATIVE_ONE) { + String tableName = sql.substring(tableIndex + INDEX_FIVE, sql.indexOf("(")); + return tableName.trim(); + } + return ""; + } + + /** + * sql Placeholder + * + * @param size size + * @return String + */ + public static String sqlPlaceholder(int size) { + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < size; i++) { + if (i == (size - 1)) { + stringBuffer.append("?"); + } else { + stringBuffer.append("?,"); + } + } + return stringBuffer.toString(); + } + + /** + * Map to String + * + * @param map Map + * @return String + */ + public static String getDeleteCondition(Map map) { + Set keySet = map.keySet(); + // Convert set collection to array + String[] keyArray = keySet.toArray(new String[keySet.size()]); + // Sort the array (ascending order) + Arrays.sort(keyArray); + // Because String splicing efficiency will be very low, so switch to String Builder + StringBuilder stringBuffer = new StringBuilder(); + for (int i = 0; i < keyArray.length; i++) { + // If the parameter value is empty, it does not participate in the signature. + // This method trim() removes spaces + if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) { + stringBuffer.append(keyArray[i]); + if (map.get(keyArray[i]) instanceof String) { + stringBuffer.append(" = '").append(String.valueOf(map.get(keyArray[i])).trim()).append("'"); + } else { + stringBuffer.append(" = `").append(String.valueOf(map.get(keyArray[i])).trim()).append("`"); + } + } + if (i != keyArray.length - 1) { + stringBuffer.append(" and "); + } + } + return stringBuffer.toString(); + } + + /** + * Map to String + * + * @param map Map + * @return String + */ + public static String mapToString(Map map) { + Set keySet = map.keySet(); + // Convert set collection to array + String[] keyArray = keySet.toArray(new String[keySet.size()]); + // Sort the array (ascending order) + Arrays.sort(keyArray); + StringBuilder stringBuffer = new StringBuilder(); + for (int i = 0; i < keyArray.length; i++) { + // If the parameter value is empty, it does not participate in the signature. + // This method trim() removes spaces + if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) { + stringBuffer.append(keyArray[i]).append(" = '").append(String.valueOf(map.get(keyArray[i])).trim()) + .append("'"); + } + if (i != keyArray.length - 1) { + stringBuffer.append("="); + } + } + return stringBuffer.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/SqlRunnable.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/SqlRunnable.java index 901a3c665..7d3a40625 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/SqlRunnable.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/databasepool/SqlRunnable.java @@ -1,176 +1,173 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -/** - * sql carried out - * - * @version 1.0 - * @date 2021/02/05 14:10 - **/ -public class SqlRunnable { - private static final Logger LOGGER = LogManager.getLogger(SqlRunnable.class); - - /** - * method - * - * @param conn Connection - * @param sql sql - * @return boolean - */ - public boolean execute(Connection conn, String sql) { - boolean result = false; - Statement stmt = null; - try { - stmt = conn.createStatement(); - result = stmt.executeUpdate(sql) > 0 ? true : false; - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } finally { - close(stmt, conn); - } - return result; - } - - /** - * executeBatch - * - * @param conn Connection - * @param ste Prepared Statement - * @return boolean - */ - public boolean executeBatch(Connection conn, PreparedStatement ste) { - try { - conn.setAutoCommit(false); - int[] result = ste.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwAbles) { - try { - conn.rollback(); - } catch (SQLException exception) { - return false; - } - } finally { - close(ste, conn); - } - return false; - } - - /** - * executeQuery - * - * @param stmt Statement - * @param sql sql - * @return ResultSet - */ - public ResultSet executeQuery(Statement stmt, String sql) { - ResultSet rs = null; - try { - rs = stmt.executeQuery(sql); - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } - return rs; - } - - /** - * close - * - * @param st Statement - */ - public void close(Statement st) { - close(st, null, null); - } - - /** - * close - * - * @param rs Result set - */ - public void close(ResultSet rs) { - close(null, rs, null); - } - - /** - * close - * - * @param con Connection - */ - public void close(Connection con) { - close(null, null, con); - } - - /** - * close - * - * @param st Statement - * @param con Connection - */ - public void close(Statement st, Connection con) { - close(st, null, con); - } - - /** - * close - * - * @param rs Result set - * @param con Connection - */ - public void close(ResultSet rs, Connection con) { - close(null, rs, con); - } - - /** - * close - * - * @param st Statement - * @param rs Result set - * @param con Connection - */ - public void close(Statement st, ResultSet rs, Connection con) { - if (st != null) { - try { - st.close(); - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - if (rs != null) { - try { - rs.close(); - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - if (con != null) { - try { - con.close(); - } catch (SQLException exception) { - LOGGER.error(exception.getMessage()); - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * sql carried out + */ +public class SqlRunnable { + private static final Logger LOGGER = LogManager.getLogger(SqlRunnable.class); + + /** + * method + * + * @param conn Connection + * @param sql sql + * @return boolean + */ + public boolean execute(Connection conn, String sql) { + boolean result = false; + Statement stmt = null; + try { + stmt = conn.createStatement(); + result = stmt.executeUpdate(sql) > 0 ? true : false; + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } finally { + close(stmt, conn); + } + return result; + } + + /** + * executeBatch + * + * @param conn Connection + * @param ste Prepared Statement + * @return boolean + */ + public boolean executeBatch(Connection conn, PreparedStatement ste) { + try { + conn.setAutoCommit(false); + int[] result = ste.executeBatch(); + conn.commit(); + return true; + } catch (SQLException throwAbles) { + try { + conn.rollback(); + } catch (SQLException exception) { + return false; + } + } finally { + close(ste, conn); + } + return false; + } + + /** + * executeQuery + * + * @param stmt Statement + * @param sql sql + * @return ResultSet + */ + public ResultSet executeQuery(Statement stmt, String sql) { + ResultSet rs = null; + try { + rs = stmt.executeQuery(sql); + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } + return rs; + } + + /** + * close + * + * @param st Statement + */ + public void close(Statement st) { + close(st, null, null); + } + + /** + * close + * + * @param rs Result set + */ + public void close(ResultSet rs) { + close(null, rs, null); + } + + /** + * close + * + * @param con Connection + */ + public void close(Connection con) { + close(null, null, con); + } + + /** + * close + * + * @param st Statement + * @param con Connection + */ + public void close(Statement st, Connection con) { + close(st, null, con); + } + + /** + * close + * + * @param rs Result set + * @param con Connection + */ + public void close(ResultSet rs, Connection con) { + close(null, rs, con); + } + + /** + * close + * + * @param st Statement + * @param rs Result set + * @param con Connection + */ + public void close(Statement st, ResultSet rs, Connection con) { + if (st != null) { + try { + st.close(); + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + if (rs != null) { + try { + rs.close(); + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + if (con != null) { + try { + con.close(); + } catch (SQLException exception) { + LOGGER.error(exception.getMessage()); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/CpuTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/CpuTable.java new file mode 100644 index 000000000..9bd72ff01 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/CpuTable.java @@ -0,0 +1,109 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Cpu table + */ +public class CpuTable extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(CpuTable.class); + private static final String CPU_DB_NAME = "cpuDb"; + + /** + * Cpu Table initialize + */ + public CpuTable() { + initialize(); + } + + /** + * initialization + */ + private void initialize() { + // processCpuInfo + List processCpuInfo = new ArrayList() { + { + add("id INTEGER primary key autoincrement not null"); + add("session LONG NOT NULL"); + add("sessionId INTEGER NOT NULL"); + add("timeStamp Long NOT NULL"); + add("Data BLOB NOT NULL"); + } + }; + List processCpuInfoIndex = new ArrayList() { + { + add("sessionId"); + add("timeStamp"); + } + }; + createTable(CPU_DB_NAME, "processCpuInfo", processCpuInfo); + createIndex("processCpuInfo", "processCpuInfoIndex", processCpuInfoIndex); + } + + /** + * insertProcessCpuInfo + * + * @param processCpuData processCpuData + * @return boolean + */ + public boolean insertProcessCpuInfo(List processCpuData) { + return insertAppInfoBatch(processCpuData); + } + + private boolean insertAppInfoBatch(List processCpuDataList) { + Optional option = getConnectByTable("processCpuInfo"); + if (option.isPresent()) { + Connection conn = option.get(); + PreparedStatement pst = null; + try { + pst = conn.prepareStatement( + "INSERT OR IGNORE INTO processCpuInfo(session, sessionId, timeStamp, Data) VALUES (?, ?, ?, ?)"); + conn.setAutoCommit(false); + if (processCpuDataList != null && processCpuDataList.size() > 0) { + for (ProcessCpuData processCpuData : processCpuDataList) { + pst.setLong(1, processCpuData.getLocalSessionId()); + pst.setInt(2, processCpuData.getSessionId()); + pst.setLong(3, processCpuData.getTimeStamp()); + pst.setBytes(4, processCpuData.getData().toByteArray()); + pst.addBatch(); + } + pst.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + return true; + } + } catch (SQLException exception) { + LOGGER.error("insert CPU data {}", exception.getMessage()); + } finally { + close(pst, conn); + } + } + return false; + } +} + diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/MemoryTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/MemoryTable.java index cb8f3c9eb..4c50bda08 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/MemoryTable.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/MemoryTable.java @@ -1,126 +1,112 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.datatable; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -import static ohos.devtools.views.common.LayoutConstants.INDEX_FOUR; -import static ohos.devtools.views.common.LayoutConstants.INDEX_ONE; -import static ohos.devtools.views.common.LayoutConstants.INDEX_THREE; -import static ohos.devtools.views.common.LayoutConstants.TWO; - -/** - * memory数据 - * - * @version 1.0 - * @date 2021/02/20 16:51 - **/ -public class MemoryTable extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(MemoryTable.class); - private static final String MEMORY_DB_NAME = "memory"; - - public MemoryTable() { - initialize(); - } - - /** - * initialization - **/ - private void initialize() { - // processMemInfo - List processMemInfo = new ArrayList() { - { - add("id INTEGER primary key autoincrement not null"); - add("session LONG NOT NULL"); - add("sessionId INTEGER NOT NULL"); - add("timeStamp Long NOT NULL"); - add("Data BLOB NOT NULL"); - } - }; - List processMemInfoIndex = new ArrayList() { - { - add("id"); - add("sessionId"); - add("timeStamp"); - } - }; - createTable(MEMORY_DB_NAME, "processMemInfo", processMemInfo); - createIndex("processMemInfo", "processMemInfoIndex", processMemInfoIndex); - } - - /** - * insertProcessMemInfo - * - * @param processMemInfo processMemInfo - * @return boolean - */ - public boolean insertProcessMemInfo(List processMemInfo) { - return insertAppInfoBatch(processMemInfo); - } - - private boolean insertAppInfoBatch(List processMemInfos) { - Optional option = getConnectByTable("processMemInfo"); - if (option.isPresent()) { - Connection conn = option.get(); - try { - PreparedStatement pst = conn.prepareStatement( - "INSERT OR IGNORE INTO processMemInfo(session, sessionId, timeStamp, Data) VALUES (?, ?, ?, ?)"); - conn.setAutoCommit(false); - processMemInfos.forEach(processMemoryInfo -> { - try { - pst.setLong(INDEX_ONE, processMemoryInfo.getLocalSessionId()); - pst.setInt(TWO, processMemoryInfo.getSessionId()); - pst.setLong(INDEX_THREE, processMemoryInfo.getTimeStamp()); - pst.setBytes(INDEX_FOUR, processMemoryInfo.getData().toByteArray()); - pst.addBatch(); - } catch (SQLException sqlException) { - LOGGER.info("insert AppInfo {}", sqlException.getMessage()); - } - }); - try { - int[] results = pst.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwAbles) { - LOGGER.info("insert AppInfo {}", throwAbles.getMessage()); - } finally { - if (pst != null) { - pst.close(); - } - if (conn != null) { - conn.close(); - } - } - } catch (SQLException exception) { - LOGGER.error("insert AppInfo {}", exception.getMessage()); - } - } - return false; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * memory数据 + */ +public class MemoryTable extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(MemoryTable.class); + private static final String MEMORY_DB_NAME = "memory"; + + /** + * Memory Table initialize + */ + public MemoryTable() { + initialize(); + } + + /** + * initialization + */ + private void initialize() { + /** + * processMem Info + */ + List processMemInfo = new ArrayList() { + { + add("id INTEGER primary key autoincrement not null"); + add("session LONG NOT NULL"); + add("sessionId INTEGER NOT NULL"); + add("timeStamp Long NOT NULL"); + add("Data BLOB NOT NULL"); + } + }; + List processMemInfoIndex = new ArrayList() { + { + add("sessionId"); + add("timeStamp"); + } + }; + createTable(MEMORY_DB_NAME, "processMemInfo", processMemInfo); + createIndex("processMemInfo", "processMemInfoIndex", processMemInfoIndex); + } + + /** + * insertProcessMemInfo + * + * @param processMemInfo processMemInfo + * @return boolean + */ + public boolean insertProcessMemInfo(List processMemInfo) { + return insertAppInfoBatch(processMemInfo); + } + + private boolean insertAppInfoBatch(List processMemInfos) { + Optional option = getConnectByTable("processMemInfo"); + if (option.isPresent()) { + Connection conn = option.get(); + PreparedStatement pst = null; + try { + conn.setAutoCommit(false); + pst = conn.prepareStatement( + "INSERT OR IGNORE INTO processMemInfo(session, sessionId, timeStamp, Data) VALUES (?, ?, ?, ?)"); + if (processMemInfos != null && processMemInfos.size() > 0) { + for (ProcessMemInfo processMemoryInfo : processMemInfos) { + pst.setLong(1, processMemoryInfo.getLocalSessionId()); + pst.setInt(2, processMemoryInfo.getSessionId()); + pst.setLong(3, processMemoryInfo.getTimeStamp()); + if (processMemoryInfo.getData() != null) { + pst.setBytes(4, processMemoryInfo.getData().toByteArray()); + } + pst.addBatch(); + } + pst.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + return true; + } + } catch (SQLException exception) { + LOGGER.error("insert AppInfo {}", exception.getMessage()); + } finally { + close(pst, conn); + } + } + return false; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/CpuData.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/CpuData.java new file mode 100644 index 000000000..ff1807f9c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/CpuData.java @@ -0,0 +1,119 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import java.io.Serializable; + +/** + * cpu data + */ +public class CpuData implements Serializable { + private static final long serialVersionUID = -8106428244173195592L; + long localSessionId; + int sessionId; + long timeStamp; + T data; + + /** + * Get session + * + * @return long + */ + public long getSession() { + return localSessionId; + } + + /** + * Get sessionId + * + * @return int + */ + public int getSessionId() { + return sessionId; + } + + /** + * Save session + * + * @param localSessionId Local sessionId + */ + public void setSession(long localSessionId) { + this.localSessionId = localSessionId; + } + + /** + * Set sessionId + * + * @param sessionId sessionId + */ + public void setSessionId(int sessionId) { + this.sessionId = sessionId; + } + + /** + * Get data + * + * @return T + */ + public T getData() { + return data; + } + + /** + * Set data + * + * @param data data + */ + public void setData(T data) { + this.data = data; + } + + /** + * get local sessionId + * + * @return long + */ + public long getLocalSessionId() { + return localSessionId; + } + + /** + * Set local sessionId + * + * @param localSessionId Local sessionId + */ + public void setLocalSessionId(long localSessionId) { + this.localSessionId = localSessionId; + } + + /** + * Get time stamp + * + * @return long + */ + public long getTimeStamp() { + return timeStamp; + } + + /** + * Set time stamp + * + * @param timeStamp Time stamp + */ + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/MemoryData.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/MemoryData.java index bf9eaa0f1..9b97db1f9 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/MemoryData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/MemoryData.java @@ -1,121 +1,119 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.datatable.enties; - -import java.io.Serializable; - -/** - * @param - * @version 1.0 - * @date 2021/02/22 15:35 - **/ -public class MemoryData implements Serializable { - private static final long serialVersionUID = -8106428244173195592L; - long localSessionId; - int sessionId; - long timeStamp; - T data; - - /** - * Get session - * - * @return long - */ - public long getSession() { - return localSessionId; - } - - /** - * Get sessionId - * - * @return int - */ - public int getSessionId() { - return sessionId; - } - - /** - * Save session - * - * @param localSessionId Local sessionId - */ - public void setSession(long localSessionId) { - this.localSessionId = localSessionId; - } - - /** - * Set sessionId - * - * @param sessionId sessionId - */ - public void setSessionId(int sessionId) { - this.sessionId = sessionId; - } - - /** - * Get data - * - * @return T - */ - public T getData() { - return data; - } - - /** - * Set data - * - * @param data data - */ - public void setData(T data) { - this.data = data; - } - - /** - * get local sessionId - * - * @return long - */ - public long getLocalSessionId() { - return localSessionId; - } - - /** - * Set local sessionId - * - * @param localSessionId Local sessionId - */ - public void setLocalSessionId(long localSessionId) { - this.localSessionId = localSessionId; - } - - /** - * Get time stamp - * - * @return long - */ - public long getTimeStamp() { - return timeStamp; - } - - /** - * Set time stamp - * - * @param timeStamp Time stamp - */ - public void setTimeStamp(long timeStamp) { - this.timeStamp = timeStamp; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import java.io.Serializable; + +/** + * @param + */ +public class MemoryData implements Serializable { + private static final long serialVersionUID = -8106428244173195592L; + long localSessionId; + int sessionId; + long timeStamp; + T data; + + /** + * Get session + * + * @return long + */ + public long getSession() { + return localSessionId; + } + + /** + * Get sessionId + * + * @return int + */ + public int getSessionId() { + return sessionId; + } + + /** + * Save session + * + * @param localSessionId Local sessionId + */ + public void setSession(long localSessionId) { + this.localSessionId = localSessionId; + } + + /** + * Set sessionId + * + * @param sessionId sessionId + */ + public void setSessionId(int sessionId) { + this.sessionId = sessionId; + } + + /** + * Get data + * + * @return T + */ + public T getData() { + return data; + } + + /** + * Set data + * + * @param data data + */ + public void setData(T data) { + this.data = data; + } + + /** + * get local sessionId + * + * @return long + */ + public long getLocalSessionId() { + return localSessionId; + } + + /** + * Set local sessionId + * + * @param localSessionId Local sessionId + */ + public void setLocalSessionId(long localSessionId) { + this.localSessionId = localSessionId; + } + + /** + * Get time stamp + * + * @return long + */ + public long getTimeStamp() { + return timeStamp; + } + + /** + * Set time stamp + * + * @param timeStamp Time stamp + */ + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/MonitorPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessCpuData.java similarity index 71% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/MonitorPanel.java rename to host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessCpuData.java index f416ac20a..216e3907e 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/MonitorPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessCpuData.java @@ -1,28 +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. - */ - -package ohos.devtools.views.layout.swing; - -import javax.swing.JPanel; - -/** - * 监控配置 - * - * @version 1.0 - * @date 2021/02/27 15:05 - **/ -public class MonitorPanel extends JPanel { -} - +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import ohos.devtools.datasources.transport.grpc.service.CpuPluginResult; + +/** + * processCpuInfo + */ +public class ProcessCpuData extends CpuData{ +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessMemInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessMemInfo.java index e393f0de8..55675a9d8 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessMemInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/ProcessMemInfo.java @@ -1,27 +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. - */ - -package ohos.devtools.datasources.databases.datatable.enties; - -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; - -/** - * ProcessMemInfo - * - * @version 1.0 - * @date 2021/02/22 10:40 - **/ -public class ProcessMemInfo extends MemoryData { -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; + +/** + * ProcessMemInfo + */ +public class ProcessMemInfo extends MemoryData { +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysMemInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysMemInfo.java index ac99aabbc..35caedcd9 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysMemInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysMemInfo.java @@ -1,27 +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. - */ - -package ohos.devtools.datasources.databases.datatable.enties; - -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; - -/** - * SysMemInfo - * - * @version 1.0 - * @date 2021/02/22 10:35 - **/ -public class SysMemInfo extends MemoryData { -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; + +/** + * SysMemInfo + */ +public class SysMemInfo extends MemoryData { +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysVmemInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysVmemInfo.java index 2205e999d..a7878e494 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysVmemInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/databases/datatable/enties/SysVmemInfo.java @@ -1,27 +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. - */ - -package ohos.devtools.datasources.databases.datatable.enties; - -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; - -/** - * SysVMemInfo - * - * @version 1.0 - * @date 2021/02/22 10:47 - **/ -public class SysVmemInfo extends MemoryData { -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable.enties; + +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; + +/** + * SysVMemInfo + */ +public class SysVmemInfo extends MemoryData { +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/CpuPlugHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/CpuPlugHelper.java new file mode 100644 index 000000000..86ebf70b0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/CpuPlugHelper.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import ohos.devtools.datasources.transport.grpc.service.CpuPluginConfig; + +import java.util.List; + +/** + * cpu plug helper + */ +public final class CpuPlugHelper { + private CpuPlugHelper() { + } + + /** + * Grpc request when requesting process information. + * + * @return MemoryConfig MemoryPluginConfig + */ + public static CpuPluginConfig.CpuConfig createProcessRequest() { + CpuPluginConfig.CpuConfig.Builder builder = CpuPluginConfig.CpuConfig.newBuilder(); + return builder.build(); + } + + /** + * The configuration object when requesting single-process memory data needs to be + * converted into binary and passed into createSessionRequest or startSessionRequest + * + * @param pid pid + * @return MemoryConfig MemoryPluginConfig + */ + public static CpuPluginConfig.CpuConfig createCpuRequest(int pid) { + CpuPluginConfig.CpuConfig.Builder builder = CpuPluginConfig.CpuConfig.newBuilder(); + if (pid > 0) { + builder.setPid(pid); + } + return builder.build(); + } + + /** + * The configuration object when requesting multi-process memory data needs to be converted + * into binary and passed into createSessionRequest or startSessionRequest + * + * @param pids pids + * @return MemoryConfig MemoryPluginConfig + */ + public static CpuPluginConfig.CpuConfig createCpuRequest(List pids) { + CpuPluginConfig.CpuConfig.Builder builder = CpuPluginConfig.CpuConfig.newBuilder(); + return builder.build(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/HiProfilerClient.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/HiProfilerClient.java index 9e1da0cae..7ae77eb38 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/HiProfilerClient.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/HiProfilerClient.java @@ -1,434 +1,480 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.transport.grpc; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import io.grpc.ManagedChannel; -import io.grpc.StatusRuntimeException; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.util.CommonUtil; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.views.common.LayoutConstants; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -import static ohos.devtools.datasources.utils.common.Constant.DEVICE_FULL_TYPE; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUGS_NAME; -import static ohos.devtools.views.common.ViewConstants.NUM_2; -import static ohos.devtools.views.common.ViewConstants.NUM_5; - -/** - * Provide device-side grpc interface encapsulation for each module in the application - * - * @version 1.0 - * @date 2021/02/01 19:23 - **/ -public final class HiProfilerClient { - private static final Logger LOGGER = LogManager.getLogger(HiProfilerClient.class); - - private static final String IP = InetAddress.getLoopbackAddress().getHostAddress(); - - /** - * Used to store the created Profiler - */ - private static ConcurrentHashMap profilerClientMap = - new ConcurrentHashMap<>(CommonUtil.collectionSize(0)); - - /** - * Singleton Class Instance - * - * @version 1.0 - * @date 2021/02/01 19:23 - **/ - private static class SingletonClassInstance { - private static final HiProfilerClient INSTANCE = new HiProfilerClient(); - } - - /** - * Get instance - * - * @return HiProfilerClient - */ - public static HiProfilerClient getInstance() { - return SingletonClassInstance.INSTANCE; - } - - private HiProfilerClient() { - } - - /** - * Get profilerclient - * - * @param ip ip address - * @param port port number - * @param channel channel - * @return ProfilerClient - */ - public ProfilerClient getProfilerClient(String ip, int port, ManagedChannel channel) { - String mapKey = IP + port; - if (port <= 0 || port > LayoutConstants.PORT) { - return null; - } - if (Objects.isNull(profilerClientMap.get(mapKey))) { - ProfilerClient profilerClient = new ProfilerClient(IP, port, channel); - profilerClientMap.put(mapKey, profilerClient); - return profilerClient; - } - return profilerClientMap.get(mapKey); - } - - /** - * get profilerClient. - * - * @param ip ip address - * @param port port number - * @return ProfilerClient - */ - public ProfilerClient getProfilerClient(String ip, int port) { - if (port <= 0 || port > LayoutConstants.PORT) { - return null; - } - String mapKey = IP + port; - if (profilerClientMap.get(mapKey) == null) { - ProfilerClient profilerClient = new ProfilerClient(IP, port); - profilerClientMap.put(mapKey, profilerClient); - return profilerClient; - } - return profilerClientMap.get(mapKey); - } - - /** - * Destroy profilerClient - * - * @param ip ip address - * @param port port number - * @return boolean - */ - public boolean destroyProfiler(String ip, int port) { - if (port <= 0 || port > LayoutConstants.PORT) { - return false; - } - String mapKey = IP + port; - if (Objects.isNull(profilerClientMap.get(mapKey))) { - return true; - } - ProfilerClient client = profilerClientMap.get(mapKey); - client.shutdown(); - return profilerClientMap.remove(mapKey, client); - } - - /** - * requestCreateSession - * - * @param port port number - * @param name name - * @param pid pid - * @param reportProcessTree report process tree - * @param deviceType device Type - * @return int - */ - public int requestCreateSession(int port, String name, int pid, boolean reportProcessTree, String deviceType) { - if (port <= 0 || port > LayoutConstants.PORT) { - return -1; - } - ProfilerClient client = getProfilerClient("", port); - LOGGER.info("process Session start222", DateTimeUtil.getNowTimeLong()); - if (client.isUsed()) { - LOGGER.info("process Session is Used", DateTimeUtil.getNowTimeLong()); - return -1; - } - client.setUsed(true); - LOGGER.info("process Session start3333", DateTimeUtil.getNowTimeLong()); - MemoryPluginConfig.MemoryConfig plug; - int pages = 2; - if (DEVICE_FULL_TYPE.equals(deviceType)) { - pages = 10; - plug = MemoryPlugHelper.createMemRequest(pid, reportProcessTree, false, false, true); - } else { - plug = MemoryPlugHelper.createMemRequest(pid, reportProcessTree, false, false, false); - } - ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = ProfilerServiceHelper - .profilerSessionConfig(true, null, pages, - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE); - CommonTypes.ProfilerPluginConfig plugConfig = - ProfilerServiceHelper.profilerPluginConfig(name, "ABDSSFDFG", 0, plug.toByteString()); - List plugs = new ArrayList(); - plugs.add(plugConfig); - ProfilerServiceTypes.CreateSessionRequest request = - ProfilerServiceHelper.createSessionRequest(CommonUtil.getRequestId(), sessionConfig, plugs); - ProfilerServiceTypes.CreateSessionResponse response = null; - try { - response = client.createSession(request); - LOGGER.info("process Session start444 {} ", DateTimeUtil.getNowTimeLong()); - } catch (StatusRuntimeException exception) { - destroyProfiler("", port); - return -1; - } - client.setUsed(false); - return response.getSessionId(); - } - - /** - * Request to start session - * - * @param deviceIp deviceIp - * @param port port number - * @param sessionId sessionId - * @return boolean - */ - public boolean requestStartSession(String deviceIp, int port, int sessionId) { - if (port <= 0 || port > LayoutConstants.PORT) { - return false; - } - return requestStartSession(deviceIp, port, sessionId, 0); - } - - private boolean requestStartSession(String deviceIp, int port, int sessionId, int retryCount) { - int retryCounts = retryCount + 1; - ProfilerServiceTypes.StartSessionRequest requestStartSession = - ProfilerServiceHelper.startSessionRequest(CommonUtil.getRequestId(), sessionId, new ArrayList<>()); - ProfilerServiceTypes.StartSessionResponse response = null; - ProfilerClient client = getProfilerClient(deviceIp, port); - if (client.isUsed()) { - return false; - } - client.setUsed(true); - try { - response = client.startSession(requestStartSession); - } catch (StatusRuntimeException exception) { - destroyProfiler("", port); - if (retryCounts > NUM_5) { - return true; - } - return requestStartSession(deviceIp, port, sessionId, retryCounts); - } - client.setUsed(false); - return response.getStatus() == 0 ? true : false; - } - - /** - * requestStopSession - * - * @param deviceIp deviceIp - * @param port port number - * @param sessionId sessionId - * @param isForce isForce - * @return boolean - */ - public boolean requestStopSession(String deviceIp, int port, int sessionId, boolean isForce) { - if (port <= 0 || port > LayoutConstants.PORT) { - return false; - } - return requestStopSession(deviceIp, port, sessionId, isForce, 0); - } - - private boolean requestStopSession(String deviceIp, int port, int sessionId, boolean isForce, int retryCount) { - ProfilerClient client = getProfilerClient(deviceIp, port); - if (isForce) { - client.setUsed(false); - } - if (client.isUsed()) { - return false; - } - client.setUsed(true); - ProfilerServiceTypes.StopSessionRequest stopSession = - ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId); - ProfilerServiceTypes.StopSessionResponse response = null; - int retryCounts = retryCount; - try { - retryCounts = retryCount + 1; - Long stopTime = DateTimeUtil.getNowTimeLong(); - LOGGER.info("startStopSession {}", stopTime); - response = client.stopSession(stopSession); - LOGGER.info("startStopEndSession {}", DateTimeUtil.getNowTimeLong() - stopTime); - } catch (StatusRuntimeException exception) { - LOGGER.info("stopSession has Exception {}", exception.getMessage()); - destroyProfiler(deviceIp, port); - if (retryCounts > NUM_2) { - return true; - } - return requestStopSession(deviceIp, port, sessionId, false, retryCounts); - } - client.setUsed(false); - return response.getStatus() == 0 ? true : false; - } - - /** - * request destory Session - * - * @param deviceIp deviceIp - * @param port port number - * @param sessionId sessionId - * @return boolean - */ - public boolean requestDestroySession(String deviceIp, int port, int sessionId) { - if (port <= 0 || port > LayoutConstants.PORT) { - return false; - } - return requestDestroySession(deviceIp, port, sessionId, 0); - } - - private boolean requestDestroySession(String deviceIp, int port, int sessionId, int retryCount) { - int retryCounts = retryCount + 1; - ProfilerClient client = getProfilerClient(deviceIp, port); - if (client.isUsed()) { - return false; - } - client.setUsed(true); - ProfilerServiceTypes.DestroySessionRequest req = - ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), sessionId); - ProfilerServiceTypes.DestroySessionResponse response = null; - try { - response = client.destroySession(req); - } catch (StatusRuntimeException exception) { - destroyProfiler(deviceIp, port); - if (retryCounts > NUM_2) { - return true; - } - return requestDestroySession(deviceIp, port, sessionId, retryCounts); - } - client.setUsed(false); - return response.getStatus() == 0 ? true : false; - } - - /** - * Fetch process data - * - * @param deviceIp deviceIp - * @param port port number - * @param sessionId sessionId - * @return List - */ - public List fetchProcessData(String deviceIp, int port, int sessionId) { - ProfilerClient client = getProfilerClient(deviceIp, port); - if (client.isUsed()) { - return new ArrayList<>(); - } - client.setUsed(true); - List processInfos = new ArrayList<>(); - ProfilerServiceTypes.FetchDataRequest fetchData = - ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), sessionId, null); - Iterator res = null; - try { - res = client.fetchData(fetchData); - } catch (StatusRuntimeException exception) { - destroyProfiler(deviceIp, port); - LOGGER.info("GrpcException {}", exception.getMessage()); - return new ArrayList<>(); - } - try { - if (res.hasNext()) { - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = res.next(); - int pluginStatus = fetchDataResponse.getStatus(); - if (pluginStatus != 0) { - client.setUsed(false); - return new ArrayList<>(); - } - List lists = fetchDataResponse.getPluginDataList(); - processInfos = extractedData(lists); - } - } catch (StatusRuntimeException statusRuntimeException) { - destroyProfiler(deviceIp, port); - LOGGER.error(" get ProcessInfo failed {}", statusRuntimeException.getMessage()); - } - client.setUsed(false); - return processInfos; - } - - private List extractedData(List lists) { - List process = new ArrayList<>(); - - for (CommonTypes.ProfilerPluginData profilerPluginData : lists) { - if (MEMORY_PLUGS_NAME.equals(profilerPluginData.getName()) || MEMORY_PLUG - .equals(profilerPluginData.getName())) { - if (profilerPluginData.getStatus() != 0) { - continue; - } - ByteString data = profilerPluginData.getData(); - MemoryPluginResult.MemoryData.Builder builder = MemoryPluginResult.MemoryData.newBuilder(); - MemoryPluginResult.MemoryData memorydata = null; - try { - memorydata = builder.mergeFrom(data).build(); - } catch (InvalidProtocolBufferException exception) { - LOGGER.info("mergeFrom failed {}", exception.getMessage()); - } - List processMemoryInfos = memorydata.getProcessesinfoList(); - for (MemoryPluginResult.ProcessMemoryInfo processMemoryInfo : processMemoryInfos) { - ProcessInfo processInfo = new ProcessInfo(); - processInfo.setProcessId(processMemoryInfo.getPid()); - processInfo.setProcessName(processMemoryInfo.getName()); - process.add(processInfo); - } - } - } - return process; - } - - /** - * Get capabilities - * - * @param deviceIp deviceIp - * @param port port number - * @return ProfilerServiceTypes.GetCapabilitiesResponse - */ - public ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities(String deviceIp, int port) { - if (port <= 0 || port > LayoutConstants.PORT) { - return null; - } - return getCapabilities(deviceIp, port, 0); - } - - /** - * Get capabilities - * - * @param deviceIp deviceIp - * @param port port number - * @param retryCount retry Count - * @return ProfilerServiceTypes.GetCapabilitiesResponse - */ - private ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities(String deviceIp, int port, int retryCount) { - int counts = retryCount + 1; - ProfilerServiceTypes.GetCapabilitiesResponse response; - ProfilerClient client = getProfilerClient(deviceIp, port); - try { - response = client.getCapabilities( - ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()) - .build()); - } catch (StatusRuntimeException exception) { - LOGGER.info("exception Error {}", exception.getMessage()); - destroyProfiler(deviceIp, port); - if (counts > NUM_2) { - return ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().build(); - } - return getCapabilities(deviceIp, port, counts); - } - return response; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.ManagedChannel; +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.LayoutConstants; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V8_PATH; +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUGS_NAME; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * Provide device-side grpc interface encapsulation for each module in the application + */ +public final class HiProfilerClient { + private static final Logger LOGGER = LogManager.getLogger(HiProfilerClient.class); + + private static final String IP = InetAddress.getLoopbackAddress().getHostAddress(); + + private static final int RETRY_COUNT = 2; + + /** + * Used to store the created Profiler + */ + private static ConcurrentHashMap profilerClientMap = + new ConcurrentHashMap<>(CommonUtil.collectionSize(0)); + + /** + * Singleton Class Instance + */ + private static class SingletonClassInstance { + private static final HiProfilerClient INSTANCE = new HiProfilerClient(); + } + + /** + * Get instance + * + * @return HiProfilerClient + */ + public static HiProfilerClient getInstance() { + return SingletonClassInstance.INSTANCE; + } + + private HiProfilerClient() { + } + + /** + * Get profilerclient + * + * @param ip ip address + * @param port port number + * @param channel channel + * @return ProfilerClient + */ + public ProfilerClient getProfilerClient(String ip, int port, ManagedChannel channel) { + String mapKey = IP + port; + if (port <= 0 || port > LayoutConstants.PORT) { + return null; + } + if (Objects.isNull(profilerClientMap.get(mapKey))) { + ProfilerClient profilerClient = new ProfilerClient(IP, port, channel); + profilerClientMap.put(mapKey, profilerClient); + return profilerClient; + } + return profilerClientMap.get(mapKey); + } + + /** + * get profilerClient. + * + * @param ip ip address + * @param port port number + * @return ProfilerClient + */ + public ProfilerClient getProfilerClient(String ip, int port) { + if (port <= 0 || port > LayoutConstants.PORT) { + return null; + } + String mapKey = IP + port; + if (profilerClientMap.get(mapKey) == null) { + ProfilerClient profilerClient = new ProfilerClient(IP, port); + profilerClientMap.put(mapKey, profilerClient); + return profilerClient; + } + return profilerClientMap.get(mapKey); + } + + /** + * Destroy profilerClient + * + * @param ip ip address + * @param port port number + * @return boolean + */ + public boolean destroyProfiler(String ip, int port) { + if (port <= 0 || port > LayoutConstants.PORT) { + return false; + } + String mapKey = IP + port; + if (Objects.isNull(profilerClientMap.get(mapKey))) { + return true; + } + ProfilerClient client = profilerClientMap.get(mapKey); + client.shutdown(); + return profilerClientMap.remove(mapKey, client); + } + + /** + * request Create Session + * + * @param port port number + * @param name name + * @param pid pid + * @param reportProcessTree report process tree + * @param deviceType DeviceType + * @return int + */ + public int requestCreateSession(int port, String name, int pid, boolean reportProcessTree, DeviceType deviceType) { + if (port <= 0 || port > LayoutConstants.PORT) { + return -1; + } + ProfilerClient client = getProfilerClient("", port); + LOGGER.info("process Session start222", DateTimeUtil.getNowTimeLong()); + LOGGER.info("process Session start3333", DateTimeUtil.getNowTimeLong()); + MemoryPluginConfig.MemoryConfig plug = + MemoryPlugHelper.createMemRequest(pid, reportProcessTree, false, false, false); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = ProfilerServiceHelper + .profilerSessionConfig(true, null, 10, + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE, 5000); + String sha256; + if (IS_SUPPORT_NEW_HDC && deviceType == LEAN_HOS_DEVICE) { + sha256 = getSTDSha256("/data/local/tmp/libmemdataplugin.z.so"); + } else { + sha256 = getSha256("/data/local/tmp/libmemdataplugin.z.so"); + } + CommonTypes.ProfilerPluginConfig plugConfig = + ProfilerServiceHelper.profilerPluginConfig(name, sha256, 0, plug.toByteString()); + List plugs = new ArrayList(); + plugs.add(plugConfig); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceHelper.createSessionRequest(CommonUtil.getRequestId(), sessionConfig, plugs); + ProfilerServiceTypes.CreateSessionResponse response = null; + try { + response = client.createSession(request); + LOGGER.info("process Session start444 {} ", DateTimeUtil.getNowTimeLong()); + } catch (StatusRuntimeException exception) { + return -1; + } + return response.getSessionId(); + } + + /** + * get Sha256 + * + * @param pluginFileName pluginFileName + * @return String + */ + public static String getSha256(String pluginFileName) { + String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1); + StringBuilder stringBuilder = new StringBuilder(SessionManager.getInstance().getPluginPath()); + stringBuilder.append(DEVTOOLS_PLUGINS_V8_PATH).append(File.separator).append(fileName).toString(); + String filePath = stringBuilder.toString(); + File pluginFile = new File(filePath); + String fileSha256 = ""; + try { + fileSha256 = DigestUtils.sha256Hex(new FileInputStream(pluginFile)); + LOGGER.info("plugin pluginFileName {}, sha256Hex {}", fileName, fileSha256); + } catch (IOException ioException) { + LOGGER.error("plugin sha256Hex IOException {}", ioException.getMessage()); + } + return fileSha256; + } + + /** + * getSTDSha256 + * + * @param pluginFileName pluginFileName + * @return String + */ + public static String getSTDSha256(String pluginFileName) { + String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1); + StringBuilder stringBuilder = new StringBuilder(SessionManager.getInstance().getPluginPath()); + stringBuilder.append("stddeveloptools").append(File.separator).append(fileName).toString(); + String filePath = stringBuilder.toString(); + File pluginFile = new File(filePath); + String fileSha256 = ""; + try { + fileSha256 = DigestUtils.sha256Hex(new FileInputStream(pluginFile)); + LOGGER.info("plugin {}, sha256Hex {}", fileName, fileSha256); + } catch (IOException ioException) { + LOGGER.error("plugin sha256Hex IOException {}", ioException.getMessage()); + } + return fileSha256; + } + + /** + * Request to start session + * + * @param deviceIp deviceIp + * @param port port number + * @param sessionId sessionId + * @return boolean + */ + public boolean requestStartSession(String deviceIp, int port, int sessionId) { + if (port <= 0 || port > LayoutConstants.PORT) { + return false; + } + return requestStartSession(deviceIp, port, sessionId, 0); + } + + private boolean requestStartSession(String deviceIp, int port, int sessionId, int retryCount) { + int retryCounts = retryCount + 1; + ProfilerServiceTypes.StartSessionRequest requestStartSession = + ProfilerServiceHelper.startSessionRequest(CommonUtil.getRequestId(), sessionId, new ArrayList<>()); + ProfilerServiceTypes.StartSessionResponse response = null; + ProfilerClient client = getProfilerClient(deviceIp, port); + try { + response = client.startSession(requestStartSession); + } catch (StatusRuntimeException exception) { + if (retryCounts > 5) { + return true; + } + return requestStartSession(deviceIp, port, sessionId, retryCounts); + } + return response.getStatus() == 0 ? true : false; + } + + /** + * requestStopSession + * + * @param deviceIp deviceIp + * @param port port number + * @param sessionId sessionId + * @param isForce isForce + * @return boolean + */ + public boolean requestStopSession(String deviceIp, int port, int sessionId, boolean isForce) { + if (port <= 0 || port > LayoutConstants.PORT) { + return false; + } + return requestStopSession(deviceIp, port, sessionId, isForce, 0); + } + + private boolean requestStopSession(String deviceIp, int port, int sessionId, boolean isForce, int retryCount) { + ProfilerClient client = getProfilerClient(deviceIp, port); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId); + ProfilerServiceTypes.StopSessionResponse response = null; + int retryCounts = retryCount; + try { + retryCounts = retryCount + 1; + Long stopTime = DateTimeUtil.getNowTimeLong(); + LOGGER.info("startStopSession {}", stopTime); + response = client.stopSession(stopSession); + LOGGER.info("startStopEndSession {}", DateTimeUtil.getNowTimeLong() - stopTime); + } catch (StatusRuntimeException exception) { + LOGGER.info("stopSession has Exception {}", exception.getMessage()); + if (retryCounts > RETRY_COUNT) { + return true; + } + return requestStopSession(deviceIp, port, sessionId, false, retryCounts); + } + return response.getStatus() == 0 ? true : false; + } + + /** + * request destory Session + * + * @param deviceIp deviceIp + * @param port port number + * @param sessionId sessionId + * @return boolean + */ + public boolean requestDestroySession(String deviceIp, int port, int sessionId) { + if (port <= 0 || port > LayoutConstants.PORT) { + return false; + } + return requestDestroySession(deviceIp, port, sessionId, 0); + } + + private boolean requestDestroySession(String deviceIp, int port, int sessionId, int retryCount) { + ProfilerClient client = getProfilerClient(deviceIp, port); + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), sessionId); + ProfilerServiceTypes.DestroySessionResponse response = null; + try { + response = client.destroySession(req); + } catch (StatusRuntimeException exception) { + LOGGER.error("requestDestroySession failed {}", exception.getMessage()); + int retryCounts = retryCount + 1; + if (retryCounts > RETRY_COUNT) { + return true; + } + return requestDestroySession(deviceIp, port, sessionId, retryCounts); + } + return response.getStatus() == 0 ? true : false; + } + + /** + * Fetch process data + * + * @param deviceIp deviceIp + * @param port port number + * @param sessionId sessionId + * @return List + */ + public List fetchProcessData(String deviceIp, int port, int sessionId) { + ProfilerClient client = getProfilerClient(deviceIp, port); + List processInfos = new ArrayList<>(); + ProfilerServiceTypes.FetchDataRequest fetchData = + ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), sessionId, null); + Iterator res = null; + try { + res = client.fetchData(fetchData); + } catch (StatusRuntimeException exception) { + LOGGER.info("GrpcException {}", exception.getMessage()); + return new ArrayList<>(); + } + try { + if (res.hasNext()) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = res.next(); + int pluginStatus = fetchDataResponse.getStatus(); + if (pluginStatus != 0) { + return new ArrayList<>(); + } + List lists = fetchDataResponse.getPluginDataList(); + processInfos = extractedData(lists); + } + } catch (StatusRuntimeException statusRuntimeException) { + LOGGER.error(" get ProcessInfo failed {}", statusRuntimeException.getMessage()); + } + return processInfos; + } + + private List extractedData(List lists) { + List process = new ArrayList<>(); + + for (CommonTypes.ProfilerPluginData profilerPluginData : lists) { + if (MEMORY_PLUGS_NAME.equals(profilerPluginData.getName()) || MEMORY_PLUG + .equals(profilerPluginData.getName())) { + if (profilerPluginData.getStatus() != 0) { + continue; + } + ByteString data = profilerPluginData.getData(); + MemoryPluginResult.MemoryData.Builder builder = MemoryPluginResult.MemoryData.newBuilder(); + MemoryPluginResult.MemoryData memorydata = null; + try { + memorydata = builder.mergeFrom(data).build(); + } catch (InvalidProtocolBufferException exception) { + LOGGER.info("mergeFrom failed {}", exception.getMessage()); + } + List processMemoryInfos = memorydata.getProcessesinfoList(); + for (MemoryPluginResult.ProcessMemoryInfo processMemoryInfo : processMemoryInfos) { + ProcessInfo processInfo = new ProcessInfo(); + processInfo.setProcessId(processMemoryInfo.getPid()); + processInfo.setProcessName(processMemoryInfo.getName()); + process.add(processInfo); + } + } + } + return process; + } + + /** + * Get capabilities + * + * @param deviceIp deviceIp + * @param port port number + * @return ProfilerServiceTypes.GetCapabilitiesResponse + */ + public ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities(String deviceIp, int port) { + if (port <= 0 || port > LayoutConstants.PORT) { + return null; + } + return getCapabilities(deviceIp, port, 0); + } + + /** + * Get capabilities + * + * @param deviceIp deviceIp + * @param port port number + * @param retryCount retry Count + * @return ProfilerServiceTypes.GetCapabilitiesResponse + */ + private ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities(String deviceIp, int port, int retryCount) { + int counts = retryCount + 1; + ProfilerServiceTypes.GetCapabilitiesResponse response; + ProfilerClient client = getProfilerClient(deviceIp, port); + try { + response = client.getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()) + .build()); + } catch (StatusRuntimeException exception) { + LOGGER.info("exception Error {}", exception.getMessage()); + if (counts > RETRY_COUNT) { + return ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().build(); + } + return getCapabilities(deviceIp, port, counts); + } + return response; + } + + /** + * keepSession + * + * @param deviceIp deviceIp + * @param port port number + * @param sessionId sessionId + * @return ProfilerServiceTypes.GetCapabilitiesResponse + * @throws StatusRuntimeException + */ + public ProfilerServiceTypes.KeepSessionResponse keepSession(String deviceIp, int port, int sessionId) + throws StatusRuntimeException { + if (port <= 0 || port > LayoutConstants.PORT) { + return null; + } + return keepSession(deviceIp, port, sessionId, 0); + } + + private ProfilerServiceTypes.KeepSessionResponse keepSession(String deviceIp, int port, int sessionId, + int retryCount) throws StatusRuntimeException { + int counts = retryCount + 1; + ProfilerClient client = getProfilerClient(deviceIp, port); + ProfilerServiceTypes.KeepSessionResponse response; + try { + response = client.keepSession( + ProfilerServiceTypes.KeepSessionRequest.newBuilder().setRequestId(CommonUtil.getRequestId()) + .setSessionId(sessionId).build()); + } catch (StatusRuntimeException exception) { + LOGGER.info("exception Error ", exception); + if (counts > RETRY_COUNT) { + LOGGER.error("exception Error ", exception); + throw exception; + } + return keepSession(deviceIp, port, sessionId, counts); + } + return response; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/MemoryPlugHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/MemoryPlugHelper.java index 2cc32c5cd..73f663fc1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/MemoryPlugHelper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/MemoryPlugHelper.java @@ -1,80 +1,77 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.transport.grpc; - -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; - -import java.util.List; - -/** - * Construct the configuration information help class of the memory plugin. - * - * @version 1.0 - * @date 2021/03/09 18:59 - **/ -public final class MemoryPlugHelper { - private MemoryPlugHelper() { - } - - /** - * Grpc request when requesting process information. - * - * @return MemoryPluginConfig.MemoryConfig - */ - public static MemoryPluginConfig.MemoryConfig createProcessRequest() { - MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); - builder.setReportProcessTree(true); - return builder.build(); - } - - /** - * The configuration object when requesting single-process memory data needs to be - * converted into binary and passed into createSessionRequest or startSessionRequest - * - * @param pid pid - * @param reportProcessTree reportProcessTree - * @param reportProcessMemInfo reportProcessMemInfo - * @param reportAppMemInfo reportAppMemInfo - * @param reportAppMemByDumpsys reportAppMemByDumpsys - * @return MemoryPluginConfig.MemoryConfig - */ - public static MemoryPluginConfig.MemoryConfig createMemRequest(int pid, boolean reportProcessTree, - boolean reportProcessMemInfo, boolean reportAppMemInfo, boolean reportAppMemByDumpsys) { - MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); - if (pid > 0) { - builder.addPid(pid); - } - builder.setReportProcessTree(reportProcessTree); - builder.setReportProcessMemInfo(reportProcessMemInfo); - builder.setReportAppMemInfo(reportAppMemInfo); - builder.setReportAppMemByDumpsys(reportAppMemByDumpsys); - return builder.build(); - } - - /** - * The configuration object when requesting multi-process memory data needs to be converted - * into binary and passed into createSessionRequest or startSessionRequest - * - * @param pids pids - * @return MemoryPluginConfig.MemoryConfig - */ - public static MemoryPluginConfig.MemoryConfig createMemRequest(List pids) { - MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); - builder.addAllPid(pids); - return builder.build(); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; + +import java.util.List; + +/** + * Construct the configuration information help class of the memory plugin. + */ +public final class MemoryPlugHelper { + private MemoryPlugHelper() { + } + + /** + * Grpc request when requesting process information. + * + * @return MemoryPluginConfig.MemoryConfig + */ + public static MemoryPluginConfig.MemoryConfig createProcessRequest() { + MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); + builder.setReportProcessTree(true); + return builder.build(); + } + + /** + * The configuration object when requesting single-process memory data needs to be + * converted into binary and passed into createSessionRequest or startSessionRequest + * + * @param pid pid + * @param reportProcessTree reportProcessTree + * @param reportProcessMemInfo reportProcessMemInfo + * @param reportAppMemInfo reportAppMemInfo + * @param reportAppMemByDumpsys reportAppMemByDumpsys + * @return MemoryPluginConfig.MemoryConfig + */ + public static MemoryPluginConfig.MemoryConfig createMemRequest(int pid, boolean reportProcessTree, + boolean reportProcessMemInfo, boolean reportAppMemInfo, boolean reportAppMemByDumpsys) { + MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); + if (pid > 0) { + builder.addPid(pid); + } + builder.setReportProcessTree(reportProcessTree); + builder.setReportProcessMemInfo(reportProcessMemInfo); + builder.setReportAppMemInfo(reportAppMemInfo); + builder.setReportAppMemByDumpsys(reportAppMemByDumpsys); + return builder.build(); + } + + /** + * The configuration object when requesting multi-process memory data needs to be converted + * into binary and passed into createSessionRequest or startSessionRequest + * + * @param pids pids + * @return MemoryPluginConfig.MemoryConfig + */ + public static MemoryPluginConfig.MemoryConfig createMemRequest(List pids) { + MemoryPluginConfig.MemoryConfig.Builder builder = MemoryPluginConfig.MemoryConfig.newBuilder(); + builder.addAllPid(pids); + return builder.build(); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerClient.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerClient.java index 467fcc0b5..9a745b488 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerClient.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerClient.java @@ -1,191 +1,193 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.transport.grpc; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.StatusRuntimeException; -import ohos.devtools.datasources.transport.grpc.service.IProfilerServiceGrpc; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.views.common.LayoutConstants; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; -import java.util.concurrent.TimeUnit; - -/** - * 提供设备侧grpc接口封装 - * - * @version 1.0 - * @date 2021/02/01 19:23 - **/ -public class ProfilerClient { - private static final Logger LOGGER = LogManager.getLogger(ProfilerClient.class); - - private ManagedChannel channel; - - private boolean isUsed; - - private String host; - - private int port; - - private IProfilerServiceGrpc.IProfilerServiceBlockingStub profilerBlockInClient; - - /** - * ProfilerClient - * - * @param host localhost - * @param port port number - */ - public ProfilerClient(String host, int port) { - this(host, port, null); - } - - /** - * ProfilerClient - * - * @param host localhost - * @param port port number - * @param channel channel - */ - public ProfilerClient(String host, int port, ManagedChannel channel) { - this.host = host; - this.port = port; - if (channel == null) { - this.channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); - } else { - this.channel = channel; - } - profilerBlockInClient = IProfilerServiceGrpc.newBlockingStub(this.channel); - } - - /** - * get profiler client - * - * @return IProfilerServiceGrpc.IProfilerServiceBlockingStub - */ - public IProfilerServiceGrpc.IProfilerServiceBlockingStub getProfilerClient() { - return profilerBlockInClient; - } - - /** - * 获取支持的插件列表 - * - * @param getCapabilitiesRequest getCapabilitiesRequest - * @return ProfilerServiceTypes.GetCapabilitiesResponse - * @throws StatusRuntimeException StatusRuntimeException - */ - public ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities( - ProfilerServiceTypes.GetCapabilitiesRequest getCapabilitiesRequest) throws StatusRuntimeException { - ProfilerServiceTypes.GetCapabilitiesResponse res = - profilerBlockInClient.withDeadlineAfter(LayoutConstants.FIVE, TimeUnit.SECONDS) - .getCapabilities(getCapabilitiesRequest); - return res; - } - - /** - * createSession - * - * @param createSessionRequest createSessionRequest - * @return ProfilerServiceTypes.CreateSessionResponse - * @throws StatusRuntimeException GrpcException - */ - public ProfilerServiceTypes.CreateSessionResponse createSession( - ProfilerServiceTypes.CreateSessionRequest createSessionRequest) throws StatusRuntimeException { - ProfilerServiceTypes.CreateSessionResponse response = - profilerBlockInClient.withDeadlineAfter(LayoutConstants.FIVE, TimeUnit.SECONDS) - .createSession(createSessionRequest); - return response; - } - - /** - * startSession - * - * @param startSessionRequest startSessionRequest - * @return ProfilerServiceTypes.StartSessionResponse - * @throws StatusRuntimeException StatusRuntimeException - */ - public ProfilerServiceTypes.StartSessionResponse startSession( - ProfilerServiceTypes.StartSessionRequest startSessionRequest) throws StatusRuntimeException { - ProfilerServiceTypes.StartSessionResponse response = - profilerBlockInClient.withDeadlineAfter(LayoutConstants.THREE, TimeUnit.SECONDS) - .startSession(startSessionRequest); - return response; - } - - /** - * 抓取数据 - * - * @param fetchDataRequest fetchDataRequest - * @return Iterator - * @throws StatusRuntimeException StatusRuntimeException - */ - public Iterator fetchData( - ProfilerServiceTypes.FetchDataRequest fetchDataRequest) throws StatusRuntimeException { - Iterator response = profilerBlockInClient.fetchData(fetchDataRequest); - return response; - } - - /** - * stop Session - * - * @param stopSessionRequest stopSessionRequest - * @return ProfilerServiceTypes.StopSessionResponse - * @throws StatusRuntimeException StatusRuntimeException - */ - public ProfilerServiceTypes.StopSessionResponse stopSession( - ProfilerServiceTypes.StopSessionRequest stopSessionRequest) throws StatusRuntimeException { - ProfilerServiceTypes.StopSessionResponse response = - profilerBlockInClient.withDeadlineAfter(1, TimeUnit.SECONDS).stopSession(stopSessionRequest); - return response; - } - - /** - * destroy Session - * - * @param destroyRequest destroyRequest - * @return ProfilerServiceTypes.DestroySessionResponse - * @throws StatusRuntimeException StatusRuntimeException - */ - public ProfilerServiceTypes.DestroySessionResponse destroySession( - ProfilerServiceTypes.DestroySessionRequest destroyRequest) throws StatusRuntimeException { - ProfilerServiceTypes.DestroySessionResponse res = - profilerBlockInClient.withDeadlineAfter(LayoutConstants.THREE_HUNDRED, TimeUnit.MILLISECONDS) - .destroySession(destroyRequest); - return res; - } - - /** - * 关闭方法 - */ - public void shutdown() { - try { - channel.shutdown().awaitTermination(1, TimeUnit.SECONDS); - } catch (InterruptedException exception) { - LOGGER.error(exception.getMessage()); - } - } - - public void setUsed(boolean used) { - isUsed = used; - } - - public boolean isUsed() { - return isUsed; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.transport.grpc.service.IProfilerServiceGrpc; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.views.common.LayoutConstants; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Iterator; +import java.util.concurrent.TimeUnit; + +/** + * 提供设备侧grpc接口封装 + */ +public class ProfilerClient { + private static final Logger LOGGER = LogManager.getLogger(ProfilerClient.class); + + private ManagedChannel channel; + + private String host; + + private int port; + + private IProfilerServiceGrpc.IProfilerServiceBlockingStub profilerBlockInClient; + + /** + * ProfilerClient + * + * @param host localhost + * @param port port number + */ + public ProfilerClient(String host, int port) { + this(host, port, null); + } + + /** + * ProfilerClient + * + * @param host localhost + * @param port port number + * @param channel channel + */ + public ProfilerClient(String host, int port, ManagedChannel channel) { + this.host = host; + this.port = port; + if (channel == null) { + this.channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); + } else { + this.channel = channel; + } + profilerBlockInClient = IProfilerServiceGrpc.newBlockingStub(this.channel); + } + + /** + * get profiler client + * + * @return IProfilerServiceGrpc.IProfilerServiceBlockingStub + */ + public IProfilerServiceGrpc.IProfilerServiceBlockingStub getProfilerClient() { + return profilerBlockInClient; + } + + /** + * 获取支持的插件列表 + * + * @param getCapabilitiesRequest getCapabilitiesRequest + * @return ProfilerServiceTypes.GetCapabilitiesResponse + * @throws StatusRuntimeException StatusRuntimeException + */ + public ProfilerServiceTypes.GetCapabilitiesResponse getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest getCapabilitiesRequest) throws StatusRuntimeException { + ProfilerServiceTypes.GetCapabilitiesResponse res = + profilerBlockInClient.withDeadlineAfter(LayoutConstants.FIVE, TimeUnit.SECONDS) + .getCapabilities(getCapabilitiesRequest); + return res; + } + + /** + * createSession + * + * @param createSessionRequest createSessionRequest + * @return ProfilerServiceTypes.CreateSessionResponse + * @throws StatusRuntimeException GrpcException + */ + public ProfilerServiceTypes.CreateSessionResponse createSession( + ProfilerServiceTypes.CreateSessionRequest createSessionRequest) throws StatusRuntimeException { + ProfilerServiceTypes.CreateSessionResponse response = + profilerBlockInClient.withDeadlineAfter(LayoutConstants.FIVE, TimeUnit.SECONDS) + .createSession(createSessionRequest); + return response; + } + + /** + * startSession + * + * @param startSessionRequest startSessionRequest + * @return ProfilerServiceTypes.StartSessionResponse + * @throws StatusRuntimeException StatusRuntimeException + */ + public ProfilerServiceTypes.StartSessionResponse startSession( + ProfilerServiceTypes.StartSessionRequest startSessionRequest) throws StatusRuntimeException { + ProfilerServiceTypes.StartSessionResponse response = + profilerBlockInClient.withDeadlineAfter(LayoutConstants.THREE, TimeUnit.SECONDS) + .startSession(startSessionRequest); + return response; + } + + /** + * 抓取数据 + * + * @param fetchDataRequest fetchDataRequest + * @return Iterator + * @throws StatusRuntimeException StatusRuntimeException + */ + public Iterator fetchData( + ProfilerServiceTypes.FetchDataRequest fetchDataRequest) throws StatusRuntimeException { + Iterator response = + profilerBlockInClient.withMaxInboundMessageSize(Integer.MAX_VALUE) + .withMaxOutboundMessageSize(Integer.MAX_VALUE).fetchData(fetchDataRequest); + return response; + } + + /** + * stop Session + * + * @param stopSessionRequest stopSessionRequest + * @return ProfilerServiceTypes.StopSessionResponse + * @throws StatusRuntimeException StatusRuntimeException + */ + public ProfilerServiceTypes.StopSessionResponse stopSession( + ProfilerServiceTypes.StopSessionRequest stopSessionRequest) throws StatusRuntimeException { + ProfilerServiceTypes.StopSessionResponse response = + profilerBlockInClient.withDeadlineAfter(3, TimeUnit.SECONDS).stopSession(stopSessionRequest); + return response; + } + + /** + * destroy Session + * + * @param destroyRequest destroyRequest + * @return ProfilerServiceTypes.DestroySessionResponse + * @throws StatusRuntimeException StatusRuntimeException + */ + public ProfilerServiceTypes.DestroySessionResponse destroySession( + ProfilerServiceTypes.DestroySessionRequest destroyRequest) throws StatusRuntimeException { + ProfilerServiceTypes.DestroySessionResponse res = + profilerBlockInClient.withDeadlineAfter(1, TimeUnit.SECONDS).destroySession(destroyRequest); + return res; + } + + /** + * keepSession + * + * @param keepSessionRequest keepSessionRequest + * @return ProfilerServiceTypes.KeepSessionResponse + * @throws StatusRuntimeException + */ + public ProfilerServiceTypes.KeepSessionResponse keepSession( + ProfilerServiceTypes.KeepSessionRequest keepSessionRequest) throws StatusRuntimeException { + ProfilerServiceTypes.KeepSessionResponse res = + profilerBlockInClient.withDeadlineAfter(1, TimeUnit.SECONDS).keepSession(keepSessionRequest); + return res; + } + + /** + * Closing method + */ + public void shutdown() { + try { + channel.shutdown().awaitTermination(1, TimeUnit.SECONDS); + } catch (InterruptedException exception) { + LOGGER.error(exception.getMessage()); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerServiceHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerServiceHelper.java index 6ba3d7fbc..36e8994d4 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerServiceHelper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/ProfilerServiceHelper.java @@ -1,191 +1,190 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.transport.grpc; - -import com.google.protobuf.ByteString; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.List; - -/** - * Create the request object of the profiler Client - * - * @version 1.0 - * @date 2021/02/25 17:25 - **/ -public final class ProfilerServiceHelper { - private static final Logger LOGGER = LogManager.getLogger(ProfilerServiceHelper.class); - - private ProfilerServiceHelper() { - } - - /** - * Create a Create Session Request object for grpc request. - * - * @param requestId requestId - * @param sessionConfig Session config - * @param pluginConfigs Plugin configs - * @return ProfilerServiceTypes.CreateSessionRequest - */ - public static ProfilerServiceTypes.CreateSessionRequest createSessionRequest(int requestId, - ProfilerServiceTypes.ProfilerSessionConfig sessionConfig, - List pluginConfigs) { - ProfilerServiceTypes.CreateSessionRequest.Builder createBuilder = - ProfilerServiceTypes.CreateSessionRequest.newBuilder(); - createBuilder.setRequestId(requestId); - if (sessionConfig != null) { - createBuilder.setSessionConfig(sessionConfig); - } - if (pluginConfigs != null) { - for (CommonTypes.ProfilerPluginConfig profilerPluginConfig : pluginConfigs) { - createBuilder.addPluginConfigs(profilerPluginConfig); - } - } - return createBuilder.build(); - } - - /** - * Create a start Session Request object for grpc request. - * - * @param requestId requestId - * @param sessionId sessionId - * @param pluginConfigs Plugin configs - * @return ProfilerServiceTypes.StartSessionRequest - */ - public static ProfilerServiceTypes.StartSessionRequest startSessionRequest(int requestId, int sessionId, - List pluginConfigs) { - ProfilerServiceTypes.StartSessionRequest.Builder startBuilder = - ProfilerServiceTypes.StartSessionRequest.newBuilder(); - startBuilder.setRequestId(requestId); - startBuilder.setSessionId(sessionId); - if (pluginConfigs != null) { - pluginConfigs.forEach(profilerPluginConfig -> { - startBuilder.addUpdateConfigs(profilerPluginConfig); - }); - } - return startBuilder.build(); - } - - /** - * Create a fetch Data Request object for grpc request - * - * @param requestId requestId - * @param sessionId sessionId - * @param addtionData addtionData not used temporarily, you can pass null - * @return ProfilerServiceTypes.FetchDataRequest - */ - public static ProfilerServiceTypes.FetchDataRequest fetchDataRequest(int requestId, int sessionId, - ByteString addtionData) { - ProfilerServiceTypes.FetchDataRequest.Builder builder = ProfilerServiceTypes.FetchDataRequest.newBuilder(); - builder.setRequestId(requestId); - builder.setSessionId(sessionId); - if (addtionData != null) { - builder.setAddtionData(addtionData); - } - return builder.build(); - } - - /** - * Create a stop Session Request object for grpc request. - * - * @param requestId requestId - * @param sessionId sessionId - * @return ProfilerServiceTypes.StopSessionRequest - */ - public static ProfilerServiceTypes.StopSessionRequest stopSessionRequest(int requestId, int sessionId) { - ProfilerServiceTypes.StopSessionRequest.Builder builder = ProfilerServiceTypes.StopSessionRequest.newBuilder(); - builder.setRequestId(requestId); - builder.setSessionId(sessionId); - return builder.build(); - } - - /** - * Create a destroy Session Request object for grpc request - * - * @param requestId requestId - * @param sessionId sessionId - * @return ProfilerServiceTypes.DestroySessionRequest - */ - public static ProfilerServiceTypes.DestroySessionRequest destroySessionRequest(int requestId, int sessionId) { - ProfilerServiceTypes.DestroySessionRequest.Builder builder = - ProfilerServiceTypes.DestroySessionRequest.newBuilder(); - builder.setRequestId(requestId); - builder.setSessionId(sessionId); - return builder.build(); - } - - /** - * Construct Session Config object - * - * @param online online Whether it is online mode, true online false offline - * @param resultFile resultFile - * @param pages pages - * @param value value - * @return ProfilerServiceTypes.ProfilerSessionConfig - */ - public static ProfilerServiceTypes.ProfilerSessionConfig profilerSessionConfig(boolean online, String resultFile, - int pages, ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy value) { - ProfilerServiceTypes.ProfilerSessionConfig.Builder builder = - ProfilerServiceTypes.ProfilerSessionConfig.newBuilder(); - if (online) { - builder.setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE); - } else { - builder.setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE); - builder.setResultFile(resultFile); - } - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder build = - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder(); - if (value != null && value.getNumber() > 0) { - build.setPolicy(value); - } - if (pages > 0) { - build.setPages(pages); - } - return builder.addBuffers(build.build()).build(); - } - - /** - * Construct profiler Plugin Config object - * - * @param name name - * @param pluginSha256 pluginSha256 - * @param sampleInterval sampleInterval - * @param confData confData Objects serialized by each plug-in - * @return CommonTypes.ProfilerPluginConfig - */ - public static CommonTypes.ProfilerPluginConfig profilerPluginConfig(String name, String pluginSha256, - int sampleInterval, ByteString confData) { - CommonTypes.ProfilerPluginConfig.Builder builder = CommonTypes.ProfilerPluginConfig.newBuilder(); - if (StringUtils.isNotBlank(name)) { - builder.setName(name); - } - if (StringUtils.isNotBlank(pluginSha256)) { - builder.setPluginSha256(pluginSha256); - } - if (sampleInterval > 0) { - builder.setSampleInterval(sampleInterval); - } - if (confData != null) { - builder.setConfigData(confData); - } - return builder.build(); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import com.google.protobuf.ByteString; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +/** + * Create the request object of the profiler Client + */ +public final class ProfilerServiceHelper { + private static final Logger LOGGER = LogManager.getLogger(ProfilerServiceHelper.class); + + private ProfilerServiceHelper() { + } + + /** + * Create a Create Session Request object for grpc request. + * + * @param requestId requestId + * @param sessionConfig Session config + * @param pluginConfigs Plugin configs + * @return ProfilerServiceTypes.CreateSessionRequest + */ + public static ProfilerServiceTypes.CreateSessionRequest createSessionRequest(int requestId, + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig, + List pluginConfigs) { + ProfilerServiceTypes.CreateSessionRequest.Builder createBuilder = + ProfilerServiceTypes.CreateSessionRequest.newBuilder(); + createBuilder.setRequestId(requestId); + if (sessionConfig != null) { + createBuilder.setSessionConfig(sessionConfig); + } + if (pluginConfigs != null) { + for (CommonTypes.ProfilerPluginConfig profilerPluginConfig : pluginConfigs) { + createBuilder.addPluginConfigs(profilerPluginConfig); + } + } + return createBuilder.build(); + } + + /** + * Create a start Session Request object for grpc request. + * + * @param requestId requestId + * @param sessionId sessionId + * @param pluginConfigs Plugin configs + * @return ProfilerServiceTypes.StartSessionRequest + */ + public static ProfilerServiceTypes.StartSessionRequest startSessionRequest(int requestId, int sessionId, + List pluginConfigs) { + ProfilerServiceTypes.StartSessionRequest.Builder startBuilder = + ProfilerServiceTypes.StartSessionRequest.newBuilder(); + startBuilder.setRequestId(requestId); + startBuilder.setSessionId(sessionId); + if (pluginConfigs != null) { + pluginConfigs.forEach(profilerPluginConfig -> { + startBuilder.addUpdateConfigs(profilerPluginConfig); + }); + } + return startBuilder.build(); + } + + /** + * Create a fetch Data Request object for grpc request + * + * @param requestId requestId + * @param sessionId sessionId + * @param addtionData addtionData not used temporarily, you can pass null + * @return ProfilerServiceTypes.FetchDataRequest + */ + public static ProfilerServiceTypes.FetchDataRequest fetchDataRequest(int requestId, int sessionId, + ByteString addtionData) { + ProfilerServiceTypes.FetchDataRequest.Builder builder = ProfilerServiceTypes.FetchDataRequest.newBuilder(); + builder.setRequestId(requestId); + builder.setSessionId(sessionId); + if (addtionData != null) { + builder.setAddtionData(addtionData); + } + return builder.build(); + } + + /** + * Create a stop Session Request object for grpc request. + * + * @param requestId requestId + * @param sessionId sessionId + * @return ProfilerServiceTypes.StopSessionRequest + */ + public static ProfilerServiceTypes.StopSessionRequest stopSessionRequest(int requestId, int sessionId) { + ProfilerServiceTypes.StopSessionRequest.Builder builder = ProfilerServiceTypes.StopSessionRequest.newBuilder(); + builder.setRequestId(requestId); + builder.setSessionId(sessionId); + return builder.build(); + } + + /** + * Create a destroy Session Request object for grpc request + * + * @param requestId requestId + * @param sessionId sessionId + * @return ProfilerServiceTypes.DestroySessionRequest + */ + public static ProfilerServiceTypes.DestroySessionRequest destroySessionRequest(int requestId, int sessionId) { + ProfilerServiceTypes.DestroySessionRequest.Builder builder = + ProfilerServiceTypes.DestroySessionRequest.newBuilder(); + builder.setRequestId(requestId); + builder.setSessionId(sessionId); + return builder.build(); + } + + /** + * Construct Session Config object + * + * @param online online Whether it is online mode, true online false offline + * @param resultFile resultFile + * @param pages pages + * @param value value + * @param keepTime keepTime + * @return ProfilerServiceTypes.ProfilerSessionConfig + */ + public static ProfilerServiceTypes.ProfilerSessionConfig profilerSessionConfig(boolean online, String resultFile, + int pages, ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy value, int keepTime) { + ProfilerServiceTypes.ProfilerSessionConfig.Builder builder = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder(); + if (online) { + builder.setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE); + } else { + builder.setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE); + builder.setResultFile(resultFile); + } + builder.setKeepAliveTime(keepTime); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder build = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder(); + if (value != null && value.getNumber() > 0) { + build.setPolicy(value); + } + if (pages > 0) { + build.setPages(pages); + } + return builder.addBuffers(build.build()).build(); + } + + /** + * Construct profiler Plugin Config object + * + * @param name name + * @param pluginSha256 pluginSha256 + * @param sampleInterval sampleInterval + * @param confData confData Objects serialized by each plug-in + * @return CommonTypes.ProfilerPluginConfig + */ + public static CommonTypes.ProfilerPluginConfig profilerPluginConfig(String name, String pluginSha256, + int sampleInterval, ByteString confData) { + CommonTypes.ProfilerPluginConfig.Builder builder = CommonTypes.ProfilerPluginConfig.newBuilder(); + if (StringUtils.isNotBlank(name)) { + builder.setName(name); + } + if (StringUtils.isNotBlank(pluginSha256)) { + builder.setPluginSha256(pluginSha256); + } + if (sampleInterval > 0) { + builder.setSampleInterval(sampleInterval); + } + if (confData != null) { + builder.setConfigData(confData); + } + return builder.build(); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/SystemTraceHelper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/SystemTraceHelper.java new file mode 100644 index 000000000..ee7a814b7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/grpc/SystemTraceHelper.java @@ -0,0 +1,394 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import com.google.protobuf.ByteString; +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.HiperfCallPluginConfigOuterClass; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass; +import ohos.devtools.datasources.utils.common.GrpcException; +import ohos.devtools.datasources.utils.common.util.BeanUtil; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.service.ProcessManager; +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.LayoutConstants; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static ohos.devtools.datasources.transport.grpc.HiProfilerClient.getSTDSha256; +import static ohos.devtools.datasources.transport.grpc.HiProfilerClient.getSha256; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * get trace data + */ +public class SystemTraceHelper { + private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); + private static final String SYSTEM_PROBES_KIND_IN_MEMORY = "inMemoryValue"; + private static final String SYSTEM_PROBES_KIND_MAX_DURATION = "maxDuration"; + private static final String SYSTEM_PROBES_KIND_FTRACE_EVENT = "ftrace_events"; + private static final String SYSTEM_PROBES_KIND_ATRACE_APPS = "atrace_apps"; + private static final int SECOND_TO_MS = 1000; + private static final int MEMORY_MB_TO_KB = 1024; + + /** + * 单例进程对象 + */ + private static SystemTraceHelper singleton; + + /** + * 获取实例 + * + * @return TraceManager + */ + public static SystemTraceHelper getSingleton() { + if (singleton == null) { + synchronized (ProcessManager.class) { + if (singleton == null) { + singleton = new SystemTraceHelper(); + } + } + } + return singleton; + } + + /** + * createSession startSession + * + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param sessionConfigParam sessionConfigParam + * @param configByteParam configByteParam + * @param pluginNameParam pluginNameParam + * @return String + */ + public String createAndStartSession(DeviceIPPortInfo deviceIPPortInfoParam, + ProfilerServiceTypes.ProfilerSessionConfig sessionConfigParam, byte[] configByteParam, String pluginNameParam) { + String sha256; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfoParam.getDeviceType() == LEAN_HOS_DEVICE) { + sha256 = getSTDSha256(pluginNameParam); + } else { + sha256 = getSha256(pluginNameParam); + } + CommonTypes.ProfilerPluginConfig plugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setPluginSha256(sha256) + .setName(pluginNameParam) + .setConfigData(ByteString.copyFrom(configByteParam)) + .build(); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceTypes.CreateSessionRequest.newBuilder() + .setRequestId(CommonUtil.getRequestId()) + .setSessionConfig(sessionConfigParam) + .addPluginConfigs(plugConfig) + .build(); + HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); + ProfilerClient client = + hiprofiler.getProfilerClient(deviceIPPortInfoParam.getIp(), deviceIPPortInfoParam.getForwardPort()); + ProfilerServiceTypes.CreateSessionResponse createSessionResponse = client.createSession(request); + ProfilerServiceTypes.StartSessionRequest requestStartSession = ProfilerServiceHelper + .startSessionRequest(CommonUtil.getRequestId(), createSessionResponse.getSessionId(), new ArrayList<>()); + // 调用哪些进程(采集数据) + client.startSession(requestStartSession); + return String.valueOf(createSessionResponse.getSessionId()); + } + + /** + * stop Session and destroy Session Request + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param sessionIdParam sessionIdParam + */ + public void stopAndDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) { + // 停止session + int sessionId = Integer.valueOf(sessionIdParam); + HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); + ProfilerClient client = + hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId); + HiProfilerClient.getInstance() + .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, true); + // 销毁session + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), sessionId); + try { + client.destroySession(req); + } catch (StatusRuntimeException exception) { + LOGGER.info("destroy session Exception: {}", exception.getMessage()); + } + } + + /** + * stop Session and destroy Session Request + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param sessionIdParam sessionIdParam + */ + public void stopSession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) { + // 停止session + int sessionId = Integer.valueOf(sessionIdParam); + HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); + ProfilerClient client = + hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId); + HiProfilerClient.getInstance() + .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, true); + } + + /** + * destroySessionRequest + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param sessionIdParam sessionIdParam + */ + public void cancelActionDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) { + int sessionId = Integer.valueOf(sessionIdParam); + HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); + ProfilerClient client = + hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + // 销毁session + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), sessionId); + try { + client.destroySession(req); + } catch (StatusRuntimeException exception) { + LOGGER.info("destroy session Exception: {}", exception.getMessage()); + } + } + + /** + * request start session + * + * @param deviceIPPortInfo device IP Port Info + * @param userCheckBoxForPerfettoStr userCheckBoxForPerfettoStr + * @param maxDurationParam maxDurationParam + * @param inMemoryValue inMemoryValue + * @param outFileName outFileName + * @param isRoot isRoot + * @return String + * @throws GrpcException GrpcException + */ + public String createSessionByTraceRequest(DeviceIPPortInfo deviceIPPortInfo, String userCheckBoxForPerfettoStr, + int maxDurationParam, int inMemoryValue, String outFileName, boolean isRoot) throws GrpcException { + BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = + BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); + build.setBuffeSize(inMemoryValue * MEMORY_MB_TO_KB); + build.setClock("boot"); + if (userCheckBoxForPerfettoStr != null && userCheckBoxForPerfettoStr.length() > 0) { + Arrays.stream(userCheckBoxForPerfettoStr.split(";")).filter(param -> param.trim().length() > 0) + .forEach(param -> build.addCategories(param)); + } else { + // catch All + build.addCategories(""); + } + build.setIsRoot(isRoot); + build.setTime(maxDurationParam); + build.setOutfileName(outFileName); + BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + int keepAliveTime = maxDurationParam + 1; + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf) + .setKeepAliveTime(keepAliveTime).build(); + // 获取插件名称 + ProfilerServiceTypes.GetCapabilitiesResponse response = + HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + List capabilitiesList = response.getCapabilitiesList(); + ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = + capabilitiesList.stream().filter(item -> item.getName().contains("libbytrace")).findFirst().get(); + String pluginName = profilerPluginCapability.getName(); + return this.createAndStartSession(deviceIPPortInfo, sessionConfig, configByte, pluginName); + } + + /** + * request start session + * + * @param deviceIPPortInfo device IP Port Info + * @param fileSuffixTimestampParam file Suffix Timestamp Param + * @param processNameParam processName Param + * @return String + * @throws GrpcException GrpcException + */ + public String createSessionByTraceRequestNoParam(DeviceIPPortInfo deviceIPPortInfo, String fileSuffixTimestampParam, + String processNameParam) throws GrpcException { + BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = + BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); + String fileStorePath = "/data/local/tmp/hiprofiler_data"; + fileStorePath = fileStorePath.concat(fileSuffixTimestampParam).concat(".bytrace"); + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + build.addCategories("freq"); + build.addCategories("idle"); + build.addCategories("workq"); + build.setIsRoot(false); + } else if (deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + build.addCategories("sched"); + build.addCategories("freq"); + build.addCategories("idle"); + build.addCategories("workq"); + build.setIsRoot(true); + } else { + build.setIsRoot(false); + build.addCategories("gfx"); + } + build.setTime(0); + build.setOutfileName(fileStorePath); + BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf) + .build(); + // 获取插件名称 + ProfilerServiceTypes.GetCapabilitiesResponse response = + HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + List capabilitiesList = response.getCapabilitiesList(); + ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = + capabilitiesList.stream().filter(item -> item.getName().contains("libbytrace")).findFirst().get(); + String pluginName = profilerPluginCapability.getName(); + return this.createAndStartSession(deviceIPPortInfo, sessionConfig, configByte, pluginName); + } + + /** + * Request start session + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param eventsList eventsList + * @param atraceEventsList atraceEventsList + * @param maxDuration maxDuration + * @param inMemoryValue inMemoryValue + * @return String + * @throws GrpcException GrpcException + */ + public String createSessionHtraceRequest(DeviceIPPortInfo deviceIPPortInfo, ArrayList> eventsList, + ArrayList> atraceEventsList, int maxDuration, int inMemoryValue) throws GrpcException { + TracePluginConfigOuterClass.TracePluginConfig.Builder build = + TracePluginConfigOuterClass.TracePluginConfig.newBuilder(); + if (eventsList != null && !eventsList.isEmpty()) { + eventsList.forEach(events -> events.forEach(event -> { + build.addFtraceEvents(event); + })); + } + if (atraceEventsList != null && !atraceEventsList.isEmpty()) { + atraceEventsList.forEach(events -> events.forEach(event -> { + build.addBytraceCategories(event); + })); + } + build.setClock("boot"); + build.setParseKsyms(true); + build.setBufferSizeKb(inMemoryValue * MEMORY_MB_TO_KB); + build.setFlushIntervalMs(1000); + build.setFlushThresholdKb(4096); + TracePluginConfigOuterClass.TracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setSampleDuration(maxDuration * SECOND_TO_MS) + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE).addBuffers(bf) + .setResultFile("/data/local/tmp/hiprofiler_data.htrace").build(); + MemoryPluginConfig.MemoryConfig.Builder memoryBuilder = MemoryPluginConfig.MemoryConfig.newBuilder(); + memoryBuilder.setReportProcessTree(true); + memoryBuilder.setReportProcessMemInfo(true); + MemoryPluginConfig.MemoryConfig memoryConfig = memoryBuilder.build(); + byte[] memoryConfigByte = BeanUtil.serializeByCodedOutPutStream(memoryConfig); + return this.createAndStartSession(deviceIPPortInfo, sessionConfig, configByte, memoryConfigByte); + } + + /** + * createAndStartSession + * + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param sessionConfigParam sessionConfigParam + * @param configByteParam configByteParam + * @param memoryConfigByteParam memoryConfigByteParam + * @return String + */ + public String createAndStartSession(DeviceIPPortInfo deviceIPPortInfoParam, + ProfilerServiceTypes.ProfilerSessionConfig sessionConfigParam, byte[] configByteParam, + byte[] memoryConfigByteParam) { + String pluginName = getPluginName(deviceIPPortInfoParam, "libftrace"); + String sha256; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfoParam.getDeviceType() == LEAN_HOS_DEVICE) { + sha256 = getSTDSha256(pluginName); + } else { + sha256 = getSha256(pluginName); + } + CommonTypes.ProfilerPluginConfig plugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setPluginSha256(sha256).setName(pluginName) + .setConfigData(ByteString.copyFrom(configByteParam)).build(); + String pluginMemoryName = getPluginName(deviceIPPortInfoParam, "libmem"); + String memSha256; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfoParam.getDeviceType() == LEAN_HOS_DEVICE) { + memSha256 = getSTDSha256(pluginMemoryName); + } else { + memSha256 = getSha256(pluginMemoryName); + } + CommonTypes.ProfilerPluginConfig memoryPlugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setPluginSha256(memSha256).setName(pluginMemoryName) + .setSampleInterval(5000).setConfigData(ByteString.copyFrom(memoryConfigByteParam)).build(); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfigParam) + .addPluginConfigs(plugConfig).addPluginConfigs(memoryPlugConfig).build(); + HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); + ProfilerClient client = + hiprofiler.getProfilerClient(deviceIPPortInfoParam.getIp(), deviceIPPortInfoParam.getForwardPort()); + ProfilerServiceTypes.CreateSessionResponse createSessionResponse = client.createSession(request); + ProfilerServiceTypes.StartSessionRequest requestStartSession = ProfilerServiceHelper + .startSessionRequest(CommonUtil.getRequestId(), createSessionResponse.getSessionId(), new ArrayList<>()); + // 调用哪些进程(采集数据) + client.startSession(requestStartSession); + return String.valueOf(createSessionResponse.getSessionId()); + } + + /** + * getPluginName + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param PluginName PluginName + * @return String + */ + public String getPluginName(DeviceIPPortInfo deviceIPPortInfo, String PluginName) { + ProfilerServiceTypes.GetCapabilitiesResponse response = + HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + List capabilitiesList = response.getCapabilitiesList(); + if (capabilitiesList.isEmpty()) { + return ""; + } + ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = + capabilitiesList.stream().filter(item -> item.getName().contains(PluginName)).findFirst().get(); + return profilerPluginCapability.getName(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCmdList.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCmdList.java new file mode 100644 index 000000000..de63f77ef --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCmdList.java @@ -0,0 +1,504 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.transport.hdc; + +import ohos.devtools.datasources.utils.session.service.SessionManager; + +import java.util.ArrayList; + +/** + * HdcCmdList + */ +public class HdcCmdList { + /** + * pluginPath + */ + public static final String PLUGIN_PATH = SessionManager.getInstance().getHdcPath(); + + /** + * HDC LIST TARGETS STR + */ + public static ArrayList HDC_LIST_TARGETS_STR = new ArrayList<>() { + private static final long serialVersionUID = -2441056417543656558L; + { + add(PLUGIN_PATH); + add("list"); + add("targets"); + add("-v"); + } + }; + + /** + * HDC GET TYPE + */ + public static ArrayList HDC_GET_TYPE = new ArrayList<>() { + private static final long serialVersionUID = -2394024522865456503L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("getprop"); + add("ro.product.cpu.abi"); + } + }; + + /** + * HDC RUN OHOS + */ + public static ArrayList HDC_RUN_OHOS = new ArrayList<>() { + private static final long serialVersionUID = -103210883565193436L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("unzipStart"); + add("%s"); + } + }; + + /** + * hdc start profilerd + */ + public static ArrayList HDC_START_PROFILERD = new ArrayList<>() { + private static final long serialVersionUID = -6892425692255758759L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("restart"); + } + }; + + /** + * hdc start javaHeap + */ + public static ArrayList HDC_START_JAVAHEAP = new ArrayList<>() { + private static final long serialVersionUID = -7953946430216933650L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("startHeap"); + add("%s"); + } + }; + + /** + * HDC CHECK SERVER + */ + public static ArrayList HDC_CHECK_SERVER = new ArrayList<>() { + private static final long serialVersionUID = -6734438879494283706L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("check_server"); + } + }; + + /** + * HDC PUSH OHOS SHELL + */ + public static ArrayList HDC_PUSH_OHOS_SHELL = new ArrayList<>() { + private static final long serialVersionUID = 7407520677035151364L; + + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("/data/local/tmp/ohosprofiler"); + } + }; + + /** + * HDC PUSH FILE SHELL + */ + public static ArrayList HDC_PUSH_FILE_SHELL = new ArrayList<>() { + private static final long serialVersionUID = 118323663337186414L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC FOR PORT + */ + public static ArrayList HDC_FOR_PORT = new ArrayList<>() { + private static final long serialVersionUID = -3646030545566427790L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("fport"); + add("tcp:%s"); + add("tcp:50051"); + } + }; + + /** + * HDC PUSH CMD + */ + public static ArrayList HDC_PUSH_CMD = new ArrayList<>() { + private static final long serialVersionUID = 7249365681950995900L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("/data/local/tmp/developtools"); + } + }; + + /** + * HDC CLEAR CMD + */ + public static ArrayList HDC_CLEAR_CMD = new ArrayList<>() { + private static final long serialVersionUID = 7563399100805170044L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("rm"); + add("-rf"); + add("/data/local/tmp/developtools/"); + } + }; + + /** + * HDC ROOT CLEAR CMD + */ + public static ArrayList HDC_ROOT_CLEAR_CMD = new ArrayList<>() { + private static final long serialVersionUID = 471178417841389616L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("su 0 rm -rf /data/local/tmp/developtools/"); + } + }; + + /** + * HDC GET PLUGIN MD5S + */ + public static ArrayList HDC_GET_PLUGIN_MD5S = new ArrayList<>() { + private static final long serialVersionUID = 5290498389644237835L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp/developtools/"); + add("&&"); + add("md5sum * | grep -v \"developtools\""); + } + }; + + /** + * hdc create heapDump + */ + public static ArrayList HDC_CREATE_HEAPDUMP = new ArrayList<>() { + private static final long serialVersionUID = 7647678596290819135L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("am"); + add("dumpheap"); + add("%s"); + add("%s"); + } + }; + + /** + * hdc recV heapDump + */ + public static ArrayList HDC_RECV_HEAPDUMP = new ArrayList<>() { + private static final long serialVersionUID = -8073939164877060309L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("/data/local/tmp/%s"); + add("%s"); + } + }; + + /** + * HDC GET TIME + */ + public static ArrayList HDC_GET_TIME = new ArrayList<>() { + private static final long serialVersionUID = -564370535864629715L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("date"); + add("+%s%N"); + } + }; + + /** + * HDC HAS TRACE FILE INFO + */ + public static ArrayList HDC_HAS_TRACE_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = -6669823431200909892L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC PULL TRACE FILE + */ + public static ArrayList HDC_PULL_TRACE_FILE = new ArrayList<>() { + private static final long serialVersionUID = -827799272692157779L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC CHMOD PROC + */ + public static ArrayList HDC_CHMOD_PROC = new ArrayList<>() { + private static final long serialVersionUID = -7606240047012790952L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("su 0 chmod 777 /proc/stat"); + } + }; + + /** + * HDC GET SimPERF FILE INFO + */ + public static ArrayList HDC_GET_SIMPER_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = -7258927152502785089L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC GET SimPERF FILE + */ + public static ArrayList HDC_GET_SIMPER_FILE = new ArrayList<>() { + private static final long serialVersionUID = -4007861967368888669L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC GET TRACE FILE INFO + */ + public static ArrayList HDC_GET_TRACE_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = -6950108406906264163L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC GET TRACE FILE + */ + public static ArrayList HDC_GET_TRACE_FILE = new ArrayList<>() { + private static final long serialVersionUID = -1592462036082926191L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC SHELL HiLOG + */ + public static ArrayList HDC_SHELL_HILOG = new ArrayList<>() { + private static final long serialVersionUID = 2078981290462881684L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("hilog"); + } + }; + + /** + * HDC HiLOG + */ + public static ArrayList HDC_HILOG = new ArrayList<>() { + private static final long serialVersionUID = -5609660539341002374L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("hilog"); + } + }; + + /** + * HDC HiLOG C + */ + public static ArrayList HDC_HILOG_C = new ArrayList<>() { + private static final long serialVersionUID = 8580129953374994618L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("hilog"); + add("-c"); + } + }; + + /** + * HDC HiLOG R + */ + public static ArrayList HDC_HILOG_R = new ArrayList<>() { + private static final long serialVersionUID = 370115372353170396L; + { + add(PLUGIN_PATH); + add("-t"); + add("%s"); + add("shell"); + add("hilog"); + add("-r"); + } + }; + + /** + * TRACE STREAMER LOAD + */ + public static ArrayList TRACE_STREAMER_LOAD = new ArrayList<>() { + private static final long serialVersionUID = -3159139340525115732L; + { + add("%s"); + add("%s"); + add("-e"); + add("%s"); + } + }; + + /** + * Add permissions + */ + public static ArrayList CHMOD_TO_OHOS = new ArrayList<>() { + private static final long serialVersionUID = -8550606962513461794L; + { + add("chmod"); + add("-R"); + add("777"); + add("%s"); + } + }; +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCommandEnum.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCommandEnum.java deleted file mode 100644 index 41e20f3d3..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcCommandEnum.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.transport.hdc; - -/** - * hdc command type - * - * @version 1.0 - * @date 2021/02/01 10:47 - **/ -public enum HdcCommandEnum { - /** - * hdc push command - */ - HDC_FILE_SEND_STR("file send"), - - /** - * Get device serial number command - */ - HDC_FPORT_STR("fport"), - - /** - * Get device serial number command - */ - HDC_LIST_TARGETS_STR("hdc list targets -v"), - - /** - * Get device device version - */ - HDC_GET_TYPE("hdc -t %s shell getprop ro.product.cpu.abi"), - - /** - * hdc shell command - */ - HDC_SHELL_STR("shell"), - - /** - * hdc command - */ - HDC_STR("hdc"), - - /** - * hdc command - */ - HDC_RUN_OHOS("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler &&sh ohosprofiler unzipStart"), - - /** - * hdc command - */ - HDC_RUN_V7_OHOS("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler &&sh ohosprofiler unzipStartV7"), - - /** - * hdc command - */ - HDC_START_PROFILERD("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler && sh ohosprofiler restart"), - - /** - * hdc command - */ - HDC_STARTV7_PROFILERD("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler && sh ohosprofiler restart"), - - /** - * hdc command - */ - HDC_START_JAVAHEAP("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler && sh ohosprofiler startHeap %s"), - - /** - * hdc command - */ - HDC_CHECK_SERVER("hdc -t %s shell cd /data/local/tmp && chmod +x ohosprofiler && sh ohosprofiler check_server"), - - /** - * hdc command - */ - HDC_PUSH_OHOS_SHELL("hdc -t %s file send %s /data/local/tmp/ohosprofiler"), - - /** - * hdc command - */ - HDC_PUSH_OHOS_ARMV7("hdc -t %s file send %s /data/local/tmp/%s"), - - /** - * hdc command - */ - HDC_FOR_PORT("hdc -t %s fport tcp:%s tcp:50051"), - /** - * hdc push - */ - HDC_PUSH_CMD("hdc -t %s file send %s /data/local/tmp/devtool"); - - private String hdcCommand; - - HdcCommandEnum(String hdcCommand) { - this.hdcCommand = hdcCommand; - } - - public String getHdcCommand() { - return hdcCommand; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcStdCmdList.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcStdCmdList.java new file mode 100644 index 000000000..665a1c018 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcStdCmdList.java @@ -0,0 +1,408 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.transport.hdc; + +import ohos.devtools.datasources.utils.session.service.SessionManager; + +import java.util.ArrayList; + +/** + * HdcStdCmdList + */ +public class HdcStdCmdList { + /** + * pluginPath + */ + public static String pluginPath = SessionManager.getInstance().getHdcStdPath(); + + /** + * HDC STD LIST TARGETS STR + */ + public static final ArrayList HDC_STD_LIST_TARGETS_STR = new ArrayList<>() { + private static final long serialVersionUID = 7328508897834721709L; + { + add(pluginPath); + add("list"); + add("targets"); + add("-v"); + } + }; + + /** + * HDC STD RUN OHOS + */ + public static ArrayList HDC_STD_RUN_OHOS = new ArrayList<>() { + private static final long serialVersionUID = -1497892508289310831L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("untarStart"); + add("%s"); + } + }; + + /** + * HDC STD START PROFILERD + */ + public static ArrayList HDC_STD_START_PROFILER = new ArrayList<>() { + private static final long serialVersionUID = -7496488704314430824L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("start_std_daemon"); + } + }; + + /** + * HDC STD CHECK SERVER + */ + public static ArrayList HDC_STD_CHECK_SERVER = new ArrayList<>() { + private static final long serialVersionUID = 2946832952090077766L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp"); + add("&&"); + add("chmod"); + add("+x"); + add("ohosprofiler"); + add("&&"); + add("sh"); + add("ohosprofiler"); + add("check_std_server"); + } + }; + + /** + * HDC STD PUSH OHOS SHELL + */ + public static ArrayList HDC_STD_PUSH_OHOS_SHELL = new ArrayList<>() { + private static final long serialVersionUID = 4164605095978787447L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("/data/local/tmp/ohosprofiler"); + } + }; + + /** + * HDC STD PUSH FILE SHELL + */ + public static ArrayList HDC_STD_PUSH_FILE_SHELL = new ArrayList<>() { + private static final long serialVersionUID = 1061960274001695519L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC STD FOR PORT + */ + public static ArrayList HDC_STD_FOR_PORT = new ArrayList<>() { + private static final long serialVersionUID = -7030468377917652399L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("fport"); + add("tcp:%s"); + add("tcp:50051"); + } + }; + + /** + * HDC STD PUSH CMD + */ + public static ArrayList HDC_STD_PUSH_CMD = new ArrayList<>() { + private static final long serialVersionUID = 8398848389297819410L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("send"); + add("%s"); + add("/data/local/tmp/developtool.tar"); + } + }; + + /** + * HDC STD ROOT CLEAR CMD + */ + public static ArrayList HDC_STD_ROOT_CLEAR_CMD = new ArrayList<>() { + private static final long serialVersionUID = 6514979196500138508L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("rm -rf /data/local/tmp/developtools/"); + } + }; + + /** + * HDC STD GET PLUGIN MD5S + */ + public static ArrayList HDC_STD_GET_PLUGIN_MD5S = new ArrayList<>() { + private static final long serialVersionUID = 3619030319143131356L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("cd"); + add("/data/local/tmp/developtools/"); + add("&&"); + add("md5sum * | grep -v \"developtools\""); + } + }; + + /** + * HDC STD GET TIME + */ + public static ArrayList HDC_STD_GET_TIME = new ArrayList<>() { + private static final long serialVersionUID = 1547277822359912982L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("date"); + add("+%s%N"); + } + }; + + /** + * HDC STD HAS TRACE FILE INFO + */ + public static ArrayList HDC_STD_HAS_TRACE_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = 7222695108774866461L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC STD PULL TRACE FILE + */ + public static ArrayList HDC_STD_PULL_TRACE_FILE = new ArrayList<>() { + private static final long serialVersionUID = -1262290397066935333L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC STD CHMOD PROC + */ + public static ArrayList HDC_STD_CHMOD_PROC = new ArrayList<>() { + private static final long serialVersionUID = 4523522563780898863L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("chmod"); + add("777"); + add("/proc/stat"); + } + }; + + /** + * HDC STD GET SimPERF FILE INFO + */ + public static ArrayList HDC_STD_GET_SIMPERF_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = -6777810598852359424L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC STD GET SimPERF FILE + */ + public static ArrayList HDC_STD_GET_SIMPERF_FILE = new ArrayList<>() { + private static final long serialVersionUID = -7999933171772577521L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC STD GET TRACE FILE INFO + */ + public static ArrayList HDC_STD_GET_TRACE_FILE_INFO = new ArrayList<>() { + private static final long serialVersionUID = -5460775654047993957L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("du"); + add("%s"); + } + }; + + /** + * HDC STD GET TRACE FILE + */ + public static ArrayList HDC_STD_GET_TRACE_FILE = new ArrayList<>() { + private static final long serialVersionUID = 4766180836351032855L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; + + /** + * HDC STD SHELL HiLOG + */ + public static ArrayList HDC_STD_SHELL_HI_LOG = new ArrayList<>() { + private static final long serialVersionUID = -8828490298923994828L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("hilog"); + } + }; + + /** + * HDC STD HiLOG R + */ + public static ArrayList HDC_STD_HILOG_R = new ArrayList<>() { + private static final long serialVersionUID = -8297376293467393930L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("hilog"); + add("-r"); + } + }; + + /** + * HDC STD START NATIVE HOOK + */ + public static ArrayList HDC_STD_START_NATIVE_HOOK = new ArrayList<>() { + private static final long serialVersionUID = 5995494856526394813L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("kill"); + add("-36"); + add("%s"); + } + }; + + /** + * HDC STD STOP NATIVE HOOK + */ + public static ArrayList HDC_STD_STOP_NATIVE_HOOK = new ArrayList<>() { + private static final long serialVersionUID = -6856650349955834515L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("shell"); + add("kill"); + add("-37"); + add("%s"); + } + }; + + /** + * HDC STD PULL FILE + */ + public static ArrayList HDC_STD_PULL_FILE = new ArrayList<>() { + private static final long serialVersionUID = -7214023004212969508L; + { + add(pluginPath); + add("-t"); + add("%s"); + add("file"); + add("recv"); + add("%s"); + add("%s"); + } + }; +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcWrapper.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcWrapper.java index a2a99c873..33cd35418 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcWrapper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/transport/hdc/HdcWrapper.java @@ -1,272 +1,425 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.transport.hdc; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -/** - * Interact with commands on the device side - * - * @version 1.0 - * @date 2021/02/01 10:47 - **/ -public class HdcWrapper { - // Log - private static final Logger LOGGER = LogManager.getLogger(HdcWrapper.class); - - /** - * Singleton Hdc command parsing object - */ - private static volatile HdcWrapper hdcWrapper; - - /** - * Get an instance - * - * @return HdcWrapper - */ - public static HdcWrapper getInstance() { - if (hdcWrapper == null) { - synchronized (HdcWrapper.class) { - if (hdcWrapper == null) { - hdcWrapper = new HdcWrapper(); - } - } - } - return hdcWrapper; - } - - private HdcWrapper() { - } - - /** - * Get hdc string result - * - * @param hdcCmd hdc command - * @return String - */ - public String getHdcStringResult(String hdcCmd) { - String line = ""; - StringBuilder cmdStrResult = new StringBuilder(); - try { - // Excuting an order - Process process = Runtime.getRuntime().exec(hdcCmd); - // Error command result output stream - // Get command result output stream - try (InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - BufferedReader brInputStream = new BufferedReader( - new InputStreamReader(inputStream, Charset.forName("gbk"))); - BufferedReader brErrorStream = new BufferedReader(new InputStreamReader(errorStream))) { - while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { - cmdStrResult.append(line).append(System.getProperty("line.separator")); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return cmdStrResult.toString(); - } - - /** - * getHdcStringArrayResult - * - * @param hdcCmd hdc command - * @return String - */ - public String getHdcStringArrayResult(String[] hdcCmd) { - String line = ""; - StringBuilder cmdStrResult = new StringBuilder(); - try { - // 执行命令 - Process process = Runtime.getRuntime().exec(hdcCmd); - // 错误命令结果输出流 - // 获取命令结果输出流 - try (InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - BufferedReader brInputStream = new BufferedReader( - new InputStreamReader(inputStream, Charset.forName("gbk"))); - BufferedReader brErrorStream = new BufferedReader(new InputStreamReader(errorStream))) { - while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { - cmdStrResult.append(line).append(System.getProperty("line.separator")); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return cmdStrResult.toString(); - } - - /** - * execCmdBy - * - * @param hdcCmd hdc command - * @return String - */ - public String execCmdBy(String hdcCmd) { - // Excuting an order - Process process = null; - String line = ""; - StringBuilder cmdStrResult = new StringBuilder(); - try { - process = Runtime.getRuntime().exec(hdcCmd); - // Get command and error command result output stream - try (InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - BufferedReader brInputStream = new BufferedReader( - new InputStreamReader(inputStream, Charset.forName("gbk"))); - BufferedReader brErrorStream = new BufferedReader(new InputStreamReader(errorStream))) { - while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { - if ("StartDaemonSuccess".equals(line)) { - break; - } - } - LOGGER.info("cmd result ok{}", cmdStrResult); - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return cmdStrResult.toString(); - } - - /** - * execCmdBy - * - * @param hdcCmd hdc command - * @param timeout timeout - * @return String - */ - public String execCmdBy(String hdcCmd, long timeout) { - // Excuting an order - Process process = null; - String line = ""; - StringBuilder cmdStrResult = new StringBuilder(); - try { - process = Runtime.getRuntime().exec(hdcCmd); - process.waitFor(timeout, TimeUnit.MILLISECONDS); - // Get command and error command result output stream - try (InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - BufferedReader brInputStream = new BufferedReader( - new InputStreamReader(inputStream, Charset.forName("gbk"))); - BufferedReader brErrorStream = new BufferedReader(new InputStreamReader(errorStream))) { - LOGGER.info("cmd result ok {}", cmdStrResult); - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException | InterruptedException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return cmdStrResult.toString(); - } - - /** - * getCliResult - * - * @param hdcStr hdc String - * @return ArrayList> - */ - public ArrayList> getCliResult(String hdcStr) { - // Each line of string read - String temp = ""; - ArrayList> result = new ArrayList<>(); - try { - Process process = Runtime.getRuntime().exec(hdcStr); - // Obtain the input stream through the process object to obtain the successful execution of the command - // Get the error flow through the process object to get the command error situation - try (InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - BufferedReader brInput = new BufferedReader(new InputStreamReader(inputStream)); - BufferedReader brError = new BufferedReader(new InputStreamReader(errorStream))) { - while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { - temp = temp.trim(); - if (!"".equals(temp)) { - ArrayList list = new ArrayList<>(); - String[] newLine = temp.split(":"); - for (String str : newLine) { - String s = str.trim(); - if (!"".equals(s)) { - list.add(s); - } - } - result.add(list); - } - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return result; - } - - /** - * Get result list - * - * @param hdcStr hdc String - * @return ArrayList> - */ - public ArrayList> getListResult(String hdcStr) { - // Each line of string read - String temp = ""; - ArrayList> devices = new ArrayList<>(); - // Number of rows read to return value - int lines = 0; - try { - Process process = Runtime.getRuntime().exec(hdcStr); - try (InputStream inputStream = process.getInputStream(); - BufferedReader brInput = new BufferedReader(new InputStreamReader(inputStream)); - InputStream errorStream = process.getErrorStream(); - BufferedReader brError = new BufferedReader(new InputStreamReader(errorStream))) { - while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { - temp = temp.trim(); - if (lines > 0 && !"".equals(temp)) { - ArrayList list = new ArrayList<>(); - String[] newLine = temp.split(" "); - for (String str : newLine) { - String s = str.trim(); - if (!"".equals(s)) { - list.add(s); - } - } - devices.add(list); - } - lines++; - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - } catch (IOException ioException) { - LOGGER.error("ioException error: " + ioException.getMessage()); - } - return devices; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.hdc; + +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Interact with commands on the device side + */ +public class HdcWrapper { + // Log + private static final Logger LOGGER = LogManager.getLogger(HdcWrapper.class); + + /** + * Singleton Hdc command parsing object + */ + private static volatile HdcWrapper hdcWrapper; + + /** + * Get an instance + * + * @return HdcWrapper + */ + public static HdcWrapper getInstance() { + if (hdcWrapper == null) { + synchronized (HdcWrapper.class) { + if (hdcWrapper == null) { + hdcWrapper = new HdcWrapper(); + } + } + } + return hdcWrapper; + } + + private HdcWrapper() { + } + + /** + * Get hdc string result + * + * @param hdcCmd hdc command + * @return String + */ + public String getHdcStringResult(ArrayList hdcCmd) { + String line; + StringBuilder cmdStrResult = new StringBuilder(); + try { + Process process = new ProcessBuilder(hdcCmd).start(); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInputStream = null; + BufferedReader brErrorStream = null; + try { + inputStream = process.getInputStream(); + errorStream = process.getErrorStream(); + brInputStream = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("gbk"))); + brErrorStream = new BufferedReader(new InputStreamReader(errorStream)); + while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { + cmdStrResult.append(line).append(System.getProperty("line.separator")); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brErrorStream); + close(brInputStream); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return cmdStrResult.toString(); + } + + /** + * execCmdBy + * + * @param hdcCmd hdc command + * @return String + */ + public String execCmdBy(ArrayList hdcCmd) { + Process process; + String line; + StringBuilder cmdStrResult = new StringBuilder(); + try { + process = new ProcessBuilder(hdcCmd).start(); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInputStream = null; + BufferedReader brErrorStream = null; + try { + inputStream = process.getInputStream(); + errorStream = process.getErrorStream(); + brInputStream = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("gbk"))); + brErrorStream = new BufferedReader(new InputStreamReader(errorStream)); + while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { + LOGGER.info("cmd result line {}", line); + cmdStrResult.append(line); + if ("StartDaemonSuccess".equals(line)) { + break; + } + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brErrorStream); + close(brInputStream); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return cmdStrResult.toString(); + } + + /** + * execCmdBy + * + * @param hdcCmd hdc command + * @param timeout timeout + * @return String + */ + public String execCmdBy(ArrayList hdcCmd, long timeout) { + if (hdcCmd.isEmpty()) { + return ""; + } + Process process; + String line; + StringBuilder cmdStrResult = new StringBuilder(); + try { + process = new ProcessBuilder(hdcCmd).start(); + process.waitFor(timeout, TimeUnit.MILLISECONDS); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInputStream = null; + BufferedReader brErrorStream = null; + try { + inputStream = process.getInputStream(); + errorStream = process.getErrorStream(); + brInputStream = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("gbk"))); + brErrorStream = new BufferedReader(new InputStreamReader(errorStream)); + while ((line = brInputStream.readLine()) != null || (line = brErrorStream.readLine()) != null) { + LOGGER.info("cmd result line {}", line); + cmdStrResult.append(line); + // shell return success flag + if ("StartDaemonSuccess".equals(line)) { + break; + } + } + LOGGER.info("cmd result ok {}", cmdStrResult); + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brErrorStream); + close(brInputStream); + } + } catch (IOException | InterruptedException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return cmdStrResult.toString(); + } + + /** + * getCliResult + * + * @param hdcStr hdc String + * @return ArrayList> + */ + public ArrayList> getCliResult(ArrayList hdcStr) { + // Each line of string read + String temp; + ArrayList> result = new ArrayList<>(); + try { + Process process = new ProcessBuilder(hdcStr).start(); + // Obtain the input stream through the process object to obtain the successful execution of the command + // Get the error flow through the process object to get the command error situation + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInput = null; + BufferedReader brError = null; + try { + inputStream = process.getInputStream(); + errorStream = process.getErrorStream(); + brInput = new BufferedReader(new InputStreamReader(inputStream)); + brError = new BufferedReader(new InputStreamReader(errorStream)); + while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { + temp = temp.trim(); + if (!"".equals(temp)) { + ArrayList list = new ArrayList<>(); + String[] newLine = temp.split(":"); + for (String str : newLine) { + String s = str.trim(); + if (!"".equals(s)) { + list.add(s); + } + } + result.add(list); + } + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brError); + close(brInput); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return result; + } + + /** + * Get result list + * + * @param hdcStr hdc String + * @return Map + */ + public Map getCmdResultMap(ArrayList hdcStr) { + Map resultMap = new HashMap<>(); + try { + Process process = new ProcessBuilder(hdcStr).start(); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInput = null; + BufferedReader brError = null; + try { + inputStream = process.getInputStream(); + brInput = new BufferedReader(new InputStreamReader(inputStream)); + errorStream = process.getErrorStream(); + brError = new BufferedReader(new InputStreamReader(errorStream)); + String temp; + while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { + String[] strings = temp.trim().split(" "); + resultMap.put(strings[1], strings[0]); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brError); + close(brInput); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return resultMap; + } + + /** + * Get result list + * + * @param hdcStr hdc String + * @return ArrayList> + */ + public ArrayList> getListResult(ArrayList hdcStr) { + // Each line of string read + String temp; + ArrayList> devices = new ArrayList<>(); + // Number of rows read to return value + int lines = 0; + try { + Process process = new ProcessBuilder(hdcStr).start(); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInput = null; + BufferedReader brError = null; + try { + inputStream = process.getInputStream(); + brInput = new BufferedReader(new InputStreamReader(inputStream)); + errorStream = process.getErrorStream(); + brError = new BufferedReader(new InputStreamReader(errorStream)); + while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { + temp = temp.trim(); + if (lines > 0 && !"".equals(temp)) { + ArrayList list = new ArrayList<>(); + String[] newLine = temp.split(" "); + for (String str : newLine) { + String s = str.trim(); + if (!"".equals(s)) { + list.add(s); + } + } + devices.add(list); + } + lines++; + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brError); + close(brInput); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return devices; + } + + /** + * Get result list + * + * @param hdcStr hdc String + * @return ArrayList> + */ + public ArrayList> getListHdcStdResult(ArrayList hdcStr) { + // Each line of string read + String temp; + ArrayList> devices = new ArrayList<>(); + // Number of rows read to return value + try { + Process process = new ProcessBuilder(hdcStr).start(); + InputStream inputStream = null; + InputStream errorStream = null; + BufferedReader brInput = null; + BufferedReader brError = null; + try { + inputStream = process.getInputStream(); + brInput = new BufferedReader(new InputStreamReader(inputStream)); + errorStream = process.getErrorStream(); + brError = new BufferedReader(new InputStreamReader(errorStream)); + while ((temp = brInput.readLine()) != null || (temp = brError.readLine()) != null) { + temp = temp.trim(); + if (!"".equals(temp)) { + ArrayList list = new ArrayList<>(); + String[] newLine = temp.split("\t"); + for (String str : newLine) { + String s = str.trim(); + if (!"".equals(s)) { + list.add(s); + } + } + devices.add(list); + } + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } finally { + close(inputStream); + close(errorStream); + close(brError); + close(brInput); + } + } catch (IOException ioException) { + LOGGER.error("ioException error: " + ioException); + } + return devices; + } + + /** + * conversionCommand + * + * @param list list + * @param args args + * @return ArrayList + */ + public static ArrayList conversionCommand(ArrayList list, String... args) { + int index = 0; + ArrayList cmdlist = new ArrayList<>(); + for (String string : list) { + if (StringUtils.equals(string, "%s")) { + cmdlist.add(args[index]); + index = index + 1; + continue; + } + + if (string.contains("%s") && !StringUtils.equals(string, "%s")) { + if (args.length <= index) { + cmdlist.add(string); + continue; + } else { + String replace = string.replace("%s", args[index]); + cmdlist.add(replace); + } + index = index + 1; + continue; + } + cmdlist.add(string); + } + return cmdlist; + } + + private void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException exception) { + LOGGER.error("IOException ", exception); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/Constant.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/Constant.java index 7ee89c027..a54f92a4c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/Constant.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/Constant.java @@ -1,210 +1,124 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.common; - -/** - * @Description constant - * @Date 2021/3/4 15:58 - **/ -public class Constant { - /** - * Destination path - */ - public static final String DEST_PATH = "/data/local/tmp"; - - /** - * Devtools plug-in (V8) path - */ - public static final String DEVTOOLS_PLUGINS_V8_PATH = "devtools.tar"; - - /** - * Devtools plug-in (V7) path - */ - public static final String DEVTOOLS_PLUGINS_V7_PATH = "devtools.tar"; - - /** - * Unzip shell plug-in path - */ - public static final String UNZIP_SHELL_PLUGINS_PATH = "ohosprofiler"; - - /** - * File name - */ - public static final String FILE_NAME = "hiprofilerd"; - - /** - * Plug-in name - */ - public static final String HIPRO_FILER_NAME = "hiprofiler_cmd"; - - /** - * Plug-in name - */ - public static final String PLUGINS_NAME = "hiprofiler_plugins"; - - /** - * HIPRO filer command name - */ - public static final String HIPRO_FILER_CMDNAME = "hiprofiler_cmd -q"; - - /** - * HIPRO filer result: OK - */ - public static final String HIPRO_FILER_RESULT_OK = "OK"; - - /** - * Installation result: success - */ - public static final String INSTALL_SUCCESS = "Success"; - - /** - * Device state: online - */ - public static final String DEVICE_STAT_ONLINE = "device"; - - /** - * Device SATA state: pushed - */ - public static final String DEVICE_SATA_STAT_PUSHED = "pushed"; - - /** - * Device state: error - */ - public static final String DEVICE_STAT_ERROR = "error"; - - /** - * Device state: closed - */ - public static final String DEVICE_STAT_CLOSED = "closed"; - - /** - * Device state: not found - */ - public static final String DEVICE_STAT_NOT_FOUND = "not found"; - - /** - * Device state: FAIL - */ - public static final String DEVICE_STAT_FAIL = "FAIL"; - - /** - * Device state: offline - */ - public static final String DEVICE_STAT_OFFLINE = "offline"; - - /** - * Device state: unauthorized - */ - public static final String DEVICE_STST_UNAUTHORIZED = "unauthorized"; - - /** - * Device full type - */ - public static final String DEVICE_FULL_TYPE = "arm64-v8a"; - - /** - * Device lean type - */ - public static final String DEVICE_LEAN_TYPE = "arm64-v7a"; - - /** - * Memory plug-in file name source file path of plug-in push - */ - public static final String SOURCE_FILEPATH = "src/main/resources/plugins/"; - - /** - * Cpu plug-in file name - */ - public static final String CPU_PLUG_NAME = "Cpu"; - - /** - * Gpu plug-in file name - */ - public static final String GPU_PLUG_NAME = "Gpu"; - - /** - * Process plug in file name - */ - public static final String PROCESS_PLUG_NAME = "Process"; - - /** - * Target file path of plug-in push - */ - public static final String TARGET_PLUG_PATH = "/data/local/tmp/"; - - /** - * File suffix pushed by plug-in - */ - public static final String FILE_SUFFIX = ".so"; - - /** - * default sampling interval - */ - public static final int SAMPLE_INTERVAL_DEFAULT = 1000; - - /** - * Radix for conversion from BigInteger to string - */ - public static final int RADIX = 16; - - /** - * End side return to normal flag - */ - public static final int NORMAL_STATUS = 0; - - /** - * File importing scene (1: real-time) - */ - public static final int REALTIME_SCENE = 1; - - /** - * File importing scene (2: real-time) - */ - public static final int FILE_IMPORT_SCENE = 2; - - /** - * size - */ - public static final int MB = 1024; - - /** - * Abnormal state - */ - public static final Long ABNORMAL = -1L; - - /** - * Memomy plug-in - */ - public static final String MEMORY_PLUG = "memory-plugin"; - - /** - * JVMTI agent plug-in - */ - public static final String JVMTI_AGENT_PLUG = "jvmtiagent"; - - /** - * memory plug - */ - public static final String MEMORY_PLUGS_NAME = "/data/local/tmp/libmemdataplugin.z.so"; - - /** - * memory plug name - */ - public static final String MEMORY_PLUGS = "libmemdataplugin"; - - private Constant() { - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common; + +/** + * constant + */ +public class Constant { + /** + * Devtools plug-in (V8) path + */ + public static final String DEVTOOLS_PLUGINS_V8_PATH = "developtools"; + + /** + * Devtools plug-in (V7) path + */ + public static final String DEVTOOLS_PLUGINS_V7_PATH = "developtool.tar"; + + /** + * Unzip shell plug-in path + */ + public static final String UNZIP_SHELL_PLUGINS_PATH = "ohosprofiler"; + + /** + * File name + */ + public static final String FILE_NAME = "hiprofilerd"; + + /** + * HIPRO filer result: OK + */ + public static final String PLUGIN_RESULT_OK = "OK"; + + /** + * need to update Version + */ + public static final String UPDATE_PLUGIN = "UPDATE PLUGIN"; + + /** + * Device state: not found + */ + public static final String PLUGIN_NOT_FOUND = "not found"; + + /** + * Device SATA state: pushed + */ + public static final String DEVICE_SATA_STAT_PUSHED = "pushed"; + + /** + * Device state: FAIL + */ + public static final String DEVICE_STAT_FAIL = "FAIL"; + + /** + * Device state: offline + */ + public static final String DEVICE_STAT_OFFLINE = "offline"; + + /** + * Radix for conversion from BigInteger to string + */ + public static final int RADIX = 16; + + /** + * size + */ + public static final int MB = 1024; + + /** + * Abnormal state + */ + public static final Long ABNORMAL = -1L; + + /** + * Memomy plug-in + */ + public static final String MEMORY_PLUG = "memory-plugin"; + + /** + * JVMTI agent plug-in + */ + public static final String JVMTI_AGENT_PLUG = "jvmtiagent"; + + /** + * memory plug + */ + public static final String MEMORY_PLUGS_NAME = "/data/local/tmp/libmemdataplugin.z.so"; + + /** + * memory plug name + */ + public static final String MEMORY_PLUGS = "libmemdataplugin"; + + /** + * cpu plug + */ + public static final String CPU_PLUGS_NAME = "/data/local/tmp/libcpudataplugin.z.so"; + + /** + * Cpu plug-in + */ + public static final String CPU_PLUG = "cpu-plugin"; + + /** + * cpu plug + */ + public static final String ENERGY_PLUGS_NAME = "/data/local/tmp/libcpudataplugin.z.so"; + + private Constant() { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/GrpcException.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/GrpcException.java index 783a67d8d..2aece963b 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/GrpcException.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/GrpcException.java @@ -1,60 +1,57 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.common; - -/** - * grpc Custom exception class - * - * @version 1.0 - * @date 2021/03/15 19:41 - **/ -public class GrpcException extends Exception { - /** - * GrpcException - */ - public GrpcException() { - super(); - } - - /** - * GrpcException - * - * @param message Grpc message - */ - public GrpcException(String message) { - super(message); - } - - /** - * GrpcException - * - * @param message Grpc message - * @param cause Throwable cause - */ - public GrpcException(String message, Throwable cause) { - super(message, cause); - } - - /** - * GrpcException - * - * @param cause Throwable cause - */ - public GrpcException(Throwable cause) { - super(cause); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common; + +/** + * grpc Custom exception class + */ +public class GrpcException extends Exception { + /** + * GrpcException + */ + public GrpcException() { + super(); + } + + /** + * GrpcException + * + * @param message Grpc message + */ + public GrpcException(String message) { + super(message); + } + + /** + * GrpcException + * + * @param message Grpc message + * @param cause Throwable cause + */ + public GrpcException(String message, Throwable cause) { + super(message, cause); + } + + /** + * GrpcException + * + * @param cause Throwable cause + */ + public GrpcException(Throwable cause) { + super(cause); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/BeanUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/BeanUtil.java index edf40beda..a4e2560cb 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/BeanUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/BeanUtil.java @@ -1,294 +1,331 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.google.protobuf.CodedOutputStream; - -import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass; -import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass; -import ohos.devtools.views.common.LayoutConstants; - -/** - * Bean object utilities class. - * - * @version 1.0 - * @date 2021/02/03 14:59 - **/ -public class BeanUtil { - private static final Logger LOGGER = LogManager.getLogger(BeanUtil.class); - - /** - * Serializes object data. - * - * @param - * @param data Indicates the data to be deserialized. - * @return byte[] - */ - public static byte[] serialize(T data) { - byte[] dataArray = null; - // 1. Create an OutputStream object. - // 2. Create an OutputStream wrapper object named ObjectOutputStream, - // with the object wwritten to the OutputStream. - try (ByteArrayOutputStream outPutStream = new ByteArrayOutputStream(); - ObjectOutputStream objectOutputStream = new ObjectOutputStream(outPutStream)) { - // 3. Write the object to OutputStream. - objectOutputStream.writeObject(data); - // 4. Convert OutputStream to a byte array. - dataArray = outPutStream.toByteArray(); - } catch (IOException exception) { - LOGGER.error("exception error {}", exception.getMessage()); - } - return dataArray; - } - - /** - * Serialize data by code output stream. - * - * @param config Indicates the configuration data. - * @return Returns a byte array. - */ - public static byte[] serializeByCodedOutPutStream(TracePluginConfigOuterClass.TracePluginConfig config) { - byte[] dataArray = null; - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); - config.writeTo(codedOutputStream); - codedOutputStream.flush(); - dataArray = outputStream.toByteArray(); - } catch (IOException exception) { - LOGGER.error("exception error {}", exception.getMessage()); - } - return dataArray; - } - - /** - * Serialize by code output stream. - * - * @param config Indicates the configuration data. - * @return Returns a byte array. - */ - public static byte[] serializeByCodedOutPutStream(BytracePluginConfigOuterClass.BytracePluginConfig config) { - byte[] dataArray = null; - com.google.protobuf.CodedOutputStream codedOutputStream = null; - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - codedOutputStream = CodedOutputStream.newInstance(outputStream, config.getSerializedSize()); - config.writeTo(codedOutputStream); - codedOutputStream.flush(); - dataArray = outputStream.toByteArray(); - } catch (IOException exception) { - LOGGER.error("exception error {}", exception.getMessage()); - } - return dataArray; - } - - /** - * Deserializes object data. - * - * @param data Indicates the data to be deserialized. - * @return Object Returns the object value. - */ - public static Object deserialize(byte[] data) { - Object object = null; - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(data); - ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) { - object = objectInputStream.readObject(); - } catch (IOException | ClassNotFoundException exception) { - LOGGER.error("exception error {}", exception.getMessage()); - } - return object; - } - - /** - * Get Fields information. - * - * @param - * @param obj Indicates the object. - * @return List Map - */ - public static List getFieldsInfo(T obj) { - Field[] fields = obj.getClass().getDeclaredFields(); - List list = new ArrayList(); - Map infoMap = null; - for (int index = 0; index < fields.length; index++) { - infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); - infoMap.put("type", fields[index].getType().toString()); - Optional fieldName = getFieldValueByName(fields[index].getName(), obj); - if (fieldName.isPresent()) { - infoMap.put(fields[index].getName(), fieldName.get()); - } - list.add(infoMap); - } - return list; - } - - /** - * Returns a list of filed values. - * - * @param - * @param obj Indicates the object. - * @return List Map - */ - public static List> getFields(T obj) { - Field[] fields = obj.getClass().getDeclaredFields(); - List list = new ArrayList(); - Map infoMap = null; - for (int index = 0; index < fields.length; index++) { - infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); - infoMap.put("type", fields[index].getType().toString()); - infoMap.put("name", fields[index].getName()); - Optional fieldName = getFieldValueByName(fields[index].getName(), obj); - if (fieldName.isPresent()) { - infoMap.put("value", fieldName.get()); - } - list.add(infoMap); - } - return list; - } - - /** - * Gets Fields information. - * - * @param obj Indicates the object. - * @param - * @return Returns a list of fields. - */ - public static Map getFiledsInfos(T obj) { - Field[] fields = obj.getClass().getDeclaredFields(); - Map infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); - for (int index = 0; index < fields.length; index++) { - Optional fieldName = getFieldValueByName(fields[index].getName(), obj); - if (fieldName.isPresent()) { - infoMap.put(fields[index].getName(), fieldName.get()); - } - } - return infoMap; - } - - /** - * Gets attribute values by attribute name. - * - * @param obj Indicates the object. - * @param - * @return Returns a list of attribute names. - */ - public static List getObjectAttributeNames(T obj) { - Field[] fields = obj.getClass().getDeclaredFields(); - List list = new ArrayList(); - for (int index = 0; index < fields.length; index++) { - list.add(fields[index].getName()); - } - return list; - } - - /** - * Get the attribute value by attribute name. - * - * @param - * @param fieldName fieldName - * @param object Indicates the object. - * @return Object Returns the object value. - */ - private static Optional getFieldValueByName(String fieldName, T object) { - String firstLetter = fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH); - String getter = "get" + firstLetter + fieldName.substring(1); - if ("getSerialVersionUID".equals(getter)) { - return Optional.empty(); - } - Method method = null; - Object value = null; - try { - method = object.getClass().getMethod(getter, new Class[] {}); - value = method.invoke(object, new Object[] {}); - } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException exception) { - LOGGER.error(exception.getMessage()); - } - - return Optional.of(value); - } - - /** - * Gets the value of a given object. - * - * @param object object - * @param - * @return List - */ - public static List getObjectValue(T object) { - if (object != null && object instanceof Serializable) { - Class objectClass = object.getClass(); - Field[] declaredFields = objectClass.getDeclaredFields(); - ArrayList list = new ArrayList<>(); - for (Field field : declaredFields) { - Type type = field.getGenericType(); - String colName = field.getName(); - if ("class java.lang.String".equals(type.toString())) { - list.add(colName + " varchar(100)"); - } - if ("class java.lang.Integer".equals(type.toString()) || "int".equals(type.toString())) { - list.add(colName + " int"); - } - if ("class java.lang.Long".equals(type.toString()) || "long".equals(type.toString())) { - list.add(colName + " long"); - } - if ("class java.lang.Double".equals(type.toString()) || "double".equals(type.toString())) { - list.add(colName + " double"); - } - if ("class java.lang.Boolean".equals(type.toString()) || "boolean".equals(type.toString())) { - list.add(colName + " boolean"); - } - if ("class java.util.Date".equals(type.toString())) { - list.add(colName + " date"); - } - } - return list; - } - return new ArrayList<>(); - } - - /** - * Get the object name. - * - * @param object Indicates the object. - * @param - * @return String - */ - public static String getObjectName(T object) { - if (object != null) { - return object.getClass().getSimpleName(); - } - return ""; - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +import ohos.devtools.datasources.transport.grpc.service.HiperfCallPluginConfigOuterClass; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.protobuf.CodedOutputStream; + +import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass; +import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass; +import ohos.devtools.views.common.LayoutConstants; + +/** + * Bean object utilities class. + */ +public class BeanUtil { + private static final Logger LOGGER = LogManager.getLogger(BeanUtil.class); + + /** + * Serializes object data. + * + * @param + * @param data Indicates the data to be deserialized. + * @return byte[] + */ + public static byte[] serialize(T data) { + byte[] dataArray = null; + // 1. Create an OutputStream object. + // 2. Create an OutputStream wrapper object named ObjectOutputStream, + // with the object wwritten to the OutputStream. + try (ByteArrayOutputStream outPutStream = new ByteArrayOutputStream(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(outPutStream)) { + // 3. Write the object to OutputStream. + objectOutputStream.writeObject(data); + // 4. Convert OutputStream to a byte array. + dataArray = outPutStream.toByteArray(); + } catch (IOException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return dataArray; + } + + /** + * Serialize data by code output stream. + * + * @param config Indicates the configuration data. + * @return Returns a byte array. + */ + public static byte[] serializeByCodedOutPutStream(TracePluginConfigOuterClass.TracePluginConfig config) { + byte[] dataArray = null; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); + config.writeTo(codedOutputStream); + codedOutputStream.flush(); + dataArray = outputStream.toByteArray(); + } catch (IOException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return dataArray; + } + + /** + * Serialize data by code output stream. + * + * @param config Indicates the configuration data. + * @return Returns a byte array. + */ + public static byte[] serializeByCodedOutPutStream(HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig config) { + byte[] dataArray = null; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); + config.writeTo(codedOutputStream); + codedOutputStream.flush(); + dataArray = outputStream.toByteArray(); + } catch (IOException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return dataArray; + } + + /** + * Serialize data by code output stream. + * + * @param config Indicates the configuration data. + * @return Returns a byte array. + */ + public static byte[] serializeByCodedOutPutStream(MemoryPluginConfig.MemoryConfig config) { + byte[] dataArray = null; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); + config.writeTo(codedOutputStream); + codedOutputStream.flush(); + dataArray = outputStream.toByteArray(); + } catch (IOException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return dataArray; + } + + /** + * Serialize by code output stream. + * + * @param config Indicates the configuration data. + * @return Returns a byte array. + */ + public static byte[] serializeByCodedOutPutStream(BytracePluginConfigOuterClass.BytracePluginConfig config) { + byte[] dataArray = null; + com.google.protobuf.CodedOutputStream codedOutputStream = null; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + codedOutputStream = CodedOutputStream.newInstance(outputStream, config.getSerializedSize()); + config.writeTo(codedOutputStream); + codedOutputStream.flush(); + dataArray = outputStream.toByteArray(); + } catch (IOException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return dataArray; + } + + /** + * Deserializes object data. + * + * @param data Indicates the data to be deserialized. + * @return Object Returns the object value. + */ + public static Object deserialize(byte[] data) { + Object object = null; + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(data); + ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) { + object = objectInputStream.readObject(); + } catch (IOException | ClassNotFoundException exception) { + LOGGER.error("exception error {}", exception.getMessage()); + } + return object; + } + + /** + * Get Fields information. + * + * @param + * @param obj Indicates the object. + * @return List Map + */ + public static List getFieldsInfo(T obj) { + Field[] fields = obj.getClass().getDeclaredFields(); + List list = new ArrayList(); + Map infoMap = null; + for (int index = 0; index < fields.length; index++) { + infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); + infoMap.put("type", fields[index].getType().toString()); + Optional fieldName = getFieldValueByName(fields[index].getName(), obj); + if (fieldName.isPresent()) { + infoMap.put(fields[index].getName(), fieldName.get()); + } + list.add(infoMap); + } + return list; + } + + /** + * Returns a list of filed values. + * + * @param + * @param obj Indicates the object. + * @return List Map + */ + public static List> getFields(T obj) { + Field[] fields = obj.getClass().getDeclaredFields(); + List list = new ArrayList(); + Map infoMap = null; + for (int index = 0; index < fields.length; index++) { + infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); + infoMap.put("type", fields[index].getType().toString()); + infoMap.put("name", fields[index].getName()); + Optional fieldName = getFieldValueByName(fields[index].getName(), obj); + if (fieldName.isPresent()) { + infoMap.put("value", fieldName.get()); + } + list.add(infoMap); + } + return list; + } + + /** + * Gets Fields information. + * + * @param obj Indicates the object. + * @param + * @return Returns a list of fields. + */ + public static Map getFiledsInfos(T obj) { + Field[] fields = obj.getClass().getDeclaredFields(); + Map infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN)); + for (int index = 0; index < fields.length; index++) { + Optional fieldName = getFieldValueByName(fields[index].getName(), obj); + if (fieldName.isPresent()) { + infoMap.put(fields[index].getName(), fieldName.get()); + } + } + return infoMap; + } + + /** + * Gets attribute values by attribute name. + * + * @param obj Indicates the object. + * @param + * @return Returns a list of attribute names. + */ + public static List getObjectAttributeNames(T obj) { + Field[] fields = obj.getClass().getDeclaredFields(); + List list = new ArrayList(); + for (int index = 0; index < fields.length; index++) { + list.add(fields[index].getName()); + } + return list; + } + + /** + * Get the attribute value by attribute name. + * + * @param + * @param fieldName fieldName + * @param object Indicates the object. + * @return Object Returns the object value. + */ + private static Optional getFieldValueByName(String fieldName, T object) { + String firstLetter = fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH); + String getter = "get" + firstLetter + fieldName.substring(1); + if ("getSerialVersionUID".equals(getter)) { + return Optional.empty(); + } + Method method = null; + Object value = null; + try { + method = object.getClass().getMethod(getter, new Class[] {}); + value = method.invoke(object, new Object[] {}); + } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException exception) { + LOGGER.error(exception.getMessage()); + } + + return Optional.of(value); + } + + /** + * Gets the value of a given object. + * + * @param object object + * @param + * @return List + */ + public static List getObjectValue(T object) { + if (object != null && object instanceof Serializable) { + Class objectClass = object.getClass(); + Field[] declaredFields = objectClass.getDeclaredFields(); + ArrayList list = new ArrayList<>(); + for (Field field : declaredFields) { + Type type = field.getGenericType(); + String colName = field.getName(); + if ("class java.lang.String".equals(type.toString())) { + list.add(colName + " varchar(100)"); + } + if ("class java.lang.Integer".equals(type.toString()) || "int".equals(type.toString())) { + list.add(colName + " int"); + } + if ("class java.lang.Long".equals(type.toString()) || "long".equals(type.toString())) { + list.add(colName + " long"); + } + if ("class java.lang.Double".equals(type.toString()) || "double".equals(type.toString())) { + list.add(colName + " double"); + } + if ("class java.lang.Boolean".equals(type.toString()) || "boolean".equals(type.toString())) { + list.add(colName + " boolean"); + } + if ("class java.util.Date".equals(type.toString())) { + list.add(colName + " date"); + } + } + return list; + } + return new ArrayList<>(); + } + + /** + * Get the object name. + * + * @param object Indicates the object. + * @param + * @return String + */ + public static String getObjectName(T object) { + if (object != null) { + return object.getClass().getSimpleName(); + } + return ""; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CharsetUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CharsetUtil.java index 07d4081a5..ccbcd066b 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CharsetUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CharsetUtil.java @@ -1,162 +1,161 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.charset.UnsupportedCharsetException; - -import static org.apache.commons.lang3.StringUtils.isBlank; - -/** - * @Description String utilities class - * @Date 2021/2/7 15:01 - **/ -public class CharsetUtil { - private static final Logger LOGGER = LogManager.getLogger(CharsetUtil.class); - - private CharsetUtil() { - } - - /** - * GBK - */ - public static final String GBK = "GBK"; - - /** - * UTF-8 - */ - public static final String UTF_8 = "UTF-8"; - - /** - * ISO-8859-1 - */ - public static final String ISO_8859_1 = "ISO-8859-1"; - - /** - * ISO-8859-1 - */ - public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1; - - /** - * UTF-8 - */ - public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8; - - /** - * GBK - */ - public static final Charset CHARSET_GBK; - - static { - Charset gbkCharset = null; - try { - gbkCharset = Charset.forName(GBK); - } catch (UnsupportedCharsetException throwAbles) { - LOGGER.info("Get GBKCharset Error {}", throwAbles.getMessage()); - } - CHARSET_GBK = gbkCharset; - } - - /** - * Parses a Charset object. - * - * @param charsetName Charset to be parsed. The default Charset will be returned if it is left empty. - * @return Parsed Charset if parsing is successful; default Charset if parsing fails. - */ - public static Charset parse(String charsetName) { - return parse(charsetName, Charset.defaultCharset()); - } - - /** - * Parses a Charset object. - * - * @param charsetName Indicates the Charset to be used if the parsing fails. - * @param defaultCharset 解析失败使用的默认编码 - * @return Returns the parsed Charset if the parsing is successful; returns the default Charset otherwise. - */ - public static Charset parse(String charsetName, Charset defaultCharset) { - if (isBlank(charsetName)) { - return defaultCharset; - } - - Charset result; - try { - result = Charset.forName(charsetName); - } catch (UnsupportedCharsetException exception) { - result = defaultCharset; - } - - return result; - } - - /** - * Convert Charset of a given string. - * - * @param source Sting to be converted. - * @param srcCharset Source Charset, which is GBK by default. - * @param destCharset Target Charset, which is UTF-8 by default. - * @return New Charset after the conversion. - */ - public static String convert(String source, String srcCharset, String destCharset) { - return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); - } - - /** - * Convert Charset of a given string. - * - * @param source Sting to be converted. - * @param srcCharset Source Charset, which is GBK by default. - * @param destCharset Target Charset, which is UTF-8 by default. - * @return New Charset after the conversion. - */ - public static String convert(String source, Charset srcCharset, Charset destCharset) { - Charset srcSet = srcCharset; - if (srcSet == null) { - srcSet = CHARSET_GBK; - } - Charset desSet = destCharset; - if (desSet == null) { - desSet = StandardCharsets.UTF_8; - } - - if (isBlank(source) || srcSet.equals(desSet)) { - return source; - } - return new String(source.getBytes(srcSet), desSet); - } - - /** - * Default Charset name - * - * @return String - */ - public static String defaultCharsetName() { - return defaultCharset().name(); - } - - /** - * Default Charset - * - * @return Charset - */ - public static Charset defaultCharset() { - return Charset.defaultCharset(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.charset.UnsupportedCharsetException; + +import static org.apache.commons.lang3.StringUtils.isBlank; + +/** + * @Description String utilities class + */ +public class CharsetUtil { + private static final Logger LOGGER = LogManager.getLogger(CharsetUtil.class); + + private CharsetUtil() { + } + + /** + * GBK + */ + public static final String GBK = "GBK"; + + /** + * UTF-8 + */ + public static final String UTF_8 = "UTF-8"; + + /** + * ISO-8859-1 + */ + public static final String ISO_8859_1 = "ISO-8859-1"; + + /** + * ISO-8859-1 + */ + public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1; + + /** + * UTF-8 + */ + public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8; + + /** + * GBK + */ + public static final Charset CHARSET_GBK; + + static { + Charset gbkCharset = null; + try { + gbkCharset = Charset.forName(GBK); + } catch (UnsupportedCharsetException throwAbles) { + LOGGER.info("Get GBKCharset Error {}", throwAbles.getMessage()); + } + CHARSET_GBK = gbkCharset; + } + + /** + * Parses a Charset object. + * + * @param charsetName Charset to be parsed. The default Charset will be returned if it is left empty. + * @return Parsed Charset if parsing is successful; default Charset if parsing fails. + */ + public static Charset parse(String charsetName) { + return parse(charsetName, Charset.defaultCharset()); + } + + /** + * Parses a Charset object. + * + * @param charsetName Indicates the Charset to be used if the parsing fails. + * @param defaultCharset 解析失败使用的默认编码 + * @return Returns the parsed Charset if the parsing is successful; returns the default Charset otherwise. + */ + public static Charset parse(String charsetName, Charset defaultCharset) { + if (isBlank(charsetName)) { + return defaultCharset; + } + + Charset result; + try { + result = Charset.forName(charsetName); + } catch (UnsupportedCharsetException exception) { + result = defaultCharset; + } + + return result; + } + + /** + * Convert Charset of a given string. + * + * @param source Sting to be converted. + * @param srcCharset Source Charset, which is GBK by default. + * @param destCharset Target Charset, which is UTF-8 by default. + * @return New Charset after the conversion. + */ + public static String convert(String source, String srcCharset, String destCharset) { + return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); + } + + /** + * Convert Charset of a given string. + * + * @param source Sting to be converted. + * @param srcCharset Source Charset, which is GBK by default. + * @param destCharset Target Charset, which is UTF-8 by default. + * @return New Charset after the conversion. + */ + public static String convert(String source, Charset srcCharset, Charset destCharset) { + Charset srcSet = srcCharset; + if (srcSet == null) { + srcSet = CHARSET_GBK; + } + Charset desSet = destCharset; + if (desSet == null) { + desSet = StandardCharsets.UTF_8; + } + + if (isBlank(source) || srcSet.equals(desSet)) { + return source; + } + return new String(source.getBytes(srcSet), desSet); + } + + /** + * Default Charset name + * + * @return String + */ + public static String defaultCharsetName() { + return defaultCharset().name(); + } + + /** + * Default Charset + * + * @return Charset + */ + public static Charset defaultCharset() { + return Charset.defaultCharset(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CloseResourceUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CloseResourceUtil.java index 5a84edea1..8aa76dbea 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CloseResourceUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CloseResourceUtil.java @@ -1,65 +1,62 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; - -/** - * Close Resource Util - * - * @version 1.0 - * @date 2021/04/26 17:21 - **/ -public class CloseResourceUtil { - /** - * Close Resource - * - * @param logger Logger - * @param conn Connection - * @param ps PreparedStatement - * @param statement Statement - */ - public static void closeResource(Logger logger, Connection conn, PreparedStatement ps, Statement statement) { - if (ps != null) { - try { - ps.close(); - } catch (SQLException exception) { - logger.error("SQLException error: " + exception.getMessage()); - } - } - - if (conn != null) { - try { - conn.close(); - } catch (SQLException exception) { - logger.error("SQLException error: " + exception.getMessage()); - } - } - - if (statement != null) { - try { - statement.close(); - } catch (SQLException exception) { - logger.error("SQLException error: " + exception.getMessage()); - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * Close Resource Util + */ +public class CloseResourceUtil { + /** + * Close Resource + * + * @param logger Logger + * @param conn Connection + * @param ps PreparedStatement + * @param statement Statement + */ + public static void closeResource(Logger logger, Connection conn, PreparedStatement ps, Statement statement) { + if (ps != null) { + try { + ps.close(); + } catch (SQLException exception) { + logger.error("SQLException error: " + exception.getMessage()); + } + } + + if (conn != null) { + try { + conn.close(); + } catch (SQLException exception) { + logger.error("SQLException error: " + exception.getMessage()); + } + } + + if (statement != null) { + try { + statement.close(); + } catch (SQLException exception) { + logger.error("SQLException error: " + exception.getMessage()); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CommonUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CommonUtil.java index 829c27410..f2792a54b 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CommonUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/CommonUtil.java @@ -1,73 +1,70 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import ohos.devtools.views.common.LayoutConstants; - -/** - * 用于单个功能工具方法的提取保存。 - * - * @version 1.0 - * @date 2021/1/23 11:13 - **/ -public class CommonUtil { - private CommonUtil() { - } - - private static volatile Integer requestId = 1; - - /** - * Sets the intial collection size. - * - * @param size size - * @return Returns the initial collection size. - */ - public static int collectionSize(int size) { - return (size <= 0) ? LayoutConstants.SIXTEEN : (int) (size / LayoutConstants.LOAD_FACTOR + 1.0F); - } - - /** - * Gets the request ID. - * - * @return Returns the initial collection size. - */ - public static int getRequestId() { - if (requestId == Integer.MAX_VALUE) { - requestId = 1; - } - return requestId++; - } - - /** - * Generates a session name. - * - * @param deviceName Indicates the device name. - * @param pid Indicates the process ID. - * @return String - */ - public static String generateSessionName(String deviceName, int pid) { - return deviceName + pid; - } - - /** - * Gets the ID of a local session. - * - * @return Long - */ - public static Long getLocalSessionId() { - return System.currentTimeMillis(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import ohos.devtools.views.common.LayoutConstants; + +/** + * 用于单个功能工具方法的提取保存。 + */ +public class CommonUtil { + private CommonUtil() { + } + + private static volatile Integer requestId = 1; + + /** + * Sets the intial collection size. + * + * @param size size + * @return Returns the initial collection size. + */ + public static int collectionSize(int size) { + return (size <= 0) ? LayoutConstants.SIXTEEN : (int) (size / LayoutConstants.LOAD_FACTOR + 1.0F); + } + + /** + * Gets the request ID. + * + * @return Returns the initial collection size. + */ + public static int getRequestId() { + if (requestId == Integer.MAX_VALUE) { + requestId = 1; + } + return requestId++; + } + + /** + * Generates a session name. + * + * @param deviceName Indicates the device name. + * @param pid Indicates the process ID. + * @return String + */ + public static String generateSessionName(String deviceName, int pid) { + return deviceName + pid; + } + + /** + * Gets the ID of a local session. + * + * @return Long + */ + public static Long getLocalSessionId() { + return System.currentTimeMillis(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/DateTimeUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/DateTimeUtil.java index f3d88119a..2855a6339 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/DateTimeUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/DateTimeUtil.java @@ -1,148 +1,147 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; - -/** - * @Description Date and time utilities - * @Date 2021/2/7 15:00 - **/ -public final class DateTimeUtil { - private DateTimeUtil() { - } - - /** - * Format: yyyy-MM-dd HH:mm:ss - */ - public static final String COMMON_PATTERN = "yyyy-MM-dd HH:mm:ss"; - - /** - * Format: HH:mm - */ - public static final String HOUR_MINUTES_PATTERN = "HH:mm"; - - /** - * Format: HH:mm:ss - */ - public static final String HOUR_MINUTES_SECONDS_PATTERN = "HH:mm:ss"; - - private static final DateTimeFormatter COMMON_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - private static final ZoneOffset DEFAULT_ZONE_OFFSET = ZoneOffset.of("+8"); - - /** - * Convert the date to a string. - * - * @param dateTime Indicates the date and time to be converted. - * @return Returns a string converted from the date and time. - */ - public static String dateToString(LocalDateTime dateTime) { - assert dateTime != null; - return COMMON_FORMATTER.format(dateTime); - } - - /** - * Converts a string to date and time. - * - * @param dateStr Indicates the string to be converted to date and time. - * @return Returns the date and time converted from the given string. - */ - public static LocalDateTime stringToDate(String dateStr) { - assert dateStr != null; - return LocalDateTime.parse(dateStr, COMMON_FORMATTER); - } - - /** - * Gets the current date and time. - * - * @return Returns the curernt date and time. - */ - public static LocalDateTime getNowTime() { - return LocalDateTime.now(); - } - - /** - * Converts the date and time to a string. - * - * @param dateTime Indicates the date and time to be converted. - * @param formatter Indicates the formatter used for formatting. - * @return Returns the date and time converted from the given string. - */ - public static String dateToString(LocalDateTime dateTime, DateTimeFormatter formatter) { - assert dateTime != null; - return formatter.format(dateTime); - } - - /** - * Converts a string to date and time. - * - * @param dateStr Indicates the string to be converted to date and time. - * @param formatter Indicates the formatter used for formatting. - * @return Returns the date and time converted from the given string. - */ - public static LocalDateTime stringToDate(String dateStr, DateTimeFormatter formatter) { - assert dateStr != null; - return LocalDateTime.parse(dateStr, formatter); - } - - /** - * Converts the date and time to Epoch time (in ms). - * - * @param dateTime Indicates the date and time to be converted. - * @return Returns a long string representing the Epoch time. - */ - public static long dateToTimeMillis(LocalDateTime dateTime) { - assert dateTime != null; - return dateTime.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli(); - } - - /** - * Converts an Epoch time (in ms) to the date and time. - * - * @param timeMills Indicates the Epoch time (in ms) to be converted. - * @return Returns the date and time converted from the given Epoch time. - */ - public static LocalDateTime timeMillisToDate(long timeMills) { - Instant instant = Instant.ofEpochMilli(timeMills); - return LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET); - } - - /** - * Gets the date and time in the given pattern. - * - * @param pattern Indicates the pattern of the date and time. - * @return Returns a string representing the date and time in the specified pattern. - */ - public static String getNowTimeString(String pattern) { - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); - return now.format(formatter); - } - - /** - * Gets the timestamp (in ms). - * - * @return Returns a long string representing the timestamp. - */ - public static Long getNowTimeLong() { - LocalDateTime now = LocalDateTime.now(); - return now.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; + +/** + * @Description Date and time utilities + */ +public final class DateTimeUtil { + private DateTimeUtil() { + } + + /** + * Format: yyyy-MM-dd HH:mm:ss + */ + public static final String COMMON_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * Format: HH:mm + */ + public static final String HOUR_MINUTES_PATTERN = "HH:mm"; + + /** + * Format: HH:mm:ss + */ + public static final String HOUR_MINUTES_SECONDS_PATTERN = "HH:mm:ss"; + + private static final DateTimeFormatter COMMON_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private static final ZoneOffset DEFAULT_ZONE_OFFSET = ZoneOffset.of("+8"); + + /** + * Convert the date to a string. + * + * @param dateTime Indicates the date and time to be converted. + * @return Returns a string converted from the date and time. + */ + public static String dateToString(LocalDateTime dateTime) { + assert dateTime != null; + return COMMON_FORMATTER.format(dateTime); + } + + /** + * Converts a string to date and time. + * + * @param dateStr Indicates the string to be converted to date and time. + * @return Returns the date and time converted from the given string. + */ + public static LocalDateTime stringToDate(String dateStr) { + assert dateStr != null; + return LocalDateTime.parse(dateStr, COMMON_FORMATTER); + } + + /** + * Gets the current date and time. + * + * @return Returns the curernt date and time. + */ + public static LocalDateTime getNowTime() { + return LocalDateTime.now(); + } + + /** + * Converts the date and time to a string. + * + * @param dateTime Indicates the date and time to be converted. + * @param formatter Indicates the formatter used for formatting. + * @return Returns the date and time converted from the given string. + */ + public static String dateToString(LocalDateTime dateTime, DateTimeFormatter formatter) { + assert dateTime != null; + return formatter.format(dateTime); + } + + /** + * Converts a string to date and time. + * + * @param dateStr Indicates the string to be converted to date and time. + * @param formatter Indicates the formatter used for formatting. + * @return Returns the date and time converted from the given string. + */ + public static LocalDateTime stringToDate(String dateStr, DateTimeFormatter formatter) { + assert dateStr != null; + return LocalDateTime.parse(dateStr, formatter); + } + + /** + * Converts the date and time to Epoch time (in ms). + * + * @param dateTime Indicates the date and time to be converted. + * @return Returns a long string representing the Epoch time. + */ + public static long dateToTimeMillis(LocalDateTime dateTime) { + assert dateTime != null; + return dateTime.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli(); + } + + /** + * Converts an Epoch time (in ms) to the date and time. + * + * @param timeMills Indicates the Epoch time (in ms) to be converted. + * @return Returns the date and time converted from the given Epoch time. + */ + public static LocalDateTime timeMillisToDate(long timeMills) { + Instant instant = Instant.ofEpochMilli(timeMills); + return LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET); + } + + /** + * Gets the date and time in the given pattern. + * + * @param pattern Indicates the pattern of the date and time. + * @return Returns a string representing the date and time in the specified pattern. + */ + public static String getNowTimeString(String pattern) { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + return now.format(formatter); + } + + /** + * Gets the timestamp (in ms). + * + * @return Returns a long string representing the timestamp. + */ + public static Long getNowTimeLong() { + LocalDateTime now = LocalDateTime.now(); + return now.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/FileSafeUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/FileSafeUtils.java index 15866ff7f..63a7f4524 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/FileSafeUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/FileSafeUtils.java @@ -1,163 +1,160 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import ohos.devtools.datasources.utils.common.Constant; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HashMap; -import java.util.Map; - -/** - * file SHA-256 - * - * @version 1.0 - * @date 2021/2/5 15:36 - **/ -public final class FileSafeUtils { - /** - * Gets a logger instance. - */ - private static final Logger LOGGER = LogManager.getLogger(FileSafeUtils.class); - - private FileSafeUtils() { - } - - /** - * Gets the MD5 code of the file. Available algorithmType options include MD5, SHA1, SHA-256, SHA-384, and SHA-512. - * - * @param file Indicates the file to obtain the MD5 code. - * @param algorithmType Indicates the algorithm type. - * @return Returns a string of the MD5 code. - */ - public static String getFileSha(File file, String algorithmType) { - if (file == null) { - return "Sha File is null"; - } - - // Check whether the file exists. - if (!file.isFile() || algorithmType == null) { - LOGGER.error("Sha File is not exists : " + file.getName()); - return "Sha File is not exists or algorithmType is null"; - } - - // Define the MessageDigest and FileInputStream for encryption. - MessageDigest messageDigest = null; - FileInputStream fileInputStream = null; - byte[] buffer = new byte[Constant.MB]; - int len; - try { - // Perform SHA algorithm encryption using file input streams. - messageDigest = MessageDigest.getInstance(algorithmType); - fileInputStream = new FileInputStream(file); - while (true) { - len = fileInputStream.read(buffer, 0, Constant.MB); - if (len == Constant.ABNORMAL) { - break; - } - messageDigest.update(buffer, 0, len); - } - } catch (NoSuchAlgorithmException exception) { - LOGGER.error("getFileMD5 fail: " + exception.getMessage()); - } catch (IOException exception) { - LOGGER.error("getFileMD5 fail: " + exception.getMessage()); - return ""; - } finally { - try { - if (fileInputStream != null) { - // Close the file input stream. - fileInputStream.close(); - } - } catch (IOException exception) { - LOGGER.error("fileInputStream: " + exception.getMessage()); - } - } - - // Use BigInteger. - BigInteger bigInteger = new BigInteger(1, messageDigest.digest()); - return bigInteger.toString(Constant.RADIX); - } - - /** - * Sets whether to recursively search files in the sub-directories for the MD code of files. - * - * @param dirFile Indicates the files in the sub-directories. - * @param algorithm Indicates the algorithm. - * @param listChild Indicates whether to recursively search files in the sub-directories. - * @return Returns Map - */ - private static Map getDirMD5(File dirFile, String algorithm, boolean listChild) { - if (!dirFile.isDirectory()) { - return new HashMap<>(); - } - Map pathAlgMap = new HashMap(); - String algCode; - File[] files = dirFile.listFiles(); - for (int index = 0; index < files.length; index++) { - File file = files[index]; - if (file.isDirectory() && listChild) { - pathAlgMap.putAll(getDirMD5(file, algorithm, listChild)); - } else { - algCode = getFileSha(file, algorithm); - if (algCode != null) { - pathAlgMap.put(file.getPath(), algCode); - } - } - } - return pathAlgMap; - } - - /** - * Compares the Hash values in two files. - * - * @param foreFileMD5 Indicates the MD5 code of the source file. - * @param laterFileMD5 Indicates the MD5 code of the target file. - * @return Returns true if the MD5 codes are the same; returns false otherwise. - */ - private static boolean checkHash(String foreFileMD5, String laterFileMD5) { - return foreFileMD5.equals(laterFileMD5); - } - - /** - * Checks for file changes. - * - * @param foreFile Indicates the original file. - * @param laterFile Indicates the new file. - * @param algorithmType Indicates the algorithm type. - * @return Returns true if there is no change in the file; returns false otherwise. - */ - private static boolean checkChange(File foreFile, File laterFile, String algorithmType) { - // Get the Hash value of the original and new files. - String foreHash = getFileSha(foreFile, algorithmType); - String laterHash = getFileSha(laterFile, algorithmType); - - // Call checkHash to compare whether there are changes in the file. - boolean checkHash = checkHash(foreHash, laterHash); - if (checkHash) { - LOGGER.debug("file : {}and file: {}name and content all the same", foreFile.getName(), laterFile.getName()); - } else { - LOGGER.debug("file: {} and file: {}name or content different", foreFile.getName(), laterFile.getName()); - } - return checkHash; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import ohos.devtools.datasources.utils.common.Constant; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; + +/** + * file SHA-256 + */ +public final class FileSafeUtils { + /** + * Gets a logger instance. + */ + private static final Logger LOGGER = LogManager.getLogger(FileSafeUtils.class); + + private FileSafeUtils() { + } + + /** + * Gets the MD5 code of the file. Available algorithmType options include MD5, SHA1, SHA-256, SHA-384, and SHA-512. + * + * @param file Indicates the file to obtain the MD5 code. + * @param algorithmType Indicates the algorithm type. + * @return Returns a string of the MD5 code. + */ + public static String getFileSha(File file, String algorithmType) { + if (file == null) { + return "Sha File is null"; + } + + // Check whether the file exists. + if (!file.isFile() || algorithmType == null) { + LOGGER.error("Sha File is not exists : " + file.getName()); + return "Sha File is not exists or algorithmType is null"; + } + + // Define the MessageDigest and FileInputStream for encryption. + MessageDigest messageDigest = null; + FileInputStream fileInputStream = null; + byte[] buffer = new byte[Constant.MB]; + int len; + try { + // Perform SHA algorithm encryption using file input streams. + messageDigest = MessageDigest.getInstance(algorithmType); + fileInputStream = new FileInputStream(file); + while (true) { + len = fileInputStream.read(buffer, 0, Constant.MB); + if (len == Constant.ABNORMAL) { + break; + } + messageDigest.update(buffer, 0, len); + } + } catch (NoSuchAlgorithmException exception) { + LOGGER.error("getFileMD5 fail: " + exception.getMessage()); + } catch (IOException exception) { + LOGGER.error("getFileMD5 fail: " + exception.getMessage()); + return ""; + } finally { + try { + if (fileInputStream != null) { + // Close the file input stream. + fileInputStream.close(); + } + } catch (IOException exception) { + LOGGER.error("fileInputStream: " + exception.getMessage()); + } + } + + // Use BigInteger. + BigInteger bigInteger = new BigInteger(1, messageDigest.digest()); + return bigInteger.toString(Constant.RADIX); + } + + /** + * Sets whether to recursively search files in the sub-directories for the MD code of files. + * + * @param dirFile Indicates the files in the sub-directories. + * @param algorithm Indicates the algorithm. + * @param listChild Indicates whether to recursively search files in the sub-directories. + * @return Returns Map + */ + private static Map getDirMD5(File dirFile, String algorithm, boolean listChild) { + if (!dirFile.isDirectory()) { + return new HashMap<>(); + } + Map pathAlgMap = new HashMap(); + String algCode; + File[] files = dirFile.listFiles(); + for (int index = 0; index < files.length; index++) { + File file = files[index]; + if (file.isDirectory() && listChild) { + pathAlgMap.putAll(getDirMD5(file, algorithm, listChild)); + } else { + algCode = getFileSha(file, algorithm); + if (algCode != null) { + pathAlgMap.put(file.getPath(), algCode); + } + } + } + return pathAlgMap; + } + + /** + * Compares the Hash values in two files. + * + * @param foreFileMD5 Indicates the MD5 code of the source file. + * @param laterFileMD5 Indicates the MD5 code of the target file. + * @return Returns true if the MD5 codes are the same; returns false otherwise. + */ + private static boolean checkHash(String foreFileMD5, String laterFileMD5) { + return foreFileMD5.equals(laterFileMD5); + } + + /** + * Checks for file changes. + * + * @param foreFile Indicates the original file. + * @param laterFile Indicates the new file. + * @param algorithmType Indicates the algorithm type. + * @return Returns true if there is no change in the file; returns false otherwise. + */ + private static boolean checkChange(File foreFile, File laterFile, String algorithmType) { + // Get the Hash value of the original and new files. + String foreHash = getFileSha(foreFile, algorithmType); + String laterHash = getFileSha(laterFile, algorithmType); + + // Call checkHash to compare whether there are changes in the file. + boolean checkHash = checkHash(foreHash, laterHash); + if (checkHash) { + LOGGER.debug("file : {}and file: {}name and content all the same", foreFile.getName(), laterFile.getName()); + } else { + LOGGER.debug("file: {} and file: {}name or content different", foreFile.getName(), laterFile.getName()); + } + return checkHash; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/PrintUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/PrintUtil.java index e49a73fb6..a40f1b92c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/PrintUtil.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/PrintUtil.java @@ -1,45 +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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import org.apache.logging.log4j.Logger; - -/** - * logger print - * - * @version 1.0 - * @date 2021/04/26 17:21 - **/ -public class PrintUtil { - /** - * print logging - * - * @param logger logging - * @param str logging message - * @param state logging state - */ - public static void print(Logger logger, String str, int state) { - if (state == 0) { - if (logger.isInfoEnabled()) { - logger.info(str); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug(str); - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import org.apache.logging.log4j.Logger; + +/** + * logger print + */ +public class PrintUtil { + /** + * print logging + * + * @param logger logging + * @param str logging message + * @param state logging state + */ + public static void print(Logger logger, String str, int state) { + if (state == 0) { + if (logger.isInfoEnabled()) { + logger.info(str); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug(str); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/Validate.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/Validate.java new file mode 100644 index 000000000..adc02a2a3 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/common/util/Validate.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.common.util; + +/** + * Validate + */ +public abstract class Validate { + /** + * validate + * + * @param obj obj + * @param + * @return + */ + public abstract boolean validate(T obj); + + /** + * addToList + * + * @param obj obj + * @param + */ + public abstract void addToList(T obj); + + /** + * batchInsertToDb + */ + public abstract void batchInsertToDb(); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AbsDataConsumer.java similarity index 79% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceDao.java rename to host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AbsDataConsumer.java index c253879fa..7092ea6e2 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AbsDataConsumer.java @@ -13,11 +13,10 @@ * limitations under the License. */ -package ohos.devtools.services.bytrace; +package ohos.devtools.datasources.utils.datahandler.datapoller; /** - * @Description Bytrace与数据库交互类 - * @Date 2021/2/7 13:58 - **/ -public class BytraceDao { + * AbsDataConsumer + */ +public abstract class AbsDataConsumer implements DataConsumerInterface { } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumer.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumer.java new file mode 100644 index 000000000..d201e3379 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumer.java @@ -0,0 +1,236 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import ohos.devtools.datasources.transport.grpc.service.AgentPluginJavaHeap; +import ohos.devtools.datasources.transport.grpc.service.AgentPluginResult; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import ohos.devtools.services.memory.agentdao.MemoryUpdateInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.TimeUnit; + +/** + * Memory Heap DataConsumer + */ +public class AgentDataConsumer extends AbsDataConsumer { + private static final Logger LOGGER = LogManager.getLogger(AgentDataConsumer.class); + private static final int MAX_SIZE = 2000; + private long agentStartTimeStamp; + private boolean agentFirstStartTimeStamp = true; + private Queue queue; + private long localSessionId; + private ClassInfoDao classInfoDao; + private MemoryInstanceDetailsDao memoryInstanceDetailsDao; + private MemoryInstanceDao memoryInstanceDao; + private MemoryHeapDao memoryHeapDao; + private boolean stopFlag = false; + private List classInfoList = new ArrayList<>(); + private List memoryInstanceDetailsInfos = new ArrayList<>(); + private List memoryHeapInfos = new ArrayList<>(); + private List memoryUpdateInfos = new ArrayList<>(); + private List memoryUpdates = new ArrayList<>(); + + /** + * MemoryHeapDataConsumer + */ + public AgentDataConsumer() { + } + + @Override + public void init(Queue queue, int sessionId, long localSessionId) { + this.queue = queue; + this.localSessionId = localSessionId; + this.classInfoDao = new ClassInfoDao(); + this.memoryInstanceDetailsDao = new MemoryInstanceDetailsDao(); + this.memoryInstanceDao = new MemoryInstanceDao(); + this.memoryHeapDao = new MemoryHeapDao(); + } + + /** + * run + */ + @Override + public void run() { + while (!stopFlag) { + CommonTypes.ProfilerPluginData dataObject = queue.poll(); + if (dataObject != null) { + handleMemoryHeapHandle(dataObject); + } else { + insertDataOrUpdate(true); + try { + TimeUnit.MILLISECONDS.sleep(20); + } catch (InterruptedException exception) { + LOGGER.info("InterruptedException"); + } + } + } + } + + private void insertDataOrUpdate(boolean isInsert) { + if (isNeedInsert() || isInsert) { + boolean insertRes = classInfoDao.insertClassInfos(classInfoList); + if (insertRes) { + classInfoList.clear(); + } + boolean memHeapInfoRes = memoryHeapDao.insertMemoryHeapInfos(memoryHeapInfos); + if (memHeapInfoRes) { + memoryHeapInfos.clear(); + } + boolean instanceRes = memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(memoryInstanceDetailsInfos); + if (instanceRes) { + memoryInstanceDetailsInfos.clear(); + } + boolean insertSuccess = memoryInstanceDao.insertMemoryInstanceInfos(memoryUpdateInfos); + if (insertSuccess) { + memoryUpdateInfos.clear(); + } + } + } + + private boolean isNeedInsert() { + return classInfoList.size() >= MAX_SIZE || memoryHeapInfos.size() >= MAX_SIZE + || memoryInstanceDetailsInfos.size() >= MAX_SIZE || memoryUpdates.size() >= MAX_SIZE; + } + + /** + * shutDown + */ + public void shutDown() { + stopFlag = true; + } + + private void handleMemoryHeapHandle(CommonTypes.ProfilerPluginData memoryData) { + if (agentFirstStartTimeStamp) { + agentStartTimeStamp = DateTimeUtil.getNowTimeLong(); + agentFirstStartTimeStamp = false; + } + ByteString data = memoryData.getData(); + AgentPluginResult.AgentData.Builder agentDataBuilder = AgentPluginResult.AgentData.newBuilder(); + AgentPluginResult.AgentData agentData = null; + try { + agentData = agentDataBuilder.mergeFrom(data).build(); + } catch (InvalidProtocolBufferException invalidProtocolBufferException) { + LOGGER.error("mergeFrom Data failed {}", invalidProtocolBufferException.getMessage()); + return; + } + if (agentData.hasJavaheapData()) { + AgentPluginJavaHeap.BatchAgentMemoryEvent javaHeapData = agentData.getJavaheapData(); + handleJavaHeapData(javaHeapData, memoryData); + } + } + + private void handleJavaHeapData(AgentPluginJavaHeap.BatchAgentMemoryEvent javaHeapData, + CommonTypes.ProfilerPluginData memoryData) { + List eventsList = javaHeapData.getEventsList(); + for (AgentPluginJavaHeap.AgentMemoryEvent agentMemoryEvent : eventsList) { + long agentTime = getAgentTime(agentMemoryEvent.getTvSec(), agentMemoryEvent.getTvNsec()); + if (agentMemoryEvent.hasClassData()) { + AgentPluginJavaHeap.ClassInfo classData = agentMemoryEvent.getClassData(); + int clazzId = classData.getClassId(); + String clzName = classData.getClassName(); + if (clazzId > 0) { + addClassInfoList(clazzId, clzName); + } + } + if (agentMemoryEvent.hasAllocData()) { + AgentPluginJavaHeap.AllocationInfo allocData = agentMemoryEvent.getAllocData(); + int instanceId = allocData.getObjectId(); + int classId = allocData.getClassId(); + List frameInfoList = allocData.getFrameInfoList(); + if (instanceId > 0) { + MemoryHeapInfo memoryHeapInfo = new MemoryHeapInfo(); + memoryHeapInfo.setAllocations(1); + callStackInfo(instanceId, frameInfoList); + memoryHeapInfo.setcId(classId); + memoryHeapInfo.setInstanceId(instanceId); + memoryHeapInfo.setSessionId(localSessionId); + memoryHeapInfo.setHeapId(allocData.getHeapId()); + memoryHeapInfo.setDeallocations(0); + long objSize = allocData.getObjectSize(); + int arrayLength = allocData.getArrayLength(); + memoryHeapInfo.setTotalCount(1); + if (arrayLength <= 0) { + memoryHeapInfo.setShallowSize(objSize); + } else { + memoryHeapInfo.setShallowSize(arrayLength * objSize); + } + memoryHeapInfo.setCreateTime(agentTime); + memoryHeapInfos.add(memoryHeapInfo); + } + } + if (agentMemoryEvent.hasFreeData()) { + AgentPluginJavaHeap.DeallocationInfo freeData = agentMemoryEvent.getFreeData(); + int objectId = freeData.getObjectId(); + if (objectId != 0) { + MemoryUpdateInfo memoryUpdateInfo = new MemoryUpdateInfo(agentTime, objectId); + memoryUpdateInfos.add(memoryUpdateInfo); + insertDataOrUpdate(false); + } + } + insertDataOrUpdate(false); + } + } + + /** + * addClassInfoList + * + * @param clazzId clazzId + * @param clzName clzName + */ + private void addClassInfoList(int clazzId, String clzName) { + ClassInfo classInfo = new ClassInfo(); + classInfo.setcId(clazzId); + classInfo.setClassName(clzName); + classInfoList.add(classInfo); + } + + private long getAgentTime(long tvSec, long tvnsec) { + return (tvSec * 1000000000L + tvnsec) / 1000000; + } + + private void callStackInfo(int instanceId, List stackFrame) { + for (AgentPluginJavaHeap.AllocationInfo.StackFrameInfo stackFrameInfo : stackFrame) { + MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); + int frameId = stackFrameInfo.getFrameId(); + String className = stackFrameInfo.getClassName(); + String methodName = stackFrameInfo.getMethodName(); + String fileName = stackFrameInfo.getFileName(); + int lineNumber = stackFrameInfo.getLineNumber(); + memoryInstanceDetailsInfo.setClassName(className); + memoryInstanceDetailsInfo.setFrameId(frameId); + memoryInstanceDetailsInfo.setMethodName(methodName); + memoryInstanceDetailsInfo.setLineNumber(lineNumber); + memoryInstanceDetailsInfo.setInstanceId(instanceId); + memoryInstanceDetailsInfo.setFieldName(fileName); + memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/CpuDataConsumer.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/CpuDataConsumer.java new file mode 100644 index 000000000..95478362f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/CpuDataConsumer.java @@ -0,0 +1,216 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.intellij.ui.JBColor; +import ohos.devtools.datasources.databases.datatable.CpuTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.CpuPluginResult; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.services.cpu.CpuDataCache; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.layout.chartview.MonitorItemDetail; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.TimeUnit; + +/** + * CpuDataConsumer + */ +public class CpuDataConsumer extends AbsDataConsumer { + private static final Logger LOGGER = LogManager.getLogger(CpuDataConsumer.class); + private static final long SAVE_FREQ = 1000; + private static CpuPluginResult.CpuData prevData = null; + private List processCpuDataList = new ArrayList<>(); + private Queue queue; + private CpuTable cpuTable; + private Integer sessionId; + private Long localSessionId; + private int logIndex = 0; + private boolean stopFlag = false; + private boolean isInsert = false; + + /** + * Time reference variable for saving data to the cpu database at the interval specified by SAVE_FREQ. + */ + private long flagTime = DateTimeUtil.getNowTimeLong(); + + /** + * CpuDataConsumer + */ + public CpuDataConsumer() { + } + + /** + * Run CpuDataConsumer. + */ + @Override + public void run() { + while (!stopFlag) { + CommonTypes.ProfilerPluginData poll = queue.poll(); + if (poll != null) { + handleCpuData(poll); + } else { + try { + TimeUnit.MILLISECONDS.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + insertCpuData(); + } + } + + @Override + public void init(Queue queue, int sessionId, long localSessionId) { + this.queue = queue; + this.cpuTable = new CpuTable(); + this.sessionId = sessionId; + this.localSessionId = localSessionId; + } + + /** + * shutDown + */ + public void shutDown() { + stopFlag = true; + } + + private void handleCpuData(CommonTypes.ProfilerPluginData cpuDataParam) { + CpuPluginResult.CpuData.Builder builder = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData cpudata = null; + try { + cpudata = builder.mergeFrom(cpuDataParam.getData()).build(); + } catch (InvalidProtocolBufferException exe) { + return; + } + if (stopFlag) { + return; + } + ProcessCpuData procCpuData = new ProcessCpuData(); + procCpuData.setData(cpudata); + procCpuData.setSession(localSessionId); + procCpuData.setSessionId(sessionId); + long timeStamp = (cpuDataParam.getTvSec() * 1000000000L + cpuDataParam.getTvNsec()) / 1000000; + procCpuData.setTimeStamp(timeStamp); + LOGGER.debug("TimeStamp {}, AppSummary {}", timeStamp, cpudata); + processCpuDataList.add(procCpuData); + addDataToCache(procCpuData); + isInsert = false; + insertCpuData(); + } + + /** + * addDataToCache + * + * @param procCpuData ProcessCpuData + */ + private void addDataToCache(ProcessCpuData procCpuData) { + List cpuDataModels = getProcessData(procCpuData.getData()); + CpuDataCache.getInstance().addCpuDataModel(localSessionId, procCpuData.getTimeStamp(), cpuDataModels); + List threadModels = getThreadStatus(procCpuData.getData()); + CpuDataCache.getInstance().addThreadDataModel(localSessionId, procCpuData.getTimeStamp(), threadModels); + } + + /** + * getProcessData + * + * @param cpuData cpuData + * @return List + */ + public static List getProcessData(CpuPluginResult.CpuData cpuData) { + ChartDataModel appModel = buildChartDataModel(MonitorItemDetail.CPU_APP); + long dataTimestamp = TimeUnit.NANOSECONDS.toMicros(cpuData.getCpuUsageInfo().getTimestamp().getTvSec()); + long elapsedTime = (cpuData.getCpuUsageInfo().getSystemBootTimeMs() - cpuData.getCpuUsageInfo() + .getPrevSystemBootTimeMs()); // system_boot_time_ms + double appValue = 100.0 * (cpuData.getCpuUsageInfo().getProcessCpuTimeMs() - cpuData.getCpuUsageInfo() + .getPrevProcessCpuTimeMs()) / elapsedTime; // process_cpu_time_ms + double systemValue = 100.0 * (cpuData.getCpuUsageInfo().getSystemCpuTimeMs() - cpuData.getCpuUsageInfo() + .getPrevSystemCpuTimeMs()) / elapsedTime; // system_cpu_time_ms + systemValue = Math.max(0, Math.min(systemValue, 100.0)); + appValue = Math.max(0, Math.min(appValue, systemValue)); + appModel.setCpuPercent(appValue); + appModel.setValue((int) appValue); + ChartDataModel systemModel = buildChartDataModel(MonitorItemDetail.CPU_SYSTEM); + systemModel.setValue((int) systemValue); + systemModel.setCpuPercent(systemValue); + prevData = cpuData; + List list = new ArrayList<>(); + list.add(systemModel); + list.add(appModel); + return list; + } + + /** + * getThreadStatus + * + * @param cpuData cpuData + * @return List + */ + public static List getThreadStatus(CpuPluginResult.CpuData cpuData) { + List list = new ArrayList<>(); + // add the thread info data + long elapsedTime = + (cpuData.getCpuUsageInfo().getSystemBootTimeMs() - cpuData.getCpuUsageInfo().getPrevSystemBootTimeMs()); + cpuData.getThreadInfoList().forEach(threadInfo -> { + double threadValue = + 100.0 * (threadInfo.getThreadCpuTimeMs() - threadInfo.getPrevThreadCpuTimeMs()) / elapsedTime; + BigDecimal bigDecimal = new BigDecimal(threadValue); + ChartDataModel threadInfoModel = new ChartDataModel(); + threadInfoModel.setIndex(threadInfo.getTid()); + threadInfoModel.setColor(JBColor.GREEN); + threadInfoModel.setName(threadInfo.getThreadName()); + threadInfoModel.setValue(threadInfo.getThreadStateValue()); + threadInfoModel.setCpuPercent(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); + list.add(threadInfoModel); + }); + return list; + } + + /** + * buildChartDataModel + * + * @param monitorItemDetail MonitorItemDetail + * @return ChartDataModel + */ + private static ChartDataModel buildChartDataModel(MonitorItemDetail monitorItemDetail) { + ChartDataModel cpuData = new ChartDataModel(); + cpuData.setIndex(monitorItemDetail.getIndex()); + cpuData.setColor(monitorItemDetail.getColor()); + cpuData.setName(monitorItemDetail.getName()); + return cpuData; + } + + private void insertCpuData() { + if (!isInsert) { + long now = DateTimeUtil.getNowTimeLong(); + if (now - flagTime > SAVE_FREQ) { + cpuTable.insertProcessCpuInfo(processCpuDataList); + processCpuDataList.clear(); + // Update flagTime. + flagTime = now; + } + isInsert = true; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataConsumerInterface.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataConsumerInterface.java new file mode 100644 index 000000000..2d5a01a97 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataConsumerInterface.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import java.util.Queue; + +/** + * DataConsumerInterface + */ +public interface DataConsumerInterface extends Runnable { + /** + * init + * + * @param queue queue + * @param sessionId sessionId + * @param localSessionId localSessionId + */ + void init(Queue queue, int sessionId, long localSessionId); + + /** + * shutDown + */ + void shutDown(); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPoller.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPoller.java index fd23e57ff..2abff0945 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPoller.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPoller.java @@ -1,228 +1,172 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import io.grpc.StatusRuntimeException; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.util.CommonUtil; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.services.memory.ClassInfoDao; -import ohos.devtools.services.memory.MemoryHeapDao; -import ohos.devtools.services.memory.MemoryInstanceDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsDao; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUGS_NAME; - -/** - * DataPoller utilities class - * - * @version 1.0 - * @date 2021/02/22 15:59 - **/ -public class DataPoller extends Thread { - private static final Logger DATA = LogManager.getLogger("Data"); - private static final Logger LOGGER = LogManager.getLogger(DataPoller.class); - private long localSessionId; - private int sessionId; - private ProfilerClient client; - private Map tableService; - private MemoryTable memoryTable; - private ClassInfoDao classInfoDao; - private MemoryInstanceDetailsDao memoryInstanceDetailsDao; - private MemoryInstanceDao memoryInstanceDao; - private MemoryHeapDao memoryHeapDao; - - private MemoryHeapDataConsumer memoryHeapDataConsumer; - private MemoryDataConsumer memoryDataConsumer; - - private Queue memoryDataQueue = new LinkedBlockingQueue(); - private Queue memoryHeapDataQueue = new LinkedBlockingQueue(); - private boolean stopFlag = false; - private boolean startRefresh = false; - - /** - * Data Poller - * - * @param localSessionId local SessionId - * @param sessionId session Id - * @param client client - * @param tableService tableService - */ - public DataPoller(Long localSessionId, int sessionId, ProfilerClient client, - Map tableService) { - this.localSessionId = localSessionId; - this.sessionId = sessionId; - this.client = client; - this.tableService = tableService; - } - - /** - * Starts polling. - */ - private void startPoll() { - LOGGER.info("start Poller DeviceInfo, {}", DateTimeUtil.getNowTimeLong()); - ProfilerServiceTypes.FetchDataRequest request = - ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), sessionId, null); - Iterator response = null; - try { - LOGGER.info("start Poller fetchData01, {}", DateTimeUtil.getNowTimeLong()); - response = client.fetchData(request); - long startTime = DateTimeUtil.getNowTimeLong(); - LOGGER.info("start Poller fetchData02, {}", startTime); - while (response.hasNext()) { - if (stopFlag) { - return; - } - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = response.next(); - List lists = fetchDataResponse.getPluginDataList(); - for (CommonTypes.ProfilerPluginData pluginData : lists) { - handleData(pluginData); - } - } - } catch (StatusRuntimeException exception) { - SessionManager.getInstance().deleteLocalSession(localSessionId); - LOGGER.error("start Poll has Exception {}", exception.getMessage()); - return; - } finally { - dataPollerEnd(); - } - } - - private void handleData(CommonTypes.ProfilerPluginData pluginData) { - if (pluginData.getStatus() != 0) { - return; - } - - if (MEMORY_PLUGS_NAME.equals(pluginData.getName()) || MEMORY_PLUG.equals(pluginData.getName())) { - handleMemoryData(pluginData); - } - if (JVMTI_AGENT_PLUG.equals(pluginData.getName())) { - handleAgentData(pluginData); - } - } - - private void handleMemoryData(CommonTypes.ProfilerPluginData pluginData) { - if (tableService.get(MEMORY_PLUG) != null && memoryTable == null) { - AbstractDataStore abstractDataStore = tableService.get(MEMORY_PLUG); - if (abstractDataStore instanceof MemoryTable) { - memoryTable = (MemoryTable) abstractDataStore; - } - memoryDataConsumer = new MemoryDataConsumer(memoryDataQueue, memoryTable, sessionId, localSessionId); - memoryDataConsumer.start(); - offerPluginData(pluginData); - } else if (tableService.get(MEMORY_PLUG) == null && memoryTable == null) { - return; - } else { - offerPluginData(pluginData); - } - } - - private void offerPluginData(CommonTypes.ProfilerPluginData pluginData) { - if (pluginData != null) { - memoryDataQueue.offer(pluginData); - if (!startRefresh) { - long timeStamp = (pluginData.getTvSec() * 1000000000L + pluginData.getTvNsec()) / 1000000; - SessionManager.getInstance().stopLoadingView(localSessionId, timeStamp); - startRefresh = true; - } - } - } - - private void handleAgentData(CommonTypes.ProfilerPluginData pluginData) { - if (tableService.get(JVMTI_AGENT_PLUG) != null && classInfoDao == null) { - LOGGER.info("get Dao info"); - if (tableService.get(JVMTI_AGENT_PLUG) instanceof ClassInfoDao) { - classInfoDao = (ClassInfoDao) tableService.get(JVMTI_AGENT_PLUG); - } - - if (tableService.get("jvmtiagentDetails") instanceof MemoryInstanceDetailsDao) { - memoryInstanceDetailsDao = (MemoryInstanceDetailsDao) tableService.get("jvmtiagentDetails"); - } - if (tableService.get("jvmtiagentInstance") instanceof MemoryInstanceDao) { - memoryInstanceDao = (MemoryInstanceDao) tableService.get("jvmtiagentInstance"); - } - if (tableService.get("jvmtiagentMemoryHeap") instanceof MemoryHeapDao) { - memoryHeapDao = (MemoryHeapDao) tableService.get("jvmtiagentMemoryHeap"); - } - memoryHeapDataConsumer = - new MemoryHeapDataConsumer(memoryHeapDataQueue, localSessionId, classInfoDao, memoryInstanceDetailsDao, - memoryInstanceDao, memoryHeapDao); - memoryHeapDataConsumer.start(); - offerHeapInfo(pluginData); - } else if (tableService.get(JVMTI_AGENT_PLUG) == null && classInfoDao == null) { - return; - } else { - offerHeapInfo(pluginData); - } - } - - private void offerHeapInfo(CommonTypes.ProfilerPluginData pluginData) { - if (pluginData != null) { - memoryHeapDataQueue.offer(pluginData); - } - } - - private void dataPollerEnd() { - if (memoryDataConsumer != null) { - memoryDataConsumer.shutDown(); - } - if (memoryHeapDataConsumer != null) { - memoryHeapDataConsumer.shutDown(); - } - client.setUsed(false); - } - - /** - * shutDown - */ - public void shutDown() { - if (memoryDataConsumer != null) { - memoryDataConsumer.shutDown(); - } - if (memoryHeapDataConsumer != null) { - memoryHeapDataConsumer.shutDown(); - } - stopFlag = true; - } - - /** - * run - */ - @Override - public void run() { - try { - startPoll(); - } catch (StatusRuntimeException exception) { - LOGGER.error("exception error{}", exception.getMessage()); - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.transport.grpc.ProfilerClient; +import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; + +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; + +/** + * DataPoller utilities class + */ +public class DataPoller extends Thread { + private static final Logger LOGGER = LogManager.getLogger(DataPoller.class); + private long localSessionId; + private int sessionId; + private ProfilerClient client; + + private boolean stopFlag = false; + private boolean startRefresh = false; + + private ExecutorService executorService = Executors.newCachedThreadPool(); + private Map queueMap = new HashMap<>(); + private List consumers = new ArrayList<>(); + + /** + * Data Poller + * + * @param localSessionId local SessionId + * @param sessionId session Id + * @param client client + */ + public DataPoller(Long localSessionId, int sessionId, ProfilerClient client) { + this.localSessionId = localSessionId; + this.sessionId = sessionId; + this.client = client; + init(); + } + + private void init() { + List items = PlugManager.getInstance().getProfilerPlugConfig(localSessionId); + for (PluginConf conf : items) { + Class consumerClass = conf.getConsumerClass(); + if (Objects.isNull(consumerClass)) { + continue; + } + AbsDataConsumer absDataConsumer = null; + try { + absDataConsumer = consumerClass.getConstructor().newInstance(); + LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue(); + queueMap.put(conf.getPluginDataName(), linkedBlockingQueue); + absDataConsumer.init(linkedBlockingQueue, sessionId, localSessionId); + executorService.execute(absDataConsumer); + consumers.add(absDataConsumer); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException + | NoSuchMethodException exception) { + LOGGER.error("start Poll init has Exception {}", exception.getMessage()); + } + } + } + + /** + * Starts polling. + */ + private void startPoll() { + LOGGER.info("start Poller DeviceInfo, {}", DateTimeUtil.getNowTimeLong()); + ProfilerServiceTypes.FetchDataRequest request = + ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), sessionId, null); + Iterator response = null; + try { + LOGGER.info("start Poller fetchData01, {}", DateTimeUtil.getNowTimeLong()); + response = client.fetchData(request); + long startTime = DateTimeUtil.getNowTimeLong(); + LOGGER.info("start Poller fetchData02, {}", startTime); + while ((!stopFlag) && response.hasNext()) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = response.next(); + List lists = fetchDataResponse.getPluginDataList(); + if (lists.isEmpty()) { + continue; + } + lists.parallelStream().forEach(pluginData -> { + handleData(pluginData); + }); + } + } catch (StatusRuntimeException exception) { + SessionManager.getInstance().deleteLocalSession(localSessionId); + LOGGER.error("start Poll has Exception {}", exception.getMessage()); + return; + } finally { + dataPollerEnd(); + } + } + + private void handleData(CommonTypes.ProfilerPluginData pluginData) { + if (pluginData.getStatus() != 0) { + return; + } + String name = pluginData.getName(); + if (name.equals(MEMORY_PLUG)) { + LOGGER.debug("get Memory Date, time is {}", DateTimeUtil.getNowTimeLong()); + } + Queue queue = queueMap.get(name); + if (Objects.nonNull(queue)) { + queue.offer(pluginData); + } + if (!startRefresh) { + long timeStamp = (pluginData.getTvSec() * 1000000000L + pluginData.getTvNsec()) / 1000000; + SessionManager.getInstance().stopLoadingView(localSessionId, timeStamp); + startRefresh = true; + } + } + + private void dataPollerEnd() { + consumers.forEach(absDataConsumer -> absDataConsumer.shutDown()); + executorService.shutdown(); + } + + /** + * shutDown + */ + public void shutDown() { + consumers.forEach(absDataConsumer -> absDataConsumer.shutDown()); + stopFlag = true; + } + + /** + * run + */ + @Override + public void run() { + try { + startPoll(); + } catch (StatusRuntimeException exception) { + LOGGER.error("exception error{}", exception.getMessage()); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumer.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumer.java index 138e06fd1..f0b7c40c7 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumer.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumer.java @@ -1,150 +1,220 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import com.google.protobuf.InvalidProtocolBufferException; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.TimeUnit; - -/** - * @Description MemoryDataConsumer - * @Date 2021/4/9 13:56 - **/ -public class MemoryDataConsumer extends Thread { - private static final Logger DATA = LogManager.getLogger("Data"); - private static final Logger LOGGER = LogManager.getLogger(MemoryDataConsumer.class); - - /** - * Interval for saving data to the database, in ms. - */ - private static final long SAVE_FREQ = 1000; - private List processMemInfoList = new ArrayList<>(); - private Queue queue; - private MemoryTable memoryTable; - private Integer sessionId; - private Long localSessionId; - private int logIndex = 0; - private boolean stopFlag = false; - private boolean isInsert = false; - - /** - * Time reference variable for saving data to the in-memory database at the interval specified by SAVE_FREQ. - */ - private long flagTime = DateTimeUtil.getNowTimeLong(); - - /** - * MemoryDataConsumer - * - * @param queue Indicates the memory queue. - * @param memoryTable Indicates the memory table. - * @param sessionId Indicates the session ID. - * @param localSessionId Indicates the local session ID. - */ - public MemoryDataConsumer(Queue queue, MemoryTable memoryTable, Integer sessionId, Long localSessionId) { - this.queue = queue; - this.memoryTable = memoryTable; - this.sessionId = sessionId; - this.localSessionId = localSessionId; - } - - /** - * Run MemoryDataConsumer. - */ - @Override - public void run() { - while (true) { - try { - if (logIndex == Integer.MAX_VALUE) { - logIndex = 0; - } - if (stopFlag) { - return; - } - long now = DateTimeUtil.getNowTimeLong(); - if (now - flagTime > SAVE_FREQ) { - try { - TimeUnit.MILLISECONDS.sleep(1); - } catch (InterruptedException exception) { - LOGGER.info("InterruptedException"); - } - } - if (queue.size() > 0) { - handleMemoryData(queue.poll()); - } - insertMemoryData(); - } catch (Exception exception) { - LOGGER.info(exception); - } - } - } - - /** - * shutDown - */ - public void shutDown() { - stopFlag = true; - } - - private void handleMemoryData(CommonTypes.ProfilerPluginData memoryData) { - MemoryPluginResult.MemoryData.Builder builder = MemoryPluginResult.MemoryData.newBuilder(); - MemoryPluginResult.MemoryData memorydata = null; - try { - memorydata = builder.mergeFrom(memoryData.getData()).build(); - } catch (InvalidProtocolBufferException exe) { - return; - } - List processMemoryInfoList = memorydata.getProcessesinfoList(); - if (stopFlag) { - return; - } - processMemoryInfoList.forEach(processMemoryInfo -> { - MemoryPluginResult.AppSummary app = processMemoryInfo.getMemsummary(); - ProcessMemInfo procMemInfo = new ProcessMemInfo(); - procMemInfo.setData(app); - procMemInfo.setSession(localSessionId); - procMemInfo.setSessionId(sessionId); - long timeStamp = (memoryData.getTvSec() * 1000000000L + memoryData.getTvNsec()) / 1000000; - procMemInfo.setTimeStamp(timeStamp); - LOGGER.debug("TimeStamp {}, AppSummary {}", timeStamp, app); - processMemInfoList.add(procMemInfo); - isInsert = false; - insertMemoryData(); - }); - } - - private void insertMemoryData() { - if (!isInsert) { - long now = DateTimeUtil.getNowTimeLong(); - if (now - flagTime > SAVE_FREQ) { - memoryTable.insertProcessMemInfo(processMemInfoList); - processMemInfoList.clear(); - // Update flagTime. - flagTime = now; - } - isInsert = true; - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import com.google.protobuf.InvalidProtocolBufferException; +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.datasources.transport.grpc.service.AgentPluginNetworkData; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.services.memory.memoryservice.MemoryDataCache; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.layout.chartview.MonitorItemDetail; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.TimeUnit; + +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_CODE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_GRAPHICS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_JAVA; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_NATIVE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_OTHERS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_STACK; + +/** + * MemoryDataConsumer + */ +public class MemoryDataConsumer extends AbsDataConsumer { + private static final Logger DATA = LogManager.getLogger("Data"); + private static final Logger LOGGER = LogManager.getLogger(MemoryDataConsumer.class); + + /** + * Interval for saving data to the database, in ms. + */ + private static final long SAVE_FREQ = 1000; + private List processMemInfoList = new ArrayList<>(); + private Queue queue; + private MemoryTable memoryTable; + private Integer sessionId; + private Long localSessionId; + private int logIndex = 0; + private boolean stopFlag = false; + private boolean isInsert = false; + + /** + * Time reference variable for saving data to the in-memory database at the interval specified by SAVE_FREQ. + */ + private long flagTime = DateTimeUtil.getNowTimeLong(); + + /** + * MemoryDataConsumer + */ + public MemoryDataConsumer() { + } + + /** + * Run MemoryDataConsumer. + */ + @Override + public void run() { + while (!stopFlag) { + CommonTypes.ProfilerPluginData poll = queue.poll(); + if (poll != null) { + handleMemoryData(poll); + } else { + try { + TimeUnit.MILLISECONDS.sleep(500); + } catch (InterruptedException exception) { + LOGGER.info("InterruptedException"); + } + } + insertMemoryData(); + } + } + + @Override + public void init(Queue queue, int sessionId, long localSessionId) { + this.queue = queue; + this.memoryTable = new MemoryTable(); + this.sessionId = sessionId; + this.localSessionId = localSessionId; + } + + /** + * shutDown + */ + public void shutDown() { + stopFlag = true; + } + + private void handleMemoryData(CommonTypes.ProfilerPluginData memoryData) { + MemoryPluginResult.MemoryData.Builder builder = MemoryPluginResult.MemoryData.newBuilder(); + MemoryPluginResult.MemoryData memorydata = null; + try { + memorydata = builder.mergeFrom(memoryData.getData()).build(); + } catch (InvalidProtocolBufferException exe) { + return; + } + List processMemoryInfoList = memorydata.getProcessesinfoList(); + processMemoryInfoList.forEach(processMemoryInfo -> { + MemoryPluginResult.AppSummary app = processMemoryInfo.getMemsummary(); + ProcessMemInfo procMemInfo = new ProcessMemInfo(); + procMemInfo.setData(app); + procMemInfo.setSession(localSessionId); + procMemInfo.setSessionId(sessionId); + long timeStamp = (memoryData.getTvSec() * 1000000000L + memoryData.getTvNsec()) / 1000000; + procMemInfo.setTimeStamp(timeStamp); + LOGGER.debug("TimeStamp {}, AppSummary {}", timeStamp, app); + processMemInfoList.add(procMemInfo); + addDataToCache(procMemInfo); + isInsert = false; + insertMemoryData(); + }); + } + + /** + * getAgentTime + * + * @param tvSec tvSec + * @param tvnsec tvnsec + * @return long + */ + private long getAgentTime(long tvSec, long tvnsec) { + return (tvSec * 1000000000L + tvnsec) / 1000000; + } + + /** + * Process and add memory info to cache + * + * @param procMemInfo ProcessMemInfo + */ + private void addDataToCache(ProcessMemInfo procMemInfo) { + List dataModels = processAppSummary(procMemInfo.getData()); + MemoryDataCache.getInstance().addDataModel(localSessionId, procMemInfo.getTimeStamp(), dataModels); + } + + /** + * Process MemoryPluginResult.AppSummary into chart needed + * + * @param app MemoryPluginResult.AppSummary + * @return List + */ + public static List processAppSummary(MemoryPluginResult.AppSummary app) { + List list = new ArrayList<>(); + + ChartDataModel memJava = buildChartDataModel(MEM_JAVA); + memJava.setValue((int) (app.getJavaHeap())); + list.add(memJava); + + ChartDataModel memNative = buildChartDataModel(MEM_NATIVE); + memNative.setValue((int) (app.getNativeHeap())); + list.add(memNative); + + ChartDataModel memGraphics = buildChartDataModel(MEM_GRAPHICS); + memGraphics.setValue((int) (app.getGraphics())); + list.add(memGraphics); + + ChartDataModel memStack = buildChartDataModel(MEM_STACK); + memStack.setValue((int) (app.getStack())); + list.add(memStack); + + ChartDataModel memCode = buildChartDataModel(MEM_CODE); + memCode.setValue((int) (app.getCode())); + list.add(memCode); + + ChartDataModel memOthers = buildChartDataModel(MEM_OTHERS); + memOthers.setValue((int) (app.getPrivateOther())); + list.add(memOthers); + // Sort by model.index from small to large + list.sort(Comparator.comparingInt(ChartDataModel::getIndex)); + return list; + } + + /** + * Build the data by MonitorItemDetail + * + * @param monitorItemDetail MonitorItemDetail + * @return ChartDataModel + */ + private static ChartDataModel buildChartDataModel(MonitorItemDetail monitorItemDetail) { + ChartDataModel memoryData = new ChartDataModel(); + memoryData.setIndex(monitorItemDetail.getIndex()); + memoryData.setColor(monitorItemDetail.getColor()); + memoryData.setName(monitorItemDetail.getName()); + return memoryData; + } + + private void insertMemoryData() { + if (!isInsert) { + long now = DateTimeUtil.getNowTimeLong(); + if (now - flagTime > SAVE_FREQ) { + memoryTable.insertProcessMemInfo(processMemInfoList); + processMemInfoList.clear(); + // Update flagTime. + flagTime = now; + } + isInsert = true; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumer.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumer.java deleted file mode 100644 index 0fe7e251f..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumer.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import com.google.protobuf.InvalidProtocolBufferException; -import ohos.devtools.datasources.transport.grpc.service.AgentPluginResult; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.services.memory.ClassInfo; -import ohos.devtools.services.memory.ClassInfoDao; -import ohos.devtools.services.memory.MemoryHeapDao; -import ohos.devtools.services.memory.MemoryHeapInfo; -import ohos.devtools.services.memory.MemoryInstanceDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsInfo; -import ohos.devtools.services.memory.MemoryInstanceInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.TimeUnit; - -/** - * @Description MemoryHeapDataConsumer - * @Date 2021/4/9 13:56 - **/ -public class MemoryHeapDataConsumer extends Thread { - private static final Logger HEAPDATA = LogManager.getLogger("HEAPDATA"); - private static final Logger LOGGER = LogManager.getLogger(MemoryHeapDataConsumer.class); - - /** - * 每隔多少毫秒保存一次数据入库 - */ - private static final long SAVE_FREQ = 500; - - private Queue queue; - private Long localSessionId; - private ClassInfoDao classInfoDao; - private MemoryInstanceDetailsDao memoryInstanceDetailsDao; - private MemoryInstanceDao memoryInstanceDao; - private MemoryHeapDao memoryHeapDao; - private Integer LogIndex = 0; - private boolean stopFlag = false; - private long firstTime = 0L; - private int firstDataCount = 0; - private boolean isInsert = false; - - /** - * Memory入库时的时间参照变量,每隔SAVE_FREQ保存一次数据入库 - */ - private long flagTime = DateTimeUtil.getNowTimeLong(); - - private List classInfoList = new ArrayList<>(); - - private List memoryInstanceDetailsInfos = new ArrayList<>(); - - private List memoryHeapInfos = new ArrayList<>(); - - private List memoryInstanceInfos = new ArrayList<>(); - - /** - * MemoryHeapDataConsumer - * - * @param queue queue - * @param localSessionId localSessionId - * @param classInfoDao classInfoDao - * @param memoryInstanceDetailsDao memoryInstanceDetailsDao - * @param memoryInstanceDao memoryInstanceDao - * @param memoryHeapDao memoryHeapDao - */ - public MemoryHeapDataConsumer(Queue queue, Long localSessionId, - ClassInfoDao classInfoDao, MemoryInstanceDetailsDao memoryInstanceDetailsDao, - MemoryInstanceDao memoryInstanceDao, MemoryHeapDao memoryHeapDao) { - this.queue = queue; - this.localSessionId = localSessionId; - this.classInfoDao = classInfoDao; - this.memoryInstanceDetailsDao = memoryInstanceDetailsDao; - this.memoryInstanceDao = memoryInstanceDao; - this.memoryHeapDao = memoryHeapDao; - } - - /** - * run - */ - @Override - public void run() { - while (true) { - try { - if (LogIndex == Integer.MAX_VALUE) { - LogIndex = 0; - } - if (stopFlag) { - return; - } - long now = DateTimeUtil.getNowTimeLong(); - if (now - flagTime > SAVE_FREQ) { - try { - TimeUnit.MILLISECONDS.sleep(10); - } catch (InterruptedException exception) { - HEAPDATA.info("InterruptedException"); - } - } - if (queue.size() > 0) { - CommonTypes.ProfilerPluginData dataObject = queue.poll(); - if (dataObject != null) { - handleMemoryHeapHandle(dataObject); - } - } - insertData(); - } catch (Exception exception) { - LOGGER.error(" exception {} ", exception.getMessage()); - } - } - } - - private void insertData() { - long now = DateTimeUtil.getNowTimeLong(); - if (now - flagTime > SAVE_FREQ) { - if (!isInsert) { - boolean insertRes = classInfoDao.insertClassInfos(classInfoList); - if (insertRes) { - classInfoList.clear(); - } - boolean instanceRes = - memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(memoryInstanceDetailsInfos); - if (instanceRes) { - memoryInstanceDetailsInfos.clear(); - } - boolean memHeapInfoRes = memoryHeapDao.insertMemoryHeapInfos(memoryHeapInfos); - if (memHeapInfoRes) { - memoryHeapInfos.clear(); - } - boolean memInstanceRes = memoryInstanceDao.insertMemoryInstanceInfos(memoryInstanceInfos); - if (memInstanceRes) { - memoryInstanceInfos.clear(); - } - isInsert = true; - flagTime = now; - } - } - } - - /** - * shutDown - */ - public void shutDown() { - stopFlag = true; - } - - private void handleMemoryHeapHandle(CommonTypes.ProfilerPluginData memoryData) { - if (firstTime == 0L) { - // utc 毫秒值 - firstTime = (memoryData.getTvSec() * 1000000000L + memoryData.getTvNsec()) / 1000000; - } - AgentPluginResult.BatchAgentMemoryEvent.Builder batchBuilder = - AgentPluginResult.BatchAgentMemoryEvent.newBuilder(); - AgentPluginResult.BatchAgentMemoryEvent bath = null; - try { - bath = batchBuilder.mergeFrom(memoryData.getData()).build(); - } catch (InvalidProtocolBufferException exception) { - LOGGER.info("mergeFrom failed {}", exception.getMessage()); - } - List agentMemoryEvents = bath.getEventsList(); - for (AgentPluginResult.AgentMemoryEvent agentMemoryEvent : agentMemoryEvents) { - if (stopFlag) { - return; - } - // 时间戳 - long timeStamp = agentMemoryEvent.getTimestamp(); - setPluginClassInfo(agentMemoryEvent); - // memoryHeapInfo信息 - AgentPluginResult.AllocationInfo alloc = agentMemoryEvent.getAllocData(); - int instanceId = alloc.getObjectId(); - int classId = alloc.getClassId(); - String threadName = alloc.getThreadName(); - List stackFram = alloc.getFrameInfoList(); - if (instanceId > 0) { - MemoryHeapInfo memoryHeapInfo = new MemoryHeapInfo(); - // 根据调用栈信息计算 - if (!stackFram.isEmpty()) { - memoryHeapInfo.setAllocations(1); - } else { - memoryHeapInfo.setAllocations(0); - } - // 调用栈信息 - callStackInfo(instanceId, stackFram); - memoryHeapInfo.setcId(classId); - memoryHeapInfo.setInstanceId(instanceId); - memoryHeapInfo.setSessionId(localSessionId); - long createTime = setMemoryHeapInfo(memoryData, timeStamp, alloc, memoryHeapInfo); - setMemoryInstanceInfo(instanceId, classId, createTime); - } - isInsert = false; - insertData(); - AgentPluginResult.DeallocationInfo deallocationInfo = agentMemoryEvent.getFreeData(); - int objectId = deallocationInfo.getObjectId(); - if (objectId != 0) { - long dellocTime = timeStamp; - memoryInstanceDao.updateInstanceInfos(dellocTime, objectId); - memoryHeapDao.updateMemoryHeapInfo(objectId); - } - } - } - - private void setPluginClassInfo(AgentPluginResult.AgentMemoryEvent agentMemoryEvent) { - AgentPluginResult.ClassInfo classData = agentMemoryEvent.getClassData(); - int clazzId = classData.getClassId(); - String clzName = classData.getClassName(); - if (clazzId > 0) { - ClassInfo classInfo = new ClassInfo(); - classInfo.setcId(clazzId); - classInfo.setClassName(clzName); - LOGGER.debug("classInfo is {}", classInfo); - classInfoList.add(classInfo); - } - } - - private void setMemoryInstanceInfo(int instanceId, int classId, long createTime) { - MemoryInstanceInfo memoryInstanceInfo = new MemoryInstanceInfo(); - memoryInstanceInfo.setInstanceId(instanceId); - memoryInstanceInfo.setCreateTime(createTime); - memoryInstanceInfo.setAllocTime(createTime); - memoryInstanceInfo.setcId(classId); - memoryInstanceInfo.setDeallocTime(0L); - HEAPDATA.debug("memoryInstanceInfo is {}", memoryInstanceInfo); - memoryInstanceInfos.add(memoryInstanceInfo); - } - - private long setMemoryHeapInfo(CommonTypes.ProfilerPluginData memoryData, long timeStamp, - AgentPluginResult.AllocationInfo alloc, MemoryHeapInfo memoryHeapInfo) { - int heapId = alloc.getHeapId(); - memoryHeapInfo.setHeapId(heapId); - memoryHeapInfo.setDeallocations(0); - long objSize = alloc.getObjectSize(); - int arrayLength = alloc.getArrayLength(); - if (arrayLength < 0) { - memoryHeapInfo.setTotalCount(1); - memoryHeapInfo.setShallowSize(objSize); - } else { - memoryHeapInfo.setTotalCount(1); - memoryHeapInfo.setShallowSize(arrayLength * objSize); - } - long createTime; - if (timeStamp == 0L) { - createTime = firstTime; - } else { - createTime = (memoryData.getTvSec() * 1000000000L + memoryData.getTvNsec()) / 1000000; - } - memoryHeapInfo.setCreateTime(createTime); - LOGGER.debug("memoryHeapInfo data is {}", memoryHeapInfo); - memoryHeapInfos.add(memoryHeapInfo); - return createTime; - } - - private void callStackInfo(int instanceId, List stackFram) { - for (AgentPluginResult.AllocationInfo.StackFrameInfo stackFrameInfo : stackFram) { - MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - int frameID = stackFrameInfo.getFrameId(); - String className = stackFrameInfo.getClassName(); - String methodName = stackFrameInfo.getMethodName(); - String fileName = stackFrameInfo.getFileName(); - int lineNumber = stackFrameInfo.getLineNumber(); - memoryInstanceDetailsInfo.setClassName(className); - memoryInstanceDetailsInfo.setFrameId(frameID); - memoryInstanceDetailsInfo.setMethodName(methodName); - memoryInstanceDetailsInfo.setLineNumber(lineNumber); - memoryInstanceDetailsInfo.setInstanceId(instanceId); - memoryInstanceDetailsInfo.setFieldName(fileName); - LOGGER.debug("memoryInstanceDetailsInfo is {}", memoryInstanceDetailsInfo); - memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/pretreatment/Pretreatment.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/pretreatment/Pretreatment.java index 1969c1fec..2e06dfee7 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/pretreatment/Pretreatment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/datahandler/pretreatment/Pretreatment.java @@ -1,23 +1,22 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.pretreatment; - -/** - * @Description 预处理核心类 - * @Date 2021/2/7 13:29 - **/ -public class Pretreatment { -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.pretreatment; + +/** + * @Description 预处理核心类 + */ +public class Pretreatment { +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceDao.java new file mode 100644 index 000000000..e398c7e5a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceDao.java @@ -0,0 +1,454 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.dao; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import org.apache.commons.lang.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ohos.devtools.datasources.utils.device.entity.DeviceType.FULL_HOS_DEVICE; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; + +/** + * Device related execution sql class + */ +public class DeviceDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(DeviceDao.class); + private static final String DEVICE_TABLE = "DeviceIPPortInfo"; + + /** + * insertDeviceIPPortInfo + * + * @param info info + */ + public void insertDeviceIPPortInfo(DeviceIPPortInfo info) { + Connection conn = null; + PreparedStatement ps = null; + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + String sql = + "insert into DeviceIPPortInfo (deviceID,deviceName,ip,deviceType,connectType," + + "deviceStatus,retryNum,port,forwardPort) values (?,?,?,?,?,?,?,?,?)"; + ps = conn.prepareStatement(sql); + ps.setString(1, info.getDeviceID()); + ps.setString(2, info.getDeviceName()); + ps.setString(3, info.getIp()); + ps.setString(4, info.getDeviceType().getCpuAbi()); + ps.setString(5, info.getConnectType()); + ps.setInt(6, info.getDeviceStatus()); + ps.setInt(7, info.getRetryNum()); + ps.setInt(8, info.getPort()); + ps.setInt(9, info.getForwardPort()); + ps.executeUpdate(); + } + } catch (SQLException throwables) { + LOGGER.info("sql Exception ", throwables); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * deleteExceptDeviceIPPort + * + * @param list List + * @return List + */ + public List selectOfflineDevice(List list) { + StringBuilder str = new StringBuilder(); + for (DeviceIPPortInfo info : list) { + str.append(" '").append(info.getDeviceID()).append("',"); + } + String selectSql; + if (StringUtils.isNotBlank(str.toString())) { + str = new StringBuilder(str.substring(0, str.length() - 1)); + selectSql = "select * from DeviceIPPortInfo where deviceID not in (" + str + ");"; + } else { + selectSql = "select * from DeviceIPPortInfo"; + } + PreparedStatement statement = null; + Connection connection = null; + ResultSet rs = null; + List deviceIPPortInfoList = new ArrayList<>(); + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + connection = optionalConnection.get(); + statement = connection.prepareStatement(selectSql); + rs = statement.executeQuery(); + while (rs.next()) { + addDeviceIPPortInfoList(deviceIPPortInfoList, rs); + } + } + } catch (SQLException throwables) { + LOGGER.error("SQLException {}", throwables.getMessage()); + } finally { + close(statement, rs, connection); + } + return deviceIPPortInfoList; + } + + /** + * addDeviceIPPortInfoList + * + * @param deviceIPPortInfoList List + * @param rs rs + * @throws SQLException SQLException + */ + private void addDeviceIPPortInfoList(List deviceIPPortInfoList, ResultSet rs) + throws SQLException { + DeviceIPPortInfo deviceInfo = new DeviceIPPortInfo(); + String deviceID = rs.getString("deviceID"); + String deviceName = rs.getString("deviceName"); + String ip = rs.getString("ip"); + String deviceType = rs.getString("deviceType"); + deviceInfo.setDeviceID(deviceID); + deviceInfo.setDeviceName(deviceName); + deviceInfo.setIp(ip); + if (deviceType.equals(FULL_HOS_DEVICE.getCpuAbi())) { + deviceInfo.setDeviceType(FULL_HOS_DEVICE); + } else { + deviceInfo.setDeviceType(LEAN_HOS_DEVICE); + } + String connectType = rs.getString("connectType"); + deviceInfo.setConnectType(connectType); + int deviceStatus = rs.getInt("deviceStatus"); + deviceInfo.setDeviceStatus(deviceStatus); + int retryNum = rs.getInt("retryNum"); + deviceInfo.setRetryNum(retryNum); + int port = rs.getInt("port"); + deviceInfo.setPort(port); + int forwardPort = rs.getInt("forwardPort"); + deviceInfo.setForwardPort(forwardPort); + deviceIPPortInfoList.add(deviceInfo); + } + + /** + * deleteExceptDeviceIPPort + * + * @param deviceIPPortInfo deviceIPPortInfo + */ + public void deleteOfflineDeviceIPPort(DeviceIPPortInfo deviceIPPortInfo) { + Optional connection = getConnectByTable(DEVICE_TABLE); + if (connection.isPresent()) { + Connection conn = connection.get(); + String delSql = "delete from DeviceIPPortInfo where deviceID = '" + deviceIPPortInfo.getDeviceID() + "'"; + LOGGER.debug("deleteExceptDeviceIPPort = {}", delSql); + execute(conn, delSql); + } + } + + /** + * delete Except Device IP Port + * + * @param list List + */ + public void deleteExceptDeviceIPPort(List list) { + StringBuilder str = new StringBuilder(); + Optional deviceIPPort = getConnectByTable(DEVICE_TABLE); + if (deviceIPPort.isPresent()) { + Connection conn = deviceIPPort.get(); + for (DeviceIPPortInfo info : list) { + str.append(" '").append(info.getDeviceID()).append("',"); + } + str = new StringBuilder(str.substring(0, str.length() - 1)); + String delSql = "delete from DeviceIPPortInfo where deviceID not in (" + str + ");"; + LOGGER.debug("deleteExceptDeviceIPPort = {}", delSql); + execute(conn, delSql); + } + } + + /** + * updateDeviceIPPortInfo + * + * @param deviceStatus deviceStatus + * @param retryCount retryCount + * @param deviceId deviceId + * @return boolean + */ + public boolean updateDeviceIPPortInfo(int deviceStatus, int retryCount, String deviceId) { + StringBuilder sql = new StringBuilder("update DeviceIPPortInfo set "); + if (deviceStatus >= 0) { + sql.append("deviceStatus = ").append(deviceStatus).append(","); + } + if (retryCount > -1) { + sql.append("retryNum = ").append(retryCount); + } + sql.append(" where deviceID = '").append(deviceId).append("'"); + Statement statement = null; + Connection conn = null; + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + statement = conn.createStatement(); + int executeUpdate = statement.executeUpdate(sql.toString()); + return executeUpdate > 0; + } + } catch (SQLException throwables) { + return false; + } finally { + close(statement, conn); + } + return false; + } + + /** + * updateDeviceInfo + * + * @param ip ip + * @param port port + * @param forwardPort forwardPort + * @param deviceId deviceId + * @return boolean + */ + public boolean updateDeviceInfo(String ip, int port, int forwardPort, String deviceId) { + StringBuilder sql = + new StringBuilder("update DeviceIPPortInfo set ip = '").append(ip).append("',").append(" port = ") + .append(port).append(",").append("forwardPort = ").append(forwardPort).append(" where deviceID = '") + .append(deviceId).append("'"); + Statement statement = null; + Connection conn = null; + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + statement = conn.createStatement(); + int executeUpdate = statement.executeUpdate(sql.toString()); + return executeUpdate > 0; + } + } catch (SQLException throwables) { + LOGGER.error("update DeviceInfo failed {}", throwables.getMessage()); + return false; + } finally { + close(statement, conn); + } + return false; + } + + /** + * Delete all device IP and port number information + */ + public void deleteAllDeviceIPPortInfo() { + Optional deviceIPPort = getConnectByTable(DEVICE_TABLE); + if (deviceIPPort.isPresent()) { + Connection conn = deviceIPPort.get(); + String sql = "delete from DeviceIPPortInfo"; + execute(conn, sql); + } + } + + /** + * Is there a device IP and port number + * + * @param serialNumber serialNumber + * @return boolean + */ + public boolean hasDeviceIPPort(String serialNumber) { + Optional deviceIPPort = getConnectByTable(DEVICE_TABLE); + boolean flag = false; + if (deviceIPPort.isPresent()) { + Connection conn = deviceIPPort.get(); + Statement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = conn.createStatement(); + String sql = + "select count(1) as hasDevice from DeviceIPPortInfo where deviceID = " + "'" + serialNumber + "';"; + LOGGER.debug("hasDevice = {}", sql); + resultSet = pstmt.executeQuery(sql); + String hasDevice = ""; + while (resultSet.next()) { + hasDevice = resultSet.getString("hasDevice"); + } + if (!"".equals(hasDevice) && Integer.parseInt(hasDevice) > 0) { + flag = true; + } + } catch (SQLException sqlException) { + LOGGER.error("sqlException error: {}", sqlException.getMessage()); + } finally { + close(pstmt, resultSet, conn); + } + } + return flag; + } + + /** + * get All Device IP Port Info + * + * @return List + */ + public List getAllDeviceIPPortInfos() { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List deviceIPPortInfos = new ArrayList<>(); + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + String sql = "select * from DeviceIPPortInfo"; + ps = conn.prepareStatement(sql); + rs = ps.executeQuery(); + DeviceIPPortInfo deviceIPPortInfo; + while (rs.next()) { + deviceIPPortInfo = new DeviceIPPortInfo(); + String deviceID = rs.getString("deviceID"); + String deviceName = rs.getString("deviceName"); + String ip = rs.getString("ip"); + String deviceType = rs.getString("deviceType"); + deviceIPPortInfo.setDeviceID(deviceID); + deviceIPPortInfo.setDeviceName(deviceName); + deviceIPPortInfo.setIp(ip); + if (deviceType.equals(FULL_HOS_DEVICE.getCpuAbi())) { + deviceIPPortInfo.setDeviceType(FULL_HOS_DEVICE); + } else { + deviceIPPortInfo.setDeviceType(LEAN_HOS_DEVICE); + } + String connectType = rs.getString("connectType"); + deviceIPPortInfo.setConnectType(connectType); + int port = rs.getInt("port"); + deviceIPPortInfo.setPort(port); + int forwardPort = rs.getInt("forwardPort"); + deviceIPPortInfo.setForwardPort(forwardPort); + deviceIPPortInfos.add(deviceIPPortInfo); + } + return deviceIPPortInfos; + } + + } catch (SQLException throwables) { + LOGGER.info("SQLException {}", throwables.getMessage()); + } finally { + close(ps, rs, conn); + } + return deviceIPPortInfos; + } + + /** + * get All Device IP Port Info + * + * @return List + */ + public List getOnlineDeviceInfoList() { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List deviceIPPortInfos = new ArrayList<>(); + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + String sql = "select * from DeviceIPPortInfo where deviceStatus = 1"; + ps = conn.prepareStatement(sql); + rs = ps.executeQuery(); + DeviceIPPortInfo deviceIPPortInfo; + while (rs.next()) { + deviceIPPortInfo = new DeviceIPPortInfo(); + String deviceID = rs.getString("deviceID"); + String deviceName = rs.getString("deviceName"); + String ip = rs.getString("ip"); + String deviceType = rs.getString("deviceType"); + deviceIPPortInfo.setDeviceID(deviceID); + deviceIPPortInfo.setDeviceName(deviceName); + deviceIPPortInfo.setIp(ip); + if (deviceType.equals(FULL_HOS_DEVICE.getCpuAbi())) { + deviceIPPortInfo.setDeviceType(FULL_HOS_DEVICE); + } else { + deviceIPPortInfo.setDeviceType(LEAN_HOS_DEVICE); + } + String connectType = rs.getString("connectType"); + deviceIPPortInfo.setConnectType(connectType); + int port = rs.getInt("port"); + deviceIPPortInfo.setPort(port); + int forwardPort = rs.getInt("forwardPort"); + deviceIPPortInfo.setForwardPort(forwardPort); + deviceIPPortInfos.add(deviceIPPortInfo); + } + return deviceIPPortInfos; + } + } catch (SQLException throwables) { + LOGGER.info("SQLException {}", throwables.getMessage()); + } finally { + close(ps, rs, conn); + } + return deviceIPPortInfos; + } + + /** + * getDeviceIPPortInfo + * + * @param deviceID deviceID + * @return Optional + */ + public Optional getDeviceIPPortInfo(String deviceID) { + Connection conn = null; + Statement statement = null; + ResultSet rs = null; + try { + Optional optionalConnection = getConnectByTable(DEVICE_TABLE); + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + String sql = "select * from DeviceIPPortInfo where deviceID = '" + deviceID + "'"; + statement = conn.createStatement(); + rs = statement.executeQuery(sql); + DeviceIPPortInfo deviceIPPortInfo = null; + while (rs.next()) { + deviceIPPortInfo = new DeviceIPPortInfo(); + String deviceId = rs.getString("deviceID"); + String deviceName = rs.getString("deviceName"); + String ip = rs.getString("ip"); + String deviceType = rs.getString("deviceType"); + deviceIPPortInfo.setDeviceID(deviceId); + deviceIPPortInfo.setDeviceName(deviceName); + deviceIPPortInfo.setIp(ip); + if (deviceType.equals(FULL_HOS_DEVICE.getCpuAbi())) { + deviceIPPortInfo.setDeviceType(FULL_HOS_DEVICE); + } else { + deviceIPPortInfo.setDeviceType(LEAN_HOS_DEVICE); + } + String connectType = rs.getString("connectType"); + deviceIPPortInfo.setConnectType(connectType); + int port = rs.getInt("port"); + deviceIPPortInfo.setPort(port); + int forwardPort = rs.getInt("forwardPort"); + deviceIPPortInfo.setForwardPort(forwardPort); + int retryNum = rs.getInt("retryNum"); + deviceIPPortInfo.setRetryNum(retryNum); + } + return Optional.ofNullable(deviceIPPortInfo); + } + } catch (SQLException throwables) { + LOGGER.info("SQLException", throwables); + } finally { + close(statement, rs, conn); + } + return Optional.empty(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceUtil.java deleted file mode 100644 index 97ac52746..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/dao/DeviceUtil.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.dao; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.databasepool.SqlRunnable; -import ohos.devtools.datasources.utils.common.util.PrintUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -/** - * Device-related execution sql class - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class DeviceUtil extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(DeviceUtil.class); - private SqlRunnable sqlRunnable = new SqlRunnable(); - - /** - * Add device information - * - * @param info info - */ - public void insertDeviceInfo(DeviceInfo info) { - boolean bool = insert(info); - if (bool) { - PrintUtil.print(LOGGER, "Successfully added data to device table DeviceInfo", 1); - } else { - PrintUtil.print(LOGGER, "Failed added data to device table DeviceInfo", 1); - } - } - - /** - * insertDeviceIPPortInfo - * - * @param info info - */ - public void insertDeviceIPPortInfo(DeviceIPPortInfo info) { - boolean bool = insert(info); - if (bool) { - PrintUtil.print(LOGGER, "Successfully added data to device table DeviceIPPortInfo", 1); - } else { - PrintUtil.print(LOGGER, "Failed added data to device table DeviceIPPortInfo", 1); - } - } - - /** - * deleteExceptDeviceIPPort - * - * @param list list - */ - public void deleteExceptDeviceIPPort(ArrayList list) { - Connection conn = null; - String str = ""; - Optional deviceIPPort = getConnectByTable("DeviceIPPortInfo"); - if (deviceIPPort.isPresent()) { - conn = deviceIPPort.get(); - } - for (DeviceIPPortInfo info : list) { - str = str + " '" + info.getDeviceID() + "',"; - } - str = str.substring(0, str.length() - 1); - String delSql = "delete from DeviceIPPortInfo where deviceID not in (" + str + ");"; - LOGGER.debug("deleteExceptDeviceIPPort = {}", delSql); - execute(conn, delSql); - } - - /** - * Delete all device IP and port number information - */ - public void deleteAllDeviceIPPortInfo() { - Connection conn = null; - Optional deviceIPPort = getConnectByTable("DeviceIPPortInfo"); - if (deviceIPPort.isPresent()) { - conn = deviceIPPort.get(); - } - String sql = "delete from DeviceIPPortInfo"; - execute(conn, sql); - } - - /** - * hasDevice - * - * @param serialNumber serialNumber - * @return boolean - */ - public boolean hasDevice(String serialNumber) { - Connection conn = null; - Optional deviceIPPort = getConnectByTable("DeviceInfo"); - if (deviceIPPort.isPresent()) { - conn = deviceIPPort.get(); - } - boolean flag = false; - try { - Statement pstmt = conn.createStatement(); - String sql = "select count(1) hasDevice from DeviceInfo where deviceID = " + "'" + serialNumber + "';"; - LOGGER.debug("hasDevice = {}", sql); - ResultSet resultSet = pstmt.executeQuery(sql); - String hasDevice = ""; - while (resultSet.next()) { - hasDevice = resultSet.getString("hasDevice"); - } - if (!"".equals(hasDevice) && Integer.parseInt(hasDevice) > 0) { - flag = true; - } - sqlRunnable.close(pstmt, resultSet, conn); - } catch (SQLException exception) { - LOGGER.error("SQLException error: {}", exception.getMessage()); - } - - return flag; - } - - /** - * Is there a device IP and port number - * - * @param serialNumber serialNumber - * @return boolean - */ - public boolean hasDeviceIPPort(String serialNumber) { - Connection conn = null; - Optional deviceIPPort = getConnectByTable("DeviceIPPortInfo"); - if (deviceIPPort.isPresent()) { - conn = deviceIPPort.get(); - } - Statement pstmt = null; - ResultSet resultSet = null; - boolean flag = false; - try { - pstmt = conn.createStatement(); - String sql = - "select count(1) hasDevice from DeviceIPPortInfo where deviceID = " + "'" + serialNumber + "';"; - LOGGER.debug("hasDevice = {}", sql); - resultSet = pstmt.executeQuery(sql); - String hasDevice = ""; - while (resultSet.next()) { - hasDevice = resultSet.getString("hasDevice"); - } - if (!"".equals(hasDevice) && Integer.parseInt(hasDevice) > 0) { - flag = true; - } - } catch (SQLException sqlException) { - LOGGER.error("sqlException error: {}", sqlException.getMessage()); - } finally { - sqlRunnable.close(pstmt, resultSet, conn); - } - return flag; - } - - /** - * Get all device information - * - * @return List - */ - public List getAllDeviceInfo() { - List list = select(DeviceInfo.class, null, null); - return list; - } - - /** - * get All Device IP Port Info - * - * @return getAllDeviceIPPortInfo - */ - public List getAllDeviceIPPortInfos() { - List list = select(DeviceIPPortInfo.class, null, null); - return list; - } - - /** - * getDeviceIPPortInfo - * - * @param deviceID deviceID - * @return DeviceIPPortInfo - */ - public DeviceIPPortInfo getDeviceIPPortInfo(String deviceID) { - Map hashMap = new HashMap<>(); - hashMap.put("deviceID", deviceID); - List list = select(DeviceIPPortInfo.class, null, hashMap); - return list.get(0); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceIPPortInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceIPPortInfo.java index 180bfc68b..ab1331739 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceIPPortInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceIPPortInfo.java @@ -1,87 +1,113 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.device.entity; - -import java.io.Serializable; - -/** - * Device IP and port number information - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class DeviceIPPortInfo implements Serializable { - private String deviceID; - private String deviceName; - private String ip; - private int port; - private String deviceType; - private int forwardPort; - - public String getDeviceType() { - return deviceType; - } - - public void setDeviceType(String deviceType) { - this.deviceType = deviceType; - } - - public String getDeviceName() { - return deviceName; - } - - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - public String getDeviceID() { - return deviceID; - } - - public void setDeviceID(String deviceID) { - this.deviceID = deviceID; - } - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public int getForwardPort() { - return forwardPort; - } - - public void setForwardPort(int forwardPort) { - this.forwardPort = forwardPort; - } - - @Override - public String toString() { - return "DeviceIPPortInfo{" + "deviceID='" + deviceID + '\'' + ", deviceName='" + deviceName + '\'' + ", ip='" - + ip + '\'' + ", port=" + port + ", deviceType=" + deviceType + ", forwardPort=" + forwardPort + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.entity; + +import ohos.devtools.views.common.LayoutConstants; + +import java.io.Serializable; + +/** + * Device IP and port number information + */ +public class DeviceIPPortInfo implements Serializable { + private static final long serialVersionUID = -290179609047525076L; + private String deviceID; + private String deviceName; + private String ip; + private int port; + private DeviceType deviceType; + private String connectType = LayoutConstants.USB; + private int forwardPort; + private int deviceStatus; + private int retryNum; + + public DeviceType getDeviceType() { + return deviceType; + } + + public void setDeviceType(DeviceType deviceType) { + this.deviceType = deviceType; + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public String getDeviceID() { + return deviceID; + } + + public void setDeviceID(String deviceID) { + this.deviceID = deviceID; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public int getForwardPort() { + return forwardPort; + } + + public void setForwardPort(int forwardPort) { + this.forwardPort = forwardPort; + } + + public String getConnectType() { + return connectType; + } + + public void setConnectType(String connectType) { + this.connectType = connectType; + } + + public int getDeviceStatus() { + return deviceStatus; + } + + public void setDeviceStatus(int deviceStatus) { + this.deviceStatus = deviceStatus; + } + + public int getRetryNum() { + return retryNum; + } + + public void setRetryNum(int retryNum) { + this.retryNum = retryNum; + } + + @Override + public String toString() { + return deviceName; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceInfo.java deleted file mode 100644 index 3b1fcdc6f..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceInfo.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.entity; - -/** - * Device Info - * - * @version 1.0 - * @date 2021/03/4 10:55 - **/ -public class DeviceInfo { - private String deviceID; - private String deviceName; - private String ramInfo; - private String romInfo; - - /** - * set Device ID - * - * @param deviceID deviceID - */ - public void setDeviceID(String deviceID) { - this.deviceID = deviceID; - } - - /** - * set Device Name - * - * @param deviceName deviceName - */ - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - /** - * set RamInfo - * - * @param ramInfo ramInfo - */ - public void setRamInfo(String ramInfo) { - this.ramInfo = ramInfo; - } - - /** - * set RomInfo - * - * @param romInfo romInfo - */ - public void setRomInfo(String romInfo) { - this.romInfo = romInfo; - } - - /** - * get DeviceID - * - * @return String - */ - public String getDeviceID() { - return deviceID; - } - - /** - * get DeviceName - * - * @return String - */ - public String getDeviceName() { - return deviceName; - } - - /** - * String - * - * @return getRamInfo - */ - public String getRamInfo() { - return ramInfo; - } - - /** - * String - * - * @return getRomInfo - */ - public String getRomInfo() { - return romInfo; - } - - @Override - public String toString() { - return "DeviceInfo{" + "deviceID='" + deviceID + '\'' + ", deviceName='" + deviceName + '\'' + ", RAMInfo='" - + ramInfo + '\'' + ", ROMInfo='" + romInfo + '\'' + '}'; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfo.java index c6d8c6d9d..0dc1abd47 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfo.java @@ -1,142 +1,139 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.device.entity; - -import java.io.Serializable; - -/** - * Equipment process - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class DeviceProcessInfo implements Serializable { - private static final long serialVersionUID = -3815785606619485252L; - private String deviceName; - private String processName; - private long localSessionId; - private String deviceType; - private long startTime; - private long endTime; - - /** - * get DeviceName - * - * @return String - */ - public String getDeviceName() { - return deviceName; - } - - /** - * set DeviceName - * - * @param deviceName deviceName - */ - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - /** - * get ProcessName - * - * @return String - */ - public String getProcessName() { - return processName; - } - - /** - * set ProcessName - * - * @param processName processName - */ - public void setProcessName(String processName) { - this.processName = processName; - } - - /** - * get Device Type - * - * @return String - */ - public String getDeviceType() { - return deviceType; - } - - /** - * set Device Type - * - * @param deviceType deviceType - */ - public void setDeviceType(String deviceType) { - this.deviceType = deviceType; - } - - /** - * get LocalSession Id - * - * @return long - */ - public long getLocalSessionId() { - return localSessionId; - } - - /** - * set LocalSession Id - * - * @param localSessionId localSessionId - */ - public void setLocalSessionId(long localSessionId) { - this.localSessionId = localSessionId; - } - - /** - * get Start Time - * - * @return long - */ - public long getStartTime() { - return startTime; - } - - /** - * set Start Time - * - * @param startTime startTime - */ - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - /** - * long - * - * @return getEndTime - */ - public long getEndTime() { - return endTime; - } - - /** - * set End Time - * - * @param endTime endTime - */ - public void setEndTime(long endTime) { - this.endTime = endTime; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.entity; + +import java.io.Serializable; + +/** + * Equipment process + */ +public class DeviceProcessInfo implements Serializable { + private static final long serialVersionUID = -3815785606619485252L; + private String deviceName; + private String processName; + private long localSessionId; + private String deviceType; + private long startTime; + private long endTime; + + /** + * get DeviceName + * + * @return String + */ + public String getDeviceName() { + return deviceName; + } + + /** + * set DeviceName + * + * @param deviceName deviceName + */ + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + /** + * get ProcessName + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * set ProcessName + * + * @param processName processName + */ + public void setProcessName(String processName) { + this.processName = processName; + } + + /** + * get Device Type + * + * @return String + */ + public String getDeviceType() { + return deviceType; + } + + /** + * set Device Type + * + * @param deviceType deviceType + */ + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + /** + * get LocalSession Id + * + * @return long + */ + public long getLocalSessionId() { + return localSessionId; + } + + /** + * set LocalSession Id + * + * @param localSessionId localSessionId + */ + public void setLocalSessionId(long localSessionId) { + this.localSessionId = localSessionId; + } + + /** + * get Start Time + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * set Start Time + * + * @param startTime startTime + */ + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + /** + * long + * + * @return getEndTime + */ + public long getEndTime() { + return endTime; + } + + /** + * set End Time + * + * @param endTime endTime + */ + public void setEndTime(long endTime) { + this.endTime = endTime; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceStatus.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceStatus.java new file mode 100644 index 000000000..220e38abd --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceStatus.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.entity; + +/** + * device Type + */ +public enum DeviceStatus { + INIT(0), OK(1), FAILED(2); + private final int status; + + DeviceStatus(int status) { + this.status = status; + } + + public int getStatus() { + return status; + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceType.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceType.java new file mode 100644 index 000000000..bb90bd515 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/DeviceType.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.device.entity; + +/** + * device Type + */ +public enum DeviceType { + FULL_HOS_DEVICE("arm64-v8a"), LEAN_HOS_DEVICE("arm64-v7a"); + + private final String cpuAbi; + + DeviceType(String cpuAbi) { + this.cpuAbi = cpuAbi; + } + + public String getCpuAbi() { + return cpuAbi; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfo.java index 8a41f81f1..bb0f5d0e6 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfo.java @@ -1,55 +1,52 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.entity; - -import java.io.Serializable; - -/** - * TraceFileInfo - * - * @version 1.0 - * @date 2021/3/26 11:31 - **/ -public class TraceFileInfo implements Serializable { - private static final long serialVersionUID = 6310938366918639648L; - private String version; - private long recordNum; - private long createTime; - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public long getRecordNum() { - return recordNum; - } - - public void setRecordNum(long recordNum) { - this.recordNum = recordNum; - } - - public long getCreateTime() { - return createTime; - } - - public void setCreateTime(long createTime) { - this.createTime = createTime; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.entity; + +import java.io.Serializable; + +/** + * TraceFileInfo + */ +public class TraceFileInfo implements Serializable { + private static final long serialVersionUID = 6310938366918639648L; + private String version; + private long recordNum; + private long createTime; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public long getRecordNum() { + return recordNum; + } + + public void setRecordNum(long recordNum) { + this.recordNum = recordNum; + } + + public long getCreateTime() { + return createTime; + } + + public void setCreateTime(long createTime) { + this.createTime = createTime; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPort.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPort.java index 3532c9daa..f1fdbebfb 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPort.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPort.java @@ -1,97 +1,99 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.transport.hdc.HdcCommandEnum; -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Locale; - -/** - * 设备转发端口类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class DeviceForwardPort { - private static final Logger LOGGER = LogManager.getLogger(DeviceForwardPort.class); - private static volatile DeviceForwardPort instance; - - /** - * getInstance - * - * @return DeviceForwardPort - */ - public static DeviceForwardPort getInstance() { - if (instance == null) { - synchronized (MultiDeviceManager.class) { - if (instance == null) { - instance = new DeviceForwardPort(); - } - } - } - return instance; - } - - private DeviceForwardPort() { - } - - /** - * 设置设备的IP和端口号信息 - * - * @param info info - * @return DeviceIPPortInfo - */ - public DeviceIPPortInfo setDeviceIPPortInfo(DeviceIPPortInfo info) { - String serialNumber = info.getDeviceID(); - while (true) { - int forward = getForwardPort(); - String cmdStr = - String.format(Locale.ENGLISH, HdcCommandEnum.HDC_FOR_PORT.getHdcCommand(), serialNumber, forward); - String res = HdcWrapper.getInstance().getHdcStringResult(cmdStr); - if (!res.contains("cannot bind")) { - info.setForwardPort(forward); - LOGGER.info("prot is {}", res); - break; - } - } - return info; - } - - /** - * getForwardPort - * - * @return int - */ - public int getForwardPort() { - int length = 55535; - int off = 10000; - SecureRandom secureRandom = null; - try { - secureRandom = SecureRandom.getInstanceStrong(); - } catch (NoSuchAlgorithmException noSuchAlgorithmException) { - LOGGER.info("create Random has Execption {}", noSuchAlgorithmException.getMessage()); - return getForwardPort(); - } - int anInt = secureRandom.nextInt(length) + off; - return anInt; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.service; + +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.ArrayList; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_FOR_PORT; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_FOR_PORT; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * device forwarding port class + */ +public class DeviceForwardPort { + private static final Logger LOGGER = LogManager.getLogger(DeviceForwardPort.class); + private static volatile DeviceForwardPort instance; + + /** + * getInstance + * + * @return DeviceForwardPort + */ + public static DeviceForwardPort getInstance() { + if (instance == null) { + synchronized (MultiDeviceManager.class) { + if (instance == null) { + instance = new DeviceForwardPort(); + } + } + } + return instance; + } + + private DeviceForwardPort() { + } + + /** + * forward port to local + * + * @param info info + * @return int + */ + public int forwardDevicePort(DeviceIPPortInfo info) { + String serialNumber = info.getDeviceID(); + while (true) { + int forward = getForwardPort(); + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && info.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_FOR_PORT, serialNumber, String.valueOf(forward)); + } else { + cmdStr = conversionCommand(HDC_FOR_PORT, serialNumber, String.valueOf(forward)); + } + String res = HdcWrapper.getInstance().getHdcStringResult(cmdStr); + if (!res.contains("cannot bind")) { + return forward; + } + } + } + + /** + * getForwardPort + * + * @return int + */ + public int getForwardPort() { + int length = 55535; + int off = 10000; + SecureRandom secureRandom; + try { + secureRandom = SecureRandom.getInstanceStrong(); + } catch (NoSuchAlgorithmException noSuchAlgorithmException) { + LOGGER.info("create Random NoSuchAlgorithmException ", noSuchAlgorithmException); + return getForwardPort(); + } + return secureRandom.nextInt(length) + off; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThread.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThread.java deleted file mode 100644 index 6fb85b644..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThread.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.transport.hdc.HdcCommandEnum; -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.device.dao.DeviceUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * DeviceGrpcThread - * - * @version 1.0 - * @date 2021/3/4 19:02 - **/ -public class DeviceGrpcThread implements Runnable { - private static final Logger LOGGER = LogManager.getLogger(DeviceGrpcThread.class); - private final DeviceUtil sqlUtil = new DeviceUtil(); - private final HdcWrapper hdcHelper = HdcWrapper.getInstance(); - private DeviceIPPortInfo info; - - public DeviceGrpcThread(DeviceIPPortInfo info) { - this.info = info; - } - - /** - * run - */ - @Override - public void run() { - doGrpcRequest(info); - } - - /** - * doGrpcRequest - * - * @param info info - */ - public void doGrpcRequest(DeviceIPPortInfo info) { - String serialNumber = info.getDeviceID(); - String ip = info.getIp(); - int port = info.getPort(); - int forwardPort = info.getForwardPort(); - - // 进行端口转发 - hdcForward(serialNumber, ip, forwardPort, port); - - // 1.根据serialNumber发送grpc请求 - LOGGER.debug("Device {} sent a grpc request", serialNumber); - - // 2.test: 自己造数据 - DeviceInfo deviceInfo = getDeviceInfo(info); - - // 返回数据后,先清空表数据,再插入。 - sqlUtil.insertDeviceInfo(deviceInfo); - } - - private DeviceInfo getDeviceInfo(DeviceIPPortInfo info) { - DeviceInfo deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceID(info.getDeviceID()); - deviceInfo.setDeviceName(info.getDeviceName()); - deviceInfo.setRamInfo("8GB"); - deviceInfo.setRomInfo("128GB"); - return deviceInfo; - } - - private void hdcForward(String serialNumber, String ip, int forwardPort, int port) { - String cmdStr = - HdcCommandEnum.HDC_STR.getHdcCommand() + " " + " -t " + serialNumber + " " + HdcCommandEnum.HDC_FPORT_STR - .getHdcCommand() + " " + ip + ":" + forwardPort + " " + ip + ":" + port; - LOGGER.debug("pushFile cmdStr = {}", cmdStr); - hdcHelper.getHdcStringResult(cmdStr); - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceManager.java deleted file mode 100644 index 4b6050ba1..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/DeviceManager.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.utils.common.util.PrintUtil; -import ohos.devtools.datasources.utils.device.dao.DeviceUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * 设备管理类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public final class DeviceManager { - private static final Logger LOGGER = LogManager.getLogger(DeviceManager.class); - private DeviceIPPortInfo info; - private final DeviceUtil sqlUtil = new DeviceUtil(); - private final ThreadPoolExecutor executor = - new ThreadPoolExecutor(1, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(3), - new ThreadPoolExecutor.DiscardOldestPolicy()); - - /** - * DeviceManager - * - * @param info info - */ - public DeviceManager(DeviceIPPortInfo info) { - this.info = info; - } - - /** - * init - */ - public void init() { - String deviceID = info.getDeviceID(); - if (!sqlUtil.hasDevice(deviceID)) { - executor.execute(new DeviceGrpcThread(info)); - } else { - PrintUtil.print(LOGGER, "The data is already in the device details table", 1); - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManager.java index 6d113d3ea..fd236b19e 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManager.java @@ -1,367 +1,552 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.transport.hdc.HdcCommandEnum; -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.common.Constant; -import ohos.devtools.datasources.utils.device.dao.DeviceUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import static ohos.devtools.datasources.transport.hdc.HdcCommandEnum.HDC_CHECK_SERVER; -import static ohos.devtools.datasources.transport.hdc.HdcCommandEnum.HDC_GET_TYPE; -import static ohos.devtools.datasources.utils.common.Constant.DEVICE_FULL_TYPE; -import static ohos.devtools.datasources.utils.common.Constant.DEVICE_LEAN_TYPE; -import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V7_PATH; -import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V8_PATH; -import static ohos.devtools.datasources.utils.common.Constant.UNZIP_SHELL_PLUGINS_PATH; - -/** - * Profiler的监控项 - * - * @since 2021/3/4 10:55 - */ -public final class MultiDeviceManager implements Runnable { - private static final Logger LOGGER = LogManager.getLogger(MultiDeviceManager.class); - - private static volatile MultiDeviceManager instance; - - private final HdcWrapper hdcHelper = HdcWrapper.getInstance(); - - private final DeviceUtil sqlUtil = new DeviceUtil(); - - private ArrayList serialNumberList = new ArrayList<>(); - - private ArrayList> listCliResult; - - private final ThreadPoolExecutor executor = - new ThreadPoolExecutor(1, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(3), - new ThreadPoolExecutor.DiscardOldestPolicy()); - - /** - * getInstance - * - * @return MultiDeviceManager - */ - public static MultiDeviceManager getInstance() { - if (instance == null) { - synchronized (MultiDeviceManager.class) { - if (instance == null) { - instance = new MultiDeviceManager(); - } - } - } - return instance; - } - - private MultiDeviceManager() { - } - - /** - * run - */ - @Override - public synchronized void run() { - init(); - } - - private void init() { - ArrayList> devices = hdcDevices(); - if (devices != null && devices.size() != 0) { - LOGGER.debug("There are currently {} devices connected to the system", devices.size()); - initSerialNumberList(devices); - // 根据serialNumber做相关业务 - doService(); - } else { - LOGGER.debug("No device is currently connected to the system {}", devices); - if (serialNumberList != null && serialNumberList.size() != 0) { - for (DeviceIPPortInfo offinleDevice : serialNumberList) { - SessionManager.getInstance().deleteSessionByOffLineDivece(offinleDevice); - } - serialNumberList.clear(); - } - sqlUtil.deleteAllDeviceIPPortInfo(); - } - } - - private String isServiceCapability(DeviceIPPortInfo deviceIPPortInfo) { - String serialNumber = deviceIPPortInfo.getDeviceID(); - String cmdStr = String.format(Locale.ENGLISH, HDC_CHECK_SERVER.getHdcCommand(), serialNumber); - LOGGER.debug("hiprofilerCliGetport cmdStr = {}", cmdStr); - listCliResult = hdcHelper.getCliResult(cmdStr); - LOGGER.debug("hiprofilerCliGetport getCliResult = {}", listCliResult); - if (listCliResult.isEmpty()) { - return Constant.DEVICE_STAT_NOT_FOUND; - } - ArrayList list = listCliResult.get(0); - if (list.contains(Constant.HIPRO_FILER_RESULT_OK)) { - return Constant.HIPRO_FILER_RESULT_OK; - } else if (list.contains(Constant.DEVICE_STAT_FAIL)) { - return Constant.DEVICE_STAT_FAIL; - } else { - return Constant.DEVICE_STAT_NOT_FOUND; - } - } - - /** - * 获取设备IP和端口号 - * - * @param serialNumber serialNumber - * @return ArrayList> - */ - public ArrayList> getDeviceIPPort(String serialNumber) { - String cmdStr = - HdcCommandEnum.HDC_STR.getHdcCommand() + " " + " -t " + serialNumber + " " + HdcCommandEnum.HDC_SHELL_STR - .getHdcCommand() + " " + " \"chmod +x /data/local/tmp/hiprofiler_cmd &&" + " " + Constant.DEST_PATH - + "/" + Constant.HIPRO_FILER_CMDNAME; - - LOGGER.debug("hiprofilerCliGetport cmdStr = {}", cmdStr); - ArrayList> cliResult = hdcHelper.getCliResult(cmdStr); - LOGGER.debug("hiprofilerCliGetport getCliResult = {}", cliResult); - return cliResult; - } - - private ArrayList> hdcDevices() { - String hdcStr = HdcCommandEnum.HDC_LIST_TARGETS_STR.getHdcCommand(); - LOGGER.debug("init hdcStr = {}", hdcStr); - ArrayList> device = hdcHelper.getListResult(hdcStr); - LOGGER.debug("init devices = {}", device); - return device; - } - - private void initSerialNumberList(ArrayList> devices) { - ArrayList serialNumbers = new ArrayList<>(); - for (ArrayList deviceInfo : devices) { - if (deviceInfo.contains(Constant.DEVICE_STAT_ONLINE)) { - DeviceIPPortInfo info = new DeviceIPPortInfo(); - String deviceId = deviceInfo.get(0); - info.setDeviceID(deviceInfo.get(0)); - String getProtocmd = String.format(Locale.ENGLISH, HDC_GET_TYPE.getHdcCommand(), deviceId); - String result = hdcHelper.getHdcStringResult(getProtocmd); - if (result.contains(DEVICE_FULL_TYPE)) { - info.setDeviceType(DEVICE_FULL_TYPE); - } else { - info.setDeviceType(DEVICE_LEAN_TYPE); - } - String deviceName = ""; - for (String str : deviceInfo) { - deviceName = getString(deviceName, str); - } - info.setDeviceName(deviceName); - serialNumbers.add(info); - } - } - ArrayList offlineDevice = new ArrayList<>(); - for (DeviceIPPortInfo preInfo : serialNumberList) { - String deviceID = preInfo.getDeviceID(); - boolean flag = false; - for (DeviceIPPortInfo info : serialNumbers) { - if (deviceID.equals(info.getDeviceID())) { - flag = true; - break; - } - } - if (!flag) { - offlineDevice.add(preInfo); - } - } - if (offlineDevice != null && offlineDevice.size() != 0) { - LOGGER.debug("offlineDeviceList = {}", offlineDevice); - for (DeviceIPPortInfo device : offlineDevice) { - SessionManager.getInstance().deleteSessionByOffLineDivece(device); - } - } - serialNumberList.clear(); - serialNumberList = serialNumbers; - if (serialNumberList != null && serialNumberList.size() != 0) { - sqlUtil.deleteExceptDeviceIPPort(serialNumberList); - } else { - sqlUtil.deleteAllDeviceIPPortInfo(); - } - } - - private String getString(String deviceName, String str) { - String devName = deviceName; - if (str.contains("product:")) { - String[] split = str.split(":"); - devName = devName + "-" + split[1]; - } - if (str.contains("model:")) { - String[] split = str.split(":"); - devName = split[1] + devName; - } - if (str.contains("transport_id:")) { - String[] split = str.split(":"); - devName = devName + split[1]; - } - return devName; - } - - private void doService() { - for (DeviceIPPortInfo info : serialNumberList) { - String serialNumber = info.getDeviceID(); - String capability = isServiceCapability(info); - if (Constant.HIPRO_FILER_RESULT_OK.equals(capability)) { - // ok 表示具备服务能力 - if (!sqlUtil.hasDeviceIPPort(serialNumber)) { - insertDeviceIPPort(info); - } else { - LOGGER.debug("The data already exists in the data table: {}", serialNumber); - } - } else if (Constant.DEVICE_STAT_NOT_FOUND.equals(capability)) { - // not found 表示还没有端侧的程序 - if (pushHiprofilerTools(info)) { - // 推送成功后,调用脚本解压,并且拉起程序 - boolean pushShellResult = pushDevToolsShell(serialNumber); - if (pushShellResult) { - uzipDevTools(info); - } - String cap = isServiceCapability(info); - if (Constant.HIPRO_FILER_RESULT_OK.equals(cap)) { - if (!sqlUtil.hasDeviceIPPort(serialNumber)) { - insertDeviceIPPort(info); - } else { - LOGGER.debug("The data already exists in the data table: {}", serialNumber); - } - } - } else { - // 推送失败 - LOGGER.debug("Device: {} push hiprofiler_cli failed", serialNumber); - } - } else { - String cmdStr = ""; - if (DEVICE_FULL_TYPE.equals(info.getDeviceType())) { - cmdStr = String - .format(Locale.ENGLISH, HdcCommandEnum.HDC_START_PROFILERD.getHdcCommand(), info.getDeviceID()); - } else if (DEVICE_LEAN_TYPE.equals(info.getDeviceType())) { - cmdStr = String.format(Locale.ENGLISH, HdcCommandEnum.HDC_STARTV7_PROFILERD.getHdcCommand(), - info.getDeviceID()); - } else { - continue; - } - LOGGER.debug("cmdStr = {}", cmdStr); - String result = hdcHelper.execCmdBy(cmdStr); - LOGGER.debug("getStringResult = {}", result); - doService(); - } - } - } - - private void insertDeviceIPPort(DeviceIPPortInfo info) { - int first = 1; - int second = 2; - String ip = listCliResult.get(first).get(first); - int port = Integer.parseInt(listCliResult.get(second).get(first)); - // IP - info.setIp(ip); - // Port - info.setPort(port); - DeviceForwardPort ins = DeviceForwardPort.getInstance(); - DeviceIPPortInfo portInfo = ins.setDeviceIPPortInfo(info); - sqlUtil.insertDeviceIPPortInfo(portInfo); - } - - /** - * pushHiprofilerTools - * - * @param info info - * @return boolean - */ - public boolean pushHiprofilerTools(DeviceIPPortInfo info) { - String cmdStr = ""; - String devToolsPath = SessionManager.getInstance().getPluginPath(); - if (DEVICE_FULL_TYPE.equals(info.getDeviceType())) { - devToolsPath = devToolsPath + DEVTOOLS_PLUGINS_V8_PATH; - cmdStr = String - .format(Locale.ENGLISH, HdcCommandEnum.HDC_PUSH_CMD.getHdcCommand(), info.getDeviceID(), devToolsPath); - } else if (DEVICE_LEAN_TYPE.equals(info.getDeviceType())) { - devToolsPath = devToolsPath + DEVTOOLS_PLUGINS_V7_PATH; - cmdStr = String - .format(Locale.ENGLISH, HdcCommandEnum.HDC_PUSH_CMD.getHdcCommand(), info.getDeviceID(), devToolsPath); - } else { - LOGGER.error("DeviceType error {}", info.getDeviceType()); - } - LOGGER.debug("pushHiprofilerCli cmdStr = {}", cmdStr); - String result = hdcHelper.getHdcStringResult(cmdStr); - LOGGER.debug("pushHiprofilerCli getStringResult = {}", result); - return result.contains(Constant.DEVICE_SATA_STAT_PUSHED); - } - - /** - * pushDevToolsShell - * - * @param serialNumber serialNumber - * @return boolean - */ - public boolean pushDevToolsShell(String serialNumber) { - String uzipPath = SessionManager.getInstance().getPluginPath() + UNZIP_SHELL_PLUGINS_PATH; - String cmdStr = - String.format(Locale.ENGLISH, HdcCommandEnum.HDC_PUSH_OHOS_SHELL.getHdcCommand(), serialNumber, uzipPath); - LOGGER.debug("cmdStr = {}", cmdStr); - String result = hdcHelper.getHdcStringResult(cmdStr); - LOGGER.debug("getStringResult = {}", result); - return result.contains(Constant.DEVICE_SATA_STAT_PUSHED); - } - - /** - * uzipDevTools - * - * @param info info - */ - public void uzipDevTools(DeviceIPPortInfo info) { - String cmdStr = ""; - if (DEVICE_FULL_TYPE.equals(info.getDeviceType())) { - cmdStr = String.format(Locale.ENGLISH, HdcCommandEnum.HDC_RUN_OHOS.getHdcCommand(), info.getDeviceID()); - } else if (DEVICE_LEAN_TYPE.equals(info.getDeviceType())) { - cmdStr = String.format(Locale.ENGLISH, HdcCommandEnum.HDC_RUN_V7_OHOS.getHdcCommand(), info.getDeviceID()); - } else { - LOGGER.error("DeviceType error {}", info.getDeviceType()); - } - LOGGER.debug("cmdStr = {}", cmdStr); - String result = hdcHelper.execCmdBy(cmdStr); - LOGGER.debug("getStringResult = {}", result); - } - - /** - * 获取设备信息 - * - * @return List - */ - public List getDevicesInfo() { - return sqlUtil.getAllDeviceInfo(); - } - - /** - * getAllDeviceIPPortInfos - * - * @return List - */ - public List getAllDeviceIPPortInfos() { - return sqlUtil.getAllDeviceIPPortInfos(); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.service; + +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.common.Constant; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.device.dao.DeviceDao; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceStatus; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ScheduledExecutorService; +import java.util.stream.Collectors; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_CHECK_SERVER; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_CLEAR_CMD; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_PLUGIN_MD5S; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_TYPE; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_LIST_TARGETS_STR; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_PUSH_CMD; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_PUSH_FILE_SHELL; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_PUSH_OHOS_SHELL; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_ROOT_CLEAR_CMD; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_RUN_OHOS; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_START_PROFILERD; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_CHECK_SERVER; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_GET_PLUGIN_MD5S; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_LIST_TARGETS_STR; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_PUSH_CMD; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_PUSH_FILE_SHELL; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_PUSH_OHOS_SHELL; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_ROOT_CLEAR_CMD; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_RUN_OHOS; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_START_PROFILER; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.datasources.utils.common.Constant.DEVICE_STAT_FAIL; +import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V7_PATH; +import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V8_PATH; +import static ohos.devtools.datasources.utils.common.Constant.PLUGIN_NOT_FOUND; +import static ohos.devtools.datasources.utils.common.Constant.PLUGIN_RESULT_OK; +import static ohos.devtools.datasources.utils.common.Constant.UNZIP_SHELL_PLUGINS_PATH; +import static ohos.devtools.datasources.utils.common.Constant.UPDATE_PLUGIN; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.FULL_HOS_DEVICE; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * DevicesManager + */ +public class MultiDeviceManager { + private static final Logger LOGGER = LogManager.getLogger(MultiDeviceManager.class); + private static final int MAX_RETRY_COUNT = 3; + private static final String PUSH_DEVICES = "StarPUsh"; + private static boolean logFindDevice = true; + private final DeviceDao deviceDao = new DeviceDao(); + + private static class SingletonClassInstance { + private static final MultiDeviceManager INSTANCE = new MultiDeviceManager(); + } + + /** + * getInstance + * + * @return MultiDeviceManager + */ + public static MultiDeviceManager getInstance() { + return MultiDeviceManager.SingletonClassInstance.INSTANCE; + } + + private MultiDeviceManager() { + } + + /** + * Start managing devices + */ + public void start() { + Optional scheduledExecutorService = + QuartzManager.getInstance().checkService(PUSH_DEVICES); + if (scheduledExecutorService.isPresent()) { + boolean shutdown = scheduledExecutorService.get().isShutdown(); + if (shutdown) { + QuartzManager.getInstance().deleteExecutor(PUSH_DEVICES); + startDevicePoller(); + } + } else { + startDevicePoller(); + } + } + + private void startDevicePoller() { + QuartzManager.getInstance().addExecutor(PUSH_DEVICES, this::devicePool); + QuartzManager.getInstance().startExecutor(PUSH_DEVICES, QuartzManager.DELAY, QuartzManager.PERIOD); + } + + /** + * stop managing devices + */ + public void shutDown() { + QuartzManager.getInstance().endExecutor(PUSH_DEVICES); + } + + /** + * main Methods Of Equipment Management Logic + */ + private void devicePool() { + List connectDevices = getConnectDevices(); + List deviceIPPortInfoList = deviceDao.selectOfflineDevice(connectDevices); + deviceIPPortInfoList.forEach(this::handleOfflineDevices); + for (DeviceIPPortInfo deviceIPPortInfo : connectDevices) { + Optional hasDeviceIPPort = deviceDao.getDeviceIPPortInfo(deviceIPPortInfo.getDeviceID()); + boolean checkUpdate = false; + if (hasDeviceIPPort.isPresent()) { + deviceIPPortInfo = hasDeviceIPPort.get(); + } else { + deviceDao.insertDeviceIPPortInfo(deviceIPPortInfo); + checkUpdate = true; + } + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + checkUpdate = false; + } + String serviceCapability = isServiceCapability(deviceIPPortInfo, checkUpdate); + switch (serviceCapability) { + case PLUGIN_RESULT_OK: + break; + case UPDATE_PLUGIN: + case PLUGIN_NOT_FOUND: + pushPluginAndRun(deviceIPPortInfo); + break; + case DEVICE_STAT_FAIL: + handleRestartDevice(deviceIPPortInfo); + break; + default: + LOGGER.error("An unknown situation has occurred"); + break; + } + } + } + + /** + * handle RestartDevice + * + * @param deviceIPPortInfo deviceIPPortInfo + */ + private void handleRestartDevice(DeviceIPPortInfo deviceIPPortInfo) { + if (deviceIPPortInfo.getRetryNum() >= MAX_RETRY_COUNT) { + return; + } + String deviceId = deviceIPPortInfo.getDeviceID(); + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_START_PROFILER, deviceId); + } else { + cmdStr = conversionCommand(HDC_START_PROFILERD, deviceId); + } + HdcWrapper.getInstance().execCmdBy(cmdStr); + String serviceCapability = isServiceCapability(deviceIPPortInfo, false); + if (PLUGIN_RESULT_OK.equals(serviceCapability)) { + deviceDao.updateDeviceIPPortInfo(DeviceStatus.OK.getStatus(), 0, deviceIPPortInfo.getDeviceID()); + } else { + deviceDao.updateDeviceIPPortInfo(DeviceStatus.FAILED.getStatus(), deviceIPPortInfo.getRetryNum() + 1, + deviceIPPortInfo.getDeviceID()); + } + } + + /** + * handleOfflineDevices + * + * @param deviceIPPortInfo deviceIPPortInfo + */ + private void handleOfflineDevices(DeviceIPPortInfo deviceIPPortInfo) { + LOGGER.info("handle offline Device {}", deviceIPPortInfo.getDeviceID()); + deviceDao.deleteOfflineDeviceIPPort(deviceIPPortInfo); + SessionManager.getInstance().deleteSessionByOffLineDevice(deviceIPPortInfo); + } + + /** + * pushPluginAndRun + * + * @param deviceIPPortInfo deviceIPPortInfo + */ + private void pushPluginAndRun(DeviceIPPortInfo deviceIPPortInfo) { + if (pushHiProfilerTools(deviceIPPortInfo)) { + boolean pushShellResult = pushDevToolsShell(deviceIPPortInfo); + if (pushShellResult) { + pushDevTools(deviceIPPortInfo); + } + String cap = isServiceCapability(deviceIPPortInfo, false); + if (PLUGIN_RESULT_OK.equals(cap)) { + deviceDao.updateDeviceIPPortInfo(DeviceStatus.OK.getStatus(), 0, deviceIPPortInfo.getDeviceID()); + logFindDevice(deviceIPPortInfo, false); + } + } else { + LOGGER.debug("Device: {} push hiprofiler_cli failed", deviceIPPortInfo.getDeviceID()); + } + } + + /** + * push Hi profiler Tools + * + * @param info info + * @return boolean + */ + public boolean pushHiProfilerTools(DeviceIPPortInfo info) { + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && info.getDeviceType() == LEAN_HOS_DEVICE) { + String devToolsPath = SessionManager.getInstance().getPluginPath() + DEVTOOLS_PLUGINS_V7_PATH; + HdcWrapper.getInstance().getHdcStringResult(conversionCommand(HDC_STD_ROOT_CLEAR_CMD, info.getDeviceID())); + cmdStr = conversionCommand(HDC_STD_PUSH_CMD, info.getDeviceID(), devToolsPath); + String result = HdcWrapper.getInstance().getHdcStringResult(cmdStr); + return result.contains("FileTransfer finish"); + } else { + String devToolsPath = SessionManager.getInstance().getPluginPath() + DEVTOOLS_PLUGINS_V8_PATH; + if (info.getDeviceType() == LEAN_HOS_DEVICE) { + HdcWrapper.getInstance().getHdcStringResult(conversionCommand(HDC_ROOT_CLEAR_CMD, info.getDeviceID())); + } else { + HdcWrapper.getInstance().getHdcStringResult(conversionCommand(HDC_CLEAR_CMD, info.getDeviceID())); + } + cmdStr = conversionCommand(HDC_PUSH_CMD, info.getDeviceID(), devToolsPath); + String result = HdcWrapper.getInstance().getHdcStringResult(cmdStr); + return result.contains(Constant.DEVICE_SATA_STAT_PUSHED); + } + } + + /** + * push Dev Tools + * + * @param info info + */ + public void pushDevTools(DeviceIPPortInfo info) { + List pluginConfig = PlugManager.getInstance().getPluginConfig(info.getDeviceType(), null); + String plugFiles = pluginConfig.stream().map(pluginConf -> { + String pluginFileName = pluginConf.getPluginFileName(); + return pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1); + }).collect(Collectors.joining(",")); + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && info.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_RUN_OHOS, info.getDeviceID(), plugFiles); + } else { + cmdStr = conversionCommand(HDC_RUN_OHOS, info.getDeviceID(), plugFiles); + } + HdcWrapper.getInstance().execCmdBy(cmdStr); + } + + /** + * push trace + * + * @param info info + */ + public void pushTrace(DeviceIPPortInfo info) { + String pluginPath = SessionManager.getInstance().getPluginPath() + "fbs_dev_1.trace"; + String pluginPath2 = SessionManager.getInstance().getPluginPath() + "fbs_dev_2.trace"; + ArrayList cmdStr; + ArrayList cmdStr2; + if (IS_SUPPORT_NEW_HDC && info.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_PUSH_FILE_SHELL, info.getDeviceID(), pluginPath, + "/data/local/tmp/fbs_dev_1.trace"); + cmdStr2 = conversionCommand(HDC_STD_PUSH_FILE_SHELL, info.getDeviceID(), pluginPath2, + "/data/local/tmp/fbs_dev_2.trace"); + } else { + cmdStr = conversionCommand(HDC_PUSH_FILE_SHELL, info.getDeviceID(), pluginPath, + "/data/local/tmp/fbs_dev_1.trace"); + cmdStr2 = conversionCommand(HDC_PUSH_FILE_SHELL, info.getDeviceID(), pluginPath2, + "/data/local/tmp/fbs_dev_2.trace"); + } + HdcWrapper.getInstance().execCmdBy(cmdStr); + HdcWrapper.getInstance().execCmdBy(cmdStr2); + } + + /** + * push DevTools Shell + * + * @param deviceIPPortInfo deviceIPPortInfo + * @return boolean + */ + public boolean pushDevToolsShell(DeviceIPPortInfo deviceIPPortInfo) { + String pluginPath = SessionManager.getInstance().getPluginPath() + UNZIP_SHELL_PLUGINS_PATH; + ArrayList cmdStr; + String deviceID = deviceIPPortInfo.getDeviceID(); + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_PUSH_OHOS_SHELL, deviceID, pluginPath); + String result = HdcWrapper.getInstance().getHdcStringResult(cmdStr); + return result.contains("FileTransfer finish"); + } else { + cmdStr = conversionCommand(HDC_PUSH_OHOS_SHELL, deviceID, pluginPath); + String result = HdcWrapper.getInstance().getHdcStringResult(cmdStr); + return result.contains(Constant.DEVICE_SATA_STAT_PUSHED); + } + } + + /** + * get Connect Devices + * + * @return List + */ + private List getConnectDevices() { + List deviceIPPortInfoList = new ArrayList<>(); + ArrayList> devices = HdcWrapper.getInstance().getListResult(HDC_LIST_TARGETS_STR); + for (List deviceInfo : devices) { + if (!deviceInfo.contains(Constant.DEVICE_STAT_OFFLINE)) { + String deviceId = deviceInfo.get(0); + ArrayList getProtoCmd = conversionCommand(HDC_GET_TYPE, deviceId); + String result = HdcWrapper.getInstance().getHdcStringResult(getProtoCmd); + DeviceIPPortInfo info; + if (result.contains(FULL_HOS_DEVICE.getCpuAbi())) { + info = buildDeviceInfo(deviceInfo, FULL_HOS_DEVICE); + } else { + info = buildDeviceInfo(deviceInfo, LEAN_HOS_DEVICE); + } + deviceIPPortInfoList.add(info); + logFindDevice(info, true); + } + } + if (IS_SUPPORT_NEW_HDC) { + ArrayList> deviceList = + HdcWrapper.getInstance().getListHdcStdResult(HDC_STD_LIST_TARGETS_STR); + for (List deviceInfo : deviceList) { + if (deviceInfo.contains("Connected")) { + DeviceIPPortInfo info = buildHdcStdDeviceInfo(deviceInfo); + deviceIPPortInfoList.add(info); + } + } + } + return deviceIPPortInfoList; + } + + /** + * run shell to check whether the service is available + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param checkUpdate checkUpdate + * @return String + */ + private String isServiceCapability(DeviceIPPortInfo deviceIPPortInfo, boolean checkUpdate) { + String serialNumber = deviceIPPortInfo.getDeviceID(); + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_CHECK_SERVER, serialNumber); + } else { + cmdStr = conversionCommand(HDC_CHECK_SERVER, serialNumber); + } + ArrayList> listCliResult = HdcWrapper.getInstance().getCliResult(cmdStr); + if (listCliResult.isEmpty()) { + return PLUGIN_NOT_FOUND; + } + ArrayList list = listCliResult.get(0); + if (list.contains(PLUGIN_RESULT_OK)) { + if (deviceIPPortInfo.getForwardPort() <= 0) { + if (checkUpdate) { + boolean updateVersion = updateVersion(deviceIPPortInfo); + if (updateVersion) { + return UPDATE_PLUGIN; + } + } + String ip; + int port; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + ip = "127.0.0.1"; + port = 50051; + } else { + int first = 1; + int second = 2; + ip = listCliResult.get(first).get(first); + port = Integer.parseInt(listCliResult.get(second).get(first)); + } + int forwardDevicePort = DeviceForwardPort.getInstance().forwardDevicePort(deviceIPPortInfo); + deviceDao.updateDeviceInfo(ip, port, forwardDevicePort, deviceIPPortInfo.getDeviceID()); + deviceDao.updateDeviceIPPortInfo(DeviceStatus.OK.getStatus(), 0, deviceIPPortInfo.getDeviceID()); + } + return PLUGIN_RESULT_OK; + } else if (list.contains(DEVICE_STAT_FAIL)) { + return DEVICE_STAT_FAIL; + } else { + return PLUGIN_NOT_FOUND; + } + } + + /** + * updateVersion + * + * @param deviceIPPortInfo deviceIPPortInfo + * @return boolean + */ + private boolean updateVersion(DeviceIPPortInfo deviceIPPortInfo) { + String devToolsPath = SessionManager.getInstance().getPluginPath() + DEVTOOLS_PLUGINS_V8_PATH; + File devtoolsPath = new File(devToolsPath); + Map cmdResultMap; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdResultMap = HdcWrapper.getInstance() + .getCmdResultMap(conversionCommand(HDC_STD_GET_PLUGIN_MD5S, deviceIPPortInfo.getDeviceID())); + } else { + cmdResultMap = HdcWrapper.getInstance() + .getCmdResultMap(conversionCommand(HDC_GET_PLUGIN_MD5S, deviceIPPortInfo.getDeviceID())); + } + Map resultMap = new HashMap<>(); + File[] pluginList = devtoolsPath.listFiles(); + for (File plugin : pluginList) { + try { + String pluginMd5 = DigestUtils.md5Hex(new FileInputStream(plugin)); + resultMap.put(plugin.getName(), pluginMd5); + } catch (IOException ioException) { + LOGGER.info("get plugin MD5 sum Failed {}", ioException.getMessage()); + return true; + } + } + return !compareWithMap(cmdResultMap, resultMap); + } + + /** + * Does parentMap contain childMap + * + * @param parentMap parentMap + * @param childMap childMap + * @return boolean + */ + private boolean compareWithMap(Map parentMap, Map childMap) { + StringBuilder builder = new StringBuilder(); + for (Map.Entry entry : parentMap.entrySet()) { + builder.append(entry.getKey()).append("_").append(entry.getValue()); + } + int count = 0; + for (Map.Entry entry : childMap.entrySet()) { + String map1KeyVal = entry.getKey() + "_" + entry.getValue(); + boolean contains = builder.toString().contains(map1KeyVal); + if (contains) { + count++; + } + } + return childMap.size() == count; + } + + /** + * buildDeviceInfo + * + * @param deviceInfo deviceInfo + * @param deviceType deviceType + * @return DeviceIPPortInfo + */ + private DeviceIPPortInfo buildDeviceInfo(List deviceInfo, DeviceType deviceType) { + DeviceIPPortInfo info = new DeviceIPPortInfo(); + info.setDeviceID(deviceInfo.get(0)); + info.setDeviceType(deviceType); + String deviceName = ""; + for (String str : deviceInfo) { + deviceName = buildDeviceName(deviceName, str); + } + info.setDeviceName(deviceName); + info.setDeviceStatus(DeviceStatus.INIT.getStatus()); + info.setRetryNum(0); + return info; + } + + /** + * buildDeviceInfo + * + * @param deviceInfo deviceInfo + * @return DeviceIPPortInfo + */ + private DeviceIPPortInfo buildHdcStdDeviceInfo(List deviceInfo) { + DeviceIPPortInfo info = new DeviceIPPortInfo(); + String deviceId = deviceInfo.get(0); + info.setDeviceID(deviceId); + info.setDeviceType(LEAN_HOS_DEVICE); + info.setDeviceName(deviceId); + info.setDeviceStatus(DeviceStatus.INIT.getStatus()); + info.setRetryNum(0); + return info; + } + + /** + * buildDeviceName + * + * @param deviceName deviceName + * @param str str + * @return String + */ + private String buildDeviceName(String deviceName, String str) { + String devName = deviceName; + if (str.contains("product:")) { + String[] split = str.split(":"); + devName = devName + "-" + split[1]; + } + if (str.contains("model:")) { + String[] split = str.split(":"); + devName = split[1] + devName; + } + if (str.contains("transport_id:")) { + String[] split = str.split(":"); + devName = devName + split[1]; + } + return devName; + } + + /** + * getAllDeviceIPPortInfos + * + * @return List + */ + public List getOnlineDeviceInfoList() { + return deviceDao.getOnlineDeviceInfoList(); + } + + /** + * getHiLogDeviceInfoList + * + * @return List + */ + public List getHiLogDeviceInfoList() { + return getConnectDevices(); + } + + private void logFindDevice(DeviceIPPortInfo deviceIPPortInfo, boolean find) { + if (logFindDevice) { + if (find) { + LOGGER + .debug("find device {}, time is {}", deviceIPPortInfo.getDeviceID(), DateTimeUtil.getNowTimeLong()); + } else { + LOGGER.debug("Device is OK {}, Time is {}", deviceIPPortInfo.getDeviceID(), + DateTimeUtil.getNowTimeLong()); + logFindDevice = false; + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDao.java index ef94a4b8c..45c6e2ef1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDao.java @@ -1,83 +1,80 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.monitorconfig.dao; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.common.util.PrintUtil; -import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.List; - -/** - * 监控项配置数据的dao层 - * - * @version 1.0 - * @date 2021/2/25 14:58 - **/ -public class MonitorConfigDao extends AbstractDataStore { - // 日志 - private static final Logger LOGGER = LogManager.getLogger(MonitorConfigDao.class); - private static volatile MonitorConfigDao singleton; - - /** - * Get an instance - * - * @return MonitorConfigDao - */ - public static MonitorConfigDao getInstance() { - if (singleton == null) { - synchronized (MonitorConfigDao.class) { - if (singleton == null) { - singleton = new MonitorConfigDao(); - } - } - } - return singleton; - } - - private MonitorConfigDao() { - } - - /** - * 插入界面返回的监控项采集项数据 - * - * @param monitorInfo monitorInfo - * @return boolean - */ - public boolean insertMonitorInfo(MonitorInfo monitorInfo) { - boolean result = false; - result = insert(monitorInfo); - if (result) { - PrintUtil.print(LOGGER, "local session Data written to the table successfully", 1); - } else { - PrintUtil.print(LOGGER, "local session Failed to write data to table", 1); - } - return true; - } - - /** - * 插入界面返回的监控项采集项数据 - * - * @param monitorInfo monitorInfo - * @return boolean - */ - public boolean insertMonitorInfos(List monitorInfo) { - return insert(monitorInfo); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.monitorconfig.dao; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.PrintUtil; +import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +/** + * 监控项配置数据的dao层 + */ +public class MonitorConfigDao extends AbstractDataStore { + // 日志 + private static final Logger LOGGER = LogManager.getLogger(MonitorConfigDao.class); + private static volatile MonitorConfigDao singleton; + + /** + * Get an instance + * + * @return MonitorConfigDao + */ + public static MonitorConfigDao getInstance() { + if (singleton == null) { + synchronized (MonitorConfigDao.class) { + if (singleton == null) { + singleton = new MonitorConfigDao(); + } + } + } + return singleton; + } + + private MonitorConfigDao() { + } + + /** + * 插入界面返回的监控项采集项数据 + * + * @param monitorInfo monitorInfo + * @return boolean + */ + public boolean insertMonitorInfo(MonitorInfo monitorInfo) { + boolean result = false; + result = insert(monitorInfo); + if (result) { + PrintUtil.print(LOGGER, "local session Data written to the table successfully", 1); + } else { + PrintUtil.print(LOGGER, "local session Failed to write data to table", 1); + } + return true; + } + + /** + * 插入界面返回的监控项采集项数据 + * + * @param monitorInfo monitorInfo + * @return boolean + */ + public boolean insertMonitorInfos(List monitorInfo) { + return insert(monitorInfo); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfo.java index b82e129b2..d1ffcc1e3 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfo.java @@ -1,176 +1,173 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.monitorconfig.entity; - -import java.util.Objects; - -/** - * MonitorInfo - * - * @version 1.0 - * @date 2021/2/19 14:53 - **/ -public final class MonitorInfo { - private long localSessionId; - private String monitorType; - private String parameter; - private String value; - - /** - * builder - * - * @return Builder - */ - public static Builder builder() { - return new Builder(); - } - - private MonitorInfo(Builder builder) { - localSessionId = builder.localSessionId; - monitorType = builder.monitorType; - parameter = builder.parameter; - value = builder.value; - } - - public long getLocalSessionId() { - return localSessionId; - } - - public void setLocalSessionId(long id) { - this.localSessionId = id; - } - - public String getMonitorType() { - return monitorType; - } - - public void setMonitorType(String type) { - this.monitorType = type; - } - - public String getParameter() { - return parameter; - } - - public void setParameter(String param) { - this.parameter = param; - } - - public String getValue() { - return value; - } - - public void setValue(String worth) { - this.value = worth; - } - - @Override - public String toString() { - return "MonitorInfo{" + "localSessionId=" + localSessionId + ", monitorType='" + monitorType + '\'' - + ", parameter='" + parameter + '\'' + ", value='" + value + '\'' + '}'; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - MonitorInfo that = null; - if (object instanceof MonitorInfo) { - that = (MonitorInfo) object; - } - if (that == null) { - return true; - } - return localSessionId == that.localSessionId && monitorType.equals(that.monitorType) && parameter - .equals(that.parameter) && value.equals(that.value); - } - - @Override - public int hashCode() { - return Objects.hash(localSessionId, monitorType, parameter, value); - } - - /** - * Builder - */ - public static final class Builder { - private long localSessionId; - private String monitorType; - private String parameter; - private String value; - - private Builder() { - } - - /** - * localSessionId - * - * @param id id - * @return Builder - */ - public Builder localSessionId(long id) { - this.localSessionId = id; - return this; - } - - /** - * monitorType - * - * @param type type - * @return Builder - */ - public Builder monitorType(String type) { - this.monitorType = type; - return this; - } - - /** - * 参数 - * - * @param param param - * @return Builder - */ - public Builder parameter(String param) { - this.parameter = param; - return this; - } - - /** - * value - * - * @param worth worth - * @return Builder - */ - public Builder value(String worth) { - this.value = worth; - return this; - } - - /** - * MonitorInfo - * - * @return build - */ - public MonitorInfo build() { - return new MonitorInfo(this); - } - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.monitorconfig.entity; + +import java.util.Objects; + +/** + * MonitorInfo + */ +public final class MonitorInfo { + private long localSessionId; + private String monitorType; + private String parameter; + private String value; + + /** + * builder + * + * @return Builder + */ + public static Builder builder() { + return new Builder(); + } + + private MonitorInfo(Builder builder) { + localSessionId = builder.localSessionId; + monitorType = builder.monitorType; + parameter = builder.parameter; + value = builder.value; + } + + public long getLocalSessionId() { + return localSessionId; + } + + public void setLocalSessionId(long id) { + this.localSessionId = id; + } + + public String getMonitorType() { + return monitorType; + } + + public void setMonitorType(String type) { + this.monitorType = type; + } + + public String getParameter() { + return parameter; + } + + public void setParameter(String param) { + this.parameter = param; + } + + public String getValue() { + return value; + } + + public void setValue(String worth) { + this.value = worth; + } + + @Override + public String toString() { + return "MonitorInfo{" + "localSessionId=" + localSessionId + ", monitorType='" + monitorType + '\'' + + ", parameter='" + parameter + '\'' + ", value='" + value + '\'' + '}'; + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object == null || getClass() != object.getClass()) { + return false; + } + MonitorInfo that = null; + if (object instanceof MonitorInfo) { + that = (MonitorInfo) object; + } + if (that == null) { + return true; + } + return localSessionId == that.localSessionId && monitorType.equals(that.monitorType) && parameter + .equals(that.parameter) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(localSessionId, monitorType, parameter, value); + } + + /** + * Builder + */ + public static final class Builder { + private long localSessionId; + private String monitorType; + private String parameter; + private String value; + + private Builder() { + } + + /** + * localSessionId + * + * @param id id + * @return Builder + */ + public Builder localSessionId(long id) { + this.localSessionId = id; + return this; + } + + /** + * monitorType + * + * @param type type + * @return Builder + */ + public Builder monitorType(String type) { + this.monitorType = type; + return this; + } + + /** + * 参数 + * + * @param param param + * @return Builder + */ + public Builder parameter(String param) { + this.parameter = param; + return this; + } + + /** + * value + * + * @param worth worth + * @return Builder + */ + public Builder value(String worth) { + this.value = worth; + return this; + } + + /** + * MonitorInfo + * + * @return build + */ + public MonitorInfo build() { + return new MonitorInfo(this); + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManager.java index 5bbe766e1..2ee014c55 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManager.java @@ -1,121 +1,118 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.monitorconfig.service; - -import com.alibaba.fastjson.JSONObject; -import ohos.devtools.datasources.utils.common.util.PrintUtil; -import ohos.devtools.datasources.utils.monitorconfig.dao.MonitorConfigDao; -import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 监控项配置管理类 - * - * @version 1.0 - * @date 2021/2/2 19:04 - **/ -public class MonitorConfigManager { - /** - * 日志 - */ - private static final Logger LOGGER = LogManager.getLogger(MonitorConfigManager.class); - - /** - * 单例 - */ - private static volatile MonitorConfigManager singleton; - - /** - * dataMap - */ - public static ConcurrentHashMap>> dataMap = new ConcurrentHashMap<>(); - - /** - * getInstance - * - * @return MonitorConfigManager - */ - public static MonitorConfigManager getInstance() { - if (singleton == null) { - synchronized (MonitorConfigManager.class) { - if (singleton == null) { - singleton = new MonitorConfigManager(); - } - } - } - return singleton; - } - - private MonitorConfigManager() { - } - - /** - * analyzeCharTarget - * - * @param localSessionId localSessionId - * @param jsonMonitor jsonMonitor - * @return Map> - */ - public Map> analyzeCharTarget(long localSessionId, JSONObject jsonMonitor) { - // 写表的实体对象传递 - MonitorInfo monitorInfo = null; - LinkedList monitorInfos = new LinkedList<>(); - - // 传递给界面的具体指标项配置(True),通过Dao获取则丢弃这个集合对象 - LinkedList monitor = null; - Map> monitors = new HashMap<>(); - - // 迭代传递的JSON对象解析,并写表 - Iterator> rtn = jsonMonitor.entrySet().iterator(); - while (rtn.hasNext()) { - Map.Entry unit = rtn.next(); - monitor = new LinkedList<>(); - - JSONObject jsonObject = jsonMonitor.getJSONObject(unit.getKey()); - Iterator> iterator = jsonObject.entrySet().iterator(); - - while (iterator.hasNext()) { - Map.Entry next = iterator.next(); - monitorInfo = MonitorInfo.builder().localSessionId(localSessionId).monitorType(unit.getKey()) - .parameter(next.getKey()).value(next.getValue().toString()).build(); - - if ("true".equals(next.getValue().toString())) { - monitor.add(next.getKey()); - } - monitorInfos.add(monitorInfo); - } - - if (monitor.size() > 0) { - // 传递给二级界面的数据monitors - monitors.put(unit.getKey(), monitor); - } - } - - dataMap.put(localSessionId, monitors); - // 解析后的数据先写表 - MonitorConfigDao.getInstance().insertMonitorInfos(monitorInfos); - PrintUtil.print(LOGGER, "analyze Chart Target success", 1); - // 返回界面所有配置(true)的指标项 - return monitors; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.monitorconfig.service; + +import com.alibaba.fastjson.JSONObject; +import ohos.devtools.datasources.utils.common.util.PrintUtil; +import ohos.devtools.datasources.utils.monitorconfig.dao.MonitorConfigDao; +import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 监控项配置管理类 + */ +public class MonitorConfigManager { + /** + * dataMap + */ + public static ConcurrentHashMap>> dataMap = new ConcurrentHashMap<>(); + + /** + * getInstance + * + * @return MonitorConfigManager + */ + public static MonitorConfigManager getInstance() { + if (singleton == null) { + synchronized (MonitorConfigManager.class) { + if (singleton == null) { + singleton = new MonitorConfigManager(); + } + } + } + return singleton; + } + + /** + * 日志 + */ + private static final Logger LOGGER = LogManager.getLogger(MonitorConfigManager.class); + + /** + * 单例 + */ + private static volatile MonitorConfigManager singleton; + + private MonitorConfigManager() { + } + + /** + * analyzeCharTarget + * + * @param localSessionId localSessionId + * @param jsonMonitor jsonMonitor + * @return Map> + */ + public Map> analyzeCharTarget(long localSessionId, JSONObject jsonMonitor) { + // 写表的实体对象传递 + MonitorInfo monitorInfo = null; + LinkedList monitorInfos = new LinkedList<>(); + + // 传递给界面的具体指标项配置(True),通过Dao获取则丢弃这个集合对象 + LinkedList monitor = null; + Map> monitors = new HashMap<>(); + + // 迭代传递的JSON对象解析,并写表 + Iterator> rtn = jsonMonitor.entrySet().iterator(); + while (rtn.hasNext()) { + Map.Entry unit = rtn.next(); + monitor = new LinkedList<>(); + + JSONObject jsonObject = jsonMonitor.getJSONObject(unit.getKey()); + Iterator> iterator = jsonObject.entrySet().iterator(); + + while (iterator.hasNext()) { + Map.Entry next = iterator.next(); + monitorInfo = MonitorInfo.builder().localSessionId(localSessionId).monitorType(unit.getKey()) + .parameter(next.getKey()).value(next.getValue().toString()).build(); + + if ("true".equals(next.getValue().toString())) { + monitor.add(next.getKey()); + } + monitorInfos.add(monitorInfo); + } + + if (monitor.size() > 0) { + // 传递给二级界面的数据monitors + monitors.put(unit.getKey(), monitor); + } + } + + dataMap.put(localSessionId, monitors); + // 解析后的数据先写表 + MonitorConfigDao.getInstance().insertMonitorInfos(monitorInfos); + PrintUtil.print(LOGGER, "analyze Chart Target success", 1); + // 返回界面所有配置(true)的指标项 + return monitors; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ICreatePluginConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ICreatePluginConfig.java new file mode 100644 index 000000000..85f46a25a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ICreatePluginConfig.java @@ -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. + */ + +package ohos.devtools.datasources.utils.plugin; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; + +/** + * ICreatePluginConfig + */ +public interface ICreatePluginConfig { + /** + * createPluginConfig + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param processInfo processInfo + * @return HiProfilerPluginConfig + */ + HiProfilerPluginConfig createPluginConfig(DeviceIPPortInfo deviceIPPortInfo, ProcessInfo processInfo); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IGetPluginName.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IGetPluginName.java new file mode 100644 index 000000000..7502dd453 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IGetPluginName.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.plugin; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; + +/** + * GetPluginName Interface + */ +public interface IGetPluginName { + /** + * getPluginName + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param processInfo processInfo + * @return String + */ + String getPluginName(DeviceIPPortInfo deviceIPPortInfo, ProcessInfo processInfo); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IPluginConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IPluginConfig.java new file mode 100644 index 000000000..197cf8eba --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/IPluginConfig.java @@ -0,0 +1,38 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.plugin; + +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; + +/** + * IPluginConfig + */ +public abstract class IPluginConfig { + /** + * registerPlugin + */ + public void registerPlugin() { + PlugManager.getInstance().registerPlugin(createConfig()); + } + + /** + * createConfig + * + * @return PluginConf + */ + public abstract PluginConf createConfig(); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ISpecialStartPlugMethod.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ISpecialStartPlugMethod.java new file mode 100644 index 000000000..e7273ded7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/ISpecialStartPlugMethod.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.plugin; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; + +/** + * ISpecialStartPlugMethod + */ +public interface ISpecialStartPlugMethod { + /** + * specialStartPlugMethod + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param processInfo processInfo + * @return boolean + */ + boolean specialStartPlugMethod(DeviceIPPortInfo deviceIPPortInfo, ProcessInfo processInfo); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/dao/PlugDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/dao/PlugDao.java deleted file mode 100644 index bf494a0e9..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/dao/PlugDao.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.plugin.dao; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPlugin; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; - -/** - * 插件dao层(与sqlite交互) - * - * @version 1.0 - * @date 2021/2/2 15:10 - **/ -public class PlugDao extends AbstractDataStore { - // 日志 - private static final Logger LOGGER = LogManager.getLogger(PlugDao.class); - - private static volatile PlugDao singleton; - - /** - * getInstance - * - * @return PlugDao - */ - public static PlugDao getInstance() { - if (singleton == null) { - synchronized (PlugDao.class) { - if (singleton == null) { - singleton = new PlugDao(); - } - } - } - return singleton; - } - - private PlugDao() { - } - - /** - * 插入自研插件Info信息 - * - * @param hiProfilerPlugin hiProfilerPlugin - * @return boolean - */ - public boolean insertPlugInfo(HiProfilerPlugin hiProfilerPlugin) { - boolean insert = false; - insert = insert(hiProfilerPlugin); - - return insert; - } - - /** - * 保存插件Info信息 - * - * @param deviceId deviceId - * @return List - */ - public List selectPlugConfig(String deviceId) { - return new ArrayList<>(); - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/DPlugin.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/DPlugin.java new file mode 100644 index 000000000..b29fe2257 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/DPlugin.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.plugin.entity; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * DPlugin + */ +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface DPlugin { + String name() default ""; +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPlugin.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPlugin.java deleted file mode 100644 index 5d895123d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPlugin.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.plugin.entity; - -import java.util.Arrays; - -/** - * 自研插件的实体类 - * - * @version 1.0 - * @date 2021/2/2 19:03 - **/ -public final class HiProfilerPlugin { - // 设备id - private String deviceId; - - // 插件的基本属性 - private int plugId; - - // 插件的名称 - private String name; - - // 插件的路径 - private String path; - - // 插件的状态 - private int status; - - // 插件的版本 - private String version; - - // 插件的签名 - private String plugSha256; - - // 插件的采集频率 - private int sampleInterval; - - // 插件的采集项配置 - private byte[] configData; - - /** - * 构建方法 - * - * @return Builder - */ - public static Builder builder() { - return new Builder(); - } - - public String getDeviceId() { - return deviceId; - } - - public int getPlugId() { - return plugId; - } - - public String getName() { - return name; - } - - public String getVersion() { - return version; - } - - public int getStatus() { - return status; - } - - public String getPlugSha256() { - return plugSha256; - } - - public int getSampleInterval() { - return sampleInterval; - } - - public byte[] getConfigData() { - if (configData != null) { - return Arrays.copyOf(configData, configData.length); - } else { - return new byte[0]; - } - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - private HiProfilerPlugin(Builder builder) { - deviceId = builder.deviceId; - plugId = builder.plugId; - name = builder.name; - path = builder.path; - status = builder.status; - version = builder.version; - plugSha256 = builder.plugSha256; - sampleInterval = builder.sampleInterval; - configData = builder.configData; - } - - @Override - public String toString() { - return "HiProfilerPlugin{" + "deviceId='" + deviceId + '\'' + ", plugId=" + plugId + ", name='" + name + '\'' - + ", path='" + path + '\'' + ", status=" + status + ", version='" + version + '\'' + ", plugSha256='" - + plugSha256 + '\'' + ", sampleInterval=" + sampleInterval + ", configData=" + Arrays.toString(configData) - + '}'; - } - - /** - * @ClassName: Builder - * @Description: HiProfilerPlugin自研插件的build类 - * @Date: 2021/2/2 19:11 - */ - public static final class Builder { - // 设备id - private String deviceId; - - // 插件的id - private int plugId; - - // 插件的名称 - private String name; - - // 插件的路径 - private String path; - - // 插件的状态 - private int status; - - // 插件的版本 - private String version; - - // 插件的签名 - private String plugSha256; - - // 插件的采集频率 - private int sampleInterval; - - // 插件的采集项配置 - private byte[] configData; - - private Builder() { - } - - /** - * deviceId - * - * @param id id - * @return Builder - */ - public Builder deviceId(String id) { - this.deviceId = id; - return this; - } - - /** - * id方法 - * - * @param pluginId pluginId - * @return Builder - */ - public Builder id(int pluginId) { - this.plugId = pluginId; - return this; - } - - /** - * name - * - * @param plugName plugName - * @return Builder - */ - public Builder name(String plugName) { - this.name = plugName; - return this; - } - - /** - * 路径 - * - * @param path path - * @return Builder - */ - public Builder path(String path) { - this.path = path; - return this; - } - - /** - * version - * - * @param plugVersion plugVersion - * @return Builder - */ - public Builder version(String plugVersion) { - this.version = plugVersion; - return this; - } - - /** - * 插件的状态 - * - * @param plugStatus plugStatus - * @return Builder - */ - public Builder status(int plugStatus) { - this.status = plugStatus; - return this; - } - - /** - * plugSha256 - * - * @param pluginSha256 pluginSha256 - * @return Builder - */ - public Builder plugSha256(String pluginSha256) { - this.plugSha256 = pluginSha256; - return this; - } - - /** - * sampleInterval - * - * @param pluginSampleInterval pluginSampleInterval - * @return Builder - */ - public Builder sampleInterval(int pluginSampleInterval) { - this.sampleInterval = pluginSampleInterval; - return this; - } - - /** - * 配置数据 - * - * @param data data - * @return Builder - */ - public Builder configData(byte[] data) { - if (data != null) { - this.configData = Arrays.copyOf(data, data.length); - } else { - this.configData = new byte[0]; - } - return this; - } - - /** - * build - * - * @return HiProfilerPlugin - */ - public HiProfilerPlugin build() { - return new HiProfilerPlugin(this); - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPluginConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPluginConfig.java new file mode 100644 index 000000000..793d936df --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/HiProfilerPluginConfig.java @@ -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. + */ + +package ohos.devtools.datasources.utils.plugin.entity; + +import com.google.protobuf.ByteString; + +/** + * HiProfilerPluginConfig + */ +public class HiProfilerPluginConfig { + private int sampleInterval; + private ByteString confData; + + /** + * HiProfilerPluginConfig + * + * @param sampleInterval sampleInterval + * @param confData confData + */ + public HiProfilerPluginConfig(int sampleInterval, ByteString confData) { + this.sampleInterval = sampleInterval; + this.confData = confData; + } + + public int getSampleInterval() { + return sampleInterval; + } + + public ByteString getConfData() { + return confData; + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginBufferConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginBufferConfig.java new file mode 100644 index 000000000..86c56a81e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginBufferConfig.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.plugin.entity; + +/** + * PluginBufferConfig + */ +public class PluginBufferConfig { + private int pages; + private Policy policy; + + /** + * PluginBufferConfig + * + * @param pages pages + * @param policy policy + */ + public PluginBufferConfig(int pages, Policy policy) { + this.pages = pages; + this.policy = policy; + } + + public int getPages() { + return pages; + } + + public Policy getPolicy() { + return policy; + } + + /** + * Policy + */ + public enum Policy { + RECYCLE, FLATTEN; + + Policy() { + } + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginConf.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginConf.java new file mode 100644 index 000000000..d210d546a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginConf.java @@ -0,0 +1,338 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.plugin.entity; + +import ohos.devtools.datasources.utils.datahandler.datapoller.AbsDataConsumer; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.plugin.ICreatePluginConfig; +import ohos.devtools.datasources.utils.plugin.IGetPluginName; +import ohos.devtools.datasources.utils.plugin.ISpecialStartPlugMethod; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; + +import java.util.ArrayList; +import java.util.List; + +/** + * PluginConf + */ +public final class PluginConf { + private String pluginFileName; + private String pluginDataName; + private IGetPluginName IGetPluginName; + private boolean isEnable = true; + private PluginMode pluginMode; + private Class consumerClass; + private boolean isChartPlugin; + private ProfilerMonitorItem monitorItem; + private PluginBufferConfig pluginBufferConfig; + private ICreatePluginConfig ICreatePluginConfig; + private boolean isSpecialStart; + private ISpecialStartPlugMethod ISpecialStartPlugMethod; + private boolean isAlwaysAdd; + private boolean operationStart = false; + private List supportDeviceTypes = new ArrayList<>(); + + /** + * PluginConf + * + * @param pluginFileName pluginFileName + * @param pluginDataName pluginDataName + * @param consumerClass consumerClass + * @param isChartPlugin isChartPlugin + * @param monitorItem monitorItem + */ + public PluginConf(String pluginFileName, String pluginDataName, Class consumerClass, + boolean isChartPlugin, ProfilerMonitorItem monitorItem) { + this.pluginFileName = pluginFileName; + this.pluginDataName = pluginDataName; + this.consumerClass = consumerClass; + this.isChartPlugin = isChartPlugin; + this.monitorItem = monitorItem; + } + + /** + * get PluginMode + * + * @return pluginMode + */ + public PluginMode getPluginMode() { + return pluginMode; + } + + /** + * set PluginMode + * + * @param pluginMode pluginMode + */ + public void setPluginMode(PluginMode pluginMode) { + this.pluginMode = pluginMode; + } + + /** + * get MonitorItem + * + * @return monitorItem + */ + public ProfilerMonitorItem getMonitorItem() { + return monitorItem; + } + + /** + * set MonitorItem + * + * @param monitorItem monitorItem + */ + public void setMonitorItem(ProfilerMonitorItem monitorItem) { + this.monitorItem = monitorItem; + } + + /** + * is ChartPlugin + * + * @return isChartPlugin + */ + public boolean isChartPlugin() { + return isChartPlugin; + } + + /** + * set ChartPlugin + * + * @param chartPlugin chartPlugin + */ + public void setChartPlugin(boolean chartPlugin) { + isChartPlugin = chartPlugin; + } + + /** + * get PluginBufferConfig + * + * @return PluginBufferConfig + */ + public PluginBufferConfig getPluginBufferConfig() { + if (pluginBufferConfig == null) { + return new PluginBufferConfig(10, PluginBufferConfig.Policy.RECYCLE); + } + return pluginBufferConfig; + } + + /** + * set PluginBufferConfig + * + * @param pluginBufferConfig pluginBufferConfig + */ + public void setPluginBufferConfig(PluginBufferConfig pluginBufferConfig) { + this.pluginBufferConfig = pluginBufferConfig; + } + + /** + * ICreatePluginConfig + * + * @return ICreatePluginConfig + */ + public ICreatePluginConfig getICreatePluginConfig() { + return ICreatePluginConfig; + } + + /** + * set ICreatePluginConfig + * + * @param ICreatePluginConfig ICreatePluginConfig + */ + public void setICreatePluginConfig(ICreatePluginConfig ICreatePluginConfig) { + this.ICreatePluginConfig = ICreatePluginConfig; + } + + /** + * get PluginFileName + * + * @return String + */ + public String getPluginFileName() { + return pluginFileName; + } + + /** + * set PluginFileName + * + * @param pluginFileName pluginFileName + */ + public void setPluginFileName(String pluginFileName) { + this.pluginFileName = pluginFileName; + } + + /** + * get PluginDataName + * + * @return String + */ + public String getPluginDataName() { + return pluginDataName; + } + + /** + * isSpecialStart + * + * @return boolean + */ + public boolean isSpecialStart() { + return isSpecialStart; + } + + /** + * set SpecialStart + * + * @param specialStart specialStart + */ + public void setSpecialStart(boolean specialStart) { + isSpecialStart = specialStart; + } + + /** + * getSpecialStartPlugMethod + * + * @return ISpecialStartPlugMethod + */ + public ISpecialStartPlugMethod getSpecialStartPlugMethod() { + return ISpecialStartPlugMethod; + } + + /** + * setSpecialStartPlugMethod + * + * @param ISpecialStartPlugMethod ISpecialStartPlugMethod + */ + public void setSpecialStartPlugMethod(ISpecialStartPlugMethod ISpecialStartPlugMethod) { + this.ISpecialStartPlugMethod = ISpecialStartPlugMethod; + } + + /** + * setPluginDataName + * + * @param pluginDataName pluginDataName + */ + public void setPluginDataName(String pluginDataName) { + this.pluginDataName = pluginDataName; + } + + /** + * isEnable + * + * @return boolean boolean + */ + public boolean isEnable() { + return isEnable; + } + + /** + * setEnable + * + * @param enable enable + */ + public void setEnable(boolean enable) { + isEnable = enable; + } + + /** + * getConsumerClass + * + * @return Class + */ + public Class getConsumerClass() { + return consumerClass; + } + + /** + * setConsumerClass + * + * @param consumerClass consumerClass + */ + public void setConsumerClass(Class consumerClass) { + this.consumerClass = consumerClass; + } + + /** + * getSupportDeviceTypes + * + * @return List + */ + public List getSupportDeviceTypes() { + return supportDeviceTypes; + } + + /** + * addSupportDeviceTypes + * + * @param supportDeviceTypes supportDeviceTypes + */ + public void addSupportDeviceTypes(DeviceType supportDeviceTypes) { + this.supportDeviceTypes.add(supportDeviceTypes); + } + + /** + * setGetPluginName + * + * @param IGetPluginName IGetPluginName + */ + public void setGetPluginName(IGetPluginName IGetPluginName) { + this.IGetPluginName = IGetPluginName; + } + + /** + * getGetPluginName + * + * @return IGetPluginName + */ + public IGetPluginName getGetPluginName() { + return IGetPluginName; + } + + /** + * isAlwaysAdd + * + * @return boolean + */ + public boolean isAlwaysAdd() { + return isAlwaysAdd; + } + + /** + * setAlwaysAdd + * + * @param alwaysAdd alwaysAdd + */ + public void setAlwaysAdd(boolean alwaysAdd) { + isAlwaysAdd = alwaysAdd; + } + + /** + * isOperationStart + * + * @return boolean + */ + public boolean isOperationStart() { + return operationStart; + } + + /** + * setOperationStart + * + * @param operationStart operationStart + */ + public void setOperationStart(boolean operationStart) { + this.operationStart = operationStart; + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceService.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginMode.java similarity index 77% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceService.java rename to host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginMode.java index 324484cd8..0d395e54c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/bytrace/BytraceService.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/entity/PluginMode.java @@ -13,11 +13,17 @@ * limitations under the License. */ -package ohos.devtools.services.bytrace; +package ohos.devtools.datasources.utils.plugin.entity; /** - * @Description Bytrace业务处理类 - * @Date 2021/2/7 13:43 - **/ -public class BytraceService { -} + * PluginMode + */ +public enum PluginMode { + OFFLINE, ONLINE; + + /** + * PluginMode + */ + PluginMode() { + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/service/PlugManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/service/PlugManager.java index 57c50dd70..e60068166 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/service/PlugManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/plugin/service/PlugManager.java @@ -1,81 +1,198 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.plugin.service; - -import ohos.devtools.datasources.utils.plugin.dao.PlugDao; -import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPlugin; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; - -/** - * 对插件和其配置的管理 - * - * @version 1.0 - * @Date 2021/2/2 15:17 - **/ -public class PlugManager { - // 日志 - private static final Logger LOGGER = LogManager.getLogger(PlugManager.class); - - // 单例 - private static volatile PlugManager singleton; - - /** - * 获取实例 - * - * @return PlugManager - */ - public static PlugManager getInstance() { - if (singleton == null) { - synchronized (PlugManager.class) { - if (singleton == null) { - singleton = new PlugManager(); - } - } - } - return singleton; - } - - private PlugManager() { - } - - /** - * 自研插件配置信息写表 - * - * @param plugin plugin - * @return boolean - */ - public boolean insertPlugInfo(HiProfilerPlugin plugin) { - boolean insert = false; - insert = PlugDao.getInstance().insertPlugInfo(plugin); - return insert; - } - - /** - * 对外提供插件配置信息查询的接口 - * - * @param deviceId deviceId - * @return List HiProfilerPlugin - */ - public List selectPlugConfig(String deviceId) { - List hiProfilerPlugins = new ArrayList<>(); - hiProfilerPlugins = PlugDao.getInstance().selectPlugConfig(deviceId); - return hiProfilerPlugins; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.plugin.service; + +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import org.apache.commons.collections.map.MultiValueMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * PlugManager + */ +public class PlugManager { + private static final Logger LOGGER = LogManager.getLogger(PlugManager.class); + private static volatile PlugManager singleton; + private MultiValueMap profilerConfigMap = new MultiValueMap(); + private List confLists = new ArrayList<>(); + + /** + * get Instance + * + * @return PlugManager + */ + public static PlugManager getInstance() { + if (singleton == null) { + synchronized (PlugManager.class) { + if (singleton == null) { + singleton = new PlugManager(); + } + } + } + return singleton; + } + + private PlugManager() { + } + + /** + * get Plugin Config + * + * @param deviceType deviceType + * @param pluginMode pluginMode + * @return List + */ + public List getPluginConfig(DeviceType deviceType, PluginMode pluginMode) { + if (Objects.isNull(pluginMode)) { + return confLists.stream().filter(hiProfilerPluginConf -> { + List supportDeviceTypes = hiProfilerPluginConf.getSupportDeviceTypes(); + if (supportDeviceTypes.isEmpty()) { + return hiProfilerPluginConf.isEnable(); + } else { + return supportDeviceTypes.contains(deviceType) && hiProfilerPluginConf.isEnable(); + } + }).collect(Collectors.toList()); + } + return confLists.stream().filter(hiProfilerPluginConf -> { + List supportDeviceTypes = hiProfilerPluginConf.getSupportDeviceTypes(); + if (supportDeviceTypes.isEmpty()) { + return hiProfilerPluginConf.isEnable() && hiProfilerPluginConf.getPluginMode() == pluginMode; + } else { + return supportDeviceTypes.contains(deviceType) && hiProfilerPluginConf.isEnable() + && hiProfilerPluginConf.getPluginMode() == pluginMode; + } + }).collect(Collectors.toList()); + } + + /** + * loadingPlug + * + * @param pluginConfigs pluginConfigs + */ + public void loadingPlugs(List> pluginConfigs) { + if (pluginConfigs != null && pluginConfigs.size() > 0) { + for (Class pluginConfigPackage : pluginConfigs) { + IPluginConfig config; + try { + if (pluginConfigPackage != null) { + config = pluginConfigPackage.getConstructor().newInstance(); + config.registerPlugin(); + } + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) { + LOGGER.error("registerPlugin exception {}", exception.getMessage()); + continue; + } + } + } + } + + /** + * loadingPlug + * + * @param pluginConfig pluginConfig + */ + public void loadingPlug(Class pluginConfig) { + IPluginConfig config; + try { + if (pluginConfig != null) { + config = pluginConfig.getConstructor().newInstance(); + config.registerPlugin(); + } + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) { + LOGGER.error("registerPlugin exception {}", exception.getMessage()); + } + } + + /** + * registerPlugin + * + * @param pluginConf pluginConf + */ + public void registerPlugin(PluginConf pluginConf) { + confLists.add(pluginConf); + } + + /** + * Add a plug-in that started successfully + * + * @param sessionId sessionId + * @param pluginConf hiProfilerPluginConf + */ + public void addPluginStartSuccess(long sessionId, PluginConf pluginConf) { + profilerConfigMap.put(sessionId, pluginConf); + } + + /** + * getProfilerMonitorItemMap + * + * @param sessionId sessionId + * @return List + */ + public List getProfilerPlugConfig(long sessionId) { + Collection collection = profilerConfigMap.getCollection(sessionId); + if (Objects.nonNull(collection)) { + return collection.stream().collect(Collectors.toList()); + } + return new ArrayList(); + } + + /** + * getProfilerMonitorItemMap + * + * @param sessionId sessionId + * @return List + */ + public List getProfilerMonitorItemList(long sessionId) { + Collection collection = profilerConfigMap.getCollection(sessionId); + if (Objects.nonNull(collection)) { + List itemList = collection.stream().filter( + hiProfilerPluginConf -> hiProfilerPluginConf.isChartPlugin() && Objects + .nonNull(hiProfilerPluginConf.getMonitorItem())) + .map(hiProfilerPluginConf -> hiProfilerPluginConf.getMonitorItem()).collect(Collectors.toList()); + if (Objects.nonNull(itemList)) { + return itemList.stream().sorted(Comparator.comparingInt(ProfilerMonitorItem::getIndex)) + .collect(Collectors.toList()); + } + } + return new ArrayList<>(); + } + + /** + * clear Profiler Monitor ItemMap + */ + public void clearProfilerMonitorItemMap() { + profilerConfigMap.clear(); + } + + /** + * clear PluginConf List + */ + public void clearPluginConfList() { + confLists.clear(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/entity/ProcessInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/entity/ProcessInfo.java index 7309251b6..b5fe934fc 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/entity/ProcessInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/entity/ProcessInfo.java @@ -1,95 +1,92 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.process.entity; - -/** - * 进程实体 - * - * @version 1.0 - * @date 2021/02/07 11:00 - **/ -public class ProcessInfo { - private String deviceId; - private Integer processId; - private String processName; - private Integer state; - private Integer startTime; - private String arch; - private String agentStatus; - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public Integer getProcessId() { - return processId; - } - - public void setProcessId(Integer processId) { - this.processId = processId; - } - - public String getProcessName() { - return processName; - } - - public void setProcessName(String processName) { - this.processName = processName; - } - - public Integer getState() { - return state; - } - - public void setState(Integer state) { - this.state = state; - } - - public Integer getStartTime() { - return startTime; - } - - public void setStartTime(Integer startTime) { - this.startTime = startTime; - } - - public String getArch() { - return arch; - } - - public void setArch(String arch) { - this.arch = arch; - } - - public String getAgentStatus() { - return agentStatus; - } - - public void setAgentStatus(String agentStatus) { - this.agentStatus = agentStatus; - } - - @Override - public String toString() { - return "ProcessInfo{" + "deviceId='" + deviceId + '\'' + ", processId=" + processId + ", processName='" - + processName + '\'' + ", state=" + state + ", startTime=" + startTime + ", arch='" + arch + '\'' - + ", agentStatus='" + agentStatus + '\'' + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.process.entity; + +/** + * 进程实体 + */ +public class ProcessInfo { + private String deviceId; + private Integer processId; + private String processName; + private Integer state; + private Integer startTime; + private String arch; + private String agentStatus; + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public Integer getProcessId() { + return processId; + } + + public void setProcessId(Integer processId) { + this.processId = processId; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public Integer getState() { + return state; + } + + public void setState(Integer state) { + this.state = state; + } + + public Integer getStartTime() { + return startTime; + } + + public void setStartTime(Integer startTime) { + this.startTime = startTime; + } + + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } + + public String getAgentStatus() { + return agentStatus; + } + + public void setAgentStatus(String agentStatus) { + this.agentStatus = agentStatus; + } + + @Override + public String toString() { + return "ProcessInfo{" + "deviceId='" + deviceId + '\'' + ", processId=" + processId + ", processName='" + + processName + '\'' + ", state=" + state + ", startTime=" + startTime + ", arch='" + arch + '\'' + + ", agentStatus='" + agentStatus + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/service/ProcessManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/service/ProcessManager.java index 4f9402813..ae6733abf 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/service/ProcessManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/process/service/ProcessManager.java @@ -1,112 +1,126 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.process.service; - -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.device.dao.DeviceUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.List; - -/** - * 进程数据处理对象 - * - * @version 1.0 - * @date 2021/02/07 11:06 - **/ -public class ProcessManager { - private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); - - /** - * 单例进程对象 - */ - private static class SingletonClassInstance { - private static final ProcessManager INSTANCE = new ProcessManager(); - } - - /** - * getInstance - * - * @return ProcessManager - */ - public static ProcessManager getInstance() { - return ProcessManager.SingletonClassInstance.INSTANCE; - } - - private ProcessManager() { - } - - /** - * 调用接口,获取进程列表详情数据 - * - * @param deviceInfo 设备对象 - * @return List - * @date 2021/02/07 11:06 - */ - public List getProcessList(DeviceIPPortInfo deviceInfo) { - LOGGER.info("start to GetProcessList {}", DateTimeUtil.getNowTimeLong()); - if (deviceInfo == null || StringUtils.isBlank(deviceInfo.getIp())) { - return new ArrayList(); - } - String deviceId = deviceInfo.getDeviceID(); - DeviceIPPortInfo deviceIPPortInfo = new DeviceUtil().getDeviceIPPortInfo(deviceId); - ProfilerServiceTypes.GetCapabilitiesResponse response = - HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - List capabilities = response.getCapabilitiesList(); - List processInfos = new ArrayList<>(); - for (ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability : capabilities) { - LOGGER.info("get Device capabilities {}", profilerPluginCapability.getName()); - if (profilerPluginCapability.getName().contains("libmemdataplugin")) { - LOGGER.info("process Session start", DateTimeUtil.getNowTimeLong()); - int sessionId = HiProfilerClient.getInstance() - .requestCreateSession(deviceIPPortInfo.getForwardPort(), profilerPluginCapability.getName(), 0, - true, deviceInfo.getDeviceType()); - if (sessionId == -1) { - LOGGER.info("createSession failed"); - return processInfos; - } - boolean startResult = HiProfilerClient.getInstance() - .requestStartSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); - if (startResult) { - processInfos = HiProfilerClient.getInstance() - .fetchProcessData(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); - } - Long stopTime = DateTimeUtil.getNowTimeLong(); - LOGGER.info("startStopSession {}", stopTime); - boolean stopRes = HiProfilerClient.getInstance() - .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, false); - - LOGGER.info("startStopEndSession {}", DateTimeUtil.getNowTimeLong()); - boolean request = HiProfilerClient.getInstance() - .requestDestroySession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); - boolean res = HiProfilerClient.getInstance() - .destroyProfiler(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - LOGGER.info("get ProcessList is {}", processInfos); - return processInfos; - } - } - LOGGER.info("end to GetProcessList {}", DateTimeUtil.getNowTimeLong()); - return processInfos; - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.process.service; + +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.device.dao.DeviceDao; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * 进程数据处理对象 + */ +public class ProcessManager { + private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); + private static final String MEM_PLUGIN_NAME = "/data/local/tmp/libmemdataplugin.z.so"; + + private boolean isRequestProcess = false; + + /** + * 单例进程对象 + */ + private static class SingletonClassInstance { + private static final ProcessManager INSTANCE = new ProcessManager(); + } + + /** + * getInstance + * + * @return ProcessManager + */ + public static ProcessManager getInstance() { + return ProcessManager.SingletonClassInstance.INSTANCE; + } + + private ProcessManager() { + } + + /** + * getProcessList + * + * @param deviceInfo deviceInfo + * @return List + */ + public List getProcessList(DeviceIPPortInfo deviceInfo) { + LOGGER.info("start to GetProcessList {}", DateTimeUtil.getNowTimeLong()); + if (deviceInfo == null || StringUtils.isBlank(deviceInfo.getIp())) { + return new ArrayList(); + } + String deviceId = deviceInfo.getDeviceID(); + DeviceIPPortInfo deviceIPPortInfo = new DeviceDao().getDeviceIPPortInfo(deviceId).get(); + ProfilerServiceTypes.GetCapabilitiesResponse response = + HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); + List capabilities = response.getCapabilitiesList(); + Optional libPlugin = getLibPlugin(capabilities, MEM_PLUGIN_NAME); + List processInfos = new ArrayList<>(); + try { + if (libPlugin.isPresent()) { + LOGGER.info("process Session start", DateTimeUtil.getNowTimeLong()); + isRequestProcess = true; + int sessionId = HiProfilerClient.getInstance() + .requestCreateSession(deviceIPPortInfo.getForwardPort(), libPlugin.get().getName(), 0, + true, deviceInfo.getDeviceType()); + if (sessionId == -1) { + LOGGER.info("createSession failed"); + return processInfos; + } + boolean startResult = HiProfilerClient.getInstance() + .requestStartSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); + if (startResult) { + processInfos = HiProfilerClient.getInstance() + .fetchProcessData(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); + } + Long stopTime = DateTimeUtil.getNowTimeLong(); + LOGGER.info("startStopSession {}", stopTime); + HiProfilerClient.getInstance() + .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, false); + LOGGER.info("startStopEndSession {}", DateTimeUtil.getNowTimeLong()); + HiProfilerClient.getInstance() + .requestDestroySession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); + return processInfos; + } + } finally { + isRequestProcess = false; + } + LOGGER.info("end to GetProcessList {}", DateTimeUtil.getNowTimeLong()); + return processInfos; + } + + private Optional getLibPlugin( + List capabilities, String libDataPlugin) { + Optional ability = capabilities.stream() + .filter(profilerPluginCapability -> profilerPluginCapability.getName().contains(libDataPlugin)).findFirst(); + return ability; + } + + /** + * isRequestProcess + * + * @return boolean boolean + */ + public boolean isRequestProcess() { + return isRequestProcess; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManager.java index 9138eb0b8..eec74b2ea 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManager.java @@ -1,84 +1,83 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.profilerlog; - -import ohos.devtools.datasources.utils.process.service.ProcessManager; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.LoggerConfig; - -/** - * @version 1.0 - * @date 2021/03/12 12:31 - **/ -public class ProfilerLogManager { - private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); - - /** - * 单例进程对象 - */ - private static ProfilerLogManager singleton = null; - - public static ProfilerLogManager getSingleton() { - if (singleton == null) { - synchronized (ProfilerLogManager.class) { - if (singleton == null) { - singleton = new ProfilerLogManager(); - } - } - } - return singleton; - } - - private Level nowLogLevel = Level.ERROR; - - /** - * 修改日志等级 - * - * @param logLevel loglevel - * @return boolean - */ - public boolean updateLogLevel(Level logLevel) { - if (logLevel == null) { - return false; - } - org.apache.logging.log4j.spi.LoggerContext context = LogManager.getContext(false); - LoggerContext loggerContext = null; - if (context instanceof LoggerContext) { - loggerContext = (LoggerContext) context; - } else { - return false; - } - Configuration config = loggerContext.getConfiguration(); - LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); - loggerConfig.setLevel(logLevel); - loggerContext.updateLoggers(); - nowLogLevel = logLevel; - return true; - } - - /** - * getNowLogLevel - * - * @return Level - */ - public Level getNowLogLevel() { - return nowLogLevel; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.profilerlog; + +import ohos.devtools.datasources.utils.process.service.ProcessManager; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.LoggerConfig; + +/** + * ProfilerLogManager + */ +public class ProfilerLogManager { + private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); + + /** + * 单例进程对象 + */ + private static ProfilerLogManager singleton = null; + + public static ProfilerLogManager getSingleton() { + if (singleton == null) { + synchronized (ProfilerLogManager.class) { + if (singleton == null) { + singleton = new ProfilerLogManager(); + } + } + } + return singleton; + } + + private Level nowLogLevel = Level.ERROR; + + /** + * 修改日志等级 + * + * @param logLevel loglevel + * @return boolean + */ + public boolean updateLogLevel(Level logLevel) { + if (logLevel == null) { + return false; + } + org.apache.logging.log4j.spi.LoggerContext context = LogManager.getContext(false); + LoggerContext loggerContext = null; + if (context instanceof LoggerContext) { + loggerContext = (LoggerContext) context; + } else { + return false; + } + Configuration config = loggerContext.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); + loggerConfig.setLevel(logLevel); + loggerContext.updateLoggers(); + nowLogLevel = logLevel; + return true; + } + + /** + * getNowLogLevel + * + * @return Level + */ + public Level getNowLogLevel() { + return nowLogLevel; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManager.java index 90c213f3c..7214d464f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManager.java @@ -1,125 +1,138 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.quartzmanager; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * timed task management - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class QuartzManager { - /** - * DELAY - */ - public static final int DELAY = 0; - - /** - * PERIOD - */ - public static final int PERIOD = 500; - private static final Logger LOGGER = LogManager.getLogger(QuartzManager.class); - private static final long DEFAULT_KEEPALIVE_MILLIS = 10L; - private static volatile QuartzManager instance; - - /** - * getInstance - * - * @return QuartzManager - */ - public static QuartzManager getInstance() { - if (instance == null) { - synchronized (QuartzManager.class) { - if (instance == null) { - instance = new QuartzManager(); - } - } - } - return instance; - } - - private Map runnableHashMap = new ConcurrentHashMap(); - - private Map executorHashMap = - new ConcurrentHashMap(); - - /** - * execution - * - * @param runName runName - * @param runnable runnable - */ - public void addExecutor(String runName, Runnable runnable) { - LOGGER.debug("add scheduleWithFixedDelay{}", runName); - ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(1); - executorHashMap.put(runName, scheduled); - runnableHashMap.put(runName, runnable); - } - - /** - * begin Execution - * - * @param runName runName - * @param delay delay - * @param period period - */ - public void startExecutor(String runName, long delay, long period) { - ScheduledExecutorService scheduled = executorHashMap.get(runName); - Runnable runnable = runnableHashMap.get(runName); - if (delay > 0) { - LOGGER.debug("scheduleWithFixedDelay start {}", delay); - scheduled.scheduleWithFixedDelay(runnable, delay, period, TimeUnit.MILLISECONDS); - } else { - LOGGER.debug("scheduleAtFixedRate start {}", delay); - scheduled.scheduleAtFixedRate(runnable, 0, period, TimeUnit.MILLISECONDS); - } - } - - /** - * deleteExecutor - * - * @param runName runName - */ - public void deleteExecutor(String runName) { - executorHashMap.get(runName).shutdown(); - if (runnableHashMap != null && runnableHashMap.size() != 0) { - runnableHashMap.remove(runName); - } - if (executorHashMap != null && executorHashMap.size() != 0) { - executorHashMap.remove(runName); - } - } - - /** - * endExecutor - * - * @param runName runName - */ - public void endExecutor(String runName) { - LOGGER.debug("endScheduledExecutor{}", runName); - executorHashMap.get(runName).shutdown(); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.quartzmanager; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * timed task management + */ +public class QuartzManager { + /** + * DELAY + */ + public static final int DELAY = 0; + + /** + * PERIOD + */ + public static final int PERIOD = 3000; + private static final Logger LOGGER = LogManager.getLogger(QuartzManager.class); + private static final long DEFAULT_KEEPALIVE_MILLIS = 10L; + private static volatile QuartzManager instance; + + /** + * getInstance + * + * @return QuartzManager + */ + public static QuartzManager getInstance() { + if (instance == null) { + synchronized (QuartzManager.class) { + if (instance == null) { + instance = new QuartzManager(); + } + } + } + return instance; + } + + private Map runnableHashMap = new ConcurrentHashMap(); + + private Map executorHashMap = + new ConcurrentHashMap(); + + /** + * execution + * + * @param runName runName + * @param runnable runnable + */ + public void addExecutor(String runName, Runnable runnable) { + LOGGER.debug("add scheduleWithFixedDelay{}", runName); + ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(1); + executorHashMap.put(runName, scheduled); + runnableHashMap.put(runName, runnable); + } + + /** + * begin Execution + * + * @param runName runName + * @param delay delay + * @param period period + */ + public void startExecutor(String runName, long delay, long period) { + ScheduledExecutorService scheduled = executorHashMap.get(runName); + Runnable runnable = runnableHashMap.get(runName); + if (delay > 0) { + LOGGER.debug("scheduleWithFixedDelay start {}", delay); + scheduled.scheduleWithFixedDelay(runnable, delay, period, TimeUnit.MILLISECONDS); + } else { + LOGGER.debug("scheduleAtFixedRate start {}", delay); + scheduled.scheduleAtFixedRate(runnable, 0, period, TimeUnit.MILLISECONDS); + } + } + + /** + * deleteExecutor + * + * @param runName runName + */ + public void deleteExecutor(String runName) { + ScheduledExecutorService scheduledExecutorService = executorHashMap.get(runName); + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + if (executorHashMap != null && executorHashMap.size() != 0) { + executorHashMap.remove(runName); + } + if (runnableHashMap != null && runnableHashMap.size() != 0) { + runnableHashMap.remove(runName); + } + } + } + + /** + * endExecutor + * + * @param runName runName + */ + public void endExecutor(String runName) { + ScheduledExecutorService scheduledExecutorService = executorHashMap.get(runName); + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + } + } + + /** + * checkService + * + * @param runName runName + * @return ScheduledExecutorService + */ + public Optional checkService(String runName) { + ScheduledExecutorService scheduledExecutorService = executorHashMap.get(runName); + return Optional.ofNullable(scheduledExecutorService); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/KeepSession.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/KeepSession.java new file mode 100644 index 000000000..f861c2b29 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/KeepSession.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.datasources.utils.session; + +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * KeepSession + */ +public class KeepSession implements Runnable { + private static final Logger LOGGER = LogManager.getLogger(KeepSession.class); + private final long localSessionId; + private final int sessionId; + private final DeviceIPPortInfo deviceIPPortInfo; + + /** + * KeepSession + * + * @param localSessionId localSessionId + * @param sessionId sessionId + * @param deviceIPPortInfo deviceIPPortInfo + */ + public KeepSession(long localSessionId, int sessionId, DeviceIPPortInfo deviceIPPortInfo) { + this.localSessionId = localSessionId; + this.sessionId = sessionId; + this.deviceIPPortInfo = deviceIPPortInfo; + } + + @Override + public void run() { + try { + ProfilerServiceTypes.KeepSessionResponse keepSessionResponse = HiProfilerClient.getInstance() + .keepSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId); + } catch (StatusRuntimeException exception) { + LOGGER.error("KeepSession StatusRuntimeException ", exception); + String keepSessionName = SessionManager.getInstance().getKeepSessionName(deviceIPPortInfo, sessionId); + QuartzManager.getInstance().deleteExecutor(keepSessionName); + SessionManager.getInstance().deleteLocalSession(localSessionId); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/entity/SessionInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/entity/SessionInfo.java index 527413318..06ee1e559 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/entity/SessionInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/entity/SessionInfo.java @@ -1,299 +1,259 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.session.entity; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.views.common.LayoutConstants; - -/** - * SessionInfo实体 - * - * @version 1.0 - * @date 2021/2/25 10:50 - **/ -public class SessionInfo { - private static SessionInfo defaultSession; - - /** - * builder - * - * @return Builder - */ - public static Builder builder() { - return new Builder(); - } - - /** - * getDefaultInstance - * - * @return SessionInfo - */ - public static SessionInfo getDefaultInstance() { - if (defaultSession == null) { - defaultSession = SessionInfo.builder().build(); - } - return defaultSession; - } - - /** - * Builder - */ - public static class Builder { - private String sessionName; - private int sessionId; - private long startTimestamp; - private long endTimestamp; - private long streamId; - private long pid; - private DeviceIPPortInfo deviceIPPortInfo; - - private Builder() { - } - - /** - * sessionName - * - * @param sessionName sessionName - * @return Builder - */ - public Builder sessionName(String sessionName) { - this.sessionName = sessionName; - return this; - } - - /** - * sessionId - * - * @param sessionId sessionId - * @return Builder - */ - public Builder sessionId(int sessionId) { - this.sessionId = sessionId; - return this; - } - - /** - * startTimestamp - * - * @param startTimestamp startTimestamp - * @return Builder - */ - public Builder startTimestamp(long startTimestamp) { - this.startTimestamp = startTimestamp; - return this; - } - - /** - * endTimestamp - * - * @param endTimestamp endTimestamp - * @return Builder - */ - public Builder endTimestamp(long endTimestamp) { - this.endTimestamp = endTimestamp; - return this; - } - - /** - * streamId - * - * @param streamId streamId - * @return Builder - */ - public Builder streamId(long streamId) { - this.streamId = streamId; - return this; - } - - /** - * 获取pid信息方法 - * - * @param pid pid - * @return Builder - */ - public Builder pid(long pid) { - this.pid = pid; - return this; - } - - /** - * 设备IP和端口号信息 - * - * @param deviceIPPortInfo deviceIPPortInfo - * @return Builder - */ - public Builder deviceIPPortInfo(DeviceIPPortInfo deviceIPPortInfo) { - this.deviceIPPortInfo = deviceIPPortInfo; - return this; - } - - /** - * build方法 - * - * @return SessionInfo - */ - public SessionInfo build() { - return new SessionInfo(this); - } - } - - private String sessionName; - private int sessionId; - private long startTimestamp; - private long endTimestamp; - private long streamId; - private long pid; - private boolean startRefsh; - private boolean offlineMode; - - private DeviceIPPortInfo deviceIPPortInfo; - - private SessionInfo(Builder builder) { - sessionName = builder.sessionName; - sessionId = builder.sessionId; - startTimestamp = builder.startTimestamp; - endTimestamp = builder.endTimestamp; - streamId = builder.streamId; - pid = builder.pid; - deviceIPPortInfo = builder.deviceIPPortInfo; - } - - public DeviceIPPortInfo getDeviceIPPortInfo() { - return deviceIPPortInfo; - } - - public String getSessionName() { - return sessionName; - } - - public void setSessionName(String sessionName) { - this.sessionName = sessionName; - } - - public int getSessionId() { - return sessionId; - } - - public void setSessionId(int sessionId) { - this.sessionId = sessionId; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - public void setStartTimestamp(long startTimestamp) { - this.startTimestamp = startTimestamp; - } - - public long getEndTimestamp() { - return endTimestamp == 0 ? Long.MAX_VALUE : endTimestamp; - } - - public void setEndTimestamp(long endTimestamp) { - this.endTimestamp = endTimestamp; - } - - public long getStreamId() { - return streamId; - } - - public void setStreamId(long streamId) { - this.streamId = streamId; - } - - public long getPid() { - return pid; - } - - public void setPid(long pid) { - this.pid = pid; - } - - public boolean isOfflineMode() { - return offlineMode; - } - - public void setOfflineMode(boolean offlineMode) { - this.offlineMode = offlineMode; - } - - /** - * equals - * - * @param object object - * @return boolean - */ - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof SessionInfo)) { - return false; - } - SessionInfo session = (SessionInfo) object; - - if (getSessionId() != session.getSessionId()) { - return false; - } - if (getStartTimestamp() != session.getStartTimestamp()) { - return false; - } - if (getEndTimestamp() != session.getEndTimestamp()) { - return false; - } - if (getStreamId() != session.getStreamId()) { - return false; - } - - if (getPid() != session.getPid()) { - return false; - } - - return getSessionName() != null ? getSessionName().equals(session.getSessionName()) : - session.getSessionName() == null; - } - - /** - * hashCode - * - * @return int - */ - @Override - public int hashCode() { - int result = getSessionName() != null ? getSessionName().hashCode() : 0; - result = LayoutConstants.THIRTY_ONE * result + (int) (getSessionId() ^ (getSessionId() - >>> LayoutConstants.THIRTY_TWO)); - result = LayoutConstants.THIRTY_ONE * result + (int) (getStartTimestamp() ^ (getStartTimestamp() - >>> LayoutConstants.THIRTY_TWO)); - result = LayoutConstants.THIRTY_ONE * result + (int) (getEndTimestamp() ^ (getEndTimestamp() - >>> LayoutConstants.THIRTY_TWO)); - result = LayoutConstants.THIRTY_ONE * result + (int) (getStreamId() ^ (getStreamId() - >>> LayoutConstants.THIRTY_TWO)); - result = LayoutConstants.THIRTY_ONE * result + (int) (getPid() ^ (getPid() >>> LayoutConstants.THIRTY_TWO)); - return result; - } - - public boolean isStartRefsh() { - return startRefsh; - } - - public void setStartRefsh(boolean startRefsh) { - this.startRefsh = startRefsh; - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.session.entity; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; + +/** + * Session Info Entity + */ +public class SessionInfo { + private static SessionInfo defaultSession; + + /** + * builder + * + * @return Builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * getDefaultInstance + * + * @return SessionInfo + */ + public static SessionInfo getDefaultInstance() { + if (defaultSession == null) { + defaultSession = SessionInfo.builder().build(); + } + return defaultSession; + } + + /** + * Builder + */ + public static class Builder { + private String sessionName; + private int sessionId; + private long startTimestamp; + private long endTimestamp; + private long streamId; + private int pid; + private String processName; + private DeviceIPPortInfo deviceIPPortInfo; + + private Builder() { + } + + /** + * sessionName + * + * @param sessionName sessionName + * @return Builder + */ + public Builder sessionName(String sessionName) { + this.sessionName = sessionName; + return this; + } + + /** + * sessionId + * + * @param sessionId sessionId + * @return Builder + */ + public Builder sessionId(int sessionId) { + this.sessionId = sessionId; + return this; + } + + /** + * startTimestamp + * + * @param startTimestamp startTimestamp + * @return Builder + */ + public Builder startTimestamp(long startTimestamp) { + this.startTimestamp = startTimestamp; + return this; + } + + /** + * endTimestamp + * + * @param endTimestamp endTimestamp + * @return Builder + */ + public Builder endTimestamp(long endTimestamp) { + this.endTimestamp = endTimestamp; + return this; + } + + /** + * streamId + * + * @param streamId streamId + * @return Builder + */ + public Builder streamId(long streamId) { + this.streamId = streamId; + return this; + } + + /** + * Method for obtaining PID information + * + * @param pid pid + * @return Builder + */ + public Builder pid(int pid) { + this.pid = pid; + return this; + } + + /** + * Method to get process name information + * + * @param processName processName + * @return Builder + */ + public Builder processName(String processName) { + this.processName = processName; + return this; + } + + /** + * Device IP and port number information + * + * @param deviceIPPortInfo deviceIPPortInfo + * @return Builder + */ + public Builder deviceIPPortInfo(DeviceIPPortInfo deviceIPPortInfo) { + this.deviceIPPortInfo = deviceIPPortInfo; + return this; + } + + /** + * build method + * + * @return SessionInfo + */ + public SessionInfo build() { + return new SessionInfo(this); + } + } + + private String sessionName; + private int sessionId; + private long startTimestamp; + private long endTimestamp; + private long streamId; + private int pid; + private String processName; + private boolean startRefsh; + private boolean offlineMode; + + private final DeviceIPPortInfo deviceIPPortInfo; + + private SessionInfo(Builder builder) { + sessionName = builder.sessionName; + sessionId = builder.sessionId; + startTimestamp = builder.startTimestamp; + endTimestamp = builder.endTimestamp; + streamId = builder.streamId; + pid = builder.pid; + processName = builder.processName; + deviceIPPortInfo = builder.deviceIPPortInfo; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public DeviceIPPortInfo getDeviceIPPortInfo() { + return deviceIPPortInfo; + } + + public String getSessionName() { + return sessionName; + } + + public void setSessionName(String sessionName) { + this.sessionName = sessionName; + } + + public int getSessionId() { + return sessionId; + } + + public void setSessionId(int sessionId) { + this.sessionId = sessionId; + } + + public long getStartTimestamp() { + return startTimestamp; + } + + public void setStartTimestamp(long startTimestamp) { + this.startTimestamp = startTimestamp; + } + + public long getEndTimestamp() { + return endTimestamp == 0 ? Long.MAX_VALUE : endTimestamp; + } + + public void setEndTimestamp(long endTimestamp) { + this.endTimestamp = endTimestamp; + } + + public long getStreamId() { + return streamId; + } + + public void setStreamId(long streamId) { + this.streamId = streamId; + } + + public int getPid() { + return pid; + } + + public void setPid(int pid) { + this.pid = pid; + } + + public boolean isOfflineMode() { + return offlineMode; + } + + public void setOfflineMode(boolean offlineMode) { + this.offlineMode = offlineMode; + } + + public boolean isStartRefsh() { + return startRefsh; + } + + public void setStartRefsh(boolean startRefsh) { + this.startRefsh = startRefsh; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/service/SessionManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/service/SessionManager.java index 91d54689c..a622ac271 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/service/SessionManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/session/service/SessionManager.java @@ -1,840 +1,1040 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.session.service; - -import com.alibaba.fastjson.JSONObject; -import com.intellij.ide.plugins.PluginManager; -import com.intellij.openapi.extensions.PluginId; -import io.grpc.StatusRuntimeException; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.MemoryPlugHelper; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper; -import ohos.devtools.datasources.transport.grpc.service.AgentPluginConfig; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.common.Constant; -import ohos.devtools.datasources.utils.common.util.CommonUtil; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.common.util.PrintUtil; -import ohos.devtools.datasources.utils.datahandler.datapoller.DataPoller; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; -import ohos.devtools.datasources.utils.device.entity.TraceFileInfo; -import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.session.entity.SessionInfo; -import ohos.devtools.services.memory.ClassInfo; -import ohos.devtools.services.memory.ClassInfoDao; -import ohos.devtools.services.memory.ClassInfoManager; -import ohos.devtools.services.memory.MemoryHeapDao; -import ohos.devtools.services.memory.MemoryHeapInfo; -import ohos.devtools.services.memory.MemoryHeapManager; -import ohos.devtools.services.memory.MemoryInstanceDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsInfo; -import ohos.devtools.services.memory.MemoryInstanceDetailsManager; -import ohos.devtools.services.memory.MemoryInstanceInfo; -import ohos.devtools.services.memory.MemoryInstanceManager; -import ohos.devtools.services.memory.MemoryService; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.JProgressBar; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import static java.util.Locale.ENGLISH; -import static ohos.devtools.datasources.transport.hdc.HdcCommandEnum.HDC_START_JAVAHEAP; -import static ohos.devtools.datasources.utils.common.Constant.DEVICE_FULL_TYPE; -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUGS; -import static ohos.devtools.views.common.LayoutConstants.TWO_THOUSAND; - -/** - * @Description session Management core class - * @Date 2021/2/7 13:30 - **/ -public class SessionManager { - /** - * Global log - */ - private static final Logger LOGGER = LogManager.getLogger(SessionManager.class); - - /** - * Singleton session. - */ - private static final SessionManager SINGLETON = new SessionManager(); - - /** - * getInstance - * - * @return SessionManager - */ - public static SessionManager getInstance() { - return SessionManager.SINGLETON; - } - - /** - * developMode - */ - private boolean developMode = false; - - /** - * Analyzed Sessions - */ - private HashMap profilingSessions; - - private HashMap dataPollerHashMap = new HashMap<>(); - - private MemoryTable memoTable; - - private ClassInfoDao classInfoDao; - - private MemoryHeapDao memoryHeapDao; - - private MemoryInstanceDao memoryInstanceDao; - - private MemoryInstanceDetailsDao memoryInstanceDetailsDao; - - private List plugs; - - private ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder; - - private SessionManager() { - profilingSessions = new HashMap<>(); - } - - /** - * Clear session Id directly, use with caution - * - * @param localSessionId localSessionId - */ - public void deleteLocalSession(Long localSessionId) { - if (profilingSessions != null) { - ProfilerChartsView profilerChartsView = ProfilerChartsView.sessionMap.get(localSessionId); - if (profilerChartsView != null) { - profilerChartsView.getObserver().stopRefresh(true); - } - profilingSessions.remove(localSessionId); - } - } - - /** - * Create Session based on device information, process information, and specific scenarios - * - * @param device device - * @param process process - * @param model model - * @param configJson configJson - * @return boolean - * @date 2021/2/7 16:22 - */ - public Long createSession(DeviceIPPortInfo device, ProcessInfo process, int model, JSONObject configJson) { - if (device == null || process == null || configJson == null || device.getForwardPort() == 0) { - return -1L; - } - int sessionId = 0; - // Real-time scene - Long localSessionID = Constant.ABNORMAL; - if (model == Constant.REALTIME_SCENE) { - localSessionID = handleAgentConfig(configJson, device, process); - if (localSessionID == Constant.ABNORMAL) { - return Constant.ABNORMAL; - } - ProfilerServiceTypes.CreateSessionRequest request = ProfilerServiceHelper - .createSessionRequest(CommonUtil.getRequestId(), sessionConfigBuilder.build(), plugs); - ProfilerClient createSessionClient = - HiProfilerClient.getInstance().getProfilerClient(device.getIp(), device.getForwardPort()); - if (createSessionClient.isUsed()) { - LOGGER.error("create Session failed"); - return Constant.ABNORMAL; - } - ProfilerServiceTypes.CreateSessionResponse respon = null; - try { - createSessionClient.setUsed(true); - respon = createSessionClient.createSession(request); - } catch (StatusRuntimeException statusRuntimeException) { - if ("UNAVAILABLE".equals(statusRuntimeException.getStatus().getCode())) { - HiProfilerClient.getInstance().destroyProfiler(device.getIp(), device.getForwardPort()); - } - LOGGER.error("status RuntimeException getStatus:{}", statusRuntimeException.getStatus()); - return Constant.ABNORMAL; - } - sessionId = respon.getSessionId(); - createSessionClient.setUsed(false); - } - int pid = process.getProcessId(); - String deviceId = device.getDeviceID(); - String sessionName = CommonUtil.generateSessionName(deviceId, pid); - SessionInfo session = - SessionInfo.builder().sessionId(sessionId).sessionName(sessionName).deviceIPPortInfo(device).build(); - // 建立LocalSessionId和端侧session的关系 - profilingSessions.put(localSessionID, session); - if (sessionId != 0) { - PrintUtil.print(LOGGER, "Task with Session created successfully.", 0); - return localSessionID; - } else { - LOGGER.error("Failed to create task with Session!"); - return Constant.ABNORMAL; - } - } - - private long handleAgentConfig(JSONObject configJson, DeviceIPPortInfo device, ProcessInfo process) { - long localSessionID = CommonUtil.getLocalSessionId(); - String agentPlug = "jvmtiagent_" + process.getProcessName(); - boolean startJavaHeap = isStartJavaHeap(device, agentPlug); - String proc = process.getProcessName(); - MonitorConfigManager.getInstance().analyzeCharTarget(localSessionID, configJson); - if (StringUtils.isNotBlank(proc) && (!startJavaHeap)) { - String hdcCommand = String.format(ENGLISH, HDC_START_JAVAHEAP.getHdcCommand(), device.getDeviceID(), proc); - String res = HdcWrapper.getInstance().getHdcStringResult(hdcCommand); - if (res.contains("javaHeapSuccess")) { - startJavaHeap = true; - } - } - LOGGER.info("Start agent status is {} ", startJavaHeap); - ProfilerServiceTypes.GetCapabilitiesResponse capabilitiesRes = - HiProfilerClient.getInstance().getCapabilities(device.getIp(), device.getForwardPort()); - List capability = capabilitiesRes.getCapabilitiesList(); - sessionConfigBuilder = ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() - .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE); - if (capability == null || capability.size() == 0) { - localSessionID = Constant.ABNORMAL; - } - List memPlug = getLibmemdataplugin(capability, MEMORY_PLUGS); - List list = getLibmemdataplugin(capability, agentPlug); - plugs = new ArrayList<>(); - MemoryPluginConfig.MemoryConfig plug = getConfig(device, process); - if (!memPlug.isEmpty()) { - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder memoryBuffer = getBuilder(); - CommonTypes.ProfilerPluginConfig plugConfig = - ProfilerServiceHelper.profilerPluginConfig(memPlug.get(0).getName(), "", 40, plug.toByteString()); - sessionConfigBuilder.addBuffers(memoryBuffer); - plugs.add(plugConfig); - } - if (startJavaHeap && (!list.isEmpty())) { - AgentPluginConfig.AgentConfig agent = - AgentPluginConfig.AgentConfig.newBuilder().setPid(process.getProcessId()).build(); - CommonTypes.ProfilerPluginConfig jvmTiAgent = - ProfilerServiceHelper.profilerPluginConfig(list.get(0).getName(), "", 100, agent.toByteString()); - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder javaHeapBuffer = - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(TWO_THOUSAND) - .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE); - sessionConfigBuilder.addBuffers(javaHeapBuffer); - plugs.add(jvmTiAgent); - } - if (plugs.isEmpty()) { - localSessionID = Constant.ABNORMAL; - } - return localSessionID; - } - - private List getLibmemdataplugin( - List capabilities, String libmemdataplugin) { - return capabilities.stream() - .filter(profilerPluginCapability -> profilerPluginCapability.getName().contains(libmemdataplugin)) - .collect(Collectors.toList()); - } - - private boolean isStartJavaHeap(DeviceIPPortInfo device, String agentPlugName) { - boolean startJavaHeap = false; - ProfilerServiceTypes.GetCapabilitiesResponse response = - HiProfilerClient.getInstance().getCapabilities(device.getIp(), device.getForwardPort()); - List capabilitiesResponse = response.getCapabilitiesList(); - List agentStatus = - getLibmemdataplugin(capabilitiesResponse, agentPlugName); - if (!agentStatus.isEmpty()) { - startJavaHeap = true; - } - return startJavaHeap; - } - - private ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder getBuilder() { - return ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.TEN) - .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE); - } - - private MemoryPluginConfig.MemoryConfig getConfig(DeviceIPPortInfo device, ProcessInfo process) { - MemoryPluginConfig.MemoryConfig plug; - if (DEVICE_FULL_TYPE.equals(device.getDeviceType())) { - plug = MemoryPlugHelper.createMemRequest(process.getProcessId(), false, true, true, true); - } else { - plug = MemoryPlugHelper.createMemRequest(process.getProcessId(), false, true, true, false); - } - return plug; - } - - /** - * Establish a session with the end side and start the session. - * - * @param localSessionId Local Session Id - * @param restartFlag Whether to start again - * @return boolean - * @date 2021/2/4 17:37 - */ - public boolean startSession(Long localSessionId, boolean restartFlag) { - if (localSessionId == null) { - return false; - } - SessionInfo session = profilingSessions.get(localSessionId); - if (session == null) { - return true; - } - if (restartFlag) { - // Click start, delete the previous data first - MemoryService.getInstance().deleteSessionData(localSessionId); - deleteAllAgentData(localSessionId, false); - } - int sessionId = session.getSessionId(); - DeviceIPPortInfo device = session.getDeviceIPPortInfo(); - return HiProfilerClient.getInstance().requestStartSession(device.getIp(), device.getForwardPort(), sessionId); - } - - /** - * Turn on polling to get data - * - * @param localSessionId localSessionId - * @return boolean Turn on polling - * @date 2021/2/22 14:57 - */ - public boolean fetchData(Long localSessionId) { - try { - if (localSessionId == null || localSessionId <= 0) { - return false; - } - SessionInfo session = profilingSessions.get(localSessionId); - if (session == null) { - return true; - } - DeviceIPPortInfo device = session.getDeviceIPPortInfo(); - ProfilerClient client = - HiProfilerClient.getInstance().getProfilerClient(device.getIp(), device.getForwardPort()); - if (client.isUsed()) { - return false; - } - client.setUsed(true); - HashMap map = new HashMap(); - map.put(MEMORY_PLUG, new MemoryTable()); - map.put(JVMTI_AGENT_PLUG, new ClassInfoDao()); - map.put("jvmtiagentDetails", new MemoryInstanceDetailsDao()); - map.put("jvmtiagentInstance", new MemoryInstanceDao()); - map.put("jvmtiagentMemoryHeap", new MemoryHeapDao()); - LOGGER.info("start new DataPoller {}", DateTimeUtil.getNowTimeLong()); - int sessionId = session.getSessionId(); - DataPoller dataPoller = new DataPoller(localSessionId, sessionId, client, map); - dataPoller.start(); - dataPollerHashMap.put(localSessionId, dataPoller); - return true; - } catch (Exception exception) { - LOGGER.error(exception.getMessage()); - return false; - } - } - - /** - * isRefsh - * - * @param localSessionId localSessionId - * @return boolean - */ - public SessionInfo isRefsh(Long localSessionId) { - return profilingSessions.get(localSessionId); - } - - /** - * View stop Loading - * - * @param localSession local Session - * @param firstTimeStamp first Time Stamp - */ - public void stopLoadingView(Long localSession, long firstTimeStamp) { - SessionInfo sessionInfo = profilingSessions.get(localSession); - if (sessionInfo != null) { - sessionInfo.setStartTimestamp(firstTimeStamp); - sessionInfo.setStartRefsh(true); - profilingSessions.put(localSession, sessionInfo); - } - } - - /** - * stop Session - * - * @param localSessionId localSessionId - * @return boolean Stop success indicator - * @date 2021/2/20 16:20 - */ - public boolean endSession(Long localSessionId) { - if (localSessionId == null || localSessionId <= 0) { - return false; - } - SessionInfo session = profilingSessions.get(localSessionId); - if (session == null) { - return true; - } - session.setStartRefsh(false); - int sessionId = session.getSessionId(); - DeviceIPPortInfo device = session.getDeviceIPPortInfo(); - boolean stopSessionRes = - HiProfilerClient.getInstance().requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true); - if (stopSessionRes) { - DataPoller dataPoller = dataPollerHashMap.get(localSessionId); - if (dataPoller != null) { - dataPoller.shutDown(); - } - - PrintUtil.print(LOGGER, "Task with Session stopped successfully.", 0); - } else { - LOGGER.error("Failed to stop task with Session!"); - } - return stopSessionRes; - } - - /** - * Delete the Session session interface - * - * @param localSessionId localSessionId - * @return boolean Is the deletion successful - */ - public boolean deleteSession(Long localSessionId) { - try { - if (localSessionId == null || localSessionId <= 0) { - return false; - } - SessionInfo session = profilingSessions.get(localSessionId); - if (session == null) { - return false; - } - // Delete session information in local memory - profilingSessions.remove(localSessionId); - // Delete the data information related to the session of the database - MemoryService.getInstance().deleteSessionData(localSessionId); - deleteAllAgentData(localSessionId, true); - if (session.isOfflineMode()) { - return true; - } - int sessionId = session.getSessionId(); - DeviceIPPortInfo device = session.getDeviceIPPortInfo(); - boolean stopSessionRes = HiProfilerClient.getInstance() - .requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true); - // Delete collection item - if (stopSessionRes) { - boolean destroySessionRes = false; - try { - destroySessionRes = HiProfilerClient.getInstance() - .requestDestroySession(device.getIp(), device.getForwardPort(), sessionId); - if (destroySessionRes) { - DataPoller dataPooler = dataPollerHashMap.get(localSessionId); - if (dataPooler != null) { - dataPooler.shutDown(); - } - HiProfilerClient.getInstance().destroyProfiler(device.getIp(), device.getForwardPort()); - } - } catch (StatusRuntimeException exception) { - LOGGER.error(exception.getMessage()); - } - PrintUtil.print(LOGGER, "Task with Session deleted successfully.", 0); - return destroySessionRes; - } else { - LOGGER.error("Failed to delete task with Session "); - return false; - } - } finally { - if (localSessionId != null && localSessionId > 0) { - MemoryService.getInstance().deleteSessionData(localSessionId); - deleteAllAgentData(localSessionId, true); - } - } - } - - private void deleteAllAgentData(Long localSessionId, boolean deleteClassInfo) { - if (memoTable == null) { - memoTable = new MemoryTable(); - } - if (memoryHeapDao == null) { - memoryHeapDao = new MemoryHeapDao(); - } - if (memoryInstanceDao == null) { - memoryInstanceDao = new MemoryInstanceDao(); - } - if (classInfoDao == null) { - classInfoDao = new ClassInfoDao(); - } - if (memoryInstanceDetailsDao == null) { - memoryInstanceDetailsDao = new MemoryInstanceDetailsDao(); - } - if (deleteClassInfo) { - classInfoDao.deleteSessionData(localSessionId); - } - memoryHeapDao.deleteSessionData(localSessionId); - memoryInstanceDao.deleteSessionData(localSessionId); - memoryInstanceDetailsDao.deleteSessionData(localSessionId); - } - - /** - * Used to notify the end side to close all session connections after the IDE is closed. - */ - public void stopAllSession() { - if (profilingSessions.isEmpty()) { - return; - } - profilingSessions.values().forEach(sessionInfo -> { - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - DeviceIPPortInfo device = sessionInfo.getDeviceIPPortInfo(); - if (device != null) { - hiprofiler - .requestStopSession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId(), true); - hiprofiler.requestDestroySession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId()); - hiprofiler.destroyProfiler(device.getIp(), device.getForwardPort()); - } - }); - } - - /** - * Save the collected data to a file. - * - * @param sessionId sessionId - * @param deviceProcessInfo deviceProcessInfo - * @param pathname pathname - * @return boolean - */ - public boolean saveSessionDataToFile(long sessionId, DeviceProcessInfo deviceProcessInfo, String pathname) { - if (sessionId <= 0 || deviceProcessInfo == null || StringUtils.isEmpty(pathname)) { - return false; - } - List memInfoList = MemoryService.getInstance().getAllData(sessionId); - List classInfos = new ClassInfoManager().getAllClassInfoData(sessionId); - List memoryHeapInfos = new MemoryHeapManager().getAllMemoryHeapInfos(sessionId); - List detailsInfos = new MemoryInstanceDetailsManager().getAllMemoryInstanceDetails(); - ArrayList memoryInstanceInfos = new MemoryInstanceManager().getAllMemoryInstanceInfos(); - FileOutputStream fileOutputStream = null; - ObjectOutputStream objectOutputStream = null; - try { - File file = new File(pathname); - fileOutputStream = new FileOutputStream(file); - objectOutputStream = new ObjectOutputStream(fileOutputStream); - // Start importing the number of meminfo in an object record file - TraceFileInfo startObj = new TraceFileInfo(); - int recordNum = memInfoList.size() + classInfos.size() + memoryHeapInfos.size() + detailsInfos.size() - + memoryInstanceInfos.size(); - startObj.setRecordNum(recordNum); - startObj.setCreateTime(new Date().getTime()); - // Set the trace file version, the subsequent file save content format changes and is not compatible with - // the previous file, you need to modify the version number, and you need to modify the version number - // in the local Session Data From File method. - startObj.setVersion("V1.0"); - objectOutputStream.writeObject(startObj); - - for (int index = 0; index < memInfoList.size(); index++) { - ProcessMemInfo memObject = memInfoList.get(index); - objectOutputStream.writeObject(memObject); - if (index == 0) { - deviceProcessInfo.setStartTime(memObject.getTimeStamp()); - } - if (index == (memInfoList.size() - 1)) { - deviceProcessInfo.setEndTime(memObject.getTimeStamp()); - } - } - writeCollectionData(objectOutputStream, classInfos, memoryHeapInfos, detailsInfos, memoryInstanceInfos); - objectOutputStream.writeObject(deviceProcessInfo); - PrintUtil.print(LOGGER, "Task with Session ID {} Save To File successfully.", 0); - } catch (IOException exception) { - return false; - } finally { - closeIoStream(null, null, fileOutputStream, objectOutputStream); - } - return true; - } - - private void writeCollectionData(ObjectOutputStream objectOutputStream, List classInfos, - List memoryHeapInfos, List detailsInfos, - ArrayList memoryInstanceInfos) throws IOException { - for (ClassInfo classInfo : classInfos) { - objectOutputStream.writeObject(classInfo); - } - for (MemoryHeapInfo memoryHeapInfo : memoryHeapInfos) { - objectOutputStream.writeObject(memoryHeapInfo); - } - for (MemoryInstanceDetailsInfo instanceDetailsInfo : detailsInfos) { - objectOutputStream.writeObject(instanceDetailsInfo); - } - for (int index = 0; index < memoryInstanceInfos.size(); index++) { - MemoryInstanceInfo instanceInfo = memoryInstanceInfos.get(index); - objectOutputStream.writeObject(instanceInfo); - } - } - - /** - * local Session Data From File - * - * @param jProgressBar jProgressBar - * @param file file - * @return Optional - */ - public Optional localSessionDataFromFile(JProgressBar jProgressBar, File file) { - if (jProgressBar == null || file == null) { - return Optional.ofNullable(null); - } - FileInputStream fileInputStream = null; - ObjectInputStream objectInputStream = null; - DeviceProcessInfo deviceProcessInfo = null; - try { - fileInputStream = new FileInputStream(file); - objectInputStream = new ObjectInputStream(fileInputStream); - Object firstObj = objectInputStream.readObject(); - TraceFileInfo traceFileInfo = null; - if (firstObj instanceof TraceFileInfo) { - traceFileInfo = (TraceFileInfo) firstObj; - if (!"V1.0".equals(traceFileInfo.getVersion())) { - // The trace file is not the latest version - return Optional.empty(); - } - } else { - // The trace file is not the latest version - return Optional.empty(); - } - deviceProcessInfo = loadFileInDataBase(jProgressBar, traceFileInfo, objectInputStream); - } catch (IOException | ClassNotFoundException exception) { - if (exception.getMessage().indexOf("invalid stream header") >= 0) { - if (file.getName().indexOf(".bin") >= 0) { - return Optional.empty(); - } - return Optional.empty(); - } - LOGGER.error("load Data Error {}", exception.getMessage()); - return Optional.empty(); - } finally { - closeIoStream(fileInputStream, objectInputStream, null, null); - } - long localSessionId = deviceProcessInfo.getLocalSessionId(); - SessionInfo session = SessionInfo.builder().sessionName(String.valueOf(localSessionId)).build(); - session.setOfflineMode(true); - profilingSessions.put(localSessionId, session); - jProgressBar.setValue(LayoutConstants.HUNDRED); - return Optional.of(deviceProcessInfo); - } - - private DeviceProcessInfo loadFileInDataBase(JProgressBar jProgressBar, TraceFileInfo traceFileInfo, - ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { - List processMemInfoList = new ArrayList(); - List classInfos = new ArrayList<>(); - List memoryHeapInfos = new ArrayList<>(); - List instanceInfos = new ArrayList<>(); - List detailsInfos = new ArrayList<>(); - long objNum = traceFileInfo.getRecordNum() + 1; - long currentNum = 0; - while (true) { - Object object = objectInputStream.readObject(); - if (object instanceof DeviceProcessInfo) { - // Finally, if there is still data in the datalist, import the database - if ((!processMemInfoList.isEmpty()) || (!classInfos.isEmpty()) || (!memoryHeapInfos.isEmpty()) - || (!instanceInfos.isEmpty()) || (!detailsInfos.isEmpty())) { - extracted(processMemInfoList, classInfos, memoryHeapInfos, instanceInfos, detailsInfos); - currentNum = currentNum + processMemInfoList.size(); - int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum); - jProgressBar.setValue(progress); - } - DeviceProcessInfo deviceProcessInfo = (DeviceProcessInfo) object; - return deviceProcessInfo; - } else if (object instanceof ClassInfo) { - ClassInfo classInfo = (ClassInfo) object; - classInfos.add(classInfo); - insertDataToDataBase(classInfos, false); - } else if (object instanceof MemoryHeapInfo) { - MemoryHeapInfo memoryHeapInfo = (MemoryHeapInfo) object; - memoryHeapInfos.add(memoryHeapInfo); - insertDataToDataBase(memoryHeapInfos, false); - } else if (object instanceof MemoryInstanceDetailsInfo) { - MemoryInstanceDetailsInfo detailsInfo = (MemoryInstanceDetailsInfo) object; - detailsInfos.add(detailsInfo); - insertDataToDataBase(detailsInfos, false); - } else if (object instanceof MemoryInstanceInfo) { - MemoryInstanceInfo memoryInstanceInfo = (MemoryInstanceInfo) object; - instanceInfos.add(memoryInstanceInfo); - insertDataToDataBase(instanceInfos, false); - } else if (object instanceof ProcessMemInfo) { - ProcessMemInfo processMem = (ProcessMemInfo) object; - processMemInfoList.add(processMem); - insertDataToDataBase(processMemInfoList, false); - } else { - continue; - } - currentNum = currentNum + 1; - loadPercentage(jProgressBar, objNum, currentNum); - } - } - - private void loadPercentage(JProgressBar jProgressBar, long objNum, long currentNum) { - int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum); - double result = progress % 25; - if (result == 0) { - jProgressBar.setValue(progress); - } - } - - private void extracted(List processMemInfoList, List classInfos, - List memoryHeapInfos, List instanceInfos, - List detailsInfos) { - insertDataToDataBase(processMemInfoList, true); - insertDataToDataBase(classInfos, true); - insertDataToDataBase(memoryHeapInfos, true); - insertDataToDataBase(instanceInfos, true); - insertDataToDataBase(detailsInfos, true); - } - - private void closeIoStream(FileInputStream fileInputStream, ObjectInputStream objectInputStream, - FileOutputStream fileOutputStream, ObjectOutputStream objectOutputStream) { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException exception) { - LOGGER.error("exception:{}", exception.getMessage()); - } - } - if (objectInputStream != null) { - try { - objectInputStream.close(); - } catch (IOException exception) { - LOGGER.error("exception:{}", exception.getMessage()); - } - } - if (fileOutputStream != null) { - try { - fileOutputStream.close(); - } catch (IOException exception) { - LOGGER.error("exception:{}", exception.getMessage()); - } - } - if (objectOutputStream != null) { - try { - objectOutputStream.close(); - } catch (IOException exception) { - LOGGER.error("exception:{}", exception.getMessage()); - } - } - } - - private void insertDataToDataBase(List dataList, boolean endData) { - if (dataList.size() < LayoutConstants.THREE_HUNDRED) { - if (!endData) { - return; - } - } - if (dataList.size() == 0) { - return; - } - if (memoTable == null) { - memoTable = new MemoryTable(); - } - if (memoryHeapDao == null) { - memoryHeapDao = new MemoryHeapDao(); - } - if (memoryInstanceDao == null) { - memoryInstanceDao = new MemoryInstanceDao(); - } - if (classInfoDao == null) { - classInfoDao = new ClassInfoDao(); - } - if (memoryInstanceDetailsDao == null) { - memoryInstanceDetailsDao = new MemoryInstanceDetailsDao(); - } - Object object = dataList.get(0); - if (object instanceof ClassInfo) { - classInfoDao.insertClassInfos(dataList); - } else if (object instanceof MemoryHeapInfo) { - memoryHeapDao.insertMemoryHeapInfos(dataList); - } else if (object instanceof MemoryInstanceDetailsInfo) { - memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(dataList); - } else if (object instanceof MemoryInstanceInfo) { - memoryInstanceDao.insertMemoryInstanceInfos(dataList); - } else if (object instanceof ProcessMemInfo) { - memoTable.insertProcessMemInfo(dataList); - } else { - return; - } - dataList.clear(); - } - - /** - * delete Session By OffLine Divece - * - * @param device device - */ - public void deleteSessionByOffLineDivece(DeviceIPPortInfo device) { - if (profilingSessions.isEmpty() || device == null) { - return; - } - Set sessionIds = profilingSessions.keySet(); - for (Long session : sessionIds) { - SessionInfo sessionInfo = profilingSessions.get(session); - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - DeviceIPPortInfo deviceSource = sessionInfo.getDeviceIPPortInfo(); - if (device.getDeviceID().equals(deviceSource.getDeviceID())) { - // 停止chart刷新 - ProfilerChartsView.sessionMap.get(session).getObserver().stopRefresh(true); - profilingSessions.remove(session); - } - } - } - - /** - * get Plugin Path - * - * @return String plugin Path - */ - public String getPluginPath() { - String pluginPath = ""; - if (developMode) { - pluginPath = "C:\\ohos\\"; - } else { - PluginId plugin = PluginManager.getPluginByClassName(this.getClass().getName()); - if (plugin != null) { - File path = PluginManager.getPlugin(plugin).getPath(); - try { - pluginPath = path.getCanonicalPath() + "\\ohos\\"; - } catch (IOException ioException) { - LOGGER.error("ioException {}", ioException.getMessage()); - } - } - } - LOGGER.debug("path is {}", pluginPath); - return pluginPath; - } - - public void setDevelopMode(boolean developMode) { - this.developMode = developMode; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.session.service; + +import com.intellij.ide.plugins.PluginManager; +import com.intellij.openapi.application.PathManager; +import com.intellij.openapi.extensions.PluginId; +import com.intellij.openapi.project.Project; +import io.grpc.StatusRuntimeException; +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.ProfilerClient; +import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.common.Constant; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.common.util.PrintUtil; +import ohos.devtools.datasources.utils.common.util.Validate; +import ohos.devtools.datasources.utils.datahandler.datapoller.DataPoller; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.device.entity.TraceFileInfo; +import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginBufferConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.KeepSession; +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.services.cpu.CpuDao; +import ohos.devtools.services.cpu.CpuValidate; +import ohos.devtools.services.memory.MemoryValidate; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import ohos.devtools.services.memory.agentdao.ClassInfoManager; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import ohos.devtools.services.memory.agentdao.MemoryHeapManager; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsManager; +import ohos.devtools.services.memory.agentdao.MemoryInstanceManager; +import ohos.devtools.services.memory.agentdao.MemoryUpdateInfo; +import ohos.devtools.services.memory.memoryservice.MemoryService; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.dialog.ExportFileChooserDialog; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import javax.swing.JProgressBar; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_CHMOD_PROC; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_CHMOD_PROC; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_V8_PATH; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.datasources.utils.plugin.entity.PluginBufferConfig.Policy.RECYCLE; +import static ohos.devtools.views.common.Constant.IS_DEVELOP_MODE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * session Management core class + */ +public class SessionManager { + /** + * Global log + */ + private static final Logger LOGGER = LogManager.getLogger(SessionManager.class); + private static final int KEEP_SESSION_TIME = 3000; + private static final int KEEP_SESSION_REQUEST_TIME = 2500; + private static final String STD_DEVELOPTOOLS = "stddeveloptools"; + + /** + * Singleton session. + */ + private static final SessionManager SINGLETON = new SessionManager(); + + /** + * getInstance + * + * @return SessionManager + */ + public static SessionManager getInstance() { + return SessionManager.SINGLETON; + } + + /** + * developMode + */ + private boolean developMode = true; + + private Project project; + + /** + * Analyzed Sessions + */ + private HashMap profilingSessions; + private HashMap dataPollerHashMap = new HashMap<>(); + private MemoryTable memoTable; + private ClassInfoDao classInfoDao; + private MemoryHeapDao memoryHeapDao; + private MemoryInstanceDao memoryInstanceDao; + private MemoryInstanceDetailsDao memoryInstanceDetailsDao; + + private SessionManager() { + profilingSessions = new HashMap<>(); + } + + /** + * Clear session Id directly, use with caution + * + * @param localSessionId localSessionId + */ + public void deleteLocalSession(Long localSessionId) { + if (profilingSessions != null) { + ProfilerChartsView profilerChartsView = ProfilerChartsView.sessionMap.get(localSessionId); + if (profilerChartsView != null) { + profilerChartsView.getPublisher().stopRefresh(true); + } + SessionInfo sessionInfo = profilingSessions.get(localSessionId); + if (Objects.nonNull(sessionInfo)) { + String keepSessionName = + getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId()); + QuartzManager.getInstance().deleteExecutor(keepSessionName); + } + profilingSessions.remove(localSessionId); + } + } + + public Project getProject() { + return project; + } + + public void setProject(Project project) { + this.project = project; + } + + /** + * Create Session based on device information, process information, and specific scenarios + * + * @param device device + * @param process process + * @return Long sessionId + */ + public Long createSession(DeviceIPPortInfo device, ProcessInfo process) { + if (device == null || process == null || device.getForwardPort() == 0) { + return Constant.ABNORMAL; + } + ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder = getSessionConfigBuilder(); + List capability = getProfilerPluginCapabilities(device); + if (capability == null || capability.size() == 0) { + return Constant.ABNORMAL; + } + long localSessionID = CommonUtil.getLocalSessionId(); + List plugs = new ArrayList(); + List configs = PlugManager.getInstance().getPluginConfig(device.getDeviceType(), PluginMode.ONLINE); + for (PluginConf conf : configs) { + if (conf.isAlwaysAdd()) { + PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf); + continue; + } + if (conf.isOperationStart()) { + continue; + } + if (conf.isSpecialStart()) { + boolean startResult = handleSpecialStartPlug(conf, device, process, plugs, sessionConfigBuilder); + if(startResult) { + PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf); + } + } else { + Optional plug = + getLibPlugin(capability, conf.getPluginFileName()); + if (plug.isPresent()) { + ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = plug.get(); + sessionConfigBuilder.addBuffers(getBufferConfig(conf)); + HiProfilerPluginConfig hiPluginConfig = + conf.getICreatePluginConfig().createPluginConfig(device, process); + CommonTypes.ProfilerPluginConfig pluginConfig = + getProfilerPluginConfig(conf, profilerPluginCapability, hiPluginConfig, device); + plugs.add(pluginConfig); + PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf); + } + } + } + ProfilerServiceTypes.CreateSessionResponse res = createSessionResponse(device, sessionConfigBuilder, plugs); + if (res.getSessionId() > 0) { + startKeepLiveSession(device, res.getSessionId(), localSessionID); + profilingSessions.put(localSessionID, createSessionInfo(device, process, res.getSessionId())); + PrintUtil.print(LOGGER, "Task with Session created successfully.", 0); + return localSessionID; + } else { + LOGGER.error("Failed to create task with Session!"); + return Constant.ABNORMAL; + } + } + + private boolean handleSpecialStartPlug(PluginConf conf, DeviceIPPortInfo device, + ProcessInfo process, List plugs, + ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder) { + boolean startResult = conf.getSpecialStartPlugMethod().specialStartPlugMethod(device, process); + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + LOGGER.error("sleep"); + } + List caps = getProfilerPluginCapabilities(device); + Optional plug = + getLibPlugin(caps, conf.getGetPluginName().getPluginName(device, process)); + LOGGER.info("plug : {}", plug); + if (startResult && plug.isPresent()) { + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bufferConfig = getBufferConfig(conf); + LOGGER.info("BufferConfig {}", bufferConfig); + sessionConfigBuilder.addBuffers(bufferConfig); + HiProfilerPluginConfig pluginConfig = + conf.getICreatePluginConfig().createPluginConfig(device, process); + CommonTypes.ProfilerPluginConfig profilerPluginConfig = + getAgentProfilerPluginConfig(conf, plug.get(), pluginConfig); + LOGGER.info("profilerPluginConfig : {}", profilerPluginConfig); + plugs.add(profilerPluginConfig); + return true; + } + return false; + } + private CommonTypes.ProfilerPluginConfig getProfilerPluginConfig(PluginConf conf, + ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig, + DeviceIPPortInfo device) { + LOGGER.info("pluginConfig is{}", pluginConfig); + String pluginFileName = conf.getPluginFileName(); + String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1); + StringBuilder stringBuilder = new StringBuilder(SessionManager.getInstance().getPluginPath()); + if (IS_SUPPORT_NEW_HDC && device.getDeviceType() == LEAN_HOS_DEVICE) { + stringBuilder.append(STD_DEVELOPTOOLS).append(File.separator).append(fileName); + } else { + stringBuilder.append(DEVTOOLS_PLUGINS_V8_PATH).append(File.separator).append(fileName); + } + String filePath = stringBuilder.toString(); + File pluginFile = new File(filePath); + try { + String fileSha256 = DigestUtils.sha256Hex(new FileInputStream(pluginFile)); + LOGGER.error("plugin sha256Hex {}", fileSha256); + return ProfilerServiceHelper + .profilerPluginConfig(plug.getName(), fileSha256, pluginConfig.getSampleInterval(), + pluginConfig.getConfData()); + } catch (IOException ioException) { + LOGGER.error("plugin sha256Hex fail {}", fileName); + return CommonTypes.ProfilerPluginConfig.getDefaultInstance(); + } + } + + private CommonTypes.ProfilerPluginConfig getAgentProfilerPluginConfig(PluginConf conf, + ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig) { + LOGGER.info("pluginConfig is{}", pluginConfig); + String pluginFileName = conf.getPluginFileName(); + String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1); + StringBuilder stringBuilder = new StringBuilder(SessionManager.getInstance().getPluginPath()); + stringBuilder.append(DEVTOOLS_PLUGINS_V8_PATH).append(File.separator).append(fileName).toString(); + String filePath = stringBuilder.toString(); + File pluginFile = new File(filePath); + try { + String fileSha256 = DigestUtils.sha256Hex(new FileInputStream(pluginFile)); + LOGGER.error("plugin sha256Hex {}", fileSha256); + return ProfilerServiceHelper + .profilerPluginConfig(plug.getName(), "", pluginConfig.getSampleInterval(), pluginConfig.getConfData()); + } catch (IOException ioException) { + LOGGER.error("plugin sha256Hex fail {}", fileName); + return CommonTypes.ProfilerPluginConfig.getDefaultInstance(); + } + } + + private ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig getBufferConfig(PluginConf conf) { + PluginBufferConfig pluginBufferConfig = conf.getPluginBufferConfig(); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder builder = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder(); + if (pluginBufferConfig.getPolicy() == RECYCLE) { + builder.setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE); + } else { + builder.setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.FLATTEN); + } + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bufferConfig = + builder.setPages(pluginBufferConfig.getPages()).build(); + return bufferConfig; + } + + private ProfilerServiceTypes.CreateSessionResponse createSessionResponse(DeviceIPPortInfo device, + ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder, + List plugs) { + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceHelper.createSessionRequest(CommonUtil.getRequestId(), sessionConfigBuilder.build(), plugs); + ProfilerClient createSessionClient = + HiProfilerClient.getInstance().getProfilerClient(device.getIp(), device.getForwardPort()); + ProfilerServiceTypes.CreateSessionResponse response = null; + try { + response = createSessionClient.createSession(request); + } catch (StatusRuntimeException statusRuntimeException) { + LOGGER.error("status RuntimeException getStatus:{}", statusRuntimeException.getStatus()); + return ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(-1).build(); + } + return response; + } + + private List getProfilerPluginCapabilities(DeviceIPPortInfo device) { + ProfilerServiceTypes.GetCapabilitiesResponse capabilitiesRes = + HiProfilerClient.getInstance().getCapabilities(device.getIp(), device.getForwardPort()); + return capabilitiesRes.getCapabilitiesList(); + } + + private ProfilerServiceTypes.ProfilerSessionConfig.Builder getSessionConfigBuilder() { + ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setKeepAliveTime(KEEP_SESSION_TIME) + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE); + return sessionConfigBuilder; + } + + private void startKeepLiveSession(DeviceIPPortInfo deviceIPPortInfo, int sessionId, long localSessionId) { + String keepSessionName = getKeepSessionName(deviceIPPortInfo, sessionId); + QuartzManager.getInstance() + .addExecutor(keepSessionName, new KeepSession(localSessionId, sessionId, deviceIPPortInfo)); + QuartzManager.getInstance().startExecutor(keepSessionName, 0, KEEP_SESSION_REQUEST_TIME); + } + + /** + * getKeepSessionName + * + * @param deviceIPPortInfo deviceIPPortInfo + * @param sessionId sessionId + * @return String + */ + public String getKeepSessionName(DeviceIPPortInfo deviceIPPortInfo, int sessionId) { + if (Objects.nonNull(deviceIPPortInfo)) { + return "KEEP" + deviceIPPortInfo.getDeviceName() + sessionId; + } else { + return ""; + } + } + + private SessionInfo createSessionInfo(DeviceIPPortInfo device, ProcessInfo process, int sessionId) { + String deviceId = device.getDeviceID(); + String sessionName = CommonUtil.generateSessionName(deviceId, process.getProcessId()); + SessionInfo session = + SessionInfo.builder().sessionId(sessionId).sessionName(sessionName).pid(process.getProcessId()) + .processName(process.getProcessName()).deviceIPPortInfo(device).build(); + return session; + } + + private Optional getLibPlugin( + List capabilities, String libDataPlugin) { + Optional ability = capabilities.stream() + .filter(profilerPluginCapability -> profilerPluginCapability.getName().contains(libDataPlugin)).findFirst(); + return ability; + } + + /** + * Establish a session with the end side and start the session. + * + * @param localSessionId Local Session Id + * @param restartFlag Whether to start again + * @return boolean + */ + public boolean startSession(Long localSessionId, boolean restartFlag) { + if (localSessionId == null) { + return false; + } + SessionInfo session = profilingSessions.get(localSessionId); + if (session == null) { + return true; + } + if (restartFlag) { + // Click start, delete the previous data first + MemoryService.getInstance().deleteSessionData(localSessionId); + deleteAllAgentData(localSessionId, false); + } + int sessionId = session.getSessionId(); + LOGGER.info("startSession sessionId {}", sessionId); + DeviceIPPortInfo device = session.getDeviceIPPortInfo(); + return HiProfilerClient.getInstance().requestStartSession(device.getIp(), device.getForwardPort(), sessionId); + } + + /** + * Turn on polling to get data + * + * @param localSessionId localSessionId + * @return boolean Turn on polling + */ + public boolean fetchData(Long localSessionId) { + if (localSessionId == null || localSessionId <= 0) { + return false; + } + // Set permissions on the process that gets CPU data + DeviceIPPortInfo deviceInfo = SessionManager.getInstance().getDeviceInfoBySessionId(localSessionId); + ArrayList cmdStr; + if (IS_SUPPORT_NEW_HDC && deviceInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_STD_CHMOD_PROC, deviceInfo.getDeviceID()); + HdcWrapper.getInstance().execCmdBy(cmdStr, 10); + } + if ((!IS_SUPPORT_NEW_HDC) && deviceInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmdStr = conversionCommand(HDC_CHMOD_PROC, deviceInfo.getDeviceID()); + HdcWrapper.getInstance().execCmdBy(cmdStr, 10); + } + try { + if (localSessionId <= 0) { + return false; + } + SessionInfo session = profilingSessions.get(localSessionId); + if (session == null) { + return true; + } + DeviceIPPortInfo device = session.getDeviceIPPortInfo(); + ProfilerClient client = + HiProfilerClient.getInstance().getProfilerClient(device.getIp(), device.getForwardPort()); + LOGGER.info("start new DataPoller {}", DateTimeUtil.getNowTimeLong()); + int sessionId = session.getSessionId(); + DataPoller dataPoller = new DataPoller(localSessionId, sessionId, client); + dataPoller.start(); + dataPollerHashMap.put(localSessionId, dataPoller); + return true; + } catch (Exception exception) { + LOGGER.error(exception.getMessage()); + return false; + } + } + + /** + * isRefsh + * + * @param localSessionId localSessionId + * @return boolean + */ + public SessionInfo getSessionInfo(Long localSessionId) { + return profilingSessions.get(localSessionId); + } + + /** + * getDeviceInfoBySessionId + * + * @param localSessionId localSessionId + * @return DeviceIPPortInfo + */ + public DeviceIPPortInfo getDeviceInfoBySessionId(long localSessionId) { + return profilingSessions.get(localSessionId).getDeviceIPPortInfo(); + } + + /** + * View stop Loading + * + * @param localSession local Session + * @param firstTimeStamp first Time Stamp + */ + public void stopLoadingView(Long localSession, long firstTimeStamp) { + SessionInfo sessionInfo = profilingSessions.get(localSession); + if (sessionInfo != null) { + sessionInfo.setStartTimestamp(firstTimeStamp); + sessionInfo.setStartRefsh(true); + profilingSessions.put(localSession, sessionInfo); + } + } + + /** + * stop Session + * + * @param localSessionId localSessionId + * @return boolean Stop success indicator + */ + public boolean endSession(Long localSessionId) { + if (localSessionId == null || localSessionId <= 0) { + return false; + } + SessionInfo session = profilingSessions.get(localSessionId); + if (session == null) { + return true; + } + session.setStartRefsh(false); + int sessionId = session.getSessionId(); + DeviceIPPortInfo device = session.getDeviceIPPortInfo(); + LOGGER.info("endSession sessionId {}", sessionId); + boolean stopSessionRes = + HiProfilerClient.getInstance().requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true); + if (stopSessionRes) { + DataPoller dataPoller = dataPollerHashMap.get(localSessionId); + if (dataPoller != null) { + dataPoller.shutDown(); + } + PrintUtil.print(LOGGER, "Task with Session stopped successfully.", 0); + } else { + LOGGER.error("Failed to stop task with Session!"); + } + return stopSessionRes; + } + + /** + * Delete the Session session interface + * + * @param localSessionId localSessionId + * @return boolean Is the deletion successful + */ + public boolean deleteSession(Long localSessionId) { + try { + if (localSessionId == null || localSessionId <= 0) { + return false; + } + SessionInfo session = profilingSessions.get(localSessionId); + if (session == null) { + return false; + } + String keepSessionName = getKeepSessionName(session.getDeviceIPPortInfo(), session.getSessionId()); + QuartzManager.getInstance().deleteExecutor(keepSessionName); + // Delete session information in local memory + profilingSessions.remove(localSessionId); + // Delete the data information related to the session of the database + MemoryService.getInstance().deleteSessionData(localSessionId); + deleteAllAgentData(localSessionId, true); + if (session.isOfflineMode()) { + return true; + } + int sessionId = session.getSessionId(); + LOGGER.info("deleteSession sessionId {}", sessionId); + DeviceIPPortInfo device = session.getDeviceIPPortInfo(); + boolean stopSessionRes = HiProfilerClient.getInstance() + .requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true); + // Delete collection item + if (stopSessionRes) { + boolean destroySessionRes = false; + try { + destroySessionRes = HiProfilerClient.getInstance() + .requestDestroySession(device.getIp(), device.getForwardPort(), sessionId); + if (destroySessionRes) { + DataPoller dataPoller = dataPollerHashMap.get(localSessionId); + if (dataPoller != null) { + dataPoller.shutDown(); + } + } + } catch (StatusRuntimeException exception) { + LOGGER.error(exception.getMessage()); + } + PrintUtil.print(LOGGER, "Task with Session deleted successfully.", 0); + return destroySessionRes; + } else { + LOGGER.error("Failed to delete task with Session "); + return false; + } + } finally { + doDeleteSessionData(localSessionId); + } + } + + /** + * doDeleteSessionData + * + * @param localSessionId localSessionId + */ + private void doDeleteSessionData(Long localSessionId) { + if (localSessionId != null && localSessionId > 0) { + boolean traceFile = ProfilerChartsView.sessionMap.get(localSessionId).getPublisher().isTraceFile(); + if (!traceFile) { + MemoryService.getInstance().deleteSessionData(localSessionId); + deleteAllAgentData(localSessionId, true); + } + } + } + + private void deleteAllAgentData(Long localSessionId, boolean deleteClassInfo) { + if (memoTable == null) { + memoTable = new MemoryTable(); + } + if (memoryHeapDao == null) { + memoryHeapDao = new MemoryHeapDao(); + } + if (memoryInstanceDao == null) { + memoryInstanceDao = new MemoryInstanceDao(); + } + if (classInfoDao == null) { + classInfoDao = new ClassInfoDao(); + } + if (memoryInstanceDetailsDao == null) { + memoryInstanceDetailsDao = new MemoryInstanceDetailsDao(); + } + if (deleteClassInfo) { + classInfoDao.deleteSessionData(localSessionId); + } + memoryHeapDao.deleteSessionData(localSessionId); + memoryInstanceDao.deleteSessionData(localSessionId); + memoryInstanceDetailsDao.deleteSessionData(localSessionId); + } + + /** + * Used to notify the end side to close all session connections after the IDE is closed. + */ + public void stopAllSession() { + if (profilingSessions.isEmpty()) { + return; + } + profilingSessions.values().forEach(sessionInfo -> { + String keepSessionName = getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId()); + QuartzManager.getInstance().deleteExecutor(keepSessionName); + DeviceIPPortInfo device = sessionInfo.getDeviceIPPortInfo(); + if (device != null) { + HiProfilerClient hiProfiler = HiProfilerClient.getInstance(); + hiProfiler + .requestStopSession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId(), true); + hiProfiler.requestDestroySession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId()); + } + }); + } + + /** + * Save the collected data to a file. + * + * @param sessionId sessionId + * @param deviceProcessInfo deviceProcessInfo + * @param pathname pathname + * @return boolean + */ + public boolean saveSessionDataToFile(long sessionId, DeviceProcessInfo deviceProcessInfo, String pathname) { + if (sessionId <= 0 || deviceProcessInfo == null || StringUtils.isEmpty(pathname)) { + return false; + } + List memInfoList = MemoryService.getInstance().getAllData(sessionId); + List classInfos = new ClassInfoManager().getAllClassInfoData(sessionId); + List memoryHeapInfos = new MemoryHeapManager().getAllMemoryHeapInfos(sessionId); + List detailsInfos = new MemoryInstanceDetailsManager().getAllMemoryInstanceDetails(); + ArrayList memoryInstanceInfos = new MemoryInstanceManager().getAllMemoryInstanceInfos(); + List cpuInfoList = CpuDao.getInstance().getAllData(sessionId); + FileOutputStream fileOutputStream = null; + ObjectOutputStream objectOutputStream = null; + try { + File file = new File(pathname); + fileOutputStream = new FileOutputStream(file); + objectOutputStream = new ObjectOutputStream(fileOutputStream); + // Start importing the number of meminfo in an object record file + TraceFileInfo startObj = new TraceFileInfo(); + int recordNum = memInfoList.size() + classInfos.size() + memoryHeapInfos.size() + detailsInfos.size() + + memoryInstanceInfos.size() + cpuInfoList.size(); + startObj.setRecordNum(recordNum); + startObj.setCreateTime(new Date().getTime()); + // Set the trace file version, the subsequent file save content format changes and is not compatible with + // the previous file, you need to modify the version number, and you need to modify the version number + // in the local Session Data From File method. + startObj.setVersion("V1.0"); + objectOutputStream.writeObject(startObj); + for (int index = 0; index < memInfoList.size(); index++) { + setDeviceProcessInfo(deviceProcessInfo, memInfoList, objectOutputStream, index); + } + for (ProcessCpuData processCpuData : cpuInfoList) { + objectOutputStream.writeObject(processCpuData); + } + writeCollectionData(objectOutputStream, classInfos, memoryHeapInfos, detailsInfos, memoryInstanceInfos); + objectOutputStream.writeObject(deviceProcessInfo); + PrintUtil.print(LOGGER, "Task with Session ID {} Save To File successfully.", 0); + } catch (IOException exception) { + return false; + } finally { + closeIoStream(null, null, fileOutputStream, objectOutputStream); + } + return true; + } + + /** + * setDeviceProcessInfo + * + * @param deviceProcessInfo deviceProcessInfo + * @param memInfoList memInfoList + * @param objectOutputStream objectOutputStream + * @param index index + * @throws IOException + */ + private void setDeviceProcessInfo(DeviceProcessInfo deviceProcessInfo, List memInfoList, + ObjectOutputStream objectOutputStream, int index) throws IOException { + ProcessMemInfo memObject = memInfoList.get(index); + objectOutputStream.writeObject(memObject); + if (index == 0) { + deviceProcessInfo.setStartTime(memObject.getTimeStamp()); + } + if (index == (memInfoList.size() - 1)) { + deviceProcessInfo.setEndTime(memObject.getTimeStamp()); + } + } + + private void writeCollectionData(ObjectOutputStream objectOutputStream, List classInfos, + List memoryHeapInfos, List detailsInfos, + ArrayList memoryInstanceInfos) throws IOException { + for (ClassInfo classInfo : classInfos) { + objectOutputStream.writeObject(classInfo); + } + for (MemoryHeapInfo memoryHeapInfo : memoryHeapInfos) { + objectOutputStream.writeObject(memoryHeapInfo); + } + for (MemoryInstanceDetailsInfo instanceDetailsInfo : detailsInfos) { + objectOutputStream.writeObject(instanceDetailsInfo); + } + + for (int index = 0; index < memoryInstanceInfos.size(); index++) { + MemoryUpdateInfo instanceInfo = memoryInstanceInfos.get(index); + objectOutputStream.writeObject(instanceInfo); + } + } + + /** + * local Session Data From File + * + * @param jProgressBar jProgressBar + * @param file file + * @return Optional + */ + public Optional localSessionDataFromFile(JProgressBar jProgressBar, File file) { + if (jProgressBar == null || file == null) { + return Optional.ofNullable(null); + } + FileInputStream fileInputStream = null; + ObjectInputStream objectInputStream = null; + DeviceProcessInfo deviceProcessInfo = null; + try { + fileInputStream = new FileInputStream(file); + objectInputStream = new ObjectInputStream(fileInputStream); + Object firstObj = objectInputStream.readObject(); + TraceFileInfo traceFileInfo = null; + if (firstObj instanceof TraceFileInfo) { + traceFileInfo = (TraceFileInfo) firstObj; + if (!"V1.0".equals(traceFileInfo.getVersion())) { + // The trace file is not the latest version + return Optional.empty(); + } + } else { + // The trace file is not the latest version + return Optional.empty(); + } + deviceProcessInfo = loadFileInDataBase(jProgressBar, traceFileInfo, objectInputStream); + } catch (IOException | ClassNotFoundException exception) { + if (exception.getMessage().indexOf("invalid stream header") >= 0) { + if (file.getName().indexOf(".bin") >= 0) { + return Optional.empty(); + } + return Optional.empty(); + } + LOGGER.error("load Data Error {}", exception.getMessage()); + return Optional.empty(); + } finally { + closeIoStream(fileInputStream, objectInputStream, null, null); + } + long localSessionId = deviceProcessInfo.getLocalSessionId(); + SessionInfo session = SessionInfo.builder().sessionName(String.valueOf(localSessionId)).build(); + session.setOfflineMode(true); + profilingSessions.put(localSessionId, session); + jProgressBar.setValue(LayoutConstants.HUNDRED); + return Optional.of(deviceProcessInfo); + } + + private DeviceProcessInfo loadFileInDataBase(JProgressBar jProgressBar, TraceFileInfo traceFileInfo, + ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { + long objNum = traceFileInfo.getRecordNum() + 1; + long currentNum = 0; + Validate[] validates = {new CpuValidate(), new MemoryValidate()}; + while (true) { + Object object = objectInputStream.readObject(); + for (Validate item : validates) { + if (item.validate(object)) { + currentNum = currentNum + 1; + loadPercentage(jProgressBar, objNum, currentNum); + item.addToList(object); + break; + } + } + if (object instanceof DeviceProcessInfo) { + // Finally, if there is still data in the datalist, import the database + int processMemInfoNum = 0; + for (Validate item : validates) { + if (item instanceof MemoryValidate) { + processMemInfoNum = ((MemoryValidate) item).getMenInfoSize(); + } + item.batchInsertToDb(); + } + currentNum = currentNum + processMemInfoNum; + int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum); + jProgressBar.setValue(progress); + DeviceProcessInfo deviceProcessInfo = (DeviceProcessInfo) object; + return deviceProcessInfo; + } else { + continue; + } + } + } + + private void loadPercentage(JProgressBar jProgressBar, long objNum, long currentNum) { + int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum); + double result = progress % 25; + if (result == 0) { + jProgressBar.setValue(progress); + } + } + + private void closeIoStream(FileInputStream fileInputStream, ObjectInputStream objectInputStream, + FileOutputStream fileOutputStream, ObjectOutputStream objectOutputStream) { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException exception) { + LOGGER.error("exception:{}", exception.getMessage()); + } + } + if (objectInputStream != null) { + try { + objectInputStream.close(); + } catch (IOException exception) { + LOGGER.error("exception:{}", exception.getMessage()); + } + } + if (fileOutputStream != null) { + try { + fileOutputStream.close(); + } catch (IOException exception) { + LOGGER.error("exception:{}", exception.getMessage()); + } + } + if (objectOutputStream != null) { + try { + objectOutputStream.close(); + } catch (IOException exception) { + LOGGER.error("exception:{}", exception.getMessage()); + } + } + } + + /** + * delete Session By OffLine Device + * + * @param device device + */ + public void deleteSessionByOffLineDevice(DeviceIPPortInfo device) { + if (profilingSessions.isEmpty() || device == null) { + return; + } + Set sessionIds = profilingSessions.keySet(); + for (Long session : sessionIds) { + SessionInfo sessionInfo = profilingSessions.get(session); + if (sessionInfo != null) { + DeviceIPPortInfo deviceSource = sessionInfo.getDeviceIPPortInfo(); + if (device.getDeviceID().equals(deviceSource.getDeviceID())) { + String keepSessionName = + getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId()); + QuartzManager.getInstance().deleteExecutor(keepSessionName); + // 停止chart刷新 + ProfilerChartsView.sessionMap.get(session).getPublisher().stopRefresh(true); + profilingSessions.remove(session); + } + } + } + } + + /** + * get Plugin Path + * + * @return String plugin Path + */ + public String getPluginPath() { + String pluginPath = ""; + if (IS_DEVELOP_MODE || developMode) { + pluginPath = "C:\\ohos\\"; + } else { + PluginId plugin = PluginManager.getPluginByClassName(this.getClass().getName()); + if (plugin != null) { + File path = PluginManager.getPlugin(plugin).getPath(); + try { + pluginPath = path.getCanonicalPath() + File.separator + "ohos" + File.separator; + } catch (IOException ioException) { + LOGGER.error("ioException ", ioException); + } + } + } + return pluginPath; + } + + /** + * get temp Path + * + * @return String temp Path + */ + public String tempPath() { + String pluginPath = ""; + if (IS_DEVELOP_MODE || developMode) { + pluginPath = "C:\\ohos\\"; + } else { + pluginPath = PathManager.getTempPath() + File.separator + "ohos" + File.separator; + } + return pluginPath; + } + + /** + * getHdcPath + * + * @return String + */ + public String getHdcPath() { + if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("mac")) { + return getPluginPath() + "macHdc" + File.separator + "hdc"; + } else { + return getPluginPath() + "winHdc" + File.separator + "hdc"; + } + } + + /** + * getHdcStdPath + * + * @return String + */ + public String getHdcStdPath() { + if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("mac")) { + return getPluginPath() + "macHdc" + File.separator + "hdc_std"; + } else { + return getPluginPath() + "winHdc" + File.separator + "hdc_std.exe"; + } + } + + /** + * get pid + * + * @param localSessionId localSessionId + * @return long + */ + public long getPid(Long localSessionId) { + return profilingSessions.get(localSessionId).getPid(); + } + + /** + * get ProcessName + * + * @param localSessionId localSessionId + * @return long + */ + public String getProcessName(Long localSessionId) { + SessionInfo sessionInfo = profilingSessions.get(localSessionId); + if (sessionInfo != null) { + return sessionInfo.getProcessName(); + } + return ""; + } + + public void setDevelopMode(boolean developMode) { + this.developMode = developMode; + } + + /** + * export File + * + * @param exportFileName exportFileName + * @param fileChooserDialog fileChooserDialog + * @return boolean + */ + public boolean exportDumpOrHookFile(String exportFileName, ExportFileChooserDialog fileChooserDialog) { + // not get from device + int line; + boolean result = true; + FileOutputStream fileOut = null; + BufferedOutputStream dataOut = null; + File file = new File(SessionManager.getInstance().tempPath() + File.separator + exportFileName); + try { + // Excuting an order + fileOut = new FileOutputStream( + fileChooserDialog.getExportFilePath() + File.separator + fileChooserDialog.getExportFileName() + + "." + fileChooserDialog.getFileType()); + dataOut = new BufferedOutputStream(fileOut); + try (InputStream inputStream = new FileInputStream(file); + BufferedInputStream brInputStream = new BufferedInputStream(inputStream);) { + while ((line = brInputStream.read()) != -1) { + dataOut.write(line); + } + } catch (IOException exception) { + LOGGER.error("exception {}", exception.getMessage()); + result = false; + } + } catch (IOException exception) { + LOGGER.error("exception {}", exception.getMessage()); + result = false; + } finally { + try { + dataOut.flush(); + if (fileOut != null) { + fileOut.close(); + } + } catch (IOException exception) { + LOGGER.error("exception {}", exception.getMessage()); + result = false; + } + } + return result; + } + + /** + * getDeviceType By sessionId + * + * @param sessionId sessionId + * @return DeviceType + */ + public DeviceType getDeviceType(long sessionId) { + SessionInfo sessionInfo = profilingSessions.get(sessionId); + if (sessionInfo == null || sessionInfo.getDeviceIPPortInfo() == null) { + return LEAN_HOS_DEVICE; + } + return sessionInfo.getDeviceIPPortInfo().getDeviceType(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/trace/service/TraceManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/trace/service/TraceManager.java deleted file mode 100644 index b323bc84d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/datasources/utils/trace/service/TraceManager.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.trace.service; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import io.grpc.StatusRuntimeException; - -import com.google.protobuf.ByteString; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper; -import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.transport.grpc.service.PtracePluginConfigOuterClass; -import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass; -import ohos.devtools.datasources.utils.common.GrpcException; -import ohos.devtools.datasources.utils.common.util.BeanUtil; -import ohos.devtools.datasources.utils.common.util.CommonUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.service.ProcessManager; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.SystemTunningProbesCheckbox; - -/** - * get trace data - * - * @version 1.0 - * @date 2021/04/12 17:07 - **/ -public class TraceManager { - private static final Logger LOGGER = LogManager.getLogger(ProcessManager.class); - - /** - * 单例进程对象 - */ - private static TraceManager singleton; - - /** - * 获取实例 - * - * @return TraceManager - */ - public static TraceManager getSingleton() { - if (singleton == null) { - synchronized (ProcessManager.class) { - if (singleton == null) { - singleton = new TraceManager(); - } - } - } - return singleton; - } - - /** - * 请求通过ptrace获取数据 - * - * @param deviceIPPortInfo deviceIPPortInfo - * @param getUserCheckBoxForPerfettoStr getUserCheckBoxForPerfettoStr - * @param isReturn isReturn - * @param maxDurationParam maxDurationParam - * @return String - * @throws GrpcException GrpcException - */ - public String createSessionRequestPerfetto(DeviceIPPortInfo deviceIPPortInfo, String getUserCheckBoxForPerfettoStr, - int maxDurationParam, Boolean isReturn) throws GrpcException { - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - ProfilerClient client = - hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - // 获取插件名称 - ProfilerServiceTypes.GetCapabilitiesResponse response = - HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - List capabilitiesList = response.getCapabilitiesList(); - ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = - capabilitiesList.stream().filter(item -> item.getName().contains("libptrace")).findFirst().get(); - String pluginName = profilerPluginCapability.getName(); - PtracePluginConfigOuterClass.PtracePluginConfig.Builder build = - PtracePluginConfigOuterClass.PtracePluginConfig.newBuilder(); - build.setConfigText(getUserCheckBoxForPerfettoStr); - build.setResultPath("/data/local/tmp/hiprofiler_data.ptrace"); - PtracePluginConfigOuterClass.PtracePluginConfig config = build.build(); - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) - .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); - ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = - ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() - .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE).addBuffers(bf) - .setResultFile("/data/local/tmp/hiprofiler_data.ptrace").build(); - CommonTypes.ProfilerPluginConfig plugConfig = - CommonTypes.ProfilerPluginConfig.newBuilder().setName(pluginName).setPluginSha256("111") - .setSampleInterval(1).setConfigData(config.toByteString()).build(); - ProfilerServiceTypes.CreateSessionRequest request = - ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) - .addPluginConfigs(plugConfig).build(); - if (isReturn) { - return getUserCheckBoxForPerfettoStr; - } else { - // 通知端侧要用那些插件(分配资源) - ProfilerServiceTypes.CreateSessionResponse response1 = client.createSession(request); - ProfilerServiceTypes.StartSessionRequest requestStartSession = ProfilerServiceHelper - .startSessionRequest(CommonUtil.getRequestId(), response1.getSessionId(), new ArrayList<>()); - // 调用哪些进程(采集数据) - ProfilerServiceTypes.StartSessionResponse startSessionResponse = client.startSession(requestStartSession); - return String.valueOf(response1.getSessionId()); - } - } - - /** - * stopSession、destroySessionRequest - * - * @param deviceIPPortInfo deviceIPPortInfo - * @param sessionIdParam sessionIdParam - */ - public void stopAndDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) { - // 停止和销毁session - int sessionId = Integer.valueOf(sessionIdParam); - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - ProfilerClient client = - hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - ProfilerServiceTypes.StopSessionRequest stopSession = - ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId); - HiProfilerClient.getInstance() - .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, true); - ProfilerServiceTypes.DestroySessionRequest req = - ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), sessionId); - try { - client.destroySession(req); - } catch (StatusRuntimeException exception) { - HiProfilerClient.getInstance() - .requestDestroySession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getPort(), sessionId); - } - client.setUsed(false); - } - - /** - * request start session - * - * @param deviceIPPortInfo device IP Port Info - * @param getUserCheckBoxForPerfettoStr getUserCheckBoxForPerfettoStr - * @param maxDurationParam maxDurationParam - * @param inMemoryValue inMemoryValue - * @param isReturn isReturn - * @return String - * @throws GrpcException GrpcException - */ - public String createSessionByTraceRequest(DeviceIPPortInfo deviceIPPortInfo, String getUserCheckBoxForPerfettoStr, - int maxDurationParam, int inMemoryValue, Boolean isReturn) throws GrpcException { - BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = - BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); - build.setBuffeSize(inMemoryValue * SystemTunningProbesCheckbox.MEMORY_MB_TO_KB); - build.setClock("boot"); - if (getUserCheckBoxForPerfettoStr != null && getUserCheckBoxForPerfettoStr.length() > 0) { - Arrays.stream(getUserCheckBoxForPerfettoStr.split(";")).filter(param -> param.trim().length() > 0) - .forEach(param -> build.addCategories(param)); - } else { - // catch All - build.addCategories(""); - } - build.setTime(maxDurationParam); - build.setOutfileName("/data/local/tmp/hiprofiler_data.bytrace"); - BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); - byte[] ccByte = BeanUtil.serializeByCodedOutPutStream(config); - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) - .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); - ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = - ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() - .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE).addBuffers(bf) - .setResultFile("/data/local/tmp/hiprofiler_data.bytrace").build(); - // 获取插件名称 - ProfilerServiceTypes.GetCapabilitiesResponse response = - HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - List capabilitiesList = response.getCapabilitiesList(); - ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = - capabilitiesList.stream().filter(item -> item.getName().contains("libbytrace")).findFirst().get(); - String pluginName = profilerPluginCapability.getName(); - CommonTypes.ProfilerPluginConfig plugConfig = - CommonTypes.ProfilerPluginConfig.newBuilder().setName(pluginName).setPluginSha256("111") - .setSampleInterval(1).setConfigData(ByteString.copyFrom(ccByte)).build(); - ProfilerServiceTypes.CreateSessionRequest request = - ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) - .addPluginConfigs(plugConfig).build(); - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - ProfilerClient client = - hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - ProfilerServiceTypes.CreateSessionResponse createSessionResponse = client.createSession(request); - ProfilerServiceTypes.StartSessionRequest requestStartSession = ProfilerServiceHelper - .startSessionRequest(CommonUtil.getRequestId(), createSessionResponse.getSessionId(), new ArrayList<>()); - // 调用哪些进程(采集数据) - client.startSession(requestStartSession); - return String.valueOf(createSessionResponse.getSessionId()); - } - - /** - * 请求启动session - * - * @param deviceIPPortInfo deviceIPPortInfo - * @param param param - * @param paramRecordSetting paramRecordSetting - * @param isReturn isReturn - * @return String - * @throws GrpcException GrpcException - */ - public String createSessionRequest(DeviceIPPortInfo deviceIPPortInfo, HashMap> param, - HashMap paramRecordSetting, Boolean isReturn) throws GrpcException { - int sampleDuration = 0; - int resultMaxSize = 0; - HiProfilerClient hiprofiler = HiProfilerClient.getInstance(); - ProfilerClient client = - hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - // 获取插件名称 - ProfilerServiceTypes.GetCapabilitiesResponse response = - HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort()); - List capabilitiesList = response.getCapabilitiesList(); - if (capabilitiesList.size() == 0) { - return ""; - } - ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = - capabilitiesList.stream().filter(item -> item.getName().contains("libtrace")).findFirst().get(); - String pluginName = null; - TracePluginConfigOuterClass.TracePluginConfig.Builder build = - TracePluginConfigOuterClass.TracePluginConfig.newBuilder(); - pluginName = profilerPluginCapability.getName(); - String configDataStr = ""; - if (param != null && !param.isEmpty()) { - for (String key : param.keySet()) { - configDataStr = getConfigDataStr(param, build, configDataStr, key); - } - } - if (paramRecordSetting != null && paramRecordSetting.size() > 0) { - for (String key : paramRecordSetting.keySet()) { - switch (key) { - case SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_KIND_IN_MEMORY: - build - .setBufferSizeKb(paramRecordSetting.get(key) * SystemTunningProbesCheckbox.MEMORY_MB_TO_KB); - // 将MB 转换为KB - resultMaxSize = paramRecordSetting.get(key) * SystemTunningProbesCheckbox.MEMORY_MB_TO_KB; - break; - case SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_KIND_MAX_DURATION: - build.setTracePeriodMs(paramRecordSetting.get(key) * SystemTunningProbesCheckbox.SECOND_TO_MS); - // 将MB 转换为KB - sampleDuration = paramRecordSetting.get(key) * SystemTunningProbesCheckbox.SECOND_TO_MS; - break; - default: - } - } - } - build.setClock("local"); - TracePluginConfigOuterClass.TracePluginConfig config = build.build(); - byte[] ccByte = BeanUtil.serializeByCodedOutPutStream(config); - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = - ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) - .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); - ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = - ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setSampleDuration(sampleDuration) - .setResultMaxSize(resultMaxSize).setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE) - .addBuffers(bf).setResultFile("/data/local/tmp/hiprofiler_data.htrace").build(); - CommonTypes.ProfilerPluginConfig plugConfig = - CommonTypes.ProfilerPluginConfig.newBuilder().setName(pluginName).setPluginSha256("111") - .setSampleInterval(1).setConfigData(ByteString.copyFrom(ccByte)).build(); - ProfilerServiceTypes.CreateSessionRequest request = - ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) - .addPluginConfigs(plugConfig).build(); - if (isReturn) { - String[] strCommand = request.toString().split("config_data"); - return strCommand[0].concat("config_data:").concat("\"").concat(configDataStr).concat("\"") - .concat(System.lineSeparator() + "}"); - } else { - // 通知端侧要用那些插件(分配资源) - ProfilerServiceTypes.CreateSessionResponse response1 = client.createSession(request); - ProfilerServiceTypes.StartSessionRequest requestStartSession = ProfilerServiceHelper - .startSessionRequest(CommonUtil.getRequestId(), response1.getSessionId(), new ArrayList<>()); - // 调用哪些进程(采集数据) - ProfilerServiceTypes.StartSessionResponse startSessionResponse = client.startSession(requestStartSession); - return ""; - } - } - - private String getConfigDataStr(HashMap> param, - TracePluginConfigOuterClass.TracePluginConfig.Builder build, String configDataStr, String key) { - String configStr = configDataStr; - switch (key) { - case SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_KIND_FTRACE_EVENT: - for (int index = 0; index < param.get(key).size(); index++) { - build.addFtraceEvents(param.get(key).get(index)); - configStr = - configStr.concat(System.lineSeparator()).concat(param.get(key).get(index)); - } - break; - case SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_KIND_ATRACE_APPS: - for (int index = 0; index < param.get(key).size(); index++) { - build.addBytraceApps(param.get(key).get(index)); - configStr.concat(param.get(key).get(index)); - } - break; - default: - } - return configStr; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/AgentConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/AgentConfig.java new file mode 100644 index 000000000..b4328edc2 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/AgentConfig.java @@ -0,0 +1,106 @@ +/* + * 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. + */ + +package ohos.devtools.pluginconfig; + +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.service.AgentPluginConfig; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.datahandler.datapoller.AgentDataConsumer; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.DPlugin; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginBufferConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_START_JAVAHEAP; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.FULL_HOS_DEVICE; + +/** + * Agent Config + */ +@DPlugin +public class AgentConfig extends IPluginConfig { + private static final Logger LOGGER = LogManager.getLogger(AgentConfig.class); + private static final String AGENT_PLUGIN_NAME = "/data/local/tmp/libagentplugin.z.so"; + + @Override + public PluginConf createConfig() { + PluginConf agentConfig = + new PluginConf(AGENT_PLUGIN_NAME, JVMTI_AGENT_PLUG, AgentDataConsumer.class, false, null); + agentConfig.setICreatePluginConfig((deviceIPPortInfo, processInfo) -> { + AgentPluginConfig.AgentConfig agent = + AgentPluginConfig.AgentConfig.newBuilder().setPid(processInfo.getProcessId()).build(); + return new HiProfilerPluginConfig(40, agent.toByteString()); + }); + agentConfig.setPluginBufferConfig(new PluginBufferConfig(3000, PluginBufferConfig.Policy.RECYCLE)); + agentConfig.setSpecialStart(true); + agentConfig.setGetPluginName((deviceIPPortInfo, processInfo) -> { + String agentPlug = "jvmtiagent_" + processInfo.getProcessName(); + return agentPlug; + }); + agentConfig.setSpecialStartPlugMethod((deviceIPPortInfo, processInfo) -> { + String pluginName = agentConfig.getGetPluginName().getPluginName(deviceIPPortInfo, processInfo); + boolean startJavaHeap = isStartJavaHeap(deviceIPPortInfo, pluginName); + String proc = processInfo.getProcessName(); + if (StringUtils.isNotBlank(proc) && (!startJavaHeap)) { + if (deviceIPPortInfo.getDeviceType() == FULL_HOS_DEVICE) { + ArrayList cmd = conversionCommand(HDC_START_JAVAHEAP, deviceIPPortInfo.getDeviceID(), proc); + String res = HdcWrapper.getInstance().getHdcStringResult(cmd); + if (res.contains("javaHeapSuccess")) { + LOGGER.info("start Agent Success"); + startJavaHeap = true; + } + } + } + return startJavaHeap; + }); + agentConfig.setPluginMode(PluginMode.ONLINE); + agentConfig.addSupportDeviceTypes(FULL_HOS_DEVICE); + return agentConfig; + } + + private boolean isStartJavaHeap(DeviceIPPortInfo device, String agentPlugName) { + boolean startJavaHeap = false; + ProfilerServiceTypes.GetCapabilitiesResponse response = + HiProfilerClient.getInstance().getCapabilities(device.getIp(), device.getForwardPort()); + List capabilitiesResponse = response.getCapabilitiesList(); + List agentStatus = + getLibDataPlugin(capabilitiesResponse, agentPlugName); + if (!agentStatus.isEmpty()) { + startJavaHeap = true; + } + return startJavaHeap; + } + + private List getLibDataPlugin( + List capabilities, String libDataPlugin) { + return capabilities.stream() + .filter(profilerPluginCapability -> profilerPluginCapability.getName().contains(libDataPlugin)) + .collect(Collectors.toList()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/BytraceConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/BytraceConfig.java new file mode 100644 index 000000000..fb7b45175 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/BytraceConfig.java @@ -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. + */ + +package ohos.devtools.pluginconfig; + +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.DPlugin; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; + +/** + * BytraceConfig + */ +@DPlugin +public class BytraceConfig extends IPluginConfig { + private static final String BYTRACE_PLUGIN_NAME = "/data/local/tmp/libbytraceplugin.z.so"; + + @Override + public PluginConf createConfig() { + PluginConf bytraceConfig = new PluginConf(BYTRACE_PLUGIN_NAME, "", null, false, null); + bytraceConfig.setPluginMode(PluginMode.OFFLINE); + return bytraceConfig; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/CpuConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/CpuConfig.java new file mode 100644 index 000000000..88983036f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/CpuConfig.java @@ -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. + */ + +package ohos.devtools.pluginconfig; + +import ohos.devtools.datasources.transport.grpc.CpuPlugHelper; +import ohos.devtools.datasources.transport.grpc.service.CpuPluginConfig; +import ohos.devtools.datasources.utils.datahandler.datapoller.CpuDataConsumer; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.DPlugin; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.cpu.CpuItemView; + +import static ohos.devtools.datasources.utils.common.Constant.CPU_PLUG; + +/** + * Cpu Config + */ +@DPlugin +public class CpuConfig extends IPluginConfig { + private static final String CPU_PLUGIN_NAME = "/data/local/tmp/libcpudataplugin.z.so"; + + @Override + public PluginConf createConfig() { + ProfilerMonitorItem cpuItem = new ProfilerMonitorItem(1, "Cpu", CpuItemView.class); + PluginConf cpuConfig = new PluginConf(CPU_PLUGIN_NAME, CPU_PLUG, CpuDataConsumer.class, true, cpuItem); + cpuConfig.setICreatePluginConfig(((deviceIPPortInfo, processInfo) -> { + CpuPluginConfig.CpuConfig plug = CpuPlugHelper.createCpuRequest(processInfo.getProcessId()); + return new HiProfilerPluginConfig(40, plug.toByteString()); + })); + cpuConfig.setPluginMode(PluginMode.ONLINE); + return cpuConfig; + } + + private static CpuPluginConfig.CpuConfig getCpuConfig(DeviceIPPortInfo device, ProcessInfo process) { + CpuPluginConfig.CpuConfig plug = CpuPlugHelper.createCpuRequest(process.getProcessId()); + return plug; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/FtraceConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/FtraceConfig.java new file mode 100644 index 000000000..c807055e9 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/FtraceConfig.java @@ -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. + */ + +package ohos.devtools.pluginconfig; + +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.DPlugin; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; + +/** + * FtraceConfig + */ +@DPlugin +public class FtraceConfig extends IPluginConfig { + private static final String TRACE_PLUGIN_NAME = "/data/local/tmp/libftrace_plugin.z.so"; + + @Override + public PluginConf createConfig() { + PluginConf fTraceConfig = new PluginConf(TRACE_PLUGIN_NAME, "", null, false, null); + fTraceConfig.setPluginMode(PluginMode.OFFLINE); + return fTraceConfig; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/MemoryConfig.java b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/MemoryConfig.java new file mode 100644 index 000000000..de815436d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/pluginconfig/MemoryConfig.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.pluginconfig; + +import ohos.devtools.datasources.transport.grpc.MemoryPlugHelper; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig; +import ohos.devtools.datasources.utils.datahandler.datapoller.MemoryDataConsumer; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.DPlugin; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.memory.MemoryItemView; + +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.FULL_HOS_DEVICE; + +/** + * MemoryConfig + */ +@DPlugin +public class MemoryConfig extends IPluginConfig { + private static final String MEM_PLUGIN_NAME = "/data/local/tmp/libmemdataplugin.z.so"; + + @Override + public PluginConf createConfig() { + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + PluginConf memoryConfig = + new PluginConf(MEM_PLUGIN_NAME, MEMORY_PLUG, MemoryDataConsumer.class, true, memoryItem); + memoryConfig.setICreatePluginConfig((deviceIPPortInfo, processInfo) -> new HiProfilerPluginConfig(40, + getConfig(deviceIPPortInfo, processInfo).toByteString())); + memoryConfig.setPluginMode(PluginMode.ONLINE); + return memoryConfig; + } + + private static MemoryPluginConfig.MemoryConfig getConfig(DeviceIPPortInfo device, ProcessInfo process) { + MemoryPluginConfig.MemoryConfig plug; + if (device.getDeviceType() == FULL_HOS_DEVICE) { + plug = MemoryPlugHelper.createMemRequest(process.getProcessId(), false, true, true, true); + } else { + plug = MemoryPlugHelper.createMemRequest(process.getProcessId(), false, true, true, false); + } + return plug; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/CacheMap.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/CacheMap.java new file mode 100644 index 000000000..50c956f1c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/CacheMap.java @@ -0,0 +1,62 @@ +/* + * 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. + */ + +package ohos.devtools.services; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Map with its own recycling mechanism + * + * @param k + * @param v + */ +public class CacheMap extends LinkedHashMap { + /** + * Cache max size + * + * @see "Cache about 40 seconds of data" + */ + private static final int CACHE_MAX_SIZE = 1000; + + /** + * Map default load factor + */ + private static final float LOAD_FACTOR = 0.75F; + + /** + * CacheMap constructor + */ + public CacheMap() { + this(CACHE_MAX_SIZE, LOAD_FACTOR, true); + } + + /** + * CacheMap constructor + * + * @param initialCapacity initialCapacity + * @param loadFactor loadFactor + * @param accessOrder accessOrder + */ + public CacheMap(int initialCapacity, float loadFactor, boolean accessOrder) { + super(initialCapacity, loadFactor, accessOrder); + } + + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > CACHE_MAX_SIZE; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDao.java index 829cd62b0..fd9e98e07 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDao.java @@ -1,24 +1,351 @@ -/* - * 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. - */ - -package ohos.devtools.services.cpu; - -/** - * @Description Cpu与数据库的交互类 - * @Date 2021/2/7 13:58 - **/ -public class CpuDao { -} - +/* + * 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. + */ + +package ohos.devtools.services.cpu; + +import com.google.protobuf.InvalidProtocolBufferException; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import ohos.devtools.datasources.transport.grpc.service.CpuPluginResult; +import ohos.devtools.datasources.utils.datahandler.datapoller.CpuDataConsumer; +import ohos.devtools.views.charts.model.ChartDataModel; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static ohos.devtools.services.cpu.CpuDao.CpuSelectStatements.SELECT_AFTER_TAIL; +import static ohos.devtools.services.cpu.CpuDao.CpuSelectStatements.SELECT_ALL_APP_CPU_INFO; +import static ohos.devtools.services.cpu.CpuDao.CpuSelectStatements.SELECT_APP_CPU_INFO; +import static ohos.devtools.services.cpu.CpuDao.CpuSelectStatements.SELECT_BEFORE_HEAD; + +/** + * Cpu Dao + */ +public class CpuDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(CpuDao.class); + private static volatile CpuDao singleton; + private Map cpuSelectMap = new HashMap<>(); + private Map threadSelectMap = new HashMap<>(); + private Connection conn; + + /** + * getInstance + * + * @return CpuDao + */ + public static CpuDao getInstance() { + if (singleton == null) { + synchronized (CpuDao.class) { + if (singleton == null) { + singleton = new CpuDao(); + } + } + } + return singleton; + } + + /** + * Cpu Select Statements + */ + public enum CpuSelectStatements { + SELECT_APP_CPU_INFO("SELECT timeStamp, Data from processCpuInfo where " + + "session = ? and timeStamp > ? and timeStamp < ?"), + SELECT_ALL_APP_CPU_INFO("SELECT timeStamp, Data from processCpuInfo where session = ?"), + DELETE_APP_CPU_INFO("delete from processCpuInfo where session = ?"), + SELECT_BEFORE_HEAD("SELECT timeStamp, Data from processCpuInfo where " + + "session = ? and timeStamp < ? order by timeStamp desc limit 1"), + SELECT_AFTER_TAIL("SELECT timeStamp, Data from processCpuInfo where " + + "session = ? and timeStamp > ? order by timeStamp asc limit 1"); + + CpuSelectStatements(String sqlStatement) { + this.sqlStatement = sqlStatement; + } + + private final String sqlStatement; + + /** + * getStatement + * + * @return String + */ + public String getStatement() { + return sqlStatement; + } + } + + private CpuDao() { + if (conn == null) { + Optional connection = getConnectBydbName("cpuDb"); + if (connection.isPresent()) { + conn = connection.get(); + } + createPrePareStatements(); + } + } + + private void createPrePareStatements() { + CpuDao.CpuSelectStatements[] values = CpuDao.CpuSelectStatements.values(); + for (CpuDao.CpuSelectStatements sta : values) { + PreparedStatement psmt = null; + try { + psmt = conn.prepareStatement(sta.getStatement()); + cpuSelectMap.put(sta, psmt); + threadSelectMap.put(sta, psmt); + } catch (SQLException throwAbles) { + LOGGER.error(" SQLException {}", throwAbles.getMessage()); + } + } + } + + /** + * getAllData + * + * @param sessionId sessionId + * @return List + */ + public List getAllData(long sessionId) { + PreparedStatement pst = cpuSelectMap.get(SELECT_ALL_APP_CPU_INFO); + List result = new ArrayList<>(); + try { + if (pst != null) { + pst.setLong(1, sessionId); + ResultSet rs = pst.executeQuery(); + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + ProcessCpuData processCpu = new ProcessCpuData(); + CpuPluginResult.CpuData.Builder builders = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData appSummary = builders.mergeFrom(data).build(); + processCpu.setData(appSummary); + processCpu.setTimeStamp(timeStamp); + processCpu.setSession(sessionId); + result.add(processCpu); + } + } + } catch (SQLException | InvalidProtocolBufferException throwables) { + LOGGER.error(" SQLException {}", throwables.getMessage()); + } + return result; + } + + /** + * get CpuData + * + * @param sessionId sessionId + * @param min min + * @param max max + * @param startTimeStamp startTimeStamp + * @param isNeedHeadTail isNeedHeadTail + * @return LinkedHashMap > + */ + public LinkedHashMap> getCpuData(long sessionId, int min, int max, + long startTimeStamp, boolean isNeedHeadTail) { + PreparedStatement pst = cpuSelectMap.get(SELECT_APP_CPU_INFO); + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail && min > 0) { + result.putAll(getCpuTargetData(sessionId, min, startTimeStamp, true)); + } + try { + pst.setLong(1, sessionId); + pst.setLong(2, startTimeStamp + min); + pst.setLong(3, startTimeStamp + max); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + CpuPluginResult.CpuData.Builder builders = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData cpuData = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTimeStamp), CpuDataConsumer.getProcessData(cpuData)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + throwAbles.printStackTrace(); + } + // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail) { + result.putAll(getCpuTargetData(sessionId, max, startTimeStamp, false)); + } + return result; + } + + /** + * getThreadData + * + * @param sessionId sessionId + * @param min min + * @param max max + * @param startTimeStamp startTimeStamp + * @param isNeedHeadTail isNeedHeadTail + * @return LinkedHashMap > + */ + public LinkedHashMap> getThreadData(long sessionId, int min, int max, + long startTimeStamp, boolean isNeedHeadTail) { + PreparedStatement pst = threadSelectMap.get(SELECT_APP_CPU_INFO); + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail && min > 0) { + result.putAll(getThreadTargetData(sessionId, min, startTimeStamp, true)); + } + try { + pst.setLong(1, sessionId); + pst.setLong(2, startTimeStamp + min); + pst.setLong(3, startTimeStamp + max); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + CpuPluginResult.CpuData.Builder builders = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData cpuData = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTimeStamp), CpuDataConsumer.getThreadStatus(cpuData)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + throwAbles.printStackTrace(); + } + // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail) { + result.putAll(getThreadTargetData(sessionId, max, startTimeStamp, false)); + } + return result; + } + + /** + * Get the data before head or after tail + * + * @param sessionId Session id + * @param offset time offset + * @param startTs start/first timestamp + * @param beforeHead true: before head, false: after tail + * @return LinkedHashMap > + */ + private LinkedHashMap> getCpuTargetData(long sessionId, int offset, long startTs, + boolean beforeHead) { + PreparedStatement pst; + if (beforeHead) { + pst = cpuSelectMap.get(SELECT_BEFORE_HEAD); + } else { + pst = cpuSelectMap.get(SELECT_AFTER_TAIL); + } + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + try { + pst.setLong(1, sessionId); + pst.setLong(2, offset + startTs); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + CpuPluginResult.CpuData.Builder builders = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData appSummary = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTs), CpuDataConsumer.getProcessData(appSummary)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + LOGGER.error(" SQLException {}", throwAbles.getMessage()); + } + return result; + } + + /** + * Get the data before head or after tail + * + * @param sessionId Session id + * @param offset time offset + * @param startTs start/first timestamp + * @param beforeHead true: before head, false: after tail + * @return LinkedHashMap > + */ + private LinkedHashMap> getThreadTargetData(long sessionId, int offset, long startTs, + boolean beforeHead) { + PreparedStatement pst; + if (beforeHead) { + pst = cpuSelectMap.get(SELECT_BEFORE_HEAD); + } else { + pst = cpuSelectMap.get(SELECT_AFTER_TAIL); + } + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + try { + pst.setLong(1, sessionId); + pst.setLong(2, offset + startTs); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + CpuPluginResult.CpuData.Builder builders = CpuPluginResult.CpuData.newBuilder(); + CpuPluginResult.CpuData appSummary = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTs), CpuDataConsumer.getThreadStatus(appSummary)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + LOGGER.error(" SQLException {}", throwAbles.getMessage()); + } + return result; + } + + /** + * deleteSessionData + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM "); + deleteSql.append("processCpuInfo").append(" WHERE session = ").append(sessionId); + Connection connection = DataBaseApi.getInstance().getConnectByTable("processCpuInfo").get(); + return execute(connection, deleteSql.toString()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDataCache.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDataCache.java new file mode 100644 index 000000000..cef92e583 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuDataCache.java @@ -0,0 +1,254 @@ +/* + * 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. + */ + +package ohos.devtools.services.cpu; + +import ohos.devtools.services.CacheMap; +import ohos.devtools.views.charts.model.ChartDataModel; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; + +/** + * CpuDataCache + */ +public class CpuDataCache { + /** + * Map default load factor + */ + private static final float LOAD_FACTOR = 0.75F; + + /** + * Cache max size + * + * @see "Cache about 40 seconds of data" + */ + private static final int CACHE_MAX_SIZE = 1500; + + /** + * Singleton + */ + private static CpuDataCache instance; + + /** + * Map of memory data saved + * + * @see "Map>>" + */ + private final Map>> cpuDataCacheMap = new ConcurrentHashMap<>(); + private final Map>> threadDataCacheMap = new ConcurrentHashMap<>(); + + /** + * Map of first data timestamp saved + * + * @see "Map" + */ + private final Map cpuFirstTsMap = new HashMap<>(); + private final Map threadFirstTsMap = new HashMap<>(); + + /** + * Private constructor + */ + private CpuDataCache() { + } + + /** + * Instance getter + * + * @return MemoryDataCache + */ + public static CpuDataCache getInstance() { + if (instance == null) { + instance = new CpuDataCache(); + } + return instance; + } + + /** + * Add Cpu data to cache map + * + * @param sessionId Session id + * @param timestamp Timestamp of data + * @param dataModels Data model list + */ + public void addCpuDataModel(long sessionId, long timestamp, List dataModels) { + CacheMap> cache = cpuDataCacheMap.get(sessionId); + // If cache map is null, generate the new map and save the current timestamp as first timestamp + if (cache == null) { + cache = genNewSessionCache(); + cpuDataCacheMap.put(sessionId, cache); + cpuFirstTsMap.put(sessionId, timestamp); + } + synchronized (cpuDataCacheMap.get(sessionId)) { + // Save relative time + int time = (int) (timestamp - cpuFirstTsMap.get(sessionId)); + cache.put(time, dataModels); + // Here we need to sort the map, otherwise the key(timestamp) of the map will be out of order + CacheMap> sorted = + cache.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors + .toMap(Map.Entry::getKey, Map.Entry::getValue, (paramX, paramY) -> paramX, CacheMap::new)); + cpuDataCacheMap.put(sessionId, sorted); + } + } + + /** + * Add Cpu data to cache map + * + * @param sessionId Session id + * @param timestamp Timestamp of data + * @param dataModels Data model list + */ + public void addThreadDataModel(long sessionId, long timestamp, List dataModels) { + CacheMap> cache = threadDataCacheMap.get(sessionId); + // If cache map is null, generate the new map and save the current timestamp as first timestamp + if (cache == null) { + cache = genNewSessionCache(); + threadDataCacheMap.put(sessionId, cache); + threadFirstTsMap.put(sessionId, timestamp); + } + synchronized (threadDataCacheMap.get(sessionId)) { + // Save relative time + int time = (int) (timestamp - threadFirstTsMap.get(sessionId)); + cache.put(time, dataModels); + // Here we need to sort the map, otherwise the key(timestamp) of the map will be out of order + CacheMap> sorted = + cache.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors + .toMap(Map.Entry::getKey, Map.Entry::getValue, (paramX, paramY) -> paramX, CacheMap::new)); + threadDataCacheMap.put(sessionId, sorted); + } + } + + /** + * Generate new session cache map + * + * @return CacheMap > + */ + private CacheMap> genNewSessionCache() { + return new CacheMap(); + } + + /** + * Get cpu data + * + * @param sessionId Session id + * @param startTime start time + * @param endTime end time + * @return LinkedHashMap > Data map + */ + public LinkedHashMap> getCpuData(long sessionId, int startTime, int endTime) { + LinkedHashMap> result = new LinkedHashMap<>(); + int timeBeforeStart = INITIAL_VALUE; + LinkedHashMap> cache = cpuDataCacheMap.get(sessionId); + if (cache == null) { + return result; + } + synchronized (cpuDataCacheMap.get(sessionId)) { + Set>> entries = cache.entrySet(); + for (Map.Entry> entry : entries) { + int time = entry.getKey(); + // Get the previous time of startTime + if (time < startTime) { + timeBeforeStart = time; + continue; + } + // Save the previous time and data of startTime, fill the chart blank and solve the boundary flicker + if (!result.containsKey(timeBeforeStart) && timeBeforeStart != INITIAL_VALUE) { + // Save time, do not save value. Otherwise, it will cause concurrent exception + result.put(timeBeforeStart, null); + } + if (time <= endTime) { + // Data saved between startTime and endTime + result.put(time, entry.getValue()); + } else { + // Save the next time and data of endTime, fill the chart blank and solve the boundary flicker + result.put(time, entry.getValue()); + // Then break the loop + break; + } + } + } + // Save the value of timeBeforeStart now + if (timeBeforeStart != INITIAL_VALUE) { + result.put(timeBeforeStart, cache.get(timeBeforeStart)); + } + return result; + } + + /** + * Get thread data + * + * @param sessionId Session id + * @param startTime start time + * @param endTime end time + * @return LinkedHashMap > Data map + */ + public LinkedHashMap> getThreadData(long sessionId, int startTime, int endTime) { + LinkedHashMap> result = new LinkedHashMap<>(); + int timeBeforeStart = INITIAL_VALUE; + LinkedHashMap> cache = threadDataCacheMap.get(sessionId); + if (cache == null) { + return result; + } + synchronized (threadDataCacheMap.get(sessionId)) { + Set>> entries = cache.entrySet(); + for (Map.Entry> entry : entries) { + int time = entry.getKey(); + // Get the previous time of startTime + if (time < startTime) { + timeBeforeStart = time; + continue; + } + // Save the previous time and data of startTime, fill the chart blank and solve the boundary flicker + if (!result.containsKey(timeBeforeStart) && timeBeforeStart != INITIAL_VALUE) { + // Save time, do not save value. Otherwise, it will cause concurrent exception + result.put(timeBeforeStart, null); + } + if (time <= endTime) { + // Data saved between startTime and endTime + result.put(time, entry.getValue()); + } else { + // Save the next time and data of endTime, fill the chart blank and solve the boundary flicker + result.put(time, entry.getValue()); + // Then break the loop + break; + } + } + } + // Save the value of timeBeforeStart now + if (timeBeforeStart != INITIAL_VALUE) { + result.put(timeBeforeStart, cache.get(timeBeforeStart)); + } + return result; + } + + /** + * Clear cache by session id when the session was deleted + * + * @param sessionId Session id + */ + public void clearCacheBySession(long sessionId) { + cpuDataCacheMap.remove(sessionId); + cpuFirstTsMap.remove(sessionId); + threadDataCacheMap.remove(sessionId); + threadFirstTsMap.remove(sessionId); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuValidate.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuValidate.java new file mode 100644 index 000000000..14418c238 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuValidate.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.services.cpu; + +import ohos.devtools.datasources.databases.datatable.CpuTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import ohos.devtools.datasources.utils.common.util.Validate; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.pluginconfig.CpuConfig; + +import java.util.ArrayList; +import java.util.List; + +/** + * Cpu Validate + */ +public class CpuValidate extends Validate { + private boolean registerCpu; + private CpuTable cpuTable = new CpuTable(); + private List cpuList = new ArrayList<>(); + + /** + * CpuValidate + * + */ + public CpuValidate() { + } + + @Override + public boolean validate(T obj) { + if (obj instanceof ProcessCpuData && !registerCpu) { + ProcessCpuData processCpuData = (ProcessCpuData) obj; + PlugManager.getInstance() + .addPluginStartSuccess(processCpuData.getLocalSessionId(), new CpuConfig().createConfig()); + registerCpu = true; + } + return obj instanceof ProcessCpuData; + } + + @Override + public void addToList(T obj) { + ProcessCpuData processCpuData = (ProcessCpuData) obj; + cpuList.add(processCpuData); + } + + @Override + public void batchInsertToDb() { + cpuTable.insertProcessCpuInfo(cpuList); + cpuList.clear(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioService.java deleted file mode 100644 index 985d4c925..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.diskio; - -/** - * @Description Diskio业务处理类 - * @Date 2021/2/7 13:44 - **/ -public class DiskioService { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceDao.java deleted file mode 100644 index 80cc2cf7d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceDao.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.ftrace; - -/** - * @Description Ftrace与数据库交互的类 - * @Date 2021/2/7 13:59 - **/ -public class FtraceDao { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceService.java deleted file mode 100644 index 2230dfddd..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/ftrace/FtraceService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.ftrace; - -/** - * @Description Ftrace业务处理类 - * @Date 2021/2/7 13:44 - **/ -public class FtraceService { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfDao.java deleted file mode 100644 index 04351e997..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfDao.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.hiperf; - -/** - * @Description Hiperf与数据库交互类 - * @Date 2021/2/7 14:00 - **/ -public class HiperfDao { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfService.java deleted file mode 100644 index 7ee9b97c9..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/hiperf/HiperfService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.hiperf; - -/** - * @Description Hiperf业务处理类 - * @Date 2021/2/7 13:45 - **/ -public class HiperfService { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ChartDataCache.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ChartDataCache.java deleted file mode 100644 index 09c29b0a7..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ChartDataCache.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.views.common.LayoutConstants; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -import static ohos.devtools.views.common.ViewConstants.INITIAL_VALUE; - -/** - * 多设备+多模式缓存区域 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public final class ChartDataCache { - private static final Logger LOGGER = LogManager.getLogger(ChartDataCache.class); - - /** - * 总内存的数据量,chart面板可以绘制20s时长额度数据,则缓存保存30s的数据 - */ - private static final int MINT = 30; - - /** - * 单例实体 - */ - private static volatile ChartDataCache instance; - - /** - * 存放各种类型缓存的map - */ - private final Map> dataCacheMap = new ConcurrentHashMap<>(); - /** - * 单个chart的缓存 - */ - private LinkedHashMap cacheBox = null; - - /** - * 0参私有化 - */ - private ChartDataCache() { - } - - /** - * 实体方法 - * - * @return ChartDataCache对象 - */ - public static ChartDataCache getInstance() { - if (instance == null) { - synchronized (ChartDataCache.class) { - if (instance == null) { - instance = new ChartDataCache(); - } - } - } - return instance; - } - - /** - * 构造方法 - * - * @param cacheName 缓存名称(设备名+模块) - * @param blockSize chart面板1s平均可获得的数据数量 - */ - public void initCache(String cacheName, int blockSize) { - int cacheMaxSize = MINT * blockSize; - cacheBox = new LinkedHashMap<>(cacheMaxSize, LayoutConstants.LOAD_FACTOR, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - if (cacheBox.size() > cacheMaxSize) { - cacheBox.remove(eldest.getKey()); - return true; - } else { - return false; - } - } - }; - dataCacheMap.put(cacheName, cacheBox); - } - - public Map> getDataCacheMap() { - return dataCacheMap; - } - - /** - * 数据块添加到cache缓存中 - * - * @param cacheName 缓存名称 - * @param cacheBlock 待从数据库获取的数据 - */ - public void addCacheBlock(String cacheName, LinkedHashMap cacheBlock) { - synchronized (dataCacheMap.get(cacheName)) { - LinkedHashMap cacheBoxAdd = dataCacheMap.get(cacheName); - for (Map.Entry entry : cacheBlock.entrySet()) { - cacheBoxAdd.put(entry.getKey(), entry.getValue()); - } - - // 这里需要给Map中的集合排序,否则会出现Map的key时间戳乱序现象 - LinkedHashMap sorted = - dataCacheMap.get(cacheName).entrySet().stream().sorted(Map.Entry.comparingByKey()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> { - throw new AssertionError(); - }, LinkedHashMap::new)); - dataCacheMap.put(cacheName, sorted); - } - } - - /** - * chart调用的接口,获取cache内存中的数据 - * - * @param cacheName 缓存名称 - * @param startTime 开始时间 - * @param endTime 结束时间 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @return LinkedHashMap - */ - public LinkedHashMap getDataCache(String cacheName, int startTime, int endTime, long firstTimestamp) { - LinkedHashMap result = new LinkedHashMap<>(); - long startTs = startTime + firstTimestamp; - long endTs = endTime + firstTimestamp; - // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 - if (startTime > 0) { - long beforeStart = getTargetTime(cacheName, startTs, true); - if (beforeStart != 0) { - result.put(beforeStart, dataCacheMap.get(cacheName).get(beforeStart)); - } - } - synchronized (dataCacheMap.get(cacheName)) { - Set> entrySet = dataCacheMap.get(cacheName).entrySet(); - for (Map.Entry entry : entrySet) { - long key = entry.getKey(); - if (key >= startTs && key <= endTs) { - result.put(key, entry.getValue()); - } - } - - // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 - long afterEnd = getTargetTime(cacheName, endTs, false); - if (afterEnd != 0) { - result.put(afterEnd, dataCacheMap.get(cacheName).get(afterEnd)); - } - } - return result; - } - - /** - * 清理数据缓存 - * - * @param cacheName cacheName - */ - public void clearDataCache(String cacheName) { - LinkedHashMap cacheBoxClear = dataCacheMap.get(cacheName); - cacheBoxClear.clear(); - } - - /** - * 在dataMap中找到给定时间的前一个时间或者后一个时间 - * - * @param cacheName String - * @param time 给定时间 - * @param isBefore true:前一个时间,false:后一个时间 - * @return 结果 - */ - private long getTargetTime(String cacheName, long time, boolean isBefore) { - synchronized (dataCacheMap.get(cacheName)) { - LinkedHashMap cacheBoxGet = dataCacheMap.get(cacheName); - if (cacheBoxGet == null || cacheBoxGet.size() == 0) { - return 0; - } - - Set keySet = cacheBoxGet.keySet(); - Long[] timeArray = keySet.toArray(new Long[0]); - // 先判断下是不是大于最大值或者小于最小值,是的话直接返回 - if (time == timeArray[0] || time == timeArray[timeArray.length - 1]) { - return 0; - } - - return timeArray[searchIndex(timeArray, time, isBefore)]; - } - } - - /** - * 在有序数组中找到目标值的前一个或后一个值的index - * - * @param arr 有序数组 - * @param value 目标值 - * @param flag true:取前一个值,false:取后一个值 - * @return 目标值的前一个或后一个值的index - */ - private static int searchIndex(Long[] arr, long value, boolean flag) { - // 开始位置 - int low = 0; - // 结束位置 - int high = arr.length - 1; - // 先判断下是不是大于最大值或者小于最小值,是的话直接返回 - if (value <= arr[low]) { - return low; - } - if (value >= arr[high]) { - return high; - } - - int halfValue = 2; - int index = INITIAL_VALUE; - while (low <= high) { - int middle = (low + high) / halfValue; - // 如果值正好相等,则直接返回查询到的索引 - if (value == arr[middle]) { - index = flag ? middle - 1 : middle + 1; - break; - } - - // 大于当前index的值,小于下一个index的值,根据flag取前一个或后一个 - if (value > arr[middle] && value < arr[middle + 1]) { - // 返回查询到的索引 - index = flag ? middle : middle + 1; - break; - } - - if (value > arr[middle]) { - low = middle + 1; - } - - if (value < arr[middle]) { - high = middle - 1; - } - } - return index; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryDao.java deleted file mode 100644 index d2513b141..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryDao.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import com.google.protobuf.InvalidProtocolBufferException; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.views.common.LayoutConstants; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import static ohos.devtools.services.memory.MemoryDao.MemorySelectStatements.SELECT_AFTER_TAIL; -import static ohos.devtools.services.memory.MemoryDao.MemorySelectStatements.SELECT_ALL_APP_MEM_INFO; -import static ohos.devtools.services.memory.MemoryDao.MemorySelectStatements.SELECT_APP_MEM_INFO; -import static ohos.devtools.services.memory.MemoryDao.MemorySelectStatements.SELECT_BEFORE_HEAD; - -/** - * @Description Memory与数据库交互的类 - * @Date 2021/2/7 14:01 - **/ -public class MemoryDao extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(MemoryDao.class); - - private static volatile MemoryDao singleton; - - /** - * 获取实例 - * - * @return MemoryDao - */ - public static MemoryDao getInstance() { - if (singleton == null) { - synchronized (MemoryDao.class) { - if (singleton == null) { - singleton = new MemoryDao(); - } - } - } - return singleton; - } - - private Map memorySelectMap = new HashMap<>(); - - /** - * MemorySelectStatements - **/ - public enum MemorySelectStatements { - SELECT_APP_MEM_INFO( - "SELECT timeStamp, Data from processMemInfo where session = ? and timeStamp > ? and timeStamp < ?"), - - SELECT_ALL_APP_MEM_INFO("SELECT timeStamp, Data from processMemInfo where session = ?"), - - DELETE_APP_MEM_INFO("delete from processMemInfo where session = ?"), - - SELECT_BEFORE_HEAD("SELECT timeStamp, Data from processMemInfo where session =" - + " ? and timeStamp < ? order by timeStamp desc limit 1"), - - SELECT_AFTER_TAIL("SELECT timeStamp, Data from processMemInfo where session =" - + " ? and timeStamp > ? order by timeStamp asc limit 1"); - - private final String sqlStatement; - - MemorySelectStatements(String sqlStatement) { - this.sqlStatement = sqlStatement; - } - - /** - * 获取sql语句 - * - * @return String - */ - public String getStatement() { - return sqlStatement; - } - } - - private Connection conn; - - private MemoryDao() { - if (conn == null) { - Optional connection = getConnectBydbName("memory"); - if (connection.isPresent()) { - conn = connection.get(); - } - createPrePareStatements(); - } - } - - private void createPrePareStatements() { - MemorySelectStatements[] values = MemorySelectStatements.values(); - for (MemorySelectStatements sta : values) { - PreparedStatement psmt = null; - try { - psmt = conn.prepareStatement(sta.getStatement()); - memorySelectMap.put(sta, psmt); - } catch (SQLException throwAbles) { - LOGGER.error(" SQLException {}", throwAbles.getMessage()); - } - } - } - - /** - * getAllData - * - * @param sessionId sessionId - * @return List - */ - public List getAllData(long sessionId) { - PreparedStatement pst = memorySelectMap.get(SELECT_ALL_APP_MEM_INFO); - List result = new ArrayList<>(); - try { - if (pst != null) { - pst.setLong(1, sessionId); - ResultSet rs = pst.executeQuery(); - while (rs.next()) { - long timeStamp = rs.getLong("timeStamp"); - byte[] data = rs.getBytes("Data"); - if (data == null) { - continue; - } - ProcessMemInfo processMem = new ProcessMemInfo(); - MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); - MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); - processMem.setTimeStamp(timeStamp); - processMem.setData(appSummary); - processMem.setSession(sessionId); - result.add(processMem); - } - } - } catch (SQLException | InvalidProtocolBufferException throwables) { - LOGGER.error(" SQLException {}", throwables.getMessage()); - } - return result; - } - - /** - * getData - * - * @param sessionId sessionId - * @param min min - * @param max max - * @param startTimeStamp startTimeStamp - * @param isNeedHeadTail isNeedHeadTail - * @return LinkedHashMap - */ - public LinkedHashMap getData(long sessionId, int min, int max, - long startTimeStamp, boolean isNeedHeadTail) { - PreparedStatement pst = memorySelectMap.get(SELECT_APP_MEM_INFO); - LinkedHashMap result = new LinkedHashMap(); - // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 - if (isNeedHeadTail && min > 0) { - LinkedHashMap head = getBeforeHead(sessionId, startTimeStamp + min); - if (head.size() > 0) { - Map.Entry headEntry = head.entrySet().iterator().next(); - Long key = -1L; - MemoryPluginResult.AppSummary value = null; - if ((headEntry.getKey()) instanceof Long) { - key = (Long) headEntry.getKey(); - } - if ((headEntry.getValue()) instanceof MemoryPluginResult.AppSummary) { - value = (MemoryPluginResult.AppSummary) headEntry.getValue(); - } - if (value != null) { - result.put(key, value); - } - } - } - if (pst != null) { - try { - long startTime = startTimeStamp + min; - long endTime = startTimeStamp + max; - pst.setLong(1, sessionId); - pst.setLong(LayoutConstants.TWO, startTime); - pst.setLong(LayoutConstants.THREE, endTime); - ResultSet rs = pst.executeQuery(); - if (rs != null) { - while (rs.next()) { - long timeStamp = rs.getLong("timeStamp"); - byte[] data = rs.getBytes("Data"); - if (data == null) { - continue; - } - MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); - MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); - result.put(timeStamp, appSummary); - } - } - } catch (SQLException | InvalidProtocolBufferException throwAbles) { - throwAbles.printStackTrace(); - } - } - // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 - result = getOutsideDataLinkedHashMap(sessionId, max, startTimeStamp, isNeedHeadTail, result); - return result; - } - - private LinkedHashMap getOutsideDataLinkedHashMap(long sessionId, int max, - long startTimeStamp, boolean isNeedHeadTail, LinkedHashMap result) { - LinkedHashMap resultData = result; - if (isNeedHeadTail) { - LinkedHashMap tail = getAfterTail(sessionId, startTimeStamp + max); - if (tail.size() > 0) { - Map.Entry tailEntry = tail.entrySet().iterator().next(); - MemoryPluginResult.AppSummary value = null; - Long key = -1L; - if ((tailEntry.getKey()) instanceof Long) { - key = (Long) tailEntry.getKey(); - } - if ((tailEntry.getValue()) instanceof MemoryPluginResult.AppSummary) { - value = (MemoryPluginResult.AppSummary) tailEntry.getValue(); - } - if (value != null) { - resultData.put(key, value); - } - } - } - return resultData; - } - - /** - * 获取目标时间的前一个时间的数据 - * - * @param sessionId 缓存名称 - * @param targetTimeStamp 开始时间 - * @return LinkedHashMap - */ - public LinkedHashMap getBeforeHead(long sessionId, long targetTimeStamp) { - PreparedStatement pst = memorySelectMap.get(SELECT_BEFORE_HEAD); - LinkedHashMap result = new LinkedHashMap(); - if (pst != null) { - try { - pst.setLong(1, sessionId); - pst.setLong(LayoutConstants.TWO, targetTimeStamp); - ResultSet rs = pst.executeQuery(); - if (rs != null) { - while (rs.next()) { - long timeStamp = rs.getLong("timeStamp"); - byte[] data = rs.getBytes("Data"); - if (data == null) { - continue; - } - MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); - MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); - result.put(timeStamp, appSummary); - } - } - } catch (SQLException | InvalidProtocolBufferException throwAbles) { - LOGGER.error(" SQLException {}", throwAbles.getMessage()); - } - } - return result; - } - - /** - * 获取目标时间的后一个时间的数据 - * - * @param sessionId 缓存名称 - * @param targetTimeStamp 开始时间 - * @return LinkedHashMap - */ - public LinkedHashMap getAfterTail(long sessionId, long targetTimeStamp) { - PreparedStatement pst = memorySelectMap.get(SELECT_AFTER_TAIL); - LinkedHashMap result = new LinkedHashMap(); - if (pst != null) { - try { - pst.setLong(1, sessionId); - pst.setLong(LayoutConstants.TWO, targetTimeStamp); - ResultSet rs = pst.executeQuery(); - if (rs != null) { - while (rs.next()) { - long timeStamp = rs.getLong("timeStamp"); - byte[] data = rs.getBytes("Data"); - if (data == null) { - continue; - } - MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); - MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); - result.put(timeStamp, appSummary); - } - } - } catch (SQLException | InvalidProtocolBufferException throwAbles) { - LOGGER.error(" SQLException {}", throwAbles.getMessage()); - } - } - return result; - } - - /** - * deleteSessionData - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - StringBuffer deleteSql = new StringBuffer("DELETE FROM "); - deleteSql.append("processMemInfo").append(" WHERE session = ").append(sessionId); - Connection connection = DataBaseApi.getInstance().getConnectByTable("processMemInfo").get(); - return execute(connection, deleteSql.toString()); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapDao.java deleted file mode 100644 index a199c3394..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapDao.java +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; - -/** - * heap数据处理对象 - * - * @version 1.0 - * @date 2021/03/30 10:52 - **/ -public class MemoryHeapDao extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(MemoryHeapDao.class); - private static volatile MemoryHeapDao singleton; - - /** - * getInstance - * - * @return MemoryHeapDao - */ - public static MemoryHeapDao getInstance() { - if (singleton == null) { - synchronized (MemoryHeapDao.class) { - if (singleton == null) { - singleton = new MemoryHeapDao(); - } - } - } - return singleton; - } - - /** - * MemoryHeapDao - */ - public MemoryHeapDao() { - createMemoryHeapInfo(); - } - - /** - * 获取数据库连接 - * - * @param tableName 表名 - * @return Connection - * @date 2021/03/30 11:00 - */ - private Connection getConnection(String tableName) { - Optional optionalConnection = getConnectByTable(tableName); - Connection conn = null; - if (optionalConnection.isPresent()) { - conn = optionalConnection.get(); - } - return conn; - } - - /** - * 堆信息数据表创建 - * - * @return boolean - */ - public boolean createMemoryHeapInfo() { - boolean createResult = false; - String dbName = JVMTI_AGENT_PLUG; - String memoryHeapInfoTable = "MemoryHeapInfo"; - String sql = - "CREATE TABLE MemoryHeapInfo " + "( " + " id Integer primary key autoincrement not null, " - + " cId int(100) not null, " + " heapId int(100) not null, " - + " instanceId int(100) not null, " + " sessionId Long(100) not null, " - + " arrangeStyle varchar(200), " + " allocations int(100) not null, " - + " deallocations int(100) not null, " + " totalCount int(100) not null, " - + " shallowSize int(100) not null, " + " createTime int(200) not null " + ");"; - - createResult = createTable(dbName, memoryHeapInfoTable, sql); - return createResult; - } - - /** - * 将端侧获取的堆信息保存在数据库 - * - * @param memoryHeapInfos 堆实例 - * @return boolean - */ - public boolean insertMemoryHeapInfos(List memoryHeapInfos) { - if (memoryHeapInfos.isEmpty()) { - return false; - } - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("MemoryHeapInfo"); - conn.setAutoCommit(false); - String sql = "insert into MemoryHeapInfo(id,cId,heapId,sessionId,arrangeStyle,allocations," - + "deallocations,totalCount,shallowSize,createTime,instanceId)values(null,?,?,?,?,?,?,?,?,?,?)"; - ps = conn.prepareStatement(sql); - for (MemoryHeapInfo memoryHeapInfo : memoryHeapInfos) { - try { - ps.setInt(1, memoryHeapInfo.getcId()); - ps.setInt(Option.SQL_INDEX_TWO, memoryHeapInfo.getHeapId()); - ps.setLong(Option.SQL_INDEX_THREE, memoryHeapInfo.getSessionId()); - ps.setString(Option.SQL_INDEX_FOUR, memoryHeapInfo.getArrangeStyle()); - ps.setLong(Option.SQL_INDEX_FIVE, memoryHeapInfo.getAllocations()); - ps.setLong(Option.SQL_INDEX_SIX, memoryHeapInfo.getDeallocations()); - ps.setInt(Option.SQL_INDEX_SEVEN, memoryHeapInfo.getTotalCount()); - ps.setLong(Option.SQL_INDEX_EIGHT, memoryHeapInfo.getShallowSize()); - ps.setLong(Option.SQL_INDEX_NINE, memoryHeapInfo.getCreateTime()); - ps.setLong(Option.SQL_INDEX_TEN, memoryHeapInfo.getInstanceId()); - ps.addBatch(); - } catch (SQLException sqlException) { - LOGGER.info("insert AppInfo {}", sqlException.getMessage()); - } - } - int[] results = ps.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwables) { - LOGGER.info("insert MemoryHeap {}", throwables.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * 获取所有的SessionId数据 - * - * @param sessionId sessionId - * @return ArrayList - */ - public ArrayList getAllMemoryHeapInfos(Long sessionId) { - Connection conn = getConnection("MemoryHeapInfo"); - PreparedStatement ps = null; - ArrayList memoryHeapInfos = new ArrayList<>(); - try { - String sql = "select id,cId,heapId,sessionId,arrangeStyle,allocations,deallocations,totalCount," - + "shallowSize,createTime,instanceId from MemoryHeapInfo where sessionId = ?"; - ps = conn.prepareStatement(sql); - ps.setLong(1, sessionId); - ResultSet rs = ps.executeQuery(); - MemoryHeapInfo memoryHeapInfo = null; - while (rs.next()) { - memoryHeapInfo = new MemoryHeapInfo(); - Integer id = rs.getInt("id"); - Integer cId = rs.getInt("cId"); - Integer heapId = rs.getInt("heapId"); - Long msessionId = rs.getLong("sessionId"); - Integer allocations = rs.getInt("allocations"); - Integer deallocations = rs.getInt("deallocations"); - Integer totalCount = rs.getInt("totalCount"); - Long shallowSize = rs.getLong("shallowSize"); - Long createTime = rs.getLong("createTime"); - Integer instanceId = rs.getInt("instanceId"); - memoryHeapInfo.setId(id); - memoryHeapInfo.setHeapId(heapId); - memoryHeapInfo.setcId(cId); - memoryHeapInfo.setSessionId(msessionId); - memoryHeapInfo.setSessionId(sessionId); - memoryHeapInfo.setAllocations(allocations); - memoryHeapInfo.setDeallocations(deallocations); - memoryHeapInfo.setTotalCount(totalCount); - memoryHeapInfo.setShallowSize(shallowSize); - memoryHeapInfo.setCreateTime(createTime); - memoryHeapInfo.setInstanceId(instanceId); - memoryHeapInfos.add(memoryHeapInfo); - } - return memoryHeapInfos; - } catch (SQLException throwables) { - LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryHeapInfos; - } - - /** - * 从数据库获取堆信息数据 - * - * @param sessionId sessionId - * @param startTime 开始时间 - * @param endTime 结束时间 - * @return ArrayList - * @date 2021/3/31 16:04 - */ - public ArrayList getMemoryHeapInfos(Long sessionId, Long startTime, Long endTime) { - Connection conn = getConnection("MemoryHeapInfo"); - PreparedStatement ps = null; - ArrayList memoryHeapInfos = new ArrayList<>(); - try { - String sql = getSqlStr(); - ps = conn.prepareStatement(sql); - ps.setLong(1, sessionId); - ps.setLong(Option.SQL_INDEX_TWO, startTime); - ps.setLong(Option.SQL_INDEX_THREE, endTime); - ps.setLong(Option.SQL_INDEX_FOUR, sessionId); - ps.setLong(Option.SQL_INDEX_FIVE, startTime); - ps.setLong(Option.SQL_INDEX_SIX, endTime); - ps.setLong(Option.SQL_INDEX_SEVEN, sessionId); - ps.setLong(Option.SQL_INDEX_EIGHT, endTime); - - ResultSet rs = ps.executeQuery(); - MemoryHeapInfo memoryHeapInfo = null; - while (rs.next()) { - memoryHeapInfo = new MemoryHeapInfo(); - Integer id = rs.getInt("id"); - Integer cId = rs.getInt("cId"); - String className = rs.getString("className"); - Integer allocations = rs.getInt("allocations"); - Integer deallocations = rs.getInt("deallocations"); - Integer totalCount = rs.getInt("totalCount"); - Long shallowSize = rs.getLong("shallowSize"); - memoryHeapInfo.setId(id); - memoryHeapInfo.setcId(cId); - memoryHeapInfo.setHeapId(0); - memoryHeapInfo.setSessionId(sessionId); - memoryHeapInfo.setClassName(className); - memoryHeapInfo.setAllocations(allocations); - memoryHeapInfo.setDeallocations(deallocations); - memoryHeapInfo.setTotalCount(totalCount); - memoryHeapInfo.setShallowSize(shallowSize); - memoryHeapInfos.add(memoryHeapInfo); - } - return memoryHeapInfos; - } catch (SQLException throwAbles) { - LOGGER.info("memoryHeapInfo Exception {}", throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryHeapInfos; - } - - /** - * 删除一次场景下的堆信息数据 - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - StringBuffer deleteSql = new StringBuffer("DELETE FROM "); - deleteSql.append("MemoryHeapInfo").append(" WHERE sessionId = ").append(sessionId); - Connection connection = DataBaseApi.getInstance().getConnectByTable("MemoryHeapInfo").get(); - return execute(connection, deleteSql.toString()); - } - - /** - * updateMemoryHeapInfo - * - * @param instanceId instanceId - * @return boolean - */ - public boolean updateMemoryHeapInfo(int instanceId) { - Connection conn = getConnection("MemoryHeapInfo"); - String updateSql = "UPDATE MemoryHeapInfo SET deallocations = 1 where instanceId = ?"; - PreparedStatement preparedStatement = null; - try { - preparedStatement = conn.prepareStatement(updateSql); - preparedStatement.setLong(1, instanceId); - return preparedStatement.executeUpdate() == 1 ? true : false; - } catch (SQLException throwables) { - LOGGER.error("SQLException {}", throwables.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, preparedStatement, null); - } - return false; - } - - private String getSqlStr() { - String sql = "SELECT d.id,d.cid,d.className,IFNULL(d.allocations, 0) as allocations, " - + "IFNULL(d.deallocations, 0) as deallocations ,IFNULL(f.totalCount, 0) as totalCount , " - + "IFNULL(f.shallowSize, 0) as shallowSize FROM((" - + "SELECT c.id, c.cId, c.className,sum( IFNULL( m.allocations, 0 ) ) AS allocations," - + "sum( IFNULL( m.deallocations, 0 ) ) AS deallocations FROM ClassInfo c " - + "LEFT JOIN MemoryHeapInfo m ON m.cId = c.cId WHERE m.sessionId = ? " - + "AND m.createTime >= ? AND m.createTime <= ? GROUP BY c.cId" - + " UNION SELECT c.id,c.cId,c.className,0 AS allocations,0 AS deallocations FROM ClassInfo c " - + "WHERE c.cId NOT IN ( SELECT b.cId FROM MemoryHeapInfo b WHERE b.sessionId = ? " - + "AND b.createTime >= ? AND b.createTime <= ? ) ) AS d LEFT JOIN(" - + "SELECT e.cId as cId,sum( IFNULL( e.totalCount, 0 ) ) AS totalCount," - + "sum( IFNULL( e.shallowSize, 0 )) AS shallowSize FROM ClassInfo l LEFT JOIN MemoryHeapInfo e" - + " ON e.cId = l.cId WHERE e.sessionId = ? AND e.createTime <= ? " - + "GROUP BY l.cId ) AS f on d.cId = f.cId) ORDER BY shallowSize DESC"; - - return sql; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryValidate.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryValidate.java new file mode 100644 index 000000000..6f9ed8562 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryValidate.java @@ -0,0 +1,135 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.datasources.utils.common.util.Validate; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.pluginconfig.MemoryConfig; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import ohos.devtools.services.memory.agentdao.MemoryUpdateInfo; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory Validate + */ +public class MemoryValidate extends Validate { + private boolean registerMemory; + private List processMemInfoList; + private List classInfos; + private List memoryHeapInfos; + private List instanceInfos; + private List detailsInfos; + private MemoryTable memoTable; + private ClassInfoDao classInfoDao; + private MemoryHeapDao memoryHeapDao; + private MemoryInstanceDao memoryInstanceDao; + private MemoryInstanceDetailsDao memoryInstanceDetailsDao; + + /** + * MemoryValidate Constructor + */ + public MemoryValidate() { + processMemInfoList = new ArrayList(); + classInfos = new ArrayList<>(); + memoryHeapInfos = new ArrayList<>(); + instanceInfos = new ArrayList<>(); + detailsInfos = new ArrayList<>(); + memoTable = new MemoryTable(); + memoryHeapDao = new MemoryHeapDao(); + memoryInstanceDao = new MemoryInstanceDao(); + classInfoDao = new ClassInfoDao(); + memoryInstanceDetailsDao = new MemoryInstanceDetailsDao(); + } + + @Override + public boolean validate(T data) { + if (data instanceof ClassInfo) { + return true; + } else if (data instanceof MemoryHeapInfo) { + return true; + } else if (data instanceof MemoryInstanceDetailsInfo) { + return true; + } else if (data instanceof MemoryUpdateInfo) { + return true; + } else if (data instanceof ProcessMemInfo) { + ProcessMemInfo processMem = (ProcessMemInfo) data; + if (!registerMemory) { + PlugManager.getInstance() + .addPluginStartSuccess(processMem.getLocalSessionId(), new MemoryConfig().createConfig()); + registerMemory = true; + } + return true; + } else { + return false; + } + } + + @Override + public void addToList(T data) { + if (data instanceof ClassInfo) { + ClassInfo classInfo = (ClassInfo) data; + classInfos.add(classInfo); + } else if (data instanceof MemoryHeapInfo) { + MemoryHeapInfo memoryHeapInfo = (MemoryHeapInfo) data; + memoryHeapInfos.add(memoryHeapInfo); + } else if (data instanceof MemoryInstanceDetailsInfo) { + MemoryInstanceDetailsInfo detailsInfo = (MemoryInstanceDetailsInfo) data; + detailsInfos.add(detailsInfo); + } else if (data instanceof MemoryUpdateInfo) { + MemoryUpdateInfo memoryInstanceInfo = (MemoryUpdateInfo) data; + instanceInfos.add(memoryInstanceInfo); + } else if (data instanceof ProcessMemInfo) { + ProcessMemInfo processMem = (ProcessMemInfo) data; + processMemInfoList.add(processMem); + } else { + return; + } + } + + @Override + public void batchInsertToDb() { + classInfoDao.insertClassInfos(classInfos); + memoryHeapDao.insertMemoryHeapInfos(memoryHeapInfos); + memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(detailsInfos); + memoryInstanceDao.insertMemoryInstanceInfos(instanceInfos); + memoTable.insertProcessMemInfo(processMemInfoList); + classInfos.clear(); + memoryHeapInfos.clear(); + detailsInfos.clear(); + instanceInfos.clear(); + processMemInfoList.clear(); + } + + /** + * get MenInfo Size + * + * @return int + */ + public int getMenInfoSize() { + return processMemInfoList.size(); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/Option.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/Option.java deleted file mode 100644 index d75499a5e..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/Option.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -/** - * memory常量对象 - * - * @version 1.0 - * @date 2021/04/07 10:00 - **/ -public class Option { - /** - * 数据库字段下标值2 - */ - public static final int SQL_INDEX_TWO = 2; - - /** - * 数据库字段下标值3 - */ - public static final int SQL_INDEX_THREE = 3; - - /** - * 数据库字段下标值4 - */ - public static final int SQL_INDEX_FOUR = 4; - - /** - * 数据库字段下标值5 - */ - public static final int SQL_INDEX_FIVE = 5; - - /** - * 数据库字段下标值6 - */ - public static final int SQL_INDEX_SIX = 6; - - /** - * 数据库字段下标值7 - */ - public static final int SQL_INDEX_SEVEN = 7; - - /** - * 数据库字段下标值8 - */ - public static final int SQL_INDEX_EIGHT = 8; - - /** - * 数据库字段下标值9 - */ - public static final int SQL_INDEX_NINE = 9; - - /** - * 数据库字段下标值10 - */ - public static final int SQL_INDEX_TEN = 10; - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/AgentHeapBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/AgentHeapBean.java new file mode 100644 index 000000000..11a2e52ed --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/AgentHeapBean.java @@ -0,0 +1,140 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory.agentbean; + +import java.util.Objects; + +/** + * Agent Heap Bean + */ +public class AgentHeapBean { + private Integer agentNodeId; + private Integer agentClazzId; + private Integer agentHeapId; + private Long sessionId; + private String agentClazzName; + private Integer agentAllocationsCount; + private Integer agentDeAllocationsCount; + private Integer agentTotalInstanceCount; + private Long agentTotalshallowSize; + + public Integer getAgentNodeId() { + return agentNodeId; + } + + public void setAgentNodeId(Integer agentNodeId) { + this.agentNodeId = agentNodeId; + } + + public Integer getAgentClazzId() { + return agentClazzId; + } + + public void setAgentClazzId(Integer agentClazzId) { + this.agentClazzId = agentClazzId; + } + + public Integer getAgentHeapId() { + return agentHeapId; + } + + public void setAgentHeapId(Integer agentHeapId) { + this.agentHeapId = agentHeapId; + } + + public Long getSessionId() { + return sessionId; + } + + public void setSessionId(Long sessionId) { + this.sessionId = sessionId; + } + + public String getAgentClazzName() { + return agentClazzName; + } + + public void setAgentClazzName(String agentClazzName) { + this.agentClazzName = agentClazzName; + } + + public Integer getAgentAllocationsCount() { + return agentAllocationsCount; + } + + public void setAgentAllocationsCount(Integer agentAllocationsCount) { + this.agentAllocationsCount = agentAllocationsCount; + } + + public Integer getAgentDeAllocationsCount() { + return agentDeAllocationsCount; + } + + public void setAgentDeAllocationsCount(Integer agentDeAllocationsCount) { + this.agentDeAllocationsCount = agentDeAllocationsCount; + } + + public Integer getAgentTotalInstanceCount() { + return agentTotalInstanceCount; + } + + public void setAgentTotalInstanceCount(Integer agentTotalInstanceCount) { + this.agentTotalInstanceCount = agentTotalInstanceCount; + } + + public Long getAgentTotalshallowSize() { + return agentTotalshallowSize; + } + + public void setAgentTotalshallowSize(Long agentTotalshallowSize) { + this.agentTotalshallowSize = agentTotalshallowSize; + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object == null || getClass() != object.getClass()) { + return false; + } + + AgentHeapBean agentHeapBean = null; + if (object instanceof AgentHeapBean) { + agentHeapBean = (AgentHeapBean) object; + } + return Objects.equals(agentNodeId, agentHeapBean.agentNodeId) && Objects + .equals(agentClazzId, agentHeapBean.agentClazzId) && Objects.equals(agentHeapId, agentHeapBean.agentHeapId) + && Objects.equals(sessionId, agentHeapBean.sessionId) && Objects + .equals(agentClazzName, agentHeapBean.agentClazzName) && Objects + .equals(agentAllocationsCount, agentHeapBean.agentAllocationsCount) && Objects + .equals(agentDeAllocationsCount, agentHeapBean.agentDeAllocationsCount) && Objects + .equals(agentTotalInstanceCount, agentHeapBean.agentTotalInstanceCount) && Objects + .equals(agentTotalshallowSize, agentHeapBean.agentTotalshallowSize); + } + + @Override + public int hashCode() { + return Objects + .hash(agentNodeId, agentClazzId, agentHeapId, sessionId, agentClazzName, agentAllocationsCount, + agentDeAllocationsCount, agentTotalInstanceCount, agentTotalshallowSize); + } + + @Override + public String toString() { + return agentClazzName; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/ClassInfo.java similarity index 69% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfo.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/ClassInfo.java index 68fc8754a..2686cc995 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/ClassInfo.java @@ -1,69 +1,99 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import java.io.Serializable; - -/** - * 类对象实体 - * - * @version 1.0 - * @date 2021/04/03 10:58 - **/ -public class ClassInfo implements Serializable { - private static final long serialVersionUID = -3958115376721507302L; - /** - * 当前对象Id - */ - private Integer id; - /** - * 端侧获取的classId - */ - private Integer cId; - /** - * 类名 - */ - private String className; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getcId() { - return cId; - } - - public void setcId(Integer cId) { - this.cId = cId; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - @Override - public String toString() { - return "ClassInfo{" + "id=" + id + ", cId=" + cId + ", className='" + className + '\'' + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentbean; + +import java.io.Serializable; + +/** + * class object entity + */ +public class ClassInfo implements Serializable { + private static final long serialVersionUID = -3958115376721507302L; + + /** + * current object id + */ + private Integer id; + + /** + * class id obtained from the end side + */ + private Integer cId; + + /** + * ClassName + */ + private String className; + + /** + * get Id + * + * @return Integer + */ + public Integer getId() { + return id; + } + + /** + * set Id + * + * @param id id + */ + public void setId(Integer id) { + this.id = id; + } + + /** + * get cId + * + * @return cId + */ + public Integer getcId() { + return cId; + } + + /** + * set cId + * + * @param cId cId + */ + public void setcId(Integer cId) { + this.cId = cId; + } + + /** + * get ClassName + * + * @return String + */ + public String getClassName() { + return className; + } + + /** + * set ClassName + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; + } + + @Override + public String toString() { + return "ClassInfo{" + "id=" + id + ", cId=" + cId + ", className='" + className + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryHeapInfo.java similarity index 52% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapInfo.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryHeapInfo.java index 28c759315..9f8cb23aa 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryHeapInfo.java @@ -1,174 +1,300 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import java.io.Serializable; - -/** - * 堆信息 - * - * @version 1.0 - * @date 2021/03/29 21:20 - **/ -public class MemoryHeapInfo implements Serializable { - private static final long serialVersionUID = -4742624779850639424L; - /** - * 当前对象Id - */ - private Integer id; - /** - * 端侧获取的classId - */ - private Integer cId; - /** - * heapId: app、zygote、image、JNI - */ - private Integer heapId; - /** - * 当前会话Id - */ - private Long sessionId; - private String arrangeStyle; - private String className; - /** - * 有调用栈信息的创建的实例个数 - */ - private Integer allocations; - /** - * 销毁的实例个数 - */ - private Integer deallocations; - /** - * 堆内存中所有的实例的个数(对应端的array_length) - */ - private Integer totalCount; - /** - * 堆内存中所有的实例的总大小(对应端的array_length*object_size) - */ - private Long shallowSize; - /** - * createTime - */ - private Long createTime; - /** - * 端侧获取的instanceId - */ - private Integer instanceId; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getcId() { - return cId; - } - - public void setcId(Integer cId) { - this.cId = cId; - } - - public Integer getHeapId() { - return heapId; - } - - public Long getSessionId() { - return sessionId; - } - - public void setSessionId(Long sessionId) { - this.sessionId = sessionId; - } - - public void setHeapId(Integer heapId) { - this.heapId = heapId; - } - - public String getArrangeStyle() { - return arrangeStyle; - } - - public void setArrangeStyle(String arrangeStyle) { - this.arrangeStyle = arrangeStyle; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Integer getAllocations() { - return allocations; - } - - public void setAllocations(Integer allocations) { - this.allocations = allocations; - } - - public Integer getDeallocations() { - return deallocations; - } - - public void setDeallocations(Integer deallocations) { - this.deallocations = deallocations; - } - - public Integer getTotalCount() { - return totalCount; - } - - public void setTotalCount(Integer totalCount) { - this.totalCount = totalCount; - } - - public Long getShallowSize() { - return shallowSize; - } - - public void setShallowSize(Long shallowSize) { - this.shallowSize = shallowSize; - } - - public Long getCreateTime() { - return createTime; - } - - public void setCreateTime(Long createTime) { - this.createTime = createTime; - } - - public Integer getInstanceId() { - return instanceId; - } - - public void setInstanceId(Integer instanceId) { - this.instanceId = instanceId; - } - - @Override - public String toString() { - return "MemoryHeapInfo{" + "id=" + id + ", cId=" + cId + ", heapId=" + heapId + ", sessionId=" + sessionId - + ", arrangeStyle='" + arrangeStyle + '\'' + ", className='" + className + '\'' + ", allocations=" - + allocations + ", deallocations=" + deallocations + ", totalCount=" + totalCount + ", shallowSize=" - + shallowSize + ", createTime=" + createTime + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentbean; + +import java.io.Serializable; + +/** + * Memory Heap Info + */ +public class MemoryHeapInfo implements Serializable { + private static final long serialVersionUID = -4742624779850639424L; + + /** + * heapId + */ + private Integer id; + + /** + * class Id + */ + private Integer cId; + + /** + * heapId: app、zygote、image、JNI + */ + private Integer heapId; + + /** + * this session Id + */ + private Long sessionId; + + /** + * class Name + */ + private String className; + + /** + * Number of instances created with call stack information + */ + private Integer allocations; + + /** + * number Of Instances Destroyed + */ + private Integer deallocations; + + /** + * The number of all instances in the heap memory (array length of the corresponding end) + */ + private Integer totalCount; + + /** + * The total size of all instances in the heap memory (array lengthobject size at the corresponding end) + */ + private Long shallowSize; + /** + * createTime + */ + private Long createTime; + + /** + * instance Id Obtained From The EndSide + */ + private Integer instanceId; + + /** + * updateTime + */ + private long updateTime; + + /** + * get instance Id + * + * @return Integer id + */ + public Integer getId() { + return id; + } + + /** + * set instance Id + * + * @param id id + */ + public void setId(Integer id) { + this.id = id; + } + + /** + * get class Id + * + * @return Integer cId + */ + public Integer getcId() { + return cId; + } + + /** + * set class Id + * + * @param cId cId + */ + public void setcId(Integer cId) { + this.cId = cId; + } + + /** + * get Heap Id + * + * @return Integer heapId + */ + public Integer getHeapId() { + return heapId; + } + + /** + * get Session Id + * + * @return Long sessionId + */ + public Long getSessionId() { + return sessionId; + } + + /** + * set SessionId + * + * @param sessionId sessionId + */ + public void setSessionId(Long sessionId) { + this.sessionId = sessionId; + } + + /** + * set HeapId + * + * @param heapId heapId + */ + public void setHeapId(Integer heapId) { + this.heapId = heapId; + } + + /** + * get ClassName + * + * @return String + */ + public String getClassName() { + return className; + } + + /** + * set ClassName + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; + } + + /** + * get Allocations + * + * @return allocations + */ + public Integer getAllocations() { + return allocations; + } + + /** + * set Allocations + * + * @param allocations allocations + */ + public void setAllocations(Integer allocations) { + this.allocations = allocations; + } + + /** + * get Deallocations + * + * @return deallocations + */ + public Integer getDeallocations() { + return deallocations; + } + + /** + * set Deallocations + * + * @param deallocations deallocations + */ + public void setDeallocations(Integer deallocations) { + this.deallocations = deallocations; + } + + /** + * get TotalCount + * + * @return totalCount + */ + public Integer getTotalCount() { + return totalCount; + } + + /** + * set TotalCount + * + * @param totalCount totalCount + */ + public void setTotalCount(Integer totalCount) { + this.totalCount = totalCount; + } + + /** + * get ShallowSize + * + * @return shallowSize + */ + public Long getShallowSize() { + return shallowSize; + } + + /** + * set ShallowSize + * + * @param shallowSize shallowSize + */ + public void setShallowSize(Long shallowSize) { + this.shallowSize = shallowSize; + } + + /** + * get CreateTime + * + * @return createTime + */ + public Long getCreateTime() { + return createTime; + } + + /** + * set CreateTime + * + * @param createTime createTime + */ + public void setCreateTime(Long createTime) { + this.createTime = createTime; + } + + /** + * get InstanceId + * + * @return instanceId + */ + public Integer getInstanceId() { + return instanceId; + } + + /** + * set InstanceId + * + * @param instanceId instanceId + */ + public void setInstanceId(Integer instanceId) { + this.instanceId = instanceId; + } + + /** + * get UpdateTime + * + * @return updateTime + */ + public long getUpdateTime() { + return updateTime; + } + + /** + * set UpdateTime + * + * @param updateTime updateTime + */ + public void setUpdateTime(long updateTime) { + this.updateTime = updateTime; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceDetailsInfo.java similarity index 87% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfo.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceDetailsInfo.java index a5327cb6b..4bab7d4a0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceDetailsInfo.java @@ -1,116 +1,123 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import java.io.Serializable; - -/** - * 调用栈信息 - * - * @version 1.0 - * @date 2021/03/29 21:25 - **/ -public class MemoryInstanceDetailsInfo implements Serializable { - private static final long serialVersionUID = -7886031529563053311L; - /** - * 当前对象Id - */ - private Integer id; - /** - * 调用栈对应的instanceId - */ - private Integer instanceId; - /** - * 端侧获取的frameId - */ - private Integer frameId; - /** - * 端侧获取的类名 - */ - private String className; - /** - * 端侧获取的方法名 - */ - private String methodName; - /** - * 端侧获取的属性名 - */ - private String fieldName; - private Integer lineNumber; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getInstanceId() { - return instanceId; - } - - public void setInstanceId(Integer instanceId) { - this.instanceId = instanceId; - } - - public Integer getFrameId() { - return frameId; - } - - public void setFrameId(Integer frameId) { - this.frameId = frameId; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public String getMethodName() { - return methodName; - } - - public void setMethodName(String methodName) { - this.methodName = methodName; - } - - public String getFieldName() { - return fieldName; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - public Integer getLineNumber() { - return lineNumber; - } - - public void setLineNumber(Integer lineNumber) { - this.lineNumber = lineNumber; - } - - @Override - public String toString() { - return "MemoryInstanceDetailsInfo{" + "frameId=" + frameId + ", className='" + className + '\'' - + ", methodName='" + methodName + '\'' + ", fieldName='" + fieldName + '\'' + ", lineNumber=" + lineNumber - + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentbean; + +import java.io.Serializable; + +/** + * Memory InstanceDetailsInfo + */ +public class MemoryInstanceDetailsInfo implements Serializable { + private static final long serialVersionUID = -7886031529563053311L; + + /** + * Id + */ + private Integer id; + + /** + * instanceId + */ + private Integer instanceId; + + /** + * frameId + */ + private Integer frameId; + + /** + * className + */ + private String className; + + /** + * methodName + */ + private String methodName; + + /** + * fieldName + */ + private String fieldName; + + /** + * lineNumber + */ + private Integer lineNumber; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getInstanceId() { + return instanceId; + } + + public void setInstanceId(Integer instanceId) { + this.instanceId = instanceId; + } + + public Integer getFrameId() { + return frameId; + } + + public void setFrameId(Integer frameId) { + this.frameId = frameId; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public Integer getLineNumber() { + return lineNumber; + } + + public void setLineNumber(Integer lineNumber) { + this.lineNumber = lineNumber; + } + + @Override + public String toString() { + return "MemoryInstanceDetailsInfo{" + "frameId=" + frameId + ", className='" + className + '\'' + + ", methodName='" + methodName + '\'' + ", fieldName='" + fieldName + '\'' + ", lineNumber=" + lineNumber + + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceInfo.java similarity index 60% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceInfo.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceInfo.java index 9413eb40c..dc9122d39 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceInfo.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentbean/MemoryInstanceInfo.java @@ -1,119 +1,193 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import java.io.Serializable; - -/** - * 具体实例信息 - * - * @version 1.0 - * @date 2021/03/29 21:22 - **/ -public class MemoryInstanceInfo implements Serializable { - private static final long serialVersionUID = -2702142952950557386L; - /** - * 当前实例对象Id - */ - private Integer id; - /** - * 端侧获取的instanceId - */ - private Integer instanceId; - /** - * 当前实例Instance对应的类Id - */ - private Integer cId; - /** - * 实例名称 - */ - private String instance; - /** - * 当前Instance的创建时间 - */ - private Long allocTime; - /** - * 当前Instance的销毁时间 - */ - private Long deallocTime; - /** - * 当前Instance的入库时间 - */ - private Long createTime; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getInstanceId() { - return instanceId; - } - - public void setInstanceId(Integer instanceId) { - this.instanceId = instanceId; - } - - public Integer getcId() { - return cId; - } - - public void setcId(Integer cId) { - this.cId = cId; - } - - public String getInstance() { - return instance; - } - - public void setInstance(String instance) { - this.instance = instance; - } - - public Long getAllocTime() { - return allocTime; - } - - public void setAllocTime(Long allocTime) { - this.allocTime = allocTime; - } - - public Long getDeallocTime() { - return deallocTime; - } - - public void setDeallocTime(Long deallocTime) { - this.deallocTime = deallocTime; - } - - public Long getCreateTime() { - return createTime; - } - - public void setCreateTime(Long createTime) { - this.createTime = createTime; - } - - @Override - public String toString() { - return "MemoryInstanceInfo{" + "id=" + id + ", instanceId=" + instanceId + ", cId=" + cId + ", instance='" - + instance + '\'' + ", allocTime=" + allocTime + ", deallocTime=" + deallocTime + ", createTime=" - + createTime + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentbean; + +import java.io.Serializable; + +/** + * specific instance information + */ +public class MemoryInstanceInfo implements Serializable { + private static final long serialVersionUID = -2702142952950557386L; + + /** + * id Of The Current Instance Object + */ + private Integer id; + + /** + * instanceId Obtained FromT he EndSide + */ + private Integer instanceId; + + /** + * Class Id corresponding to the current instance Instance + */ + private Integer cId; + + /** + * instance Name + */ + private String instance; + + /** + * creation time of the current instance + */ + private Long allocTime; + + /** + * Destruction Time Of The CurrentInstance + */ + private Long deallocTime; + + /** + * Storage Time Of The CurrentInstance + */ + private Long createTime; + + /** + * get Id + * + * @return id + */ + public Integer getId() { + return id; + } + + /** + * setId + * + * @param id id + */ + public void setId(Integer id) { + this.id = id; + } + + /** + * getInstance Id + * + * @return instanceId + */ + public Integer getInstanceId() { + return instanceId; + } + + /** + * set InstanceId + * + * @param instanceId instanceId + */ + public void setInstanceId(Integer instanceId) { + this.instanceId = instanceId; + } + + /** + * get class Id + * + * @return Integer + */ + public Integer getcId() { + return cId; + } + + /** + * set class Id + * + * @param cId cId + */ + public void setcId(Integer cId) { + this.cId = cId; + } + + /** + * get Instance + * + * @return instance + */ + public String getInstance() { + return instance; + } + + /** + * setInstance + * + * @param instance instance + */ + public void setInstance(String instance) { + this.instance = instance; + } + + /** + * getAllocTime + * + * @return allocTime + */ + public Long getAllocTime() { + return allocTime; + } + + /** + * setAllocTime + * + * @param allocTime allocTime + */ + public void setAllocTime(Long allocTime) { + this.allocTime = allocTime; + } + + /** + * getDeallocTime + * + * @return deallocTime + */ + public Long getDeallocTime() { + return deallocTime; + } + + /** + * setDeallocTime + * + * @param deallocTime deallocTime + */ + public void setDeallocTime(Long deallocTime) { + this.deallocTime = deallocTime; + } + + /** + * getCreateTime + * + * @return createTime + */ + public Long getCreateTime() { + return createTime; + } + + /** + * setCreateTime + * + * @param createTime createTime + */ + public void setCreateTime(Long createTime) { + this.createTime = createTime; + } + + @Override + public String toString() { + return "MemoryInstanceInfo{" + "id=" + id + ", instanceId=" + instanceId + ", cId=" + cId + ", instance='" + + instance + '\'' + ", allocTime=" + allocTime + ", deallocTime=" + deallocTime + ", createTime=" + + createTime + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoDao.java similarity index 83% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoDao.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoDao.java index 52d564bbe..d2a6b0d1c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoDao.java @@ -1,221 +1,220 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; - -/** - * 处理端侧获取的类数据 - * - * @version 1.0 - * @date 2021/04/03 11:03 - **/ -public class ClassInfoDao extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(ClassInfoDao.class); - private static final int SQL_INDEX_TWO = 2; - private static final int SQL_INDEX_THREE = 3; - private static volatile ClassInfoDao singleton; - - /** - * ClassInfoDao - * - * @return ClassInfoDao - */ - public static ClassInfoDao getInstance() { - if (singleton == null) { - synchronized (ClassInfoDao.class) { - if (singleton == null) { - singleton = new ClassInfoDao(); - } - } - } - return singleton; - } - - public ClassInfoDao() { - createClassInfo(); - } - - /** - * 获取数据库连接 - * - * @param tableName 表名 - * @return Connection - * @date 2021/4/3 11:44 - */ - private Connection getConnection(String tableName) { - Optional optionalConnection = getConnectByTable(tableName); - Connection conn = null; - if (optionalConnection.isPresent()) { - conn = optionalConnection.get(); - } - return conn; - } - - /** - * createClassInfo - * - * @return boolean - */ - public boolean createClassInfo() { - boolean createResult = false; - String dbName = JVMTI_AGENT_PLUG; - String classInfoTable = "ClassInfo"; - String sql = "CREATE TABLE ClassInfo " + "( id Integer primary key autoincrement not null, " - + " cId int not null, " + " className varchar not null " + ");"; - createResult = createTable(dbName, classInfoTable, sql); - return createResult; - } - - /** - * insertClassInfo - * - * @param classInfo classInfo - */ - public void insertClassInfo(ClassInfo classInfo) { - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("ClassInfo"); - String sql = "insert into ClassInfo (id,cId,className) values (null,?,?)"; - ps = conn.prepareStatement(sql); - ps.setInt(1, classInfo.getcId()); - ps.setString(Option.SQL_INDEX_TWO, classInfo.getClassName()); - ps.executeUpdate(); - } catch (SQLException throwables) { - throwables.printStackTrace(); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * insertClassInfos - * - * @param classInfos classInfos - * @return boolean - */ - public boolean insertClassInfos(List classInfos) { - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("ClassInfo"); - conn.setAutoCommit(false); - String sql = "insert into ClassInfo (id,cId,className) values (null,?,?)"; - ps = conn.prepareStatement(sql); - for (ClassInfo classInfo : classInfos) { - ps.setInt(1, classInfo.getcId()); - ps.setString(SQL_INDEX_TWO, classInfo.getClassName()); - ps.addBatch(); - } - int[] results = ps.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwables) { - LOGGER.error("SQLException error: " + throwables.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * 获取所有的ClassInfo数据. - * - * @param sessionId sessionId - * @return List - */ - public List getAllClassInfoData(Long sessionId) { - Connection conn = getConnection("ClassInfo"); - PreparedStatement ps = null; - ArrayList classInfos = new ArrayList<>(); - try { - String sql = "select id,cId,className from ClassInfo"; - ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - ClassInfo classInfo = null; - while (rs.next()) { - classInfo = new ClassInfo(); - Integer id = rs.getInt("id"); - Integer cId = rs.getInt("cId"); - String className = rs.getString("className"); - classInfo.setId(id); - classInfo.setcId(cId); - classInfo.setClassName(className); - classInfos.add(classInfo); - } - return classInfos; - } catch (SQLException throwables) { - LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return classInfos; - } - - /** - * 获取所有的ClassInfo数据. - * - * @param className className - * @return int cid - */ - public int getClassIdByClassName(String className) { - Connection conn = getConnection("ClassInfo"); - PreparedStatement ps = null; - int cId = 0; - try { - String sql = "select cId from ClassInfo where className = '" + className + "'"; - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery(sql); - if (rs.next()) { - cId = rs.getInt("cId"); - } - return cId; - } catch (SQLException throwables) { - LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return cId; - } - - /** - * 删除一次场景下的堆信息数据 - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - StringBuffer deleteSql = new StringBuffer("DELETE FROM ClassInfo"); - Connection connection = DataBaseApi.getInstance().getConnectByTable("ClassInfo").get(); - return execute(connection, deleteSql.toString()); - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; + +/** + * processing the class data obtained on the end side + */ +public class ClassInfoDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(ClassInfoDao.class); + private static volatile ClassInfoDao singleton; + + /** + * ClassInfoDao + * + * @return ClassInfoDao + */ + public static ClassInfoDao getInstance() { + if (singleton == null) { + synchronized (ClassInfoDao.class) { + if (singleton == null) { + singleton = new ClassInfoDao(); + } + } + } + return singleton; + } + + /** + * ClassInfoDao constructor + */ + public ClassInfoDao() { + createClassInfo(); + } + + /** + * get database connection + * + * @param tableName TableName + * @return Connection + */ + private Connection getConnection(String tableName) { + Optional optionalConnection = getConnectByTable(tableName); + Connection conn = null; + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + } + return conn; + } + + /** + * create ClassInfo + * + * @return boolean + */ + public boolean createClassInfo() { + boolean createResult = false; + String dbName = JVMTI_AGENT_PLUG; + String classInfoTable = "ClassInfo"; + String sql = "CREATE TABLE ClassInfo " + "(" + + " cId int not null, " + " className varchar not null " + ");"; + createResult = createTable(dbName, classInfoTable, sql); + return createResult; + } + + /** + * insert ClassInfo + * + * @param classInfo classInfo + */ + public void insertClassInfo(ClassInfo classInfo) { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("ClassInfo"); + String sql = "insert into ClassInfo (cId,className) values (?,?)"; + ps = conn.prepareStatement(sql); + ps.setInt(1, classInfo.getcId()); + ps.setString(2, classInfo.getClassName()); + ps.executeUpdate(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * insert ClassInfos + * + * @param classInfos List + * @return boolean + */ + public boolean insertClassInfos(List classInfos) { + if (classInfos.isEmpty()) { + return false; + } + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("ClassInfo"); + conn.setAutoCommit(false); + String sql = "insert into ClassInfo (cId,className) values (?,?)"; + ps = conn.prepareStatement(sql); + for (ClassInfo classInfo : classInfos) { + ps.setInt(1, classInfo.getcId()); + ps.setString(2, classInfo.getClassName()); + ps.addBatch(); + } + int[] results = ps.executeBatch(); + conn.commit(); + return true; + } catch (SQLException throwables) { + LOGGER.error("SQLException error: " + throwables.getMessage()); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * get All ClassInfoData. + * + * @param sessionId sessionId + * @return List + */ + public List getAllClassInfoData(Long sessionId) { + Connection conn = getConnection("ClassInfo"); + PreparedStatement ps = null; + ArrayList classInfos = new ArrayList<>(); + try { + String sql = "select cId,className from ClassInfo"; + ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + ClassInfo classInfo = null; + while (rs.next()) { + classInfo = new ClassInfo(); + Integer cId = rs.getInt("cId"); + String className = rs.getString("className"); + classInfo.setcId(cId); + classInfo.setClassName(className); + classInfos.add(classInfo); + } + return classInfos; + } catch (SQLException throwables) { + LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return classInfos; + } + + /** + * get all class info data. + * + * @param className className + * @return int cid + */ + public int getClassIdByClassName(String className) { + Connection conn = getConnection("ClassInfo"); + PreparedStatement ps = null; + int cId = 0; + try { + String sql = "select cId from ClassInfo where className = '" + className + "'"; + Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery(sql); + if (rs.next()) { + cId = rs.getInt("cId"); + } + return cId; + } catch (SQLException throwables) { + LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return cId; + } + + /** + * delete the heap information data in a scene + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM ClassInfo"); + Connection connection = DataBaseApi.getInstance().getConnectByTable("ClassInfo").get(); + return execute(connection, deleteSql.toString()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoManager.java similarity index 79% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoManager.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoManager.java index 83ccd373b..6c154019d 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/ClassInfoManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/ClassInfoManager.java @@ -1,57 +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. - */ - -package ohos.devtools.services.memory; - -import java.util.List; - -/** - * 类信息业务处理对象 - * - * @version 1.0 - * @date 2021/04/05 11:00 - **/ -public class ClassInfoManager { - private final ClassInfoDao classInfoDao = ClassInfoDao.getInstance(); - - /** - * insertClassInfo - * - * @param classInfo classInfo - */ - public void insertClassInfo(ClassInfo classInfo) { - classInfoDao.insertClassInfo(classInfo); - } - - /** - * 获取所有的数据至文件 - * - * @param sessionId sessionId - * @return List - */ - public List getAllClassInfoData(Long sessionId) { - return classInfoDao.getAllClassInfoData(sessionId); - } - - /** - * 获取所有的数据至文件 - * - * @param sessionId sessionId - * @return List - */ - public int getClassIdByClassName(String className) { - return classInfoDao.getClassIdByClassName(className); - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.services.memory.agentbean.ClassInfo; + +import java.util.List; + +/** + * ClassInfo Manager + */ +public class ClassInfoManager { + private final ClassInfoDao classInfoDao = ClassInfoDao.getInstance(); + + /** + * insertClassInfo + * + * @param classInfo classInfo + */ + public void insertClassInfo(ClassInfo classInfo) { + classInfoDao.insertClassInfo(classInfo); + } + + /** + * get All ClassInfoData + * + * @param sessionId sessionId + * @return List + */ + public List getAllClassInfoData(Long sessionId) { + return classInfoDao.getAllClassInfoData(sessionId); + } + + /** + * get ClassId By ClassName + * + * @param className className + * @return int + */ + public int getClassIdByClassName(String className) { + return classInfoDao.getClassIdByClassName(className); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapDao.java new file mode 100644 index 000000000..fb82d62b4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapDao.java @@ -0,0 +1,371 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; + +/** + * heap data processing object + */ +public class MemoryHeapDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(MemoryHeapDao.class); + + /** + * Singleton MemoryHeapDao. + */ + private static final MemoryHeapDao SINGLETON = new MemoryHeapDao(); + + /** + * getInstance + * + * @return MemoryHeapDao + */ + public static MemoryHeapDao getInstance() { + return MemoryHeapDao.SINGLETON; + } + + /** + * MemoryHeapDao + */ + public MemoryHeapDao() { + createMemoryHeapInfo(); + } + + /** + * get database connection + * + * @param tableName tableName + * @return Connection + */ + private Connection getConnection(String tableName) { + Optional optionalConnection = getConnectByTable(tableName); + Connection conn = null; + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + } + return conn; + } + + /** + * heap information data table creation + * + * @return boolean + */ + public boolean createMemoryHeapInfo() { + boolean createResult = false; + String dbName = JVMTI_AGENT_PLUG; + String memoryHeapInfoTable = "MemoryHeapInfo"; + String sql = "CREATE TABLE MemoryHeapInfo (" + + "cId int(100) not null, " + + "heapId int(100) not null, " + + "instanceId int(100) not null, " + + "sessionId Long(100) not null, " + + "allocations int(100) not null, " + + "deallocations int(100) not null, " + + "totalCount int(100) not null, " + + "shallowSize int(100) not null, " + + "createTime int(200) not null, " + + "updateTime int(200) DEFAULT -1" + + ");"; + createResult = createTable(dbName, memoryHeapInfoTable, sql); + return createResult; + } + + /** + * insert MemoryHeapInfos + * + * @param memoryHeapInfos 堆实例 + * @return boolean + */ + public boolean insertMemoryHeapInfos(List memoryHeapInfos) { + if (memoryHeapInfos.isEmpty()) { + return false; + } + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("MemoryHeapInfo"); + conn.setAutoCommit(false); + String sql = "insert into MemoryHeapInfo(cId,heapId,sessionId,allocations," + + "deallocations,totalCount,shallowSize,createTime,instanceId)values(?,?,?,?,?,?,?,?,?)"; + ps = conn.prepareStatement(sql); + for (MemoryHeapInfo memoryHeapInfo : memoryHeapInfos) { + try { + ps.setInt(1, memoryHeapInfo.getcId()); + ps.setInt(2, memoryHeapInfo.getHeapId()); + ps.setLong(3, memoryHeapInfo.getSessionId()); + ps.setLong(4, memoryHeapInfo.getAllocations()); + ps.setLong(5, memoryHeapInfo.getDeallocations()); + ps.setInt(6, memoryHeapInfo.getTotalCount()); + ps.setLong(7, memoryHeapInfo.getShallowSize()); + ps.setLong(8, memoryHeapInfo.getCreateTime()); + ps.setLong(9, memoryHeapInfo.getInstanceId()); + ps.addBatch(); + } catch (SQLException sqlException) { + LOGGER.info("insert AppInfo {}", sqlException.getMessage()); + } + } + ps.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + ps.clearParameters(); + return true; + } catch (SQLException throwables) { + LOGGER.info("insert MemoryHeap {}", throwables.getMessage()); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * get All MemoryHeapInfos + * + * @param sessionId sessionId + * @return ArrayList + */ + public ArrayList getAllMemoryHeapInfos(Long sessionId) { + Connection conn = getConnection("MemoryHeapInfo"); + PreparedStatement ps = null; + ArrayList memoryHeapInfos = new ArrayList<>(); + try { + String sql = "select cId,heapId,sessionId,allocations,deallocations,totalCount," + + "shallowSize,createTime,instanceId, updateTime from MemoryHeapInfo where sessionId = ?"; + ps = conn.prepareStatement(sql); + ps.setLong(1, sessionId); + ResultSet rs = ps.executeQuery(); + MemoryHeapInfo memoryHeapInfo = null; + while (rs.next()) { + memoryHeapInfo = new MemoryHeapInfo(); + Integer cId = rs.getInt("cId"); + Integer heapId = rs.getInt("heapId"); + Long msessionId = rs.getLong("sessionId"); + Integer allocations = rs.getInt("allocations"); + Integer deallocations = rs.getInt("deallocations"); + Integer totalCount = rs.getInt("totalCount"); + Long shallowSize = rs.getLong("shallowSize"); + Long createTime = rs.getLong("createTime"); + Integer instanceId = rs.getInt("instanceId"); + Long updateTime = rs.getLong("updateTime"); + memoryHeapInfo.setHeapId(heapId); + memoryHeapInfo.setcId(cId); + memoryHeapInfo.setSessionId(msessionId); + memoryHeapInfo.setSessionId(sessionId); + memoryHeapInfo.setAllocations(allocations); + memoryHeapInfo.setDeallocations(deallocations); + memoryHeapInfo.setTotalCount(totalCount); + memoryHeapInfo.setShallowSize(shallowSize); + memoryHeapInfo.setCreateTime(createTime); + memoryHeapInfo.setInstanceId(instanceId); + memoryHeapInfo.setUpdateTime(updateTime); + memoryHeapInfos.add(memoryHeapInfo); + } + ps.clearParameters(); + return memoryHeapInfos; + } catch (SQLException throwables) { + LOGGER.info("memoryHeapInfo Exception {}", throwables.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryHeapInfos; + } + + /** + * get MemoryHeapInfos + * + * @param sessionId sessionId + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return ArrayList + */ + public List getMemoryHeapInfos(Long sessionId, Long startTime, Long endTime) { + Connection conn = getConnection("MemoryHeapInfo"); + PreparedStatement ps = null; + List memoryHeapInfos = new ArrayList<>(); + try { + String sql = getSql(); + ps = conn.prepareStatement(sql); + setPreparedStatementData(sessionId, startTime, endTime, ps); + ResultSet rs = ps.executeQuery(); + AgentHeapBean memoryHeapInfo = null; + while (rs.next()) { + memoryHeapInfo = new AgentHeapBean(); + Integer cId = rs.getInt("cId"); + String className = rs.getString("className"); + Integer allocations = rs.getInt("allocations"); + Integer deallocations = rs.getInt("deallocations"); + Integer totalCount = rs.getInt("totalCount"); + Long shallowSize = rs.getLong("shallowSize"); + memoryHeapInfo.setAgentClazzId(cId); + memoryHeapInfo.setAgentHeapId(0); + memoryHeapInfo.setSessionId(sessionId); + memoryHeapInfo.setAgentClazzName(className); + memoryHeapInfo.setAgentAllocationsCount(allocations); + memoryHeapInfo.setAgentDeAllocationsCount(deallocations); + memoryHeapInfo.setAgentTotalInstanceCount(totalCount); + memoryHeapInfo.setAgentTotalshallowSize(shallowSize); + memoryHeapInfos.add(memoryHeapInfo); + } + ps.clearParameters(); + return memoryHeapInfos; + } catch (SQLException throwAbles) { + LOGGER.info("memoryHeapInfo Exception {}", throwAbles.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryHeapInfos; + } + + /** + * set PreparedStatement Data + * + * @param sessionId sessionId + * @param startTime startTime + * @param endTime endTime + * @param ps ps + * @throws SQLException + */ + private void setPreparedStatementData(Long sessionId, Long startTime, Long endTime, PreparedStatement ps) + throws SQLException { + ps.setLong(1, sessionId); + ps.setLong(2, startTime); + ps.setLong(3, endTime); + ps.setLong(4, startTime); + ps.setLong(5, endTime); + ps.setLong(6, sessionId); + ps.setLong(7, startTime); + ps.setLong(8, endTime); + ps.setLong(9, sessionId); + ps.setLong(10, startTime); + ps.setLong(11, endTime); + ps.setLong(12, startTime); + ps.setLong(13, endTime); + ps.setLong(14, sessionId); + ps.setLong(15, startTime); + ps.setLong(16, endTime); + ps.setLong(17, sessionId); + ps.setLong(18, startTime); + ps.setLong(19, endTime); + ps.setLong(20, startTime); + ps.setLong(21, endTime); + ps.setLong(22, sessionId); + ps.setLong(23, endTime); + } + + /** + * delete SessionData by sessionId + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM "); + deleteSql.append("MemoryHeapInfo").append(" WHERE sessionId = ").append(sessionId); + Connection connection = DataBaseApi.getInstance().getConnectByTable("MemoryHeapInfo").get(); + return execute(connection, deleteSql.toString()); + } + + /** + * updateMemoryHeapInfoList + * + * @param memoryUpdateInfos memoryUpdateInfos + * @return boolean + */ + public boolean updateMemoryHeapInfoList(List memoryUpdateInfos) { + if (memoryUpdateInfos.isEmpty()) { + return true; + } + Connection conn = getConnection("MemoryHeapInfo"); + PreparedStatement ps = null; + try { + conn.setAutoCommit(false); + ps = conn.prepareStatement( + "UPDATE MemoryHeapInfo SET deallocations = 1, updateTime = ? where instanceId = ? "); + for (MemoryUpdateInfo memoryUpdateInfo : memoryUpdateInfos) { + ps.setLong(1, memoryUpdateInfo.getUpdateTime()); + ps.setLong(2, memoryUpdateInfo.getInstanceId()); + ps.addBatch(); + } + ps.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + ps.clearParameters(); + return true; + } catch (SQLException throwables) { + return false; + } finally { + close(ps, conn); + } + } + + @NotNull + private String getSql() { + String str1 = "SELECT d.cid,d.className,IFNULL( d.allocations, 0 ) AS allocations," + + "IFNULL( d.deallocations, 0 ) AS deallocations,IFNULL( f.totalCount, 0 ) AS totalCount," + + "IFNULL( f.shallowSize, 0 ) AS shallowSize " + + "FROM ((SELECT c.cId,c.className,sum( IFNULL( heaptable.allocations, 0 ) ) AS allocations," + + "sum( IFNULL( heaptable.deallocations, 0 ) ) AS deallocations FROM ClassInfo c LEFT JOIN " + + "(SELECT m.cId,m.heapId,m.instanceId,m.sessionId,m.allocations,m.totalCount,m.shallowSize,m.createTime," + + "instance.deallocTime,1 AS deallocations FROM MemoryHeapInfo m LEFT JOIN MemoryInstanceInfo instance ON" + + " instance.instanceId = m.instanceId WHERE m.sessionId = ? " + + "AND (( m.createTime >= ? AND m.createTime <= ? ) " + + "AND ( instance.deallocTime >= ? AND instance.deallocTime <= ? ) ) UNION " + + "SELECT m.cId,m.heapId,m.instanceId,m.sessionId,m.allocations,m.totalCount,m.shallowSize,m.createTime," + + "IFNULL( instance.deallocTime, 0 ) AS deallocTime,0 AS deallocations FROM MemoryHeapInfo m LEFT JOIN " + + "MemoryInstanceInfo instance ON instance.instanceId = m.instanceId WHERE m.sessionId = ? " + + "AND ( ( m.createTime >= ? AND m.createTime <= ? ) ) AND m.instanceId NOT IN (SELECT m.instanceId " + + "FROM MemoryHeapInfo m LEFT JOIN MemoryInstanceInfo instance ON instance.instanceId = m.instanceId " + + "WHERE m.sessionId = ? AND (( m.createTime >= ? AND m.createTime <= ? ) AND ( instance.deallocTime >= ? " + + "AND instance.deallocTime <= ? ) ) ) UNION SELECT m.cId,m.heapId,m.instanceId,m.sessionId," + + "0 AS allocations,m.totalCount,m.shallowSize,m.createTime," + + "IFNULL( instance.deallocTime, 0 ) AS deallocTime,1 AS deallocations FROM MemoryHeapInfo m " + + "LEFT JOIN MemoryInstanceInfo instance ON instance.instanceId = m.instanceId " + + "WHERE m.sessionId = ? AND ( ( instance.deallocTime >= ? AND instance.deallocTime <= ? ) ) " + + "AND m.instanceId NOT IN (SELECT m.instanceId FROM MemoryHeapInfo m LEFT" + + " JOIN MemoryInstanceInfo instance " + + "ON instance.instanceId = m.instanceId WHERE m.sessionId = ? " + + "AND (( m.createTime >= ? AND m.createTime <= ? ) AND ( instance.deallocTime >= ? " + + "AND instance.deallocTime <= ? ) ) ) ) AS heaptable ON c.cId = heaptable.cId GROUP BY c.cId ) " + + "AS d LEFT JOIN (SELECT e.cId AS cId,sum( IFNULL( e.totalCount, 0 ) ) AS totalCount," + + "sum( IFNULL( e.shallowSize, 0 ) ) AS shallowSize FROM ClassInfo l LEFT JOIN MemoryHeapInfo e " + + "ON e.cId = l.cId WHERE e.sessionId = ? AND e.createTime <= ? GROUP BY l.cId ) AS f ON d.cId = f.cId) " + + "ORDER BY shallowSize DESC"; + return str1; + } + + + + + + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapManager.java similarity index 65% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapManager.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapManager.java index 3788d409e..37eabd10c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryHeapManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryHeapManager.java @@ -1,52 +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. - */ - -package ohos.devtools.services.memory; - -import java.util.ArrayList; - -/** - * agent数据处理对象 - * - * @version 1.0 - * @date 2021/03/30 10:11 - **/ -public class MemoryHeapManager { - private final MemoryHeapDao memoryHeapDao = MemoryHeapDao.getInstance(); - - /** - * 获取框选时间段内的数据,提供给UI的堆信息查询接口 - * - * @param sessionId sessionId - * @param startTime 起始时间 - * @param endTime 结束时间 - * @return ArrayList - * @date 2021/03/30 20:25 - */ - public ArrayList getMemoryHeapInfos(Long sessionId, Long startTime, Long endTime) { - return memoryHeapDao.getMemoryHeapInfos(sessionId, startTime, endTime); - } - - /** - * 获取MemoryHeapInfos的数据 - * - * @param sessionId sessionId - * @return ArrayList - */ - public ArrayList getAllMemoryHeapInfos(Long sessionId) { - return memoryHeapDao.getAllMemoryHeapInfos(sessionId); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; + +import java.util.ArrayList; +import java.util.List; + +/** + * MemoryHeapManager + */ +public class MemoryHeapManager { + private final MemoryHeapDao memoryHeapDao = MemoryHeapDao.getInstance(); + + /** + * get MemoryHeapInfos + * + * @param sessionId sessionId + * @param startTime startTime + * @param endTime endTime + * @return ArrayList + */ + public List getMemoryHeapInfos(Long sessionId, Long startTime, Long endTime) { + return memoryHeapDao.getMemoryHeapInfos(sessionId, startTime, endTime); + } + + /** + * get AllMemoryHeapInfos + * + * @param sessionId sessionId + * @return ArrayList + */ + public ArrayList getAllMemoryHeapInfos(Long sessionId) { + return memoryHeapDao.getAllMemoryHeapInfos(sessionId); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDao.java similarity index 51% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDao.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDao.java index f39b960a8..c06c188ac 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDao.java @@ -1,294 +1,247 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; -import static ohos.devtools.services.memory.Option.SQL_INDEX_TWO; - -/** - * 实例数据处理对象 - * - * @version 1.0 - * @date 2021/03/30 18:47 - **/ -public class MemoryInstanceDao extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(MemoryInstanceDao.class); - private static volatile MemoryInstanceDao singleton; - - /** - * 获取单例对象 - * - * @return MemoryInstanceDao - */ - public static MemoryInstanceDao getInstance() { - if (singleton == null) { - synchronized (MemoryInstanceDao.class) { - if (singleton == null) { - singleton = new MemoryInstanceDao(); - } - } - } - return singleton; - } - - /** - * MemoryInstanceDao - */ - public MemoryInstanceDao() { - createMemoryInstance(); - } - - /** - * 获取数据库连接 - * - * @param tableName 表名 - * @return Connection - */ - private Connection getConnection(String tableName) { - Optional optionalConnection = getConnectByTable(tableName); - Connection conn = null; - if (optionalConnection.isPresent()) { - conn = optionalConnection.get(); - } - return conn; - } - - /** - * 实例对象表创建 - * - * @return boolean - */ - public boolean createMemoryInstance() { - String dbName = JVMTI_AGENT_PLUG; - String memoryInstanceInfoTable = "MemoryInstanceInfo"; - String sql = "CREATE TABLE MemoryInstanceInfo " + "( " - + " id Integer primary key autoincrement not null, " - + " instanceId int(100) not null, " + " cId int(100) not null, " - + " instance varchar(200), " + " createTime Long(200), " + " allocTime int(100), " - + " deallocTime int(100) " + ");"; - return createTable(dbName, memoryInstanceInfoTable, sql); - } - - /** - * 将端侧获取的实例信息保存在数据库 - * - * @param memoryInstanceInfo memoryInstanceInfo - */ - public void insertMemoryInstanceInfo(MemoryInstanceInfo memoryInstanceInfo) { - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("MemoryInstanceInfo"); - String sql = - "insert into MemoryInstanceInfo(id,instanceId,cId,instance,createTime,allocTime,deallocTime) values" - + "(null,?,?,?,?,?,?)"; - ps = conn.prepareStatement(sql); - ps.setInt(1, memoryInstanceInfo.getInstanceId()); - ps.setInt(SQL_INDEX_TWO, memoryInstanceInfo.getcId()); - ps.setString(Option.SQL_INDEX_THREE, memoryInstanceInfo.getInstance()); - ps.setLong(Option.SQL_INDEX_FOUR, memoryInstanceInfo.getCreateTime()); - ps.setLong(Option.SQL_INDEX_FIVE, memoryInstanceInfo.getAllocTime()); - ps.setLong(Option.SQL_INDEX_SIX, memoryInstanceInfo.getDeallocTime()); - ps.executeUpdate(); - } catch (SQLException throwAbles) { - LOGGER.error("SQLException error: " + throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * insertMemoryInstanceInfos - * - * @param memoryInstanceInfos memoryInstanceInfos - * @return boolean - */ - public boolean insertMemoryInstanceInfos(List memoryInstanceInfos) { - if (memoryInstanceInfos.isEmpty()) { - return false; - } - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("MemoryInstanceInfo"); - conn.setAutoCommit(false); - String sql = - "insert into MemoryInstanceInfo(id,instanceId,cId,instance,createTime,allocTime,deallocTime) values" - + "(null,?,?,?,?,?,?)"; - ps = conn.prepareStatement(sql); - for (MemoryInstanceInfo memoryInstanceInfo : memoryInstanceInfos) { - try { - ps.setInt(1, memoryInstanceInfo.getInstanceId()); - ps.setInt(SQL_INDEX_TWO, memoryInstanceInfo.getcId()); - ps.setString(Option.SQL_INDEX_THREE, memoryInstanceInfo.getInstance()); - ps.setLong(Option.SQL_INDEX_FOUR, memoryInstanceInfo.getCreateTime()); - ps.setLong(Option.SQL_INDEX_FIVE, memoryInstanceInfo.getAllocTime()); - ps.setLong(Option.SQL_INDEX_SIX, memoryInstanceInfo.getDeallocTime()); - ps.addBatch(); - } catch (SQLException sqlException) { - LOGGER.info("insert AppInfo {}", sqlException.getMessage()); - } - } - int[] results = ps.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwables) { - LOGGER.error("SQLException error: " + throwables.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * 根据该实例的父Id(对应的类对象hId),从数据库获取具体的实例信息 - * - * @param cId 父cd - * @param startTime 开始时间 - * @param endTime 结束时间 - * @return ArrayList - */ - public ArrayList getMemoryInstanceInfos(Integer cId, Long startTime, Long endTime) { - Connection conn = getConnection("MemoryInstanceInfo"); - PreparedStatement ps = null; - ArrayList memoryInstanceInfos = new ArrayList<>(); - try { - String sql = "select * from MemoryInstanceInfo where cId = ? and createTime >= ? and createTime <= ?"; - ps = conn.prepareStatement(sql); - ps.setInt(1, cId); - ps.setLong(SQL_INDEX_TWO, startTime); - ps.setLong(Option.SQL_INDEX_THREE, endTime); - - ResultSet rs = ps.executeQuery(); - MemoryInstanceInfo memoryInstanceInfo = null; - while (rs.next()) { - memoryInstanceInfo = new MemoryInstanceInfo(); - Integer id = rs.getInt("id"); - Integer instanceId = rs.getInt("instanceId"); - String instance = rs.getString("instance"); - Long allocTime = rs.getLong("allocTime"); - Long deallocTime = rs.getLong("deallocTime"); - Long createTime = rs.getLong("createTime"); - memoryInstanceInfo.setId(id); - memoryInstanceInfo.setInstanceId(instanceId); - memoryInstanceInfo.setcId(cId); - memoryInstanceInfo.setInstance(instance); - memoryInstanceInfo.setAllocTime(allocTime); - memoryInstanceInfo.setDeallocTime(deallocTime); - memoryInstanceInfo.setCreateTime(createTime); - memoryInstanceInfos.add(memoryInstanceInfo); - } - return memoryInstanceInfos; - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryInstanceInfos; - } - - /** - * 从数据库获取全部的实例信息 - * - * @return ArrayList - */ - public ArrayList getAllMemoryInstanceInfos() { - Connection conn = getConnection("MemoryInstanceInfo"); - PreparedStatement ps = null; - ArrayList memoryInstanceInfos = new ArrayList<>(); - try { - String sql = "select id,instanceId,cId,instance,createTime,allocTime,deallocTime from MemoryInstanceInfo"; - ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - MemoryInstanceInfo memoryInstanceInfo = null; - while (rs.next()) { - memoryInstanceInfo = new MemoryInstanceInfo(); - Integer id = rs.getInt("id"); - Integer instanceId = rs.getInt("instanceId"); - Integer cId = rs.getInt("cId"); - String instance = rs.getString("instance"); - Long allocTime = rs.getLong("allocTime"); - Long deallocTime = rs.getLong("deallocTime"); - Long createTime = rs.getLong("createTime"); - memoryInstanceInfo.setId(id); - memoryInstanceInfo.setInstanceId(instanceId); - memoryInstanceInfo.setcId(cId); - memoryInstanceInfo.setInstance(instance); - memoryInstanceInfo.setAllocTime(allocTime); - memoryInstanceInfo.setDeallocTime(deallocTime); - memoryInstanceInfo.setCreateTime(createTime); - memoryInstanceInfos.add(memoryInstanceInfo); - } - return memoryInstanceInfos; - } catch (SQLException throwAbles) { - LOGGER.error(throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryInstanceInfos; - } - - /** - * updateInstanceInfos - * - * @param timeStamp timeStamp - * @param instanceId instanceId - * @return boolean - */ - public boolean updateInstanceInfos(Long timeStamp, int instanceId) { - Connection conn = getConnection("MemoryInstanceInfo"); - String updateSql = "UPDATE MemoryInstanceInfo SET deallocTime = ? where instanceId = ?"; - PreparedStatement preparedStatement = null; - try { - preparedStatement = conn.prepareStatement(updateSql); - preparedStatement.setLong(1, timeStamp); - preparedStatement.setInt(SQL_INDEX_TWO, instanceId); - return preparedStatement.executeUpdate() == 1 ? true : false; - } catch (SQLException throwables) { - LOGGER.error("SQLException {}", throwables.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, preparedStatement, null); - } - return false; - } - - /** - * 删除一次场景下的堆信息数据 - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - StringBuffer deleteSql = new StringBuffer("DELETE FROM MemoryInstanceInfo"); - Connection connection = DataBaseApi.getInstance().getConnectByTable("MemoryInstanceInfo").get(); - return execute(connection, deleteSql.toString()); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.services.memory.agentbean.MemoryInstanceInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; + +/** + * instance data processing object + */ +public class MemoryInstanceDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(MemoryInstanceDao.class); + private static volatile MemoryInstanceDao singleton; + + /** + * get Instance + * + * @return MemoryInstanceDao + */ + public static MemoryInstanceDao getInstance() { + if (singleton == null) { + synchronized (MemoryInstanceDao.class) { + if (singleton == null) { + singleton = new MemoryInstanceDao(); + } + } + } + return singleton; + } + + /** + * MemoryInstanceDao + */ + public MemoryInstanceDao() { + createMemoryInstance(); + } + + /** + * get database connection + * + * @param tableName tableName + * @return Connection + */ + private Connection getConnection(String tableName) { + Optional optionalConnection = getConnectByTable(tableName); + Connection conn = null; + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + } + return conn; + } + + /** + * INSTANCE OBJECT TABLE CREATION + * + * @return boolean + */ + public boolean createMemoryInstance() { + String dbName = JVMTI_AGENT_PLUG; + String memoryInstanceInfoTable = "MemoryInstanceInfo"; + String sql = "CREATE TABLE MemoryInstanceInfo (instanceId int(100) not null, deallocTime int(100));"; + return createTable(dbName, memoryInstanceInfoTable, sql); + } + + /** + * Save the instance information obtained from the end-side in the database + * + * @param memoryUpdateInfo memoryUpdateInfo + */ + public void insertMemoryInstanceInfo(MemoryUpdateInfo memoryUpdateInfo) { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("MemoryInstanceInfo"); + String sql = "insert into MemoryInstanceInfo(instanceId,deallocTime) values (?,?)"; + ps = conn.prepareStatement(sql); + ps.setLong(1, memoryUpdateInfo.getInstanceId()); + ps.setLong(2, memoryUpdateInfo.getUpdateTime()); + ps.executeUpdate(); + } catch (SQLException throwAbles) { + LOGGER.error("SQLException error: " + throwAbles.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * insert MemoryInstanceInfos + * + * @param memoryUpdateInfos memoryInstanceInfos + * @return boolean + */ + public boolean insertMemoryInstanceInfos(List memoryUpdateInfos) { + if (memoryUpdateInfos.isEmpty()) { + return false; + } + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("MemoryInstanceInfo"); + conn.setAutoCommit(false); + String sql = "insert into MemoryInstanceInfo(instanceId,deallocTime) values (?,?)"; + ps = conn.prepareStatement(sql); + for (MemoryUpdateInfo memoryInstanceInfo : memoryUpdateInfos) { + try { + ps.setLong(1, memoryInstanceInfo.getInstanceId()); + ps.setLong(2, memoryInstanceInfo.getUpdateTime()); + ps.addBatch(); + } catch (SQLException sqlException) { + LOGGER.info("insert AppInfo {}", sqlException.getMessage()); + } + } + ps.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + ps.clearParameters(); + return true; + } catch (SQLException throwables) { + LOGGER.error("SQLException error: " + throwables.getMessage()); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * get MemoryInstanceInfos by cId + * + * @param cId cId + * @param startTime startTime + * @param endTime endTime + * @return ArrayList + */ + public ArrayList getMemoryInstanceInfos(Integer cId, Long startTime, Long endTime) { + Connection conn = getConnection("MemoryHeapInfo"); + PreparedStatement ps = null; + ArrayList memoryInstanceInfos = new ArrayList<>(); + try { + String sql = "select memory.instanceId," + "memory.createTime," + "memory.cid," + + "IFNULL( instance.deallocTime , 0 ) AS deallocTime" + " from MemoryHeapInfo as memory " + + "LEFT JOIN MemoryInstanceInfo AS instance " + + "ON instance.instanceId = memory.instanceId " + + "WHERE memory.cid = ? and ((createTime >= ? and createTime <= ?) or (deallocTime >= ? " + + "and deallocTime <= ?))"; + ps = conn.prepareStatement(sql); + ps.setInt(1, cId); + ps.setLong(2, startTime); + ps.setLong(3, endTime); + ps.setLong(4, startTime); + ps.setLong(5, endTime); + ResultSet rs = ps.executeQuery(); + MemoryInstanceInfo memoryInstanceInfo = null; + while (rs.next()) { + memoryInstanceInfo = new MemoryInstanceInfo(); + Integer instanceId = rs.getInt("instanceId"); + Long allocTime = rs.getLong("createTime"); + Long deallocTime = rs.getLong("deallocTime"); + memoryInstanceInfo.setInstanceId(instanceId); + memoryInstanceInfo.setcId(cId); + memoryInstanceInfo.setAllocTime(allocTime); + memoryInstanceInfo.setDeallocTime(deallocTime); + memoryInstanceInfo.setCreateTime(allocTime); + memoryInstanceInfos.add(memoryInstanceInfo); + } + ps.clearParameters(); + return memoryInstanceInfos; + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryInstanceInfos; + } + + /** + * get All Memory InstanceInfos + * + * @return ArrayList + */ + public ArrayList getAllMemoryInstanceInfos() { + Connection conn = getConnection("MemoryInstanceInfo"); + PreparedStatement ps = null; + ArrayList memoryInstanceInfos = new ArrayList<>(); + try { + String sql = "select instanceId,deallocTime from MemoryInstanceInfo"; + ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + MemoryUpdateInfo memoryInstanceInfo = null; + while (rs.next()) { + Integer instanceId = rs.getInt("instanceId"); + Long deallocTime = rs.getLong("deallocTime"); + memoryInstanceInfo = new MemoryUpdateInfo(instanceId, deallocTime); + memoryInstanceInfos.add(memoryInstanceInfo); + } + ps.clearParameters(); + return memoryInstanceInfos; + } catch (SQLException throwAbles) { + LOGGER.error(throwAbles.getMessage()); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryInstanceInfos; + } + + /** + * deleteSessionData + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM MemoryInstanceInfo"); + Optional connection = DataBaseApi.getInstance().getConnectByTable("MemoryInstanceInfo"); + if (connection.isPresent()) { + return execute(connection.get(), deleteSql.toString()); + } + return true; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsDao.java similarity index 74% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsDao.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsDao.java index 08b0d196b..5da941cda 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsDao.java @@ -1,266 +1,233 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; - -/** - * 实例详情数据处理对象 - * - * @version 1.0 - * @date 2021/03/30 18:50 - **/ -public class MemoryInstanceDetailsDao extends AbstractDataStore { - private static final Logger LOGGER = LogManager.getLogger(MemoryInstanceDetailsDao.class); - - private static volatile MemoryInstanceDetailsDao singleton; - - /** - * getInstance - * - * @return MemoryInstanceDetailsDao - */ - public static MemoryInstanceDetailsDao getInstance() { - if (singleton == null) { - synchronized (MemoryInstanceDetailsDao.class) { - if (singleton == null) { - singleton = new MemoryInstanceDetailsDao(); - } - } - } - return singleton; - } - - /** - * MemoryInstanceDetailsDao - */ - public MemoryInstanceDetailsDao() { - createMemoryInstanceDetails(); - } - - /** - * 获取数据库连接 - * - * @param tableName 表名 - * @return Connection - * @date 2021/03/30 18:49 - */ - private Connection getConnection(String tableName) { - Optional optionalConnection = getConnectByTable(tableName); - Connection conn = null; - if (optionalConnection.isPresent()) { - conn = optionalConnection.get(); - } - return conn; - } - - /** - * 具体实例对象信息详情表的创建 - * - * @return boolean - */ - public boolean createMemoryInstanceDetails() { - String dbName = JVMTI_AGENT_PLUG; - String memoryInstanceDetailsInfoTable = "MemoryInstanceDetailsInfo"; - String sql = "CREATE TABLE MemoryInstanceDetailsInfo " + "( " - + " id Integer primary key autoincrement not null, " - + " instanceId int(100) not null, " + " frameId int(100) not null, " - + " className varchar(200) not null, " + " methodName varchar(200) not null, " - + " fieldName varchar(200) not null, " + " lineNumber int(100) " + ");"; - return createTable(dbName, memoryInstanceDetailsInfoTable, sql); - } - - /** - * 将端侧获取的实例对象对应的调用栈信息保存在数据库 - * - * @param memoryInstanceDetailsInfo memoryInstanceDetailsInfo - */ - public void insertMemoryInstanceDetailsInfo(MemoryInstanceDetailsInfo memoryInstanceDetailsInfo) { - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("MemoryInstanceDetailsInfo"); - String sql = "insert into MemoryInstanceDetailsInfo(id,instanceId,frameId,className,methodName,fieldName," - + "lineNumber) values(null,?,?,?,?,?,?)"; - ps = conn.prepareStatement(sql); - ps.setInt(1, memoryInstanceDetailsInfo.getInstanceId()); - ps.setInt(Option.SQL_INDEX_TWO, memoryInstanceDetailsInfo.getFrameId()); - ps.setString(Option.SQL_INDEX_THREE, memoryInstanceDetailsInfo.getClassName()); - ps.setString(Option.SQL_INDEX_FOUR, memoryInstanceDetailsInfo.getMethodName()); - ps.setString(Option.SQL_INDEX_FIVE, memoryInstanceDetailsInfo.getFieldName()); - ps.setInt(Option.SQL_INDEX_SIX, memoryInstanceDetailsInfo.getLineNumber()); - ps.executeUpdate(); - } catch (SQLException throwAbles) { - LOGGER.error("insert Exception {}", throwAbles.getMessage()); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * insertMemoryInstanceDetailsInfo - * - * @param memoryInstanceDetailsInfos memoryInstanceDetailsInfos - * @return boolean - */ - public boolean insertMemoryInstanceDetailsInfo(List memoryInstanceDetailsInfos) { - if (memoryInstanceDetailsInfos.isEmpty()) { - return false; - } - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection("MemoryInstanceDetailsInfo"); - conn.setAutoCommit(false); - String sql = "insert into MemoryInstanceDetailsInfo(id,instanceId,frameId,className,methodName,fieldName," - + "lineNumber) values(null,?,?,?,?,?,?)"; - ps = conn.prepareStatement(sql); - for (MemoryInstanceDetailsInfo memoryInstanceDetailsInfo : memoryInstanceDetailsInfos) { - try { - ps.setInt(1, memoryInstanceDetailsInfo.getInstanceId()); - ps.setInt(Option.SQL_INDEX_TWO, memoryInstanceDetailsInfo.getFrameId()); - ps.setString(Option.SQL_INDEX_THREE, memoryInstanceDetailsInfo.getClassName()); - ps.setString(Option.SQL_INDEX_FOUR, memoryInstanceDetailsInfo.getMethodName()); - ps.setString(Option.SQL_INDEX_FIVE, memoryInstanceDetailsInfo.getFieldName()); - ps.setInt(Option.SQL_INDEX_SIX, memoryInstanceDetailsInfo.getLineNumber()); - ps.addBatch(); - } catch (SQLException sqlException) { - LOGGER.info("insert AppInfo {}", sqlException.getMessage()); - } - } - int[] results = ps.executeBatch(); - conn.commit(); - return true; - } catch (SQLException throwables) { - LOGGER.error("insert Exception {}", throwables.getMessage()); - return false; - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - } - - /** - * getMemoryInstanceDetails - * - * @param instanceId instanceId - * @return ArrayList - */ - public ArrayList getMemoryInstanceDetails(Integer instanceId) { - Connection conn = getConnection("MemoryInstanceDetailsInfo"); - PreparedStatement ps = null; - ArrayList memoryInstanceDetailsInfos = new ArrayList<>(); - try { - String sql = "select * from MemoryInstanceDetailsInfo where instanceId = ?"; - ps = conn.prepareStatement(sql); - ps.setInt(1, instanceId); - ResultSet rs = ps.executeQuery(); - MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = null; - while (rs.next()) { - memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - Integer id = rs.getInt("id"); - Integer frameId = rs.getInt("frameId"); - String className = rs.getString("className"); - String methodName = rs.getString("methodName"); - String fieldName = rs.getString("fieldName"); - Integer lineNumber = rs.getInt("lineNumber"); - memoryInstanceDetailsInfo.setId(id); - memoryInstanceDetailsInfo.setInstanceId(instanceId); - memoryInstanceDetailsInfo.setFrameId(frameId); - memoryInstanceDetailsInfo.setClassName(className); - memoryInstanceDetailsInfo.setMethodName(methodName); - memoryInstanceDetailsInfo.setFieldName(fieldName); - memoryInstanceDetailsInfo.setLineNumber(lineNumber); - memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); - } - return memoryInstanceDetailsInfos; - } catch (SQLException throwables) { - throwables.printStackTrace(); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryInstanceDetailsInfos; - } - - /** - * getAllMemoryInstanceDetails - * - * @return ArrayList - */ - public List getAllMemoryInstanceDetails() { - Connection conn = getConnection("MemoryInstanceDetailsInfo"); - PreparedStatement ps = null; - ArrayList memoryInstanceDetailsInfos = new ArrayList<>(); - try { - String sql = "select id,instanceId,frameId,className,methodName,fieldName," - + "lineNumber from MemoryInstanceDetailsInfo"; - ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = null; - while (rs.next()) { - memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - - Integer id = rs.getInt("id"); - Integer instanceId = rs.getInt("instanceId"); - Integer frameId = rs.getInt("frameId"); - String className = rs.getString("className"); - String methodName = rs.getString("methodName"); - String fieldName = rs.getString("fieldName"); - Integer lineNumber = rs.getInt("lineNumber"); - - memoryInstanceDetailsInfo.setId(id); - memoryInstanceDetailsInfo.setInstanceId(instanceId); - memoryInstanceDetailsInfo.setFrameId(frameId); - memoryInstanceDetailsInfo.setClassName(className); - memoryInstanceDetailsInfo.setMethodName(methodName); - memoryInstanceDetailsInfo.setFieldName(fieldName); - memoryInstanceDetailsInfo.setLineNumber(lineNumber); - memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); - } - return memoryInstanceDetailsInfos; - } catch (SQLException throwables) { - throwables.printStackTrace(); - } finally { - CloseResourceUtil.closeResource(LOGGER, conn, ps, null); - } - return memoryInstanceDetailsInfos; - } - - /** - * 删除一次场景下的堆信息数据 - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - StringBuffer deleteSql = new StringBuffer("DELETE FROM MemoryInstanceDetailsInfo"); - Connection connection = DataBaseApi.getInstance().getConnectByTable("MemoryInstanceDetailsInfo").get(); - return execute(connection, deleteSql.toString()); - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.utils.common.util.CloseResourceUtil; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; + +/** + * Memory InstanceDetailsDao + */ +public class MemoryInstanceDetailsDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(MemoryInstanceDetailsDao.class); + + private static volatile MemoryInstanceDetailsDao singleton; + + /** + * get Instance + * + * @return MemoryInstanceDetailsDao + */ + public static MemoryInstanceDetailsDao getInstance() { + if (singleton == null) { + synchronized (MemoryInstanceDetailsDao.class) { + if (singleton == null) { + singleton = new MemoryInstanceDetailsDao(); + } + } + } + return singleton; + } + + /** + * Memory InstanceDetails Dao + */ + public MemoryInstanceDetailsDao() { + createMemoryInstanceDetails(); + } + + /** + * get database connection + * + * @param tableName TableName + * @return Connection + */ + private Connection getConnection(String tableName) { + Optional optionalConnection = getConnectByTable(tableName); + Connection conn = null; + if (optionalConnection.isPresent()) { + conn = optionalConnection.get(); + } + return conn; + } + + /** + * Creation of a detailed table of object information for specific instances + * + * @return boolean + */ + public boolean createMemoryInstanceDetails() { + String dbName = JVMTI_AGENT_PLUG; + String memoryInstanceDetailsInfoTable = "MemoryInstanceDetailsInfo"; + String sql = "CREATE TABLE MemoryInstanceDetailsInfo " + "( " + + " instanceId int(100) not null, " + " frameId int(100) not null, " + + " className varchar(200) not null, " + " methodName varchar(200) not null, " + + " fieldName varchar(200) not null, " + " lineNumber int(100) " + ");"; + return createTable(dbName, memoryInstanceDetailsInfoTable, sql); + } + + /** + * insert MemoryInstanceDetailsInfo + * + * @param memoryInstanceDetailsInfos memoryInstanceDetailsInfos + * @return boolean + */ + public boolean insertMemoryInstanceDetailsInfo(List memoryInstanceDetailsInfos) { + if (memoryInstanceDetailsInfos.isEmpty()) { + return false; + } + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection("MemoryInstanceDetailsInfo"); + conn.setAutoCommit(false); + String sql = "insert into MemoryInstanceDetailsInfo(instanceId,frameId,className,methodName,fieldName," + + "lineNumber) values(?,?,?,?,?,?)"; + ps = conn.prepareStatement(sql); + for (MemoryInstanceDetailsInfo memoryInstanceDetailsInfo : memoryInstanceDetailsInfos) { + try { + ps.setInt(1, memoryInstanceDetailsInfo.getInstanceId()); + ps.setInt(2, memoryInstanceDetailsInfo.getFrameId()); + ps.setString(3, memoryInstanceDetailsInfo.getClassName()); + ps.setString(4, memoryInstanceDetailsInfo.getMethodName()); + ps.setString(5, memoryInstanceDetailsInfo.getFieldName()); + ps.setInt(6, memoryInstanceDetailsInfo.getLineNumber()); + ps.addBatch(); + } catch (SQLException sqlException) { + LOGGER.info("insert AppInfo {}", sqlException.getMessage()); + } + } + ps.executeBatch(); + conn.commit(); + conn.setAutoCommit(true); + ps.clearParameters(); + return true; + } catch (SQLException throwables) { + LOGGER.error("insert Exception {}", throwables.getMessage()); + return false; + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + } + + /** + * get MemoryInstanceDetails + * + * @param instanceId instanceId + * @return ArrayList + */ + public ArrayList getMemoryInstanceDetails(Integer instanceId) { + Connection conn = getConnection("MemoryInstanceDetailsInfo"); + PreparedStatement ps = null; + ArrayList memoryInstanceDetailsInfos = new ArrayList<>(); + try { + String sql = "select * from MemoryInstanceDetailsInfo where instanceId = ?"; + ps = conn.prepareStatement(sql); + ps.setInt(1, instanceId); + ResultSet rs = ps.executeQuery(); + MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = null; + while (rs.next()) { + memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); + Integer frameId = rs.getInt("frameId"); + String className = rs.getString("className"); + String methodName = rs.getString("methodName"); + String fieldName = rs.getString("fieldName"); + Integer lineNumber = rs.getInt("lineNumber"); + memoryInstanceDetailsInfo.setInstanceId(instanceId); + memoryInstanceDetailsInfo.setFrameId(frameId); + memoryInstanceDetailsInfo.setClassName(className); + memoryInstanceDetailsInfo.setMethodName(methodName); + memoryInstanceDetailsInfo.setFieldName(fieldName); + memoryInstanceDetailsInfo.setLineNumber(lineNumber); + memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); + } + ps.clearParameters(); + return memoryInstanceDetailsInfos; + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryInstanceDetailsInfos; + } + + /** + * get All MemoryInstanceDetails + * + * @return ArrayList + */ + public List getAllMemoryInstanceDetails() { + Connection conn = getConnection("MemoryInstanceDetailsInfo"); + PreparedStatement ps = null; + ArrayList memoryInstanceDetailsInfos = new ArrayList<>(); + try { + String sql = "select instanceId,frameId,className,methodName,fieldName," + + "lineNumber from MemoryInstanceDetailsInfo"; + ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + MemoryInstanceDetailsInfo memoryInstanceDetailsInfo = null; + while (rs.next()) { + memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); + Integer instanceId = rs.getInt("instanceId"); + Integer frameId = rs.getInt("frameId"); + String className = rs.getString("className"); + String methodName = rs.getString("methodName"); + String fieldName = rs.getString("fieldName"); + Integer lineNumber = rs.getInt("lineNumber"); + memoryInstanceDetailsInfo.setInstanceId(instanceId); + memoryInstanceDetailsInfo.setFrameId(frameId); + memoryInstanceDetailsInfo.setClassName(className); + memoryInstanceDetailsInfo.setMethodName(methodName); + memoryInstanceDetailsInfo.setFieldName(fieldName); + memoryInstanceDetailsInfo.setLineNumber(lineNumber); + memoryInstanceDetailsInfos.add(memoryInstanceDetailsInfo); + } + ps.clearParameters(); + return memoryInstanceDetailsInfos; + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + CloseResourceUtil.closeResource(LOGGER, conn, ps, null); + } + return memoryInstanceDetailsInfos; + } + + /** + * delete SessionData by sessionId + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM MemoryInstanceDetailsInfo"); + Connection connection = DataBaseApi.getInstance().getConnectByTable("MemoryInstanceDetailsInfo").get(); + return execute(connection, deleteSql.toString()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsManager.java similarity index 60% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsManager.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsManager.java index 448f6d73f..59eecb074 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceDetailsManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceDetailsManager.java @@ -1,58 +1,47 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Instance对应的调用栈信息处理对象 - * - * @version 1.0 - * @date 2021/03/31 21:07 - **/ -public class MemoryInstanceDetailsManager { - private final MemoryInstanceDetailsDao memoryInstanceDetailsDao = MemoryInstanceDetailsDao.getInstance(); - - /** - * 根据instanceId在数据库中查到instance对应的调用信息,提供给UI的查询接口 - * - * @param instanceId 实例Id - * @return ArrayList - */ - public ArrayList getMemoryInstanceDetailsInfos(Integer instanceId) { - return memoryInstanceDetailsDao.getMemoryInstanceDetails(instanceId); - } - - /** - * insertMemoryInstanceDetailsInfo - * - * @param memoryInstanceDetailsInfo memoryInstanceDetailsInfo - */ - public void insertMemoryInstanceDetailsInfo(MemoryInstanceDetailsInfo memoryInstanceDetailsInfo) { - memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(memoryInstanceDetailsInfo); - } - - /** - * 根据instanceId在数据库中查到instance对应的调用信息 - * - * @return ArrayList - */ - public List getAllMemoryInstanceDetails() { - return memoryInstanceDetailsDao.getAllMemoryInstanceDetails(); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; + +import java.util.ArrayList; +import java.util.List; + +/** + * MemoryInstanceDetailsManager + */ +public class MemoryInstanceDetailsManager { + private final MemoryInstanceDetailsDao memoryInstanceDetailsDao = MemoryInstanceDetailsDao.getInstance(); + + /** + * get MemoryInstanceDetailsInfos + * + * @param instanceId instance Id + * @return ArrayList + */ + public ArrayList getMemoryInstanceDetailsInfos(Integer instanceId) { + return memoryInstanceDetailsDao.getMemoryInstanceDetails(instanceId); + } + + /** + * get All MemoryInstanceDetails + * + * @return List + */ + public List getAllMemoryInstanceDetails() { + return memoryInstanceDetailsDao.getAllMemoryInstanceDetails(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceManager.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceManager.java similarity index 57% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceManager.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceManager.java index 582800174..ae46d3690 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryInstanceManager.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryInstanceManager.java @@ -1,59 +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. - */ - -package ohos.devtools.services.memory; - -import java.util.ArrayList; - -/** - * 实例对象业务处理类 - * - * @version 1.0 - * @date 2021/03/31 19:44 - **/ -public class MemoryInstanceManager { - /** - * 根据类的Id在数据库中查到相应的instance信息,提供给UI的查询接口 - * - * @param cId 父Id - * @param startTime 开始时间 - * @param endTime 结束时间 - * @return ArrayList - */ - public ArrayList getMemoryInstanceInfos(Integer cId, Long startTime, Long endTime) { - MemoryInstanceDao memoryInstanceDao = MemoryInstanceDao.getInstance(); - return memoryInstanceDao.getMemoryInstanceInfos(cId, startTime, endTime); - } - - /** - * insertMemoryInstanceInfo - * - * @param memoryInstanceInfo memoryInstanceInfo - */ - public void insertMemoryInstanceInfo(MemoryInstanceInfo memoryInstanceInfo) { - MemoryInstanceDao memoryInstanceDao = MemoryInstanceDao.getInstance(); - memoryInstanceDao.insertMemoryInstanceInfo(memoryInstanceInfo); - } - - /** - * 根据类的查instance信息 - * - * @return ArrayList - */ - public ArrayList getAllMemoryInstanceInfos() { - MemoryInstanceDao memoryInstanceDao = MemoryInstanceDao.getInstance(); - return memoryInstanceDao.getAllMemoryInstanceInfos(); - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.agentdao; + +import ohos.devtools.services.memory.agentbean.MemoryInstanceInfo; + +import java.util.ArrayList; + +/** + * Memory InstanceManager + */ +public class MemoryInstanceManager { + /** + * get MemoryInstanceInfos + * + * @param cId parent Id + * @param startTime start time + * @param endTime end time + * @return ArrayList + */ + public ArrayList getMemoryInstanceInfos(Integer cId, Long startTime, Long endTime) { + MemoryInstanceDao memoryInstanceDao = MemoryInstanceDao.getInstance(); + return memoryInstanceDao.getMemoryInstanceInfos(cId, startTime, endTime); + } + + /** + * get All MemoryInstanceInfos + * + * @return ArrayList + */ + public ArrayList getAllMemoryInstanceInfos() { + MemoryInstanceDao memoryInstanceDao = MemoryInstanceDao.getInstance(); + return memoryInstanceDao.getAllMemoryInstanceInfos(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryUpdateInfo.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryUpdateInfo.java new file mode 100644 index 000000000..a5f264b91 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/agentdao/MemoryUpdateInfo.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.services.memory.agentdao; + +import java.io.Serializable; + +/** + * MemoryUpdateInfo + */ +public class MemoryUpdateInfo implements Serializable { + private static final long serialVersionUID = 1679168310864454754L; + private long updateTime; + private long instanceId; + + /** + * MemoryUpdateInfo + * + * @param updateTime updateTime + * @param instanceId instanceId + */ + public MemoryUpdateInfo(long updateTime, long instanceId) { + this.updateTime = updateTime; + this.instanceId = instanceId; + } + + /** + * get UpdateTime + * + * @return updateTime + */ + public long getUpdateTime() { + return updateTime; + } + + /** + * set UpdateTime + * + * @param updateTime updateTime + */ + public void setUpdateTime(long updateTime) { + this.updateTime = updateTime; + } + + /** + * get InstanceId + * + * @return instanceId + */ + public long getInstanceId() { + return instanceId; + } + + /** + * set InstanceId + * + * @param instanceId instanceId + */ + public void setInstanceId(long instanceId) { + this.instanceId = instanceId; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java new file mode 100644 index 000000000..627d5b857 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java @@ -0,0 +1,273 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory.memorydao; + +import com.google.protobuf.InvalidProtocolBufferException; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.utils.datahandler.datapoller.MemoryDataConsumer; +import ohos.devtools.views.charts.model.ChartDataModel; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_AFTER_TAIL; +import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_ALL_APP_MEM_INFO; +import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_APP_MEM_INFO; +import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_BEFORE_HEAD; + +/** + * memory And Database Interaction Class + */ +public class MemoryDao extends AbstractDataStore { + private static final Logger LOGGER = LogManager.getLogger(MemoryDao.class); + + private static volatile MemoryDao singleton; + + /** + * get Instance + * + * @return MemoryDao + */ + public static MemoryDao getInstance() { + if (singleton == null) { + synchronized (MemoryDao.class) { + if (singleton == null) { + singleton = new MemoryDao(); + } + } + } + return singleton; + } + + private Map memorySelectMap = new HashMap<>(); + + /** + * Memory Select Statements + */ + public enum MemorySelectStatements { + SELECT_APP_MEM_INFO( + "SELECT timeStamp, Data from processMemInfo where session = ? and timeStamp > ? and timeStamp < ?"), + + SELECT_ALL_APP_MEM_INFO("SELECT timeStamp, Data from processMemInfo where session = ?"), + + DELETE_APP_MEM_INFO("delete from processMemInfo where session = ?"), + + SELECT_BEFORE_HEAD("SELECT timeStamp, Data from processMemInfo where session =" + + " ? and timeStamp < ? order by timeStamp desc limit 1"), + + SELECT_AFTER_TAIL("SELECT timeStamp, Data from processMemInfo where session =" + + " ? and timeStamp > ? order by timeStamp asc limit 1"); + + private final String sqlStatement; + + MemorySelectStatements(String sqlStatement) { + this.sqlStatement = sqlStatement; + } + + /** + * get Statement + * + * @return String + */ + public String getStatement() { + return sqlStatement; + } + } + + private Connection conn; + + private MemoryDao() { + if (conn == null) { + Optional connection = getConnectBydbName("memory"); + if (connection.isPresent()) { + conn = connection.get(); + } + createPrePareStatements(); + } + } + + private void createPrePareStatements() { + MemorySelectStatements[] values = MemorySelectStatements.values(); + for (MemorySelectStatements sta : values) { + PreparedStatement psmt = null; + try { + psmt = conn.prepareStatement(sta.getStatement()); + memorySelectMap.put(sta, psmt); + } catch (SQLException throwAbles) { + LOGGER.error(" SQLException {}", throwAbles.getMessage()); + } + } + } + + /** + * get AllData + * + * @param sessionId sessionId + * @return List + */ + public List getAllData(long sessionId) { + PreparedStatement pst = memorySelectMap.get(SELECT_ALL_APP_MEM_INFO); + List result = new ArrayList<>(); + try { + if (pst != null) { + pst.setLong(1, sessionId); + ResultSet rs = pst.executeQuery(); + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + ProcessMemInfo processMem = new ProcessMemInfo(); + MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); + MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); + processMem.setTimeStamp(timeStamp); + processMem.setData(appSummary); + processMem.setSession(sessionId); + result.add(processMem); + } + } + } catch (SQLException | InvalidProtocolBufferException throwables) { + LOGGER.error(" SQLException {}", throwables.getMessage()); + } + return result; + } + + /** + * get Data + * + * @param sessionId sessionId + * @param min min + * @param max max + * @param startTimeStamp startTimeStamp + * @param isNeedHeadTail isNeedHeadTail + * @return LinkedHashMap > + */ + public LinkedHashMap> getData(long sessionId, int min, int max, long startTimeStamp, + boolean isNeedHeadTail) { + PreparedStatement pst = memorySelectMap.get(SELECT_APP_MEM_INFO); + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail && min > 0) { + result.putAll(getTargetData(sessionId, min, startTimeStamp, true)); + } + try { + pst.setLong(1, sessionId); + pst.setLong(2, startTimeStamp + min); + pst.setLong(3, startTimeStamp + max); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); + MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTimeStamp), MemoryDataConsumer.processAppSummary(appSummary)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + throwAbles.printStackTrace(); + } + + // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 + if (isNeedHeadTail) { + result.putAll(getTargetData(sessionId, max, startTimeStamp, false)); + } + return result; + } + + /** + * Get the data before head or after tail + * + * @param sessionId Session id + * @param offset time offset + * @param startTs start/first timestamp + * @param beforeHead true: before head, false: after tail + * @return LinkedHashMap > + */ + private LinkedHashMap> getTargetData(long sessionId, int offset, long startTs, + boolean beforeHead) { + PreparedStatement pst; + if (beforeHead) { + pst = memorySelectMap.get(SELECT_BEFORE_HEAD); + } else { + pst = memorySelectMap.get(SELECT_AFTER_TAIL); + } + LinkedHashMap> result = new LinkedHashMap<>(); + if (pst == null) { + return result; + } + + try { + pst.setLong(1, sessionId); + pst.setLong(2, offset + startTs); + ResultSet rs = pst.executeQuery(); + if (rs != null) { + while (rs.next()) { + long timeStamp = rs.getLong("timeStamp"); + byte[] data = rs.getBytes("Data"); + if (data == null) { + continue; + } + MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); + MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); + result.put((int) (timeStamp - startTs), MemoryDataConsumer.processAppSummary(appSummary)); + } + } + } catch (SQLException | InvalidProtocolBufferException throwAbles) { + LOGGER.error(" SQLException {}", throwAbles.getMessage()); + } + return result; + } + + /** + * delete SessionData by sessionId + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + StringBuffer deleteSql = new StringBuffer("DELETE FROM "); + deleteSql.append("processMemInfo").append(" WHERE session = ").append(sessionId); + Optional processMemInfo = DataBaseApi.getInstance().getConnectByTable("processMemInfo"); + Connection connection = null; + if (processMemInfo.isPresent()) { + connection = processMemInfo.get(); + } else { + return false; + } + return execute(connection, deleteSql.toString()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryDataCache.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryDataCache.java new file mode 100644 index 000000000..05608d885 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryDataCache.java @@ -0,0 +1,180 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory.memoryservice; + +import ohos.devtools.services.CacheMap; +import ohos.devtools.views.charts.model.ChartDataModel; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; + +/** + * Memory data cache + */ +public class MemoryDataCache { + /** + * Map default load factor + */ + private static final float LOAD_FACTOR = 0.75F; + + /** + * Cache max size + * + * @see "Cache about 40 seconds of data" + */ + private static final int CACHE_MAX_SIZE = 1500; + + /** + * Singleton + */ + private static MemoryDataCache instance; + + /** + * Map of memory data saved + * + * @see "Map>>" + */ + private final Map>> dataCacheMap = new ConcurrentHashMap<>(); + + /** + * Map of first data timestamp saved + * + * @see "Map" + */ + private final Map firstTsMap = new HashMap<>(); + + /** + * Private constructor + */ + private MemoryDataCache() { + } + + /** + * Instance getter + * + * @return MemoryDataCache + */ + public static MemoryDataCache getInstance() { + if (instance == null) { + instance = new MemoryDataCache(); + } + return instance; + } + + /** + * Add memory data to cache map + * + * @param sessionId Session id + * @param timestamp Timestamp of data + * @param dataModels Data model list + */ + public void addDataModel(long sessionId, long timestamp, List dataModels) { + CacheMap> cache = dataCacheMap.get(sessionId); + // If cache map is null, generate the new map and save the current timestamp as first timestamp + if (cache == null) { + cache = genNewSessionCache(); + dataCacheMap.put(sessionId, cache); + firstTsMap.put(sessionId, timestamp); + } + synchronized (dataCacheMap.get(sessionId)) { + // Save relative time + int time = (int) (timestamp - firstTsMap.get(sessionId)); + cache.put(time, dataModels); + // Here we need to sort the map, otherwise the key(timestamp) of the map will be out of order + CacheMap> sorted = + cache.entrySet().stream().sorted(Map.Entry.comparingByKey()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (paramX, paramY) -> paramX, + CacheMap::new)); + dataCacheMap.put(sessionId, sorted); + } + } + + /** + * Generate new session cache map + * + * @return CacheMap > + */ + private CacheMap> genNewSessionCache() { + return new CacheMap(); + } + + /** + * Get memory data + * + * @param sessionId Session id + * @param startTime start time + * @param endTime end time + * @return LinkedHashMap > + */ + public LinkedHashMap> getData(long sessionId, int startTime, int endTime) { + LinkedHashMap> result = new LinkedHashMap<>(); + int timeBeforeStart = INITIAL_VALUE; + LinkedHashMap> cache = dataCacheMap.get(sessionId); + if (cache == null) { + return result; + } + synchronized (dataCacheMap.get(sessionId)) { + Set>> entries = cache.entrySet(); + for (Map.Entry> entry : entries) { + int time = entry.getKey(); + // Get the previous time of startTime + if (time < startTime) { + timeBeforeStart = time; + continue; + } + + // Save the previous time and data of startTime, fill the chart blank and solve the boundary flicker + if (!result.containsKey(timeBeforeStart) && timeBeforeStart != INITIAL_VALUE) { + // Save time, do not save value. Otherwise, it will cause concurrent exception + result.put(timeBeforeStart, null); + } + + if (time <= endTime) { + // Data saved between startTime and endTime + result.put(time, entry.getValue()); + } else { + // Save the next time and data of endTime, fill the chart blank and solve the boundary flicker + result.put(time, entry.getValue()); + // Then break the loop + break; + } + } + } + + // Save the value of timeBeforeStart now + if (timeBeforeStart != INITIAL_VALUE) { + result.put(timeBeforeStart, cache.get(timeBeforeStart)); + } + return result; + } + + /** + * Clear cache by session id when the session was deleted + * + * @param sessionId Session id + */ + public void clearCacheBySession(long sessionId) { + dataCacheMap.remove(sessionId); + firstTsMap.remove(sessionId); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryService.java similarity index 53% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryService.java rename to host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryService.java index 1c52307df..0dbe39abc 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/MemoryService.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memoryservice/MemoryService.java @@ -1,103 +1,71 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.LinkedHashMap; -import java.util.List; - -/** - * @Description Memory业务处理类 - * @Date 2021/2/7 13:47 - **/ -public class MemoryService { - private static final Logger LOGGER = LogManager.getLogger(MemoryService.class); - - private static MemoryService instance; - - /** - * MemoryService - * - * @return MemoryService - */ - public static MemoryService getInstance() { - if (instance == null) { - synchronized (MemoryService.class) { - if (instance == null) { - instance = new MemoryService(); - } - } - } - return instance; - } - - private LinkedHashMap memordata; - - private MemoryService() { - } - - /** - * 添加数据 - * - * @param sessionId sessionId - * @param min min - * @param max max - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - */ - public void addData(long sessionId, int min, int max, long firstTimestamp) { - memordata = MemoryDao.getInstance().getData(sessionId, min, max, firstTimestamp, false); - ChartDataCache.getInstance().addCacheBlock(String.valueOf(sessionId), memordata); - } - - /** - * 获取数据 - * - * @param sessionId sessionId - * @param min min - * @param max max - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @return LinkedHashMap - */ - public LinkedHashMap getData(long sessionId, int min, int max, - long firstTimestamp) { - return MemoryDao.getInstance().getData(sessionId, min, max, firstTimestamp, false); - } - - /** - * 获取所有数据 - * - * @param sessionId sessionId - * @return List - */ - public List getAllData(long sessionId) { - List listData = MemoryDao.getInstance().getAllData(sessionId); - return listData; - } - - /** - * deleteSessionData - * - * @param sessionId sessionId - * @return boolean - */ - public boolean deleteSessionData(long sessionId) { - return MemoryDao.getInstance().deleteSessionData(sessionId); - } -} +/* + * 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. + */ + +package ohos.devtools.services.memory.memoryservice; + +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.services.memory.memorydao.MemoryDao; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +/** + * Memory业务处理类 + */ +public class MemoryService { + private static final Logger LOGGER = LogManager.getLogger(MemoryService.class); + + private static MemoryService instance; + + /** + * MemoryService + * + * @return MemoryService + */ + public static MemoryService getInstance() { + if (instance == null) { + synchronized (MemoryService.class) { + if (instance == null) { + instance = new MemoryService(); + } + } + } + return instance; + } + + private MemoryService() { + } + + /** + * get All Data + * + * @param sessionId sessionId + * @return List + */ + public List getAllData(long sessionId) { + return MemoryDao.getInstance().getAllData(sessionId); + } + + /** + * deleteSessionData + * + * @param sessionId sessionId + * @return boolean + */ + public boolean deleteSessionData(long sessionId) { + return MemoryDao.getInstance().deleteSessionData(sessionId); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkDao.java deleted file mode 100644 index 0570d0eff..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkDao.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.network; - -/** - * @Description Network与数据库交互类 - * @Date 2021/2/7 14:10 - **/ -public class NetworkDao { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkService.java deleted file mode 100644 index e81904e92..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/network/NetworkService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.network; - -/** - * @Description Network业务处理类 - * @Date 2021/2/7 13:48 - **/ -public class NetworkService { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerDao.java deleted file mode 100644 index 58e4d69a4..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerDao.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.power; - -/** - * @Description Power与数据库交互类 - * @Date 2021/2/7 14:11 - **/ -public class PowerDao { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerService.java b/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerService.java deleted file mode 100644 index 9b8593685..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/power/PowerService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.power; - -/** - * @Description Power业务处理类 - * @Date 2021/2/7 13:49 - **/ -public class PowerService { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AllData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AllData.java new file mode 100644 index 000000000..d11aae3e7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AllData.java @@ -0,0 +1,475 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace; + +import ohos.devtools.views.applicationtrace.bean.AppFunc; +import ohos.devtools.views.applicationtrace.bean.Cpu; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.applicationtrace.bean.Thread; +import ohos.devtools.views.applicationtrace.bean.TreeTableBean; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.bean.Process; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeNode; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.groupingBy; + +/** + * app data + * + * @date: 2021/5/20 18:00 + */ +public class AllData { + /** + * cpu data map + */ + public static Map> cpuMap = new HashMap<>(); + + /** + * thread data map + */ + public static Map> threadMap = new HashMap<>(); + + /** + * function data map + */ + public static Map> funcMap = new HashMap<>(); + + /** + * function names map + */ + public static Map threadNames = new HashMap<>(); + + /** + * list of process data + */ + public static List processes = new ArrayList<>(); + + /** + * get right TopDown tree by time range + * + * @param startNS startNS + * @param endNS endNS + * @return List + */ + public static List getFuncTreeTopDown(long startNS, long endNS) { + if (Objects.isNull(funcMap)) { + return new ArrayList<>(); + } + if (Objects.isNull(threadMap)) { + return new ArrayList<>(); + } + return getFuncTreeTopDown(startNS, endNS, null); + } + + /** + * get right TopDown tree by time range and selected thread + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + * @return List + */ + public static List getFuncTreeTopDown(long startNS, long endNS, List threadIds) { + if (Objects.isNull(funcMap)) { + return new ArrayList<>(); + } + if (Objects.isNull(threadMap)) { + return new ArrayList<>(); + } + Map> collect = funcMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> new ArrayList<>(entry.getValue()))); + return DataProcess.getFuncTreeTopDown(collect, startNS, endNS, threadIds); + } + + /** + * get right BottomUp tree by time range + * + * @param startNS startNS + * @param endNS endNS + * @return List tree node List + */ + public static List getFuncTreeBottomUp(long startNS, long endNS) { + return getFuncTreeBottomUp(startNS, endNS, null); + } + + /** + * get right BottomUp tree by time range and thread + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + * @return List tree node List + */ + public static List getFuncTreeBottomUp(long startNS, long endNS, List threadIds) { + Map> collect = funcMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> new ArrayList<>(entry.getValue()))); + return DataProcess.getFuncTreeBottomUp(collect, startNS, endNS, threadIds); + } + + /** + * get right TopDown tree by selected func + * + * @param func func + * @return List tree node List + */ + public static List getFuncTreeByFuncTopDown(Func func) { + List collect = funcMap.get(func.getTid()).stream().filter( + item -> TimeUtils.isRangeCross(func.getStartTs(), func.getEndTs(), item.getStartTs(), item.getEndTs()) + && item.getDepth() > func.getDepth()).collect(Collectors.toList()); + Map longTreeTableBeanMap = funcGroupByStackId(func, collect, null); + List treeTableBeans = setNumForNodes(longTreeTableBeanMap); + TreeTableBean treeTableBean = new TreeTableBean(); + treeTableBean.setName(func.getFuncName()); + long totalUs = TimeUnit.NANOSECONDS.toMicros(func.getDur()); + treeTableBean.setThreadDur(totalUs); + treeTableBean.setTotalNum(totalUs); + long threadFuncDuration = TimeUnit.NANOSECONDS.toMicros( + collect.stream().filter(item -> item.getDepth() == func.getDepth() + 1).mapToLong(Func::getDur).sum()); + treeTableBean.setChildrenNS(func.getDur()); + treeTableBean.setChildrenNum(threadFuncDuration); + treeTableBean.setSelfNum(totalUs - threadFuncDuration); + DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(treeTableBean); + Map treeNodeMap = + treeTableBeans.stream().collect(Collectors.toMap(TreeTableBean::getStackId, DefaultMutableTreeNode::new)); + treeTableBeans.forEach(listBean -> { + if (listBean.getParentStackId() == func.getStackId()) { + rootNode.add(treeNodeMap.get(listBean.getStackId())); + } else { + if (treeNodeMap.containsKey(listBean.getParentStackId())) { + treeNodeMap.get(listBean.getParentStackId()).add(treeNodeMap.get(listBean.getStackId())); + } + } + }); + ArrayList defaultMutableTreeNodes = new ArrayList<>(); + defaultMutableTreeNodes.add(rootNode); + return defaultMutableTreeNodes; + } + + /** + * get right BottomUp tree by selected func + * + * @param func func + * @return List + */ + public static List getFuncTreeByFuncBottomUp(Func func) { + ArrayList nodes = new ArrayList<>(); + List collect = funcMap.get(func.getTid()).stream().filter( + item -> TimeUtils.isRangeCross(func.getStartTs(), func.getEndTs(), item.getStartTs(), item.getEndTs())) + .collect(Collectors.toList()); + Map> nameToId = new HashMap<>(); + Map treeNodeMap = funcGroupByStackId(func, collect, nameToId); + setNumForNodes(treeNodeMap); + nameToId.forEach((name, ids) -> { + TreeTableBean treeTableBean = new TreeTableBean(TimeUnit.NANOSECONDS.toMicros(func.getDur())); + treeTableBean.setName(name); + long totalNum = 0; + long childrenNum = 0; + long selfNum = 0; + for (Long id : ids) { + TreeTableBean tableBean = treeNodeMap.get(id); + totalNum += tableBean.getTotalNum(); + childrenNum += tableBean.getChildrenNum(); + selfNum += tableBean.getSelfNum(); + } + treeTableBean.setTotalNum(totalNum); + treeTableBean.setSelfNum(selfNum); + treeTableBean.setChildrenNum(childrenNum); + DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(treeTableBean); + ids.forEach( + id -> recursionNode(rootNode, treeNodeMap.get(id).getParentStackId(), threadNames.get(func.getTid()), + treeNodeMap, id)); + if (ids.stream().noneMatch(id -> + collect.stream().filter(item -> item.getStackId() == id && item.getDepth() < func.getDepth()) + .toArray().length > 0)) { + nodes.add(rootNode); + } + }); + return nodes; + } + + private static Map funcGroupByStackId(Func func, List collect, + Map> nameToId) { + long totalUs = TimeUnit.NANOSECONDS.toMicros(func.getDur()); + Map map = collect.stream().collect(groupingBy(Func::getStackId)).entrySet().stream() + .collect(Collectors.toMap(entry -> entry.getKey(), entry -> { + TreeTableBean uniteBean = new TreeTableBean(totalUs); + uniteBean.setStackId(entry.getKey()); + if (entry.getValue().size() > 0) { + uniteBean.setName(entry.getValue().get(0).getFuncName()); + uniteBean.setParentStackId(entry.getValue().get(0).getParentStackId()); + if (nameToId != null) { + if (nameToId.containsKey(entry.getValue().get(0).getFuncName())) { + nameToId.get(entry.getValue().get(0).getFuncName()) + .add(entry.getValue().get(0).getStackId()); + } else { + List ids = new ArrayList<>(); + ids.add(entry.getValue().get(0).getStackId()); + nameToId.put(entry.getValue().get(0).getFuncName(), ids); + } + } + } + long childrenTotal = entry.getValue().stream().mapToLong(mapper -> TimeUtils + .getIntersection(func.getStartTs(), func.getEndTs(), mapper.getStartTs(), mapper.getEndTs())).sum(); + uniteBean.setTotalNum(childrenTotal); + uniteBean.setChildrenNS(entry.getValue().stream().mapToLong(mapper -> TimeUtils + .getNanoIntersection(func.getStartTs(), func.getEndTs(), + mapper.getStartTs(), mapper.getEndTs())) + .sum()); + return uniteBean; + })); + return map; + } + + private static Map funcGroupByStackId(long startNS, long endNS, List list, + Map> nameToId) { + long dur = endNS - startNS; + Map map = + list.stream().filter(func -> func.getEndTs() > startNS && func.getStartTs() < endNS) + .collect(groupingBy(Func::getStackId)).entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, a1 -> { + TreeTableBean uniteBean = new TreeTableBean(dur); + uniteBean.setThreadDur(dur); + uniteBean.setStackId(a1.getKey()); + if (a1.getValue().size() > 0) { + uniteBean.setName(a1.getValue().get(0).getFuncName()); + uniteBean.setParentStackId(a1.getValue().get(0).getParentStackId()); + if (nameToId != null) { + if (nameToId.containsKey(a1.getValue().get(0).getFuncName())) { + nameToId.get(a1.getValue().get(0).getFuncName()).add(a1.getValue().get(0).getStackId()); + } else { + ArrayList ids = new ArrayList<>(); + ids.add(a1.getValue().get(0).getStackId()); + nameToId.put(a1.getValue().get(0).getFuncName(), ids); + } + } + } + long childrenTotal = a1.getValue().stream().mapToLong(mapper -> TimeUtils + .getIntersection(startNS, endNS, mapper.getStartTs(), + mapper.getStartTs() + mapper.getDur())) + .sum(); + uniteBean.setTotalNum(childrenTotal); + uniteBean.setChildrenNS(a1.getValue().stream().mapToLong(mapper -> TimeUtils + .getNanoIntersection(startNS, endNS, mapper.getStartTs(), + mapper.getStartTs() + mapper.getDur())).sum()); + return uniteBean; + })); + return map; + } + + /** + * set nodes data + * + * @param map map + * @return List set node userObject + */ + public static List setNumForNodes(Map map) { // Set up presentation data + List treeNodes = new ArrayList<>(map.values()); // Sort the array + for (TreeTableBean ts : treeNodes) { // Loop set children and total data + ts.setSelfNum(ts.getTotalNum() - ts.getChildrenNum()); + if (map.containsKey(ts.getParentStackId())) { + TreeTableBean mapUserObject = map.get(ts.getParentStackId()); + mapUserObject.setChildrenNum(mapUserObject.getChildrenNum() + ts.getTotalNum()); + mapUserObject.setSelfNum(mapUserObject.getTotalNum() - mapUserObject.getChildrenNum()); + } + } + return treeNodes; + } + + private static void recursionNode(DefaultMutableTreeNode rootNode, long parentId, String threadName, + Map treeNodeMap, long id) { + if (rootNode.getUserObject() instanceof TreeTableBean) { + TreeTableBean topBean = (TreeTableBean) rootNode.getUserObject(); + TreeTableBean timeBean = treeNodeMap.get(id); + if (parentId == 0) { // Leaf node + recursionNodeLeaf(threadName, rootNode, topBean, timeBean); + } else { // Non-leaf nodes + recursionNodeNonLeaf(threadName, rootNode, timeBean, treeNodeMap, id, parentId); + } + } + } + + private static void recursionNodeLeaf(String threadName, DefaultMutableTreeNode rootNode, + TreeTableBean topBean, TreeTableBean timeBean){ + if (rootNode.getChildCount() == 0) { // The child node is thread and there are currently no child nodes + TreeTableBean bean = new TreeTableBean(topBean.getThreadDur()); + bean.setName(threadName); + bean.setTotalNum(timeBean.getTotalNum()); + bean.setSelfNum(timeBean.getTotalNum()); + bean.setSelfNum(timeBean.getSelfNum()); + DefaultMutableTreeNode node = new DefaultMutableTreeNode(bean); + rootNode.add(node); + } else { // Merge leaf nodes + TreeNode tNode = rootNode.getChildAt(rootNode.getChildCount() - 1); + if (tNode instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode leafNode = (DefaultMutableTreeNode) tNode; + if (leafNode.getUserObject() instanceof TreeTableBean) { + TreeTableBean leafNodeUserObject = (TreeTableBean) leafNode.getUserObject(); + leafNodeUserObject.setTotalNum(leafNodeUserObject.getTotalNum() + timeBean.getTotalNum()); + leafNodeUserObject.setSelfNum(leafNodeUserObject.getSelfNum() + timeBean.getTotalNum()); + leafNodeUserObject + .setChildrenNum(leafNodeUserObject.getSelfNum() + timeBean.getChildrenNum()); + leafNode.setUserObject(leafNodeUserObject); + } + } + } + } + + private static void recursionNodeNonLeaf(String threadName, DefaultMutableTreeNode rootNode, + TreeTableBean timeBean, Map treeNodeMap, long id, long parentId) { + final TreeTableBean idBean = treeNodeMap.get(parentId); + boolean sameName = false; + Enumeration enumeration = rootNode.children(); + while (enumeration.hasMoreElements()) { + /* Compare whether there are node names in the current hierarchy that need to be merged */ + TreeNode nodeObj = enumeration.nextElement(); + if (nodeObj instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode nextElement = (DefaultMutableTreeNode) nodeObj; + if (nextElement.getUserObject() instanceof TreeTableBean) { + TreeTableBean nextElementUserObject = (TreeTableBean) nextElement.getUserObject(); + if (nextElementUserObject.getName().equals(idBean.getName())) { // The merge time difference + nextElementUserObject.setSelfNum(nextElementUserObject.getSelfNum() + timeBean.getSelfNum()); + nextElementUserObject + .setChildrenNum(nextElementUserObject.getChildrenNum() + timeBean.getChildrenNum()); + nextElementUserObject.setTotalNum(nextElementUserObject.getTotalNum() + timeBean.getTotalNum()); + recursionNode(nextElement, idBean.getParentStackId(), threadName, treeNodeMap, id); + sameName = true; + } + } + } + } + if (!sameName) { // No same node needs to be merged + TreeTableBean bean = new TreeTableBean(); + bean.setName(idBean.getName()); + bean.setTotalNum(timeBean.getTotalNum()); + bean.setSelfNum(timeBean.getSelfNum()); + bean.setChildrenNum(timeBean.getChildrenNum()); + DefaultMutableTreeNode addNode = new DefaultMutableTreeNode(bean); + rootNode.add(addNode); + recursionNode(addNode, idBean.getParentStackId(), threadName, treeNodeMap, id); + } + } + + /** + * get right flame chart data by time range + * + * @param startNS startNS + * @param endNS endNS + * @return List flame node list + */ + public static List getFuncTreeFlameChart(long startNS, long endNS) { + List funcTreeTopDown = getFuncTreeTopDown(startNS, endNS); + funcTreeTopDown.forEach(AllData::resortNode); + sortNodeList(funcTreeTopDown); + return funcTreeTopDown; + } + + /** + * get right flame chart data by selected func + * + * @param func func + * @return List flame node list + */ + public static List getFuncTreeFlameChart(Func func) { + return getFuncTreeByFuncTopDown(func); + } + + /** + * get right flame chart data by time range and selected thread + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + * @return List flame node list + */ + public static List getFuncTreeFlameChart(long startNS, long endNS, + List threadIds) { + List funcTreeTopDown = getFuncTreeTopDown(startNS, endNS, threadIds); + funcTreeTopDown.forEach(AllData::resortNode); + sortNodeList(funcTreeTopDown); + return funcTreeTopDown; + } + + private static void resortNode(DefaultMutableTreeNode root) { + Consumer sort = parent -> { + Enumeration children = parent.children(); + List childs = new ArrayList<>(); + while (children.hasMoreElements()) { + TreeNode node = children.nextElement(); + if (node instanceof DefaultMutableTreeNode) { + childs.add((DefaultMutableTreeNode) node); + } + } + parent.removeAllChildren(); + sortNodeList(childs).forEach(parent::add); + }; + Enumeration enumeration = root.depthFirstEnumeration(); + while (enumeration.hasMoreElements()) { + Object nodeObj = enumeration.nextElement(); + if (nodeObj instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeObj; + if (!node.isLeaf() && node.getChildCount() > 1) { + sort.accept(node); + } + } + } + } + + private static List sortNodeList(List list) { + return list.stream().sorted((child1, child2) -> { + if (child1.getUserObject() instanceof TreeTableBean && child2.getUserObject() instanceof TreeTableBean) { + TreeTableBean bean1 = (TreeTableBean) child1.getUserObject(); + TreeTableBean bean2 = (TreeTableBean) child2.getUserObject(); + return Long.compare(bean1.getTotalNum(), bean2.getTotalNum()); + } + return 0; + }).collect(Collectors.toList()); + } + + /** + * clear all static data + */ + public static void clearData() { + if (cpuMap != null) { + cpuMap.values().forEach(List::clear); + cpuMap.clear(); + } + if (threadMap != null) { + threadMap.values().forEach(List::clear); + threadMap.clear(); + } + if (funcMap != null) { + funcMap.values().forEach(List::clear); + funcMap.clear(); + } + if (threadNames != null) { + threadNames.clear(); + } + if (processes != null) { + processes.clear(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AppTracePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AppTracePanel.java new file mode 100644 index 000000000..bef48769f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/AppTracePanel.java @@ -0,0 +1,552 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace; + +import com.intellij.ui.JBColor; +import com.intellij.ui.JBSplitter; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.transport.grpc.service.CpuPluginResult; +import ohos.devtools.views.applicationtrace.analysis.AnalysisEnum; +import ohos.devtools.views.applicationtrace.bean.Cpu; +import ohos.devtools.views.applicationtrace.bean.CpuFreq; +import ohos.devtools.views.applicationtrace.bean.CpuFreqMax; +import ohos.devtools.views.applicationtrace.bean.CpuMax; +import ohos.devtools.views.applicationtrace.bean.CpuScale; +import ohos.devtools.views.applicationtrace.bean.DisplayFunc; +import ohos.devtools.views.applicationtrace.bean.Duration; +import ohos.devtools.views.applicationtrace.bean.Frame; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.applicationtrace.bean.Thread; +import ohos.devtools.views.applicationtrace.bean.VsyncAppBean; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.CpuDb; +import ohos.devtools.views.trace.Db; +import ohos.devtools.views.trace.EventDispatcher; +import ohos.devtools.views.trace.ExpandPanel; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.Tip; +import ohos.devtools.views.trace.TracePanel; +import ohos.devtools.views.trace.TraceSimpleRow; +import ohos.devtools.views.trace.TraceThreadRow; +import ohos.devtools.views.trace.bean.Process; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.event.AncestorEvent; +import javax.swing.event.AncestorListener; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Rectangle; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.geom.Rectangle2D; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * AppTracePanel + * + * @version 1.0 + */ +public class AppTracePanel extends JBPanel { + private TracePanel tracePanel; + private DataPanel dataPanel; + private Integer processId; + private Tip tip = Tip.getInstance(); + private String cpuName; + + /** + * struct function + */ + public AppTracePanel() { + addAncestorListener(new AncestorListener() { + @Override + public void ancestorAdded(AncestorEvent event) { + } + + @Override + public void ancestorRemoved(AncestorEvent event) { + tip.hidden(); + } + + @Override + public void ancestorMoved(AncestorEvent event) { + } + }); + addComponentListener(new ComponentAdapter() { + @Override + public void componentHidden(ComponentEvent e) { + super.componentHidden(e); + tip.hidden(); + } + }); + } + + /** + * load the data from db file + * + * @param name name + * @param cpuName cpuName + * @param isLocal isLocal + */ + public void load(final String name, final String cpuName, final boolean isLocal) { + load(name, cpuName, null, isLocal); + } + + /** + * load the data from db file + * + * @param name name + * @param cpuName cpuName + * @param pId pId + * @param isLocal isLocal + */ + public void load(final String name, final String cpuName, final Integer pId, final boolean isLocal) { + Utils.resetPool(); + recycleData(); + this.cpuName = cpuName; + Db.setDbName(name); + Db.load(isLocal); + if (Objects.nonNull(cpuName) && !cpuName.isEmpty()) { + CpuDb.setDbName(cpuName); + CpuDb.load(isLocal); + } + if (Objects.nonNull(pId)) { + loadProcess(pId); + } else { + loadProcess(null); + } + } + + private void recycleData() { + removeAll(); + AllData.clearData(); + EventDispatcher.clearData(); + TracePanel.currentSelectThreadIds.clear(); + } + + private void loadProcess(Integer pId) { + CompletableFuture.runAsync(() -> { + List processes = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_PROCESS, processes); + AllData.processes = processes; + SwingUtilities.invokeLater(() -> { + if (Objects.nonNull(pId)) { + loadProcessWithPid(pId); + } else { + loadProcessWithoutPid(processes); + } + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + + private void loadProcessWithPid(int pId) { + processId = pId; + tracePanel = new TracePanel(); + dataPanel = new DataPanel(AnalysisEnum.APP); + setLayout(new MigLayout("insets 0")); + JBSplitter splitter = new JBSplitter(); + splitter.setFirstComponent(tracePanel); + splitter.setSecondComponent(dataPanel); + add(splitter, "push,grow"); + List dur = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_TOTAL_TIME, dur); + if (dur.size() > 0) { + TracePanel.DURATION = dur.get(0).getTotal(); + TracePanel.START_TS = dur.get(0).getStartTs(); + TracePanel.END_TS = dur.get(0).getEndTs(); + } + List cpuMaxList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_CPU_MAX, cpuMaxList); + if (cpuMaxList.size() > 0) { + cpuMaxList.get(0).getCpu(); + } + if (Objects.nonNull(cpuName) && !cpuName.isEmpty()) { + insertCpuScale(); + } + int cpuMax = 0; + insertDisplay(); + insertCpu(cpuMax); + insertProcess(); + tip.setJLayeredPane(AppTracePanel.this.getRootPane().getLayeredPane()); + } + + private void loadProcessWithoutPid(List processes) { + Object processObj = JOptionPane + .showInputDialog(JOptionPane.getRootFrame(), "select process", "process", JOptionPane.PLAIN_MESSAGE, null, + processes.toArray(), processes.size() > 0 ? processes.get(0).toString() : ""); + if (processObj instanceof Process) { + Process process = (Process) processObj; + processId = process.getPid(); + tracePanel = new TracePanel(); + dataPanel = new DataPanel(AnalysisEnum.APP); + setLayout(new MigLayout("insets 0")); + JBSplitter splitter = new JBSplitter(); + splitter.setFirstComponent(tracePanel); + splitter.setSecondComponent(dataPanel); + add(splitter, "push,grow"); + if (Objects.nonNull(process)) { + List dur = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_TOTAL_TIME, dur); + TracePanel.DURATION = dur.get(0).getTotal(); + TracePanel.START_TS = dur.get(0).getStartTs(); + TracePanel.END_TS = dur.get(0).getEndTs(); + List cpuMaxList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_CPU_MAX, cpuMaxList); + int cpuMax = cpuMaxList.get(0).getCpu(); + if (Objects.nonNull(cpuName) && !cpuName.isEmpty()) { + insertCpuScale(); + } + insertDisplay(); + insertCpu(cpuMax); + insertProcess(); + tip.setJLayeredPane(AppTracePanel.this.getRootPane().getLayeredPane()); + } + } + } + + private void insertInteraction() { + TraceSimpleRow user = new TraceSimpleRow("User"); + TraceSimpleRow lifecycle = new TraceSimpleRow("Lifecycle"); + ExpandPanel panel = new ExpandPanel("Interaction"); + panel.addTraceRow(user); + panel.addTraceRow(lifecycle); + tracePanel.getContentPanel().add(panel, "pushx,growx"); + } + + private void insertCpuScale() { + List cpuScales = new ArrayList<>() { + }; + CpuDb.getInstance().query(Sql.QUERY_CPU_SCALE, cpuScales); + List list = new ArrayList<>(); + cpuScales.forEach(scale -> { + CpuPluginResult.CpuData.Builder builder = CpuPluginResult.CpuData.newBuilder(); + try { + CpuPluginResult.CpuData cpuData = builder.mergeFrom(scale.getData()).build(); + CpuPluginResult.CpuUsageInfo cpuUsageInfo = cpuData.getCpuUsageInfo(); + list.add(cpuUsageInfo); + scale.setScale(getCpuScale(cpuUsageInfo)); + scale.setStartNs(TimeUnit.MILLISECONDS.toNanos(cpuUsageInfo.getPrevSystemBootTimeMs())); + scale.setEndNs(TimeUnit.MILLISECONDS.toNanos(cpuUsageInfo.getSystemBootTimeMs())); + } catch (IOException exception) { + exception.printStackTrace(); + } + }); + tracePanel.paintTimeShaft(g2 -> { + Rectangle bounds = tracePanel.getTimeShaft().getBounds(); + if (cpuScales == null || cpuScales.isEmpty()) { + g2.setColor(JBColor.foreground()); + Common.setAlpha(g2, 1f); + Common.drawStringVHCenter(g2, "No CPU usage data available for this imported trace", bounds); + return; + } + g2.setColor(JBColor.foreground().brighter()); + Common.setAlpha(g2, 0.7f); + long min = cpuScales.stream().mapToLong(value -> value.getTimeStamp()).min().orElse(0); + long max = cpuScales.stream().mapToLong(value -> value.getTimeStamp()).max().orElse(0); + long dur = max - min; + int height = tracePanel.getTimeShaft().getHeight(); + cpuScales.forEach(it -> { + long sts = it.getTimeStamp() - min; + int px = (int) Common.nsToXByDur(sts, bounds, dur); + int py = (int) Math.round(height * (1.0 - it.getScale())); + tracePanel.getTimeShaft().putRateMap(px, it.getScale()); + g2.drawLine(px, py, px, height); + }); + Common.setAlpha(g2, 1.0f); + }); + } + + private double getCpuScale(CpuPluginResult.CpuUsageInfo cpuUsageInfo) { + return (cpuUsageInfo.getSystemCpuTimeMs() - cpuUsageInfo.getPrevSystemCpuTimeMs()) * 1.0 / ( + cpuUsageInfo.getSystemBootTimeMs() - cpuUsageInfo.getPrevSystemBootTimeMs()); + } + + private void insertDisplay() { + ExpandPanel panel = new ExpandPanel("Display"); + TraceSimpleRow frames = new TraceSimpleRow("Frames"); + panel.addTraceRow(frames); + insertFrame(frames); + + TraceSimpleRow surfaceflinger = new TraceSimpleRow("Surfaceflinger"); + panel.addTraceRow(surfaceflinger); + insertSurface(surfaceflinger); + + TraceSimpleRow vsync = new TraceSimpleRow("VSYNC"); + panel.addTraceRow(vsync); + insertVsyc(vsync); + + tracePanel.getContentPanel().add(panel, "pushx,growx"); + } + + private void insertFrame(TraceSimpleRow frames) { + frames.setSupplier(() -> { + List renderThreadList = new ArrayList<>() { + }; + List frameThreadList = new ArrayList<>() { + }; + int pid = processId; + List renderFuncList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.GET_THREAD_FUNC_BY_NAME, renderFuncList, pid); + if (renderFuncList.size() > 0) { + Db.getInstance().query(Sql.QUERY_THREAD_DATA, renderThreadList, renderFuncList.get(0).getTid()); + } + Db.getInstance().query(Sql.QUERY_THREAD_DATA, frameThreadList, pid); + ArrayList frameFuncList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.GET_FUN_DATA_BY_TID, frameFuncList, pid); + setFuncIdel(renderFuncList, renderThreadList); + setFuncIdel(frameFuncList, frameThreadList); + List frameList = new ArrayList<>(); + frameFuncList.stream().filter(frameFunc -> frameFunc.getFuncName().contains("doFrame")).forEach(func -> { + Frame frame = new Frame(func); + frame.setRenderList(renderFuncList.stream().filter(renderFunc -> TimeUtils + .isInRange(func.getStartTs(), func.getStartTs() + func.getDur(), renderFunc.getStartTs(), + renderFunc.getStartTs() + renderFunc.getDur())).collect(Collectors.toList())); + frameList.add(frame); + }); + return frameList; + }); + frames.setRender((graphics2D, data) -> { + data.forEach(node -> { + node.setRect(frames.getRectByNode(node, 20)); + node.draw(graphics2D); + }); + }); + } + + private void insertSurface(TraceSimpleRow surfaceflinger) { + surfaceflinger.setRender((graphics2D, data) -> { + data.forEach(node -> { + node.setRect(surfaceflinger.getRectByNode(node, 5, 20)); + node.draw(graphics2D); + }); + }); + surfaceflinger.setSupplier(() -> { + Process sfProcess = AllData.processes.stream() + .filter(process -> Objects.equals(process.getName(), "/system/bin/surfaceflinger")).findAny() + .orElse(null); + List flingerThreads = new ArrayList<>() { + }; + if (sfProcess == null) { + return new ArrayList<>(); + } else { + Db.getInstance().query(Sql.GET_FUN_DATA_BY_TID, flingerThreads, sfProcess.getPid()); + flingerThreads = + flingerThreads.stream().filter(func -> func.getDepth() == 0).collect(Collectors.toList()); + return flingerThreads.stream().map(DisplayFunc::new).collect(Collectors.toList()); + } + }); + } + + private void insertVsyc(TraceSimpleRow vsync) { + vsync.setRender((g2, data) -> { + data.stream().filter(data::contains).forEach(node -> { + node.setRect(vsync.getRectByNode(node)); + node.draw(g2); + }); + }); + vsync.setSupplier(() -> { + List tracks = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_VSYNC_APP, tracks); + for (int idx = 0, len = tracks.size(); idx < len; idx++) { + VsyncAppBean it = tracks.get(idx); + if (idx == len - 1) { + it.setDuration(AnalystPanel.DURATION - it.getStartTime()); + } else { + it.setDuration(tracks.get(idx + 1).getStartTime() - it.getStartTime()); + } + } + return tracks; + }); + } + + private void insertCpu(int num) { + List cpuFreqMaxList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_CPU_MAX_FREQ, cpuFreqMaxList); + CpuFreqMax freqMax = cpuFreqMaxList.get(0).math(); + ExpandPanel panel = new ExpandPanel("CPU cores (" + (num + 1) + ")"); + IntStream.rangeClosed(0, num).forEachOrdered(index -> { + TraceSimpleRow row = new TraceSimpleRow("CPU " + index); + TraceSimpleRow rowFreq = new TraceSimpleRow("CPU " + index + " Frequency"); + insertCpuRow(row, index); + insertCpuRowFreq(rowFreq, index, row, freqMax); + panel.addTraceRow(row); + panel.addTraceRow(rowFreq); + }); + tracePanel.getContentPanel().add(panel, "growx,pushx"); + } + + private void insertCpuRowFreq(TraceSimpleRow rowFreq, int index, TraceSimpleRow row, + CpuFreqMax freqMax) { + rowFreq.setSupplier(() -> { + List list = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_CPU_FREQ_DATA, list, index); + for (int idx = 0, len = list.size(); idx < len; idx++) { + CpuFreq cpuGraph = list.get(idx); + if (idx == len - 1) { + cpuGraph.setDuration(AnalystPanel.DURATION - cpuGraph.getStartTime()); + } else { + cpuGraph.setDuration(list.get(idx + 1).getStartTime() - cpuGraph.getStartTime()); + } + } + return list; + }); + rowFreq.setRender((g2, data) -> { + data.stream().filter(item -> row.contains(item)).forEach(node -> { + node.setRect(row.getRectByNode(node)); + node.setMax(freqMax.getValue()); + node.draw(g2); + }); + g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency + Rectangle2D bounds = g2.getFontMetrics().getStringBounds(freqMax.getName(), g2); + g2.setColor(Color.lightGray); + g2.drawString(freqMax.getName(), 2, (int) (Utils.getY(row.getContentBounds()) + 2 + bounds.getHeight())); + }); + } + + private void insertCpuRow(TraceSimpleRow row, int index) { + row.setSupplier(() -> { + List cpus = new ArrayList<>() { + }; + int count = + Db.getInstance().queryCount(Sql.QUERY_CPU_DATA_COUNT, index, TracePanel.startNS, TracePanel.endNS); + if (count > Final.CAPACITY) { + Db.getInstance() + .query(Sql.QUERY_CPU_DATA_LIMIT, cpus, index, TracePanel.startNS, TracePanel.endNS, Final.CAPACITY); + } else { + Db.getInstance().query(Sql.QUERY_CPU_DATA, cpus, index, TracePanel.startNS, TracePanel.endNS); + } + AllData.cpuMap.put(index, cpus); + return cpus; + }); + row.setRender((g2, data1) -> { + data1.stream().filter(row::contains).forEach(node -> { + node.setRect(row.getRectByNode(node, 5)); + node.draw(g2); + }); + }); + } + + private void insertProcess() { + List threads = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_THREADS_BY_PID, threads, processId); + AllData.threadNames = threads.stream().collect(Collectors.toMap(th -> th.getTid(), th -> th.getThreadName())); + ExpandPanel panel = new ExpandPanel("Threads (" + threads.size() + ")"); + for (Thread thread : threads) { + TraceThreadRow row = new TraceThreadRow<>(thread.getThreadName(), thread.getTid()); + row.setRender((g2, data1, data2) -> { + data1.stream().filter(item -> row.contains(item)).forEach(th -> { + th.setRect(row.getRectByNode(th, row.getThreadHeight())); + th.draw(g2); + }); + if (data2 != null) { + data2.stream().filter(item -> row.contains(item)).forEach(func -> { + func.setRect(row.getRectByNode(func, row.getFuncHeight(), row.getFuncHeight())); + func.draw(g2); + }); + } + }); + row.setSupplier(() -> { + List threadList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.QUERY_THREAD_DATA, threadList, thread.getTid()); + AllData.threadMap.put(thread.getTid(), threadList); + return threadList; + }); + row.setSupplier2(() -> { + List funcs = new ArrayList<>() { + }; + Db.getInstance().query(Sql.GET_FUN_DATA_BY_TID, funcs, thread.getTid()); + if (AllData.threadMap.containsKey(thread.getTid())) { + List threadList = AllData.threadMap.get(thread.getTid()); + setFuncIdel(funcs, threadList); + Func threadFunc = new Func(); + threadFunc.setFuncName(thread.getThreadName()); + threadFunc.setThreadName(thread.getThreadName()); + threadFunc.setTid(thread.getTid()); + threadFunc.setDepth(-1); + threadFunc.setBloodId(Utils.md5String(thread.getThreadName())); + threadFunc.setStartTs(0); + threadFunc.setEndTs(TracePanel.END_TS - TracePanel.START_TS); + funcs.add(threadFunc); + List sortedList = funcs.stream().filter((item) -> item.getDepth() != -1) + .sorted(Comparator.comparingInt(Func::getDepth)).collect(Collectors.toList()); + Map map = funcs.stream().collect(Collectors.toMap(Func::getId, func -> func)); + sortedList.forEach((func) -> { + func.setThreadName(thread.getThreadName()); + if (func.getDepth() != 0) { + func.setParentBloodId(map.get(func.getParentId()).getBloodId()); + } + func.setEndTs(func.getStartTs() + func.getDur()); + func.createBloodId(); + }); + } + AllData.funcMap.put(thread.getTid(), funcs); + int maxDept = funcs.stream().mapToInt(Func::getDepth).max().orElse(0) + 1; + int maxHeight = maxDept * row.getFuncHeight() + row.getFuncHeight(); + if (maxHeight < 30) { + maxHeight = 30; + } + row.setMaxDept(maxDept); + if (panel.getContent().getLayout() instanceof MigLayout) { + ((MigLayout) panel.getContent().getLayout()) + .setComponentConstraints(row, "growx,pushx,h " + maxHeight + "!"); + } + row.updateUI(); + return funcs; + }); + panel.addTraceRow(row); + } + tracePanel.getContentPanel().add(panel, "pushx,growx"); + } + + private void setFuncIdel(List funcList, List threadList) { + if (funcList.size() > 0 && threadList.size() > 0) { + funcList.forEach(func -> func.setIdle(threadList.stream().filter(threadValue -> TimeUtils + .isInRange(func.getStartTs(), func.getEndTs(), threadValue.getStartTime(), + threadValue.getStartTime() + threadValue.getDuration()) && !"Running" + .equals(threadValue.getState())).mapToLong(Thread::getDuration).sum())); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataPanel.java new file mode 100644 index 000000000..ff929ddc2 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataPanel.java @@ -0,0 +1,139 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace; + +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.SideBorder; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.util.ui.JBInsets; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.analysis.AllThreadPanel; +import ohos.devtools.views.applicationtrace.analysis.AnalysisEnum; +import ohos.devtools.views.applicationtrace.analysis.OtherFunctionPanel; +import ohos.devtools.views.applicationtrace.analysis.OtherThreadPanel; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.trace.EventDispatcher; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.TracePanel; + +import java.util.ArrayList; +import java.util.List; + +/** + * DataPanel + * + * @version 1.0 + * @date: 2021/5/13 13:22 + */ +public class DataPanel extends EventPanel { + /** + * enum analysis + */ + public static AnalysisEnum analysisEnum; + + private JBTabbedPane analysisTab; + private List currentTids = new ArrayList<>(); + private OtherFunctionPanel otherFunctionPanel; + private OtherThreadPanel otherThreadPanel; + + /** + * construction + * + * @param analysisEnum analysisEnum + */ + public DataPanel(AnalysisEnum analysisEnum) { + setLayout(new MigLayout("inset 0", "[grow,fill]", "[grow,fill]")); + analysisTab = new JBTabbedPane(); + analysisTab.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + analysisTab.setTabComponentInsets(JBInsets.create(0, 0)); + this.analysisEnum = analysisEnum; + initComp(); + } + + private void initComp() { + removeAll(); + analysisTab.removeAll(); + analysisTab.addTab("Analysis", new JBPanel<>()); + analysisTab.addTab("All Threads", new AllThreadPanel(analysisEnum)); + otherThreadPanel = new OtherThreadPanel(analysisEnum); + analysisTab.setEnabledAt(0, false); + analysisTab.setSelectedIndex(1); + otherFunctionPanel = new OtherFunctionPanel(); + add(analysisTab, "growx,pushx"); + EventDispatcher.addClickListener(node -> { + String tabName = ""; + if (node instanceof Func) { + tabName = ((Func) node).getFuncName(); + } + if (tabName != null && tabName.length() > 20) { + tabName = tabName.substring(0, 20) + "..."; + } + if (analysisTab.getTabCount() == 3) { + analysisTab.remove(analysisTab.getTabCount() - 1); + } + analysisTab.addTab(tabName, otherFunctionPanel); + analysisTab.setSelectedIndex(analysisTab.getTabCount() - 1); + }); + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + if (threadIds.size() == 0) { + if (analysisTab.getTabCount() == 3) { + analysisTab.remove(analysisTab.getTabCount() - 1); + } + } else { + if (analysisTab.getTabCount() == 3) { + if (analysisTab.getComponentAt(analysisTab.getTabCount() - 1) instanceof OtherFunctionPanel) { + analysisTab.remove(analysisTab.getTabCount() - 1); + analysisTab.addTab(createTabName(threadIds), otherThreadPanel); + } else { + if (!threadIds.equals(currentTids)) { + analysisTab.setTitleAt(analysisTab.getTabCount() - 1, createTabName(threadIds)); + } + } + } else { + analysisTab.addTab(createTabName(threadIds), otherThreadPanel); + } + } + analysisTab.setSelectedIndex(analysisTab.getTabCount() - 1); + } + + @Override + public void change(long startNS, long endNS, long scale) { + if (analysisTab.getTabCount() != 3) { + change(startNS, endNS, TracePanel.currentSelectThreadIds); + } + } + + private String createTabName(List ids) { + if (ids.size() == 1 && ids.get(0) != null) { + String name = null; + if (analysisEnum.equals(AnalysisEnum.APP)) { + if (AllData.threadNames != null) { + name = AllData.threadNames.get(ids.get(0)); + } + } + if (name != null && name.length() > 20) { + name = name.substring(0, 20) + "..."; + } + return name == null ? "" : name; + } else { + return ids.size() + " Threads"; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataProcess.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataProcess.java new file mode 100644 index 000000000..3288d3c38 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/DataProcess.java @@ -0,0 +1,241 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace; + +import ohos.devtools.views.applicationtrace.bean.AppFunc; +import ohos.devtools.views.applicationtrace.bean.TreeTableBean; +import ohos.devtools.views.applicationtrace.util.TimeUtils; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeNode; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.groupingBy; + +/** + * DataProcess + * + * @date: 2021/5/12 16:34 + */ +public class DataProcess { + /** + * get the get TopDown FuncTree by startNS、endNS and threadIds + * + * @param funcMap funcMap + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + * @return list nodes + */ + public static List getFuncTreeTopDown(Map> funcMap, long startNS, + long endNS, List threadIds) { + if (Objects.isNull(funcMap)) { + return new ArrayList<>(); + } + List funcs = + funcMap.entrySet().stream().filter(entry -> threadIds == null || threadIds.contains(entry.getKey())) + .flatMap(entry -> entry.getValue().stream()).collect(Collectors.toList()); + Map map = funcGroupByStackId(startNS, endNS, funcs, null); + List treeTableBeans = setNumForNodes(map); + Map treeNodeMap = treeTableBeans.stream() + .collect(Collectors.toMap(TreeTableBean::getPrefStackId, DefaultMutableTreeNode::new)); + treeTableBeans.forEach(treeTableBean -> { + if (!treeTableBean.getPrefParentStackId().isEmpty()) { + if (treeNodeMap.containsKey(treeTableBean.getPrefParentStackId())) { + treeNodeMap.get(treeTableBean.getPrefParentStackId()) + .add(treeNodeMap.get(treeTableBean.getPrefStackId())); + } + } + }); + List threadNodes = treeNodeMap.values().stream().filter(node -> { + if (node.getUserObject() instanceof TreeTableBean) { + return ((TreeTableBean) node.getUserObject()).getPrefParentStackId().isEmpty(); + } + return false; + }).collect(Collectors.toList()); + return threadNodes; + } + + /** + * get the get BottomUp FuncTree by startNS、endNS and threadIds + * + * @param funcMap funcMap + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + * @return list nodes + */ + public static List getFuncTreeBottomUp(Map> funcMap, long startNS, + long endNS, List threadIds) { + long dur = TimeUnit.NANOSECONDS.toMicros(endNS - startNS); + ArrayList nodes = new ArrayList<>(); + Map> nameToId = new HashMap<>(); + List funcs = + funcMap.entrySet().stream().filter(entry -> threadIds == null || threadIds.contains(entry.getKey())) + .flatMap(entry -> entry.getValue().stream()).collect(Collectors.toList()); + Map treeNodeMap = funcGroupByStackId(startNS, endNS, funcs, nameToId); + setNumForNodes(treeNodeMap); + nameToId.forEach((name, ids) -> { + DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); + rootNode.setUserObject(new TreeTableBean(dur) {{ + setName(name); + long totalNum = 0; + long childrenNum = 0; + long selfNum = 0; + for (String id : ids) { + TreeTableBean tableBean = treeNodeMap.get(id); + totalNum += tableBean.getTotalNum(); + childrenNum += tableBean.getChildrenNum(); + selfNum += tableBean.getSelfNum(); + } + setTotalNum(totalNum); + setSelfNum(selfNum); + setChildrenNum(childrenNum); + }}); + ids.forEach(id -> recursionNode(rootNode, treeNodeMap.get(id).getPrefParentStackId(), treeNodeMap, id)); + nodes.add(rootNode); + }); + return nodes; + } + + private static Map funcGroupByStackId(long startNS, long endNS, List list, + Map> nameToId) { // Group by stacked + long dur = TimeUnit.NANOSECONDS.toMicros(endNS - startNS); + List>> list1 = list.stream().filter(func -> { + long funcEndTs = func.getEndTs(); + long funcStartTs = func.getStartTs(); + return funcEndTs >= startNS && funcStartTs <= endNS; + }).collect(groupingBy(AppFunc::getBloodId)).entrySet().stream().collect(Collectors.toList()); + return list1.stream().collect(Collectors.toMap(Map.Entry::getKey, a1 -> { + TreeTableBean uniteBean = new TreeTableBean(dur); + uniteBean.setThreadDur(dur); + uniteBean.setPrefStackId(a1.getKey()); + if (a1.getValue().size() > 0) { + uniteBean.setName(a1.getValue().get(0).getFuncName()); + uniteBean.setPrefParentStackId(a1.getValue().get(0).getParentBloodId()); + if (nameToId != null) { + if (nameToId.containsKey(a1.getValue().get(0).getFuncName())) { + nameToId.get(a1.getValue().get(0).getFuncName()).add(a1.getValue().get(0).getBloodId()); + } else { + nameToId.put(a1.getValue().get(0).getFuncName(), new ArrayList<>() {{ + add(a1.getValue().get(0).getBloodId()); + }}); + } + } + } + long childrenTotal = a1.getValue().stream() + .mapToLong(child -> TimeUtils.getIntersection(startNS, endNS, child.getStartTs(), child.getEndTs())) + .sum(); + uniteBean.setTotalNum(childrenTotal); + uniteBean.setChildrenNS(a1.getValue().stream() + .mapToLong(child -> TimeUtils.getNanoIntersection(startNS, endNS, child.getStartTs(), child.getEndTs())) + .sum()); + return uniteBean; + })); + } + + /** + * Set up presentation data + * + * @param map map + * @return list TreeTableBean + */ + private static List setNumForNodes(Map map) { + List treeNodes = new ArrayList<>(map.values()); // Sort the array + for (TreeTableBean ts : treeNodes) { // Loop set children and total data + ts.setSelfNum(ts.getTotalNum() - ts.getChildrenNum()); + if (map.containsKey(ts.getPrefParentStackId())) { + TreeTableBean mapUserObject = map.get(ts.getPrefParentStackId()); + mapUserObject.setChildrenNum(mapUserObject.getChildrenNum() + ts.getTotalNum()); + mapUserObject.setSelfNum(mapUserObject.getTotalNum() - mapUserObject.getChildrenNum()); + } + } + return treeNodes; + } + + private static void recursionNode(DefaultMutableTreeNode rootNode, String parentId, + Map treeNodeMap, String id) { + if (rootNode.getUserObject() instanceof TreeTableBean) { + TreeTableBean topBean = (TreeTableBean) rootNode.getUserObject(); + TreeTableBean timeBean = treeNodeMap.get(id); + if (parentId.isEmpty()) { // Leaf node + recursionNodeLeaf(rootNode, timeBean); + } else { // Non-leaf nodes + recursionNodeNonLeaf(rootNode, timeBean, topBean, treeNodeMap, parentId, id); + } + } + } + + private static void recursionNodeNonLeaf(DefaultMutableTreeNode rootNode, TreeTableBean timeBean, + TreeTableBean topBean, Map treeNodeMap, String parentId, String id) { + final TreeTableBean idBean = treeNodeMap.get(parentId); + boolean sameName = false; + Enumeration enumeration = rootNode.children(); + while (enumeration.hasMoreElements()) { + /* Compare whether there are node names in the current hierarchy that need to be merged */ + TreeNode treeNode = enumeration.nextElement(); + if (treeNode instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode nextElement = (DefaultMutableTreeNode) treeNode; + if (nextElement.getUserObject() instanceof TreeTableBean) { + TreeTableBean nextElementUserObject = (TreeTableBean) nextElement.getUserObject(); + if (nextElementUserObject.getName().equals(idBean.getName())) { // The merge time difference + nextElementUserObject.setSelfNum(nextElementUserObject.getSelfNum() + timeBean.getSelfNum()); + nextElementUserObject + .setChildrenNum(nextElementUserObject.getChildrenNum() + timeBean.getChildrenNum()); + nextElementUserObject.setTotalNum(nextElementUserObject.getTotalNum() + timeBean.getTotalNum()); + recursionNode(nextElement, idBean.getPrefParentStackId(), treeNodeMap, id); + sameName = true; + } + } + } + } + if (!sameName) { // No same node needs to be merged + DefaultMutableTreeNode addNode = new DefaultMutableTreeNode() {{ + setUserObject(new TreeTableBean(topBean.getThreadDur()) {{ // Calculate the time difference + setName(idBean.getName()); + setTotalNum(timeBean.getTotalNum()); + setSelfNum(timeBean.getSelfNum()); + setChildrenNum(timeBean.getChildrenNum()); + }}); + }}; + rootNode.add(addNode); + recursionNode(addNode, idBean.getPrefParentStackId(), treeNodeMap, id); + } + } + + private static void recursionNodeLeaf(DefaultMutableTreeNode rootNode, TreeTableBean timeBean) { + if (rootNode.getChildCount() != 0) { // The child node is thread and there are currently no child nodes + TreeNode child = rootNode.getChildAt(rootNode.getChildCount() - 1); + if (child instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode leafNode = (DefaultMutableTreeNode) child; + if (leafNode.getUserObject() instanceof TreeTableBean) { + TreeTableBean leafNodeUserObject = (TreeTableBean) leafNode.getUserObject(); + leafNodeUserObject.setTotalNum(leafNodeUserObject.getTotalNum() + timeBean.getTotalNum()); + leafNodeUserObject.setSelfNum(leafNodeUserObject.getSelfNum() + timeBean.getTotalNum()); + leafNodeUserObject.setChildrenNum(leafNodeUserObject.getSelfNum() + timeBean.getChildrenNum()); + leafNode.setUserObject(leafNodeUserObject); + } + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadPanel.java new file mode 100644 index 000000000..3945dc856 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadPanel.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; + +import java.util.Objects; + +/** + * app data all thread show panel + * + * @date: 2021/5/20 18:00 + */ +public class AllThreadPanel extends JBPanel { + private JBTabbedPane allThreadTab; + private AllThreadSummaryPanel allThreadSummaryPanel = new AllThreadSummaryPanel(); + private TopBottomPanel topDownPanel; + private TopBottomPanel bottomUpPanel; + private FlameSearchChart flameSearchChart; + + /** + * AllThreadPanel structure function + * + * @param analysisEnum analysisEnum + */ + public AllThreadPanel(AnalysisEnum analysisEnum) { + setLayout(new MigLayout("insets 0 0 10 0", "[grow,fill]", "[grow,fill]")); + allThreadTab = new JBTabbedPane(); + allThreadTab.setBackground(JBColor.background().darker()); + setBorder(JBUI.Borders.empty(5, 8)); + if (Objects.equals(analysisEnum, AnalysisEnum.APP)) { + topDownPanel = new TopBottomPanel( + (startNS, endNS, scale) -> AllData.getFuncTreeTopDown(startNS, endNS), + null); + bottomUpPanel = new TopBottomPanel( + (startNS, endNS, scale) -> AllData.getFuncTreeBottomUp(startNS, endNS), null); + flameSearchChart = new FlameSearchChart( + (startNS, endNS, scale) -> AllData.getFuncTreeFlameChart(startNS, endNS), null); + } + allThreadTab.addTab("Summary", allThreadSummaryPanel); + allThreadTab.addTab("Top Down", topDownPanel); + allThreadTab.addTab("Flame Chart", flameSearchChart); + allThreadTab.addTab("Bottom Up", bottomUpPanel); + add(allThreadTab); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadSummaryPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadSummaryPanel.java new file mode 100644 index 000000000..11a4e014d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AllThreadSummaryPanel.java @@ -0,0 +1,63 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.EventPanel; + +import java.util.List; + +/** + * app data all thread summary panel + * + * @date: 2021/5/20 18:00 + */ +public class AllThreadSummaryPanel extends EventPanel { + private JBLabel timeRange = new JBLabel(); + private JBLabel duration = new JBLabel(); + + /** + * AllThreadSummaryPanel structure function + */ + public AllThreadSummaryPanel() { + setLayout(new MigLayout("inset 0")); + setData(); + } + + private void setData() { + removeAll(); + setBorder(JBUI.Borders.empty(15, 15)); + add(new JBLabel("Time Range")); + add(timeRange, "growx,pushx,wrap"); + add(new JBLabel("Duration")); + add(duration, "growx,pushx"); + setBackground(JBColor.background().brighter()); + } + + @Override + public void change(long startNS, long endNS, long scale) { + timeRange.setText(TimeUtils.getTimeFormatString(startNS) + "~" + TimeUtils.getTimeFormatString(endNS)); + duration.setText(TimeUtils.getTimeWithUnit(endNS - startNS)); + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuService.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AnalysisEnum.java similarity index 82% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuService.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AnalysisEnum.java index 7a737ce13..46dc583fc 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/cpu/CpuService.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/AnalysisEnum.java @@ -13,11 +13,12 @@ * limitations under the License. */ -package ohos.devtools.services.cpu; +package ohos.devtools.views.applicationtrace.analysis; /** - * @Description Cpu业务处理类 - * @Date 2021/2/7 13:43 - **/ -public class CpuService { + * enum of Analysis type + */ +public enum AnalysisEnum { + PREF, + APP } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/EventTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/EventTable.java new file mode 100644 index 000000000..e421a9351 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/EventTable.java @@ -0,0 +1,273 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.JBColor; +import com.intellij.ui.SideBorder; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; +import ohos.devtools.views.applicationtrace.DataPanel; +import ohos.devtools.views.applicationtrace.bean.EventBean; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.applicationtrace.util.TimeUtils; + +import javax.annotation.Nullable; +import javax.swing.ListSelectionModel; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableRowSorter; +import java.awt.Dimension; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * EventTable + * + * @date: 2021/5/24 12:22 + */ +public class EventTable extends JBPanel { + private final int RowHeight = 25; + /** + * event data source + */ + public List dataSource = new ArrayList<>(); + private final int RowHeadHeight = 30; + private List> columnNames = new ArrayList<>(); + private JBScrollPane jScrollPane; + private EventTableModel tableColumnModel; + private JBTable jbTable; + private ITableSizeChangeListener listener; + + /** + * Constructor + * + * @param listener listener + */ + public EventTable(ITableSizeChangeListener listener) { + columnNames.add(new Col<>("Start Time", bean -> TimeUtils.getTimeFormatString(bean.getStartTime()))); + columnNames.add(new Col<>("Name", EventBean::getName)); + columnNames.add(new Col<>("Wall Duration", bean -> TimeUtils.getTimeWithUnit(bean.getWallDuration()))); + columnNames.add(new Col<>("Self Time", bean -> TimeUtils.getTimeWithUnit(bean.getSelfTime()))); + columnNames.add(new Col<>("Cpu Duration", bean -> TimeUtils.getTimeWithUnit(bean.getCpuDuration()))); + columnNames.add(new Col<>("Cpu Self Time", bean -> TimeUtils.getTimeWithUnit(bean.getCpuSelfTime()))); + this.listener = listener; + setLayout(new MigLayout("insets 0", "[grow,fill]", "[grow,fill]")); + tableColumnModel = new EventTableModel(); + jbTable = new JBTable(tableColumnModel); + jbTable.setShowGrid(true); + JTableHeader tableHeader = jbTable.getTableHeader(); + tableHeader.setPreferredSize(new Dimension(tableHeader.getWidth(), RowHeadHeight)); + tableHeader.setBackground(JBColor.background()); + jbTable.setRowHeight(RowHeight); + jbTable.setShowGrid(false); + jbTable.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + jbTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + jbTable.setBackground(JBColor.background().darker()); + initColumns(); + jScrollPane = new JBScrollPane(jbTable, javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, + javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + jScrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + add(jScrollPane); + } + + private void initColumns() { + TableRowSorter rowSorter = new TableRowSorter<>(tableColumnModel); + rowSorter.setComparator(2, getComparator()); + rowSorter.setComparator(3, getComparator()); + rowSorter.setComparator(4, getComparator()); + rowSorter.setComparator(5, getComparator()); + jbTable.setRowSorter(rowSorter); + } + + private Comparator getComparator() { + Comparator comparator = (left, right) -> { + double leftTime = stringToTime(left); + double rightTime = stringToTime(right); + return Double.compare(leftTime, rightTime); + }; + return comparator; + } + + private double stringToTime(String str) { + if (str.contains("μs")) { + return Double.parseDouble(str.replace("μs", "")) * 1000; + } else if (str.contains("ms")) { + return Double.parseDouble(str.replace("ms", "")) * 1000000; + } else if (str.contains("s")) { + return Double.parseDouble(str.replace("s", "")) * 1000000000; + } else if (str.contains("m")) { + return Double.parseDouble(str.replace("m", "")) * 60000000000L; + } else { + return 0D; + } + } + + private void getAppData(long startNS, long endNS, List threadIds) { + List funcList = new ArrayList<>(); + threadIds.forEach(threadId -> { + if (AllData.funcMap.containsKey(threadId)) { + funcList.addAll(AllData.funcMap.get(threadId).stream().filter(func -> func.getDepth() != -1 && TimeUtils + .isRangeCross(startNS, endNS, func.getStartTs(), func.getEndTs())).collect(Collectors.toList())); + } + }); + Map> collect = funcList.stream().collect(Collectors.groupingBy(Func::getParentStackId)); + dataSource = funcList.stream().sorted(Comparator.comparingLong(Func::getDur).reversed()).limit(10).map(func -> { + EventBean eventBean = new EventBean(); + long selfTime; + long cupSelfTime; + long duration = func.getDur(); + long cpuDuration = func.getRunning(); + if (collect.containsKey(func.getStackId())) { + selfTime = func.getDur() - collect.get(func.getStackId()).stream().filter(func1 -> TimeUtils + .isRangeCross(func.getStartTs(), func.getEndTs(), func1.getStartTs(), func1.getEndTs())) + .mapToLong(Func::getDur).sum(); + cupSelfTime = cpuDuration - collect.get(func.getStackId()).stream().filter(func1 -> TimeUtils + .isRangeCross(func.getStartTs(), func.getEndTs(), func1.getStartTs(), func1.getEndTs())) + .mapToLong(Func::getRunning).sum(); + } else { + cupSelfTime = func.getRunning(); + selfTime = func.getDur(); + } + eventBean.setWallDuration(duration); + eventBean.setSelfTime(selfTime); + eventBean.setStartTime(func.getStartTs()); + eventBean.setCpuSelfTime(cupSelfTime); + eventBean.setCpuDuration(cpuDuration); + eventBean.setName(func.getFuncName()); + return eventBean; + }).collect(Collectors.toList()); + } + + /** + * getData + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + */ + public void getData(long startNS, long endNS, List threadIds) { + if (DataPanel.analysisEnum.equals(AnalysisEnum.APP)) { + getAppData(startNS, endNS, threadIds); + } + if (listener != null) { + if (dataSource.size() == 10) { + listener.onTableSizeChange("Longest runing events top (10)"); + } else if (dataSource.size() == 0) { + listener.onTableSizeChange(null); + } else { + listener.onTableSizeChange("Longest runing events (" + dataSource.size() + ")"); + } + } + tableColumnModel.fireTableDataChanged(); + jScrollPane + .setPreferredSize(new Dimension(jScrollPane.getWidth(), dataSource.size() * RowHeight + RowHeadHeight)); + } + + /** + * freshData + */ + public void freshData() { + tableColumnModel.fireTableDataChanged(); + jScrollPane + .setPreferredSize(new Dimension(jScrollPane.getWidth(), dataSource.size() * RowHeight + RowHeadHeight)); + } + + /** + * table size change listener + */ + public interface ITableSizeChangeListener { + + /** + * Table Size Change Callback + * + * @param title table title + */ + void onTableSizeChange(@Nullable String title); + } + + /** + * Col Class + * + * @param T type + */ + public static class Col { + /** + * name + */ + public String name; + + /** + * callable + */ + public Function callable; + + /** + * Constructor + * + * @param name name + * @param callable callable + */ + public Col(String name, Function callable) { + this.name = name; + this.callable = callable; + } + } + + /** + * EventTableModel + * + * @date: 2021/5/24 12:22 + */ + public class EventTableModel extends AbstractTableModel { + @Override + public int getRowCount() { + return dataSource.size(); + } + + @Override + public int getColumnCount() { + return columnNames.size(); + } + + @Override + public String getColumnName(int column) { + return columnNames.get(column).name; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + return columnNames.get(columnIndex).callable.apply(dataSource.get(rowIndex)); + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public Class getColumnClass(int columnIndex) { + return super.getColumnClass(columnIndex); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/ExpandTreeTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/ExpandTreeTable.java new file mode 100644 index 000000000..b4c10a7c8 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/ExpandTreeTable.java @@ -0,0 +1,105 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.components.JBTreeTable; +import com.intellij.ui.treeStructure.treetable.TreeTableModel; +import org.jetbrains.annotations.NotNull; + +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeExpansionListener; +import javax.swing.tree.TreePath; +import java.util.Vector; + +/** + * ExpandTreeTable + * + * @date: 2021/5/19 16:39 + */ +public class ExpandTreeTable extends JBTreeTable { + private Vector expandList = new Vector(); + private Vector expandRowList = new Vector(); + + /** + * Constructor + * + * @param model model + */ + public ExpandTreeTable(@NotNull TreeTableModel model) { + super(model); + getTree().addTreeExpansionListener(new TreeExpansionListener() { + @Override + public void treeExpanded(TreeExpansionEvent event) { + if (event.getPath() != null && !expandList.contains(event.getPath())) { + expandList.add(event.getPath()); + } + if (event.getPath() != null && !expandRowList.contains(getTree().getRowForPath(event.getPath()))) { + expandRowList.add(getTree().getRowForPath(event.getPath())); + } + } + + @Override + public void treeCollapsed(TreeExpansionEvent event) { + if (event.getPath() != null && expandList.contains(event.getPath())) { + expandList.remove(event.getPath()); + } + if (event.getPath() != null && expandRowList.contains(getTree().getRowForPath(event.getPath()))) { + expandRowList.remove(Integer.valueOf(getTree().getRowForPath(event.getPath()))); + + } + } + }); + } + + /** + * fresh the tree expand + */ + public void freshTreeExpand() { + expandList.forEach(item -> { + if (!getTree().isExpanded(item)) { + getTree().expandPath(item); + } + }); + } + + /** + * fresh the tree row expand + */ + public void freshTreeRowExpand() { + expandRowList.forEach(item -> { + getTree().expandRow(item); + }); + } + + /** + * get the expand list + * + * @return selected Vector TreePath + */ + public Vector getExpandList() { + return expandList; + } + + /** + * set the expand list + * + * @param expandList expandList + */ + public void setExpandList(Vector expandList) { + this.expandList = expandList; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameChart.java new file mode 100644 index 000000000..45328b8da --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameChart.java @@ -0,0 +1,379 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBScrollPane; +import ohos.devtools.views.applicationtrace.bean.TreeTableBean; +import ohos.devtools.views.applicationtrace.listener.IAllThreadDataListener; +import ohos.devtools.views.applicationtrace.listener.IOtherThreadDataListener; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.Tip; +import ohos.devtools.views.trace.TracePanel; +import ohos.devtools.views.trace.util.Utils; +import org.apache.commons.lang3.Range; + +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static java.awt.event.KeyEvent.VK_A; +import static java.awt.event.KeyEvent.VK_D; +import static java.awt.event.KeyEvent.VK_S; +import static java.awt.event.KeyEvent.VK_W; + +/** + * FlameChart + * + * @version 1.0 + * @date: 2021/5/24 11:57 + */ +public class FlameChart extends EventPanel implements KeyListener, MouseListener, MouseMotionListener { + private static final int ROW_HEIGHT = 16; + + private List data; + private long duration; + private int xPoint = 0; + private int visibleWidth; + private IAllThreadDataListener iAllThreadDataListener; + private IOtherThreadDataListener iOtherThreadDataListener; + private List dataBean = new ArrayList<>(); + private TreeTableBean activeBean; + private DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root"); + private String currentSearchText = ""; + private double percent = 0; + + /** + * constructor + */ + public FlameChart() { + this(null, null); + } + + /** + * constructor with listener + * + * @param iAllThreadDataListener all thread data listener + * @param iOtherThreadDataListener other thread data listener + */ + public FlameChart(IAllThreadDataListener iAllThreadDataListener, + IOtherThreadDataListener iOtherThreadDataListener) { + this.iOtherThreadDataListener = iOtherThreadDataListener; + this.iAllThreadDataListener = iAllThreadDataListener; + initChart(); + } + + private void initChart() { + setOpaque(true); + setBackground(JBColor.background().brighter()); + addKeyListener(this); + addMouseListener(this); + addMouseMotionListener(this); + } + + @Override + public void change(long startNS, long endNS, long scale) { + if (iAllThreadDataListener != null) { + freshData(startNS, endNS, null, scale); + } + if (iOtherThreadDataListener != null && TracePanel.rangeStartNS == null && TracePanel.rangeEndNS == null) { + change(startNS, endNS, TracePanel.currentSelectThreadIds); + } + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + if (iOtherThreadDataListener != null) { + freshData(startNS, endNS, threadIds, 0); + } + } + + /** + * set the serach input text + * + * @param currentSearchText currentSearchText + */ + public void setCurrentSearchText(String currentSearchText) { + this.currentSearchText = currentSearchText; + TopBottomPanel.getNodeContainSearch(rootNode, currentSearchText); + int maxDepth = data.stream().mapToInt(it -> it.getDepth()).max().orElse(0); + setPreferredSize(new Dimension(0, (maxDepth + 3) * ROW_HEIGHT)); + scrollToBottom(); + } + + private void freshData(long startNS, long endNS, List threadIds, long scale) { + duration = endNS - startNS; + if (threadIds == null) { + data = iAllThreadDataListener.getAllThreadData(startNS, endNS, scale); + } else { + data = iOtherThreadDataListener.getOtherThreadData(startNS, endNS, threadIds); + } + setAllNode(data); + } + + /** + * set all node in flame chart + * + * @param datasource datasource + * @param dur dur + */ + public void setAllNode(List datasource, long dur) { + duration = dur; + setAllNode(datasource); + } + + /** + * set all node in flame chart + * + * @param datasource datasource + */ + public void setAllNode(List datasource) { + data = datasource; + rootNode.removeAllChildren(); + datasource.forEach(item -> { + rootNode.add(item); + }); + TopBottomPanel.getNodeContainSearch(rootNode, currentSearchText); + int maxDepth = datasource.stream().mapToInt(it -> it.getDepth()).max().orElse(0); + setPreferredSize(new Dimension(0, (maxDepth + 3) * ROW_HEIGHT)); + SwingUtilities.invokeLater(this::scrollToBottom); + } + + /** + * reset all node in flame chart + */ + public void resetAllNode() { + TopBottomPanel.resetAllNode(rootNode); + int maxDepth = data.stream().mapToInt(it -> it.getDepth()).max().orElse(0); + setPreferredSize(new Dimension(0, (maxDepth + 3) * ROW_HEIGHT)); + scrollToBottom(); + } + + @Override + public void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + if (graphics instanceof Graphics2D) { + dataBean.clear(); + Graphics2D g2 = (Graphics2D) graphics; + if (data != null && data.size() > 0) { + int threadWidth = getWidth() / data.size(); + for (int index = 0; index < data.size(); index++) { + DefaultMutableTreeNode node = data.get(index); + if (node.getUserObject() instanceof TreeTableBean) { + TreeTableBean bean = (TreeTableBean) node.getUserObject(); + bean.setRect( + new Rectangle(threadWidth * index, getHeight() - ROW_HEIGHT * 2, threadWidth, ROW_HEIGHT)); + bean.draw(g2); + dataBean.add(bean); + if (node.getChildCount() > 0) { + duration = bean.getChildrenNS(); + paintChild(g2, node, threadWidth * index, getHeight() - ROW_HEIGHT * 2, threadWidth); + } + } + } + } + } + } + + private void paintChild(Graphics2D g2, DefaultMutableTreeNode node, int xPoint, int yPoint, int tWidth) { + int childCount = node.getChildCount(); + int left = xPoint; + int tw = (int) (tWidth * 1.0); + ArrayList lines = new ArrayList<>(); + for (int index = 0; index < childCount; index++) { + if (node.getChildAt(index) instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode nd = (DefaultMutableTreeNode) node.getChildAt(index); + if (nd.getUserObject() instanceof TreeTableBean) { + TreeTableBean bean = (TreeTableBean) nd.getUserObject(); + int funcWidth = getFuncWidth(bean.getChildrenNS(), tw); + lines.add(funcWidth); + bean.setRect(new Rectangle(left, yPoint - ROW_HEIGHT, funcWidth, ROW_HEIGHT)); + bean.draw(g2); + dataBean.add(bean); + left += funcWidth; + if (nd.getChildCount() > 0) { + paintChild(g2, nd, Utils.getX(bean.getRect()), yPoint - ROW_HEIGHT, tw); + } + } + } + } + if (lines.stream().allMatch(line -> Objects.equals(line, 0))) { + Common.setAlpha(g2, getAlpha(lines)); + g2.fillRect(xPoint, yPoint - ROW_HEIGHT, 1, ROW_HEIGHT); + } + } + + private float getAlpha(List list) { + int size = list.size(); + float alpha; + if (Range.between(1, 2).contains(size)) { + alpha = 0.9f; + } else if (Range.between(3, 5).contains(size)) { + alpha = 0.8f; + } else if (Range.between(6, 8).contains(size)) { + alpha = 0.7f; + } else if (Range.between(9, 11).contains(size)) { + alpha = 0.6f; + } else { + alpha = 0.5f; + } + return alpha; + } + + private int getFuncWidth(long dur, int tw) { + long dura = dur; + if (dur > duration) { + dura = duration; + } + double wid = dura * tw * 1.0 / duration; + return (int) wid; + } + + @Override + public void keyTyped(KeyEvent event) { + } + + @Override + public void keyPressed(KeyEvent event) { + switch (event.getExtendedKeyCode()) { + case VK_A: + translation(-1); + break; + case VK_D: + translation(1); + break; + case VK_W: + scale(1); + break; + case VK_S: + scale(-1); + break; + default: + break; + } + } + + @Override + public void keyReleased(KeyEvent event) { + } + + @Override + public void mouseClicked(MouseEvent event) { + } + + @Override + public void mousePressed(MouseEvent event) { + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + requestFocusInWindow(); + } + + @Override + public void mouseExited(MouseEvent event) { + Tip.getInstance().hidden(); + } + + private void translation(int index) { + if (getParent().getParent() instanceof JBScrollPane) { + JBScrollPane parent = (JBScrollPane) getParent().getParent(); + int width = parent.getViewport().getVisibleRect().width; + int offset = width / 10; + JScrollBar jsBar = parent.getHorizontalScrollBar(); + if (index > 0) { + xPoint += offset; + if (xPoint >= jsBar.getMaximum() - width) { + xPoint = jsBar.getMaximum() - width; + } + } else { + xPoint -= offset; + if (xPoint <= jsBar.getMinimum()) { + xPoint = jsBar.getMinimum(); + } + } + jsBar.setValue(xPoint); + percent = jsBar.getValue() * 1.0 / (jsBar.getMaximum()); + } + } + + private void scale(int index) { + if (getParent().getParent() instanceof JBScrollPane) { + JBScrollPane parent = (JBScrollPane) getParent().getParent(); + visibleWidth = parent.getViewport().getVisibleRect().width; + JScrollBar jsBar = parent.getHorizontalScrollBar(); + int fixWidth = getWidth(); + if (index > 0) { + fixWidth += getWidth() * 0.2; + } else { + fixWidth -= getWidth() * 0.2; + } + if (fixWidth < visibleWidth) { + fixWidth = visibleWidth; + } + xPoint = jsBar.getValue(); + setPreferredSize(new Dimension(fixWidth, 0)); + jsBar.setValue((int) (jsBar.getMaximum() * percent)); + revalidate(); + repaint(); + } + } + + private void scrollToBottom() { + if (getParent().getParent() instanceof JBScrollPane) { + JBScrollPane parent = (JBScrollPane) getParent().getParent(); + JScrollBar jsBar = parent.getVerticalScrollBar(); + jsBar.setValue(jsBar.getMaximum()); + revalidate(); + repaint(); + } + } + + @Override + public void mouseDragged(MouseEvent event) { + } + + @Override + public void mouseMoved(MouseEvent event) { + if (Objects.nonNull(activeBean)) { + activeBean.moveOut(event.getPoint(), this); + Tip.getInstance().hidden(); + } + dataBean.stream().filter(it -> it.getRect().contains(event.getPoint())).forEach(it -> { + it.moveIn(event.getPoint(), this); + List stringList = it.getStringList(""); + Tip.getInstance().display(this, event.getPoint(), stringList); + activeBean = it; + }); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameSearchChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameSearchChart.java new file mode 100644 index 000000000..75cf23593 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/FlameSearchChart.java @@ -0,0 +1,101 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.SideBorder; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.components.JBTextField; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.listener.IAllThreadDataListener; +import ohos.devtools.views.applicationtrace.listener.IOtherThreadDataListener; + +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.List; + +/** + * FlameSearchChart + * + * @date 2021/04/22 12:25 + */ +public class FlameSearchChart extends JBPanel { + private JBScrollPane scrollPane; + private FlameChart flameChart; + private JBTextField search = new JBTextField(); + private String currentSearchText = ""; + + /** + * structure + */ + public FlameSearchChart() { + this(null, null); + } + + /** + * structure with listener + * + * @param iAllThreadDataListener all thread listener + * @param iOtherThreadDataListener other thread listener + */ + public FlameSearchChart(IAllThreadDataListener iAllThreadDataListener, + IOtherThreadDataListener iOtherThreadDataListener) { + flameChart = new FlameChart(iAllThreadDataListener, iOtherThreadDataListener); + init(); + } + + private void init() { + search.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent event) { + currentSearchText = search.getText(); + flameChart.setCurrentSearchText(currentSearchText); + } + + @Override + public void removeUpdate(DocumentEvent event) { + currentSearchText = search.getText(); + if (currentSearchText.isEmpty()) { + flameChart.resetAllNode(); + } else { + flameChart.setCurrentSearchText(currentSearchText); + } + } + + @Override + public void changedUpdate(DocumentEvent event) { + } + }); + scrollPane = new JBScrollPane(flameChart, JBScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JBScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + setLayout(new MigLayout("inset 10", "[grow,fill]", "[][grow,fill]")); + add(search, "wrap"); + add(scrollPane); + } + + /** + * fresh current data + * + * @param datasource datasource + * @param dur dur + */ + public void freshData(List datasource, long dur) { + flameChart.setAllNode(datasource, dur); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionPanel.java new file mode 100644 index 000000000..9ca5836c0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionPanel.java @@ -0,0 +1,63 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.trace.EventDispatcher; + +/** + * The OtherFunctionPanel + * + * @date 2021/04/22 12:25 + */ +public class OtherFunctionPanel extends JBPanel { + private JBTabbedPane otherFunctionTab; + private TopBottomPanel topBottomPanel; + private TopBottomPanel bottomUpPanel; + private FlameSearchChart flameSearchChart; + + /** + * structure + */ + public OtherFunctionPanel() { + setLayout(new MigLayout("inset 0", "[grow,fill]", "[grow,fill]")); + otherFunctionTab = new JBTabbedPane(); + otherFunctionTab.setBackground(JBColor.background().darker()); + setBorder(JBUI.Borders.empty(5, 8)); + topBottomPanel = new TopBottomPanel(); + bottomUpPanel = new TopBottomPanel(); + flameSearchChart = new FlameSearchChart(); + otherFunctionTab.addTab("Summary", new OtherFunctionSummaryPanel()); + otherFunctionTab.addTab("Top Down", topBottomPanel); + otherFunctionTab.addTab("Flame Chart", flameSearchChart); + otherFunctionTab.addTab("Bottom Up", bottomUpPanel); + add(otherFunctionTab); + EventDispatcher.addClickListener(node -> { + if (node instanceof Func) { + Func func = (Func) node; + topBottomPanel.freshTreeData(AllData.getFuncTreeByFuncTopDown(func)); + bottomUpPanel.freshTreeData(AllData.getFuncTreeByFuncBottomUp(func)); + flameSearchChart.freshData(AllData.getFuncTreeFlameChart(func), func.getDur()); + } + }); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionSummaryPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionSummaryPanel.java new file mode 100644 index 000000000..4482bd6fe --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherFunctionSummaryPanel.java @@ -0,0 +1,189 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; +import ohos.devtools.views.applicationtrace.DataPanel; +import ohos.devtools.views.applicationtrace.bean.AppFunc; +import ohos.devtools.views.applicationtrace.bean.EventBean; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.applicationtrace.util.MathUtils; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.EventDispatcher; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.ExpandPanel; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The OtherFunctionSummaryPanel + * + * @date 2021/04/22 12:25 + */ +public class OtherFunctionSummaryPanel extends EventPanel { + private JBLabel timeRange = new JBLabel(); + private JBLabel dataType = new JBLabel(); + private EventTable selectEventTable = new EventTable(null); + private EventTable funcTable = new EventTable(null); + private ExpandPanel topFuncPanel; + private JBPanel numberStatistics = new JBPanel(); + private JBLabel count = new JBLabel(""); + private JBLabel average = new JBLabel(""); + private JBLabel max = new JBLabel(""); + private JBLabel min = new JBLabel(""); + private JBLabel stdDev = new JBLabel(""); + private Object currentNode; + + /** + * structure + */ + public OtherFunctionSummaryPanel() { + setLayout(new MigLayout("inset 0")); + setBackground(JBColor.background().brighter()); + EventDispatcher.addClickListener(node -> { + if (node != currentNode) { + currentNode = node; + if (node instanceof AppFunc) { + setPageData((AppFunc) node); + } + } + }); + setData(); + } + + private void setData() { + removeAll(); + setBorder(JBUI.Borders.empty(15, 15)); + add(new JBLabel("Time Range")); + add(timeRange, "growx,pushx,wrap"); + add(new JBLabel("Data Type")); + dataType.setText("Stack Frame"); + add(dataType, "growx,pushx,wrap"); + add(new JBLabel(), "growx,pushx,wrap"); + JBLabel selectEvent = new JBLabel("Selected event"); + add(selectEvent, "growx,pushx,wrap"); + add(selectEventTable, "span 2,growx,pushx,wrap"); + topFuncPanel = new ExpandPanel(""); + setStatistics(); + topFuncPanel.getContent().setBackground(JBColor.background().brighter()); + topFuncPanel.getContent().add(numberStatistics, "w 50%!,wrap"); + JBLabel jbLabel = new JBLabel("Longest running occurrences (select row to navigate)"); + jbLabel.setBorder(JBUI.Borders.empty(10, 0, 10, 0)); + topFuncPanel.getContent().add(jbLabel, "pushx,growx,wrap"); + topFuncPanel.getContent().add(funcTable, "growx,pushx,wrap"); + add(topFuncPanel, "span 2,growx,pushx,wrap"); + } + + private void setStatistics() { + numberStatistics.setBackground(JBColor.background().brighter()); + numberStatistics.setBorder(JBUI.Borders.empty(0, 15, 0, 15)); + numberStatistics + .setLayout(new MigLayout("inset 0", "[grow,12.5%] [grow,12.5%] [grow,12.5%] [grow,12.5%]", "[] []")); + numberStatistics.add(count); + numberStatistics.add(average); + numberStatistics.add(max); + numberStatistics.add(min); + numberStatistics.add(stdDev, "wrap"); + numberStatistics.add(new JBLabel("Count")); + numberStatistics.add(new JBLabel("Average")); + numberStatistics.add(new JBLabel("Max")); + numberStatistics.add(new JBLabel("Min")); + numberStatistics.add(new JBLabel("Std Dev"), "wrap"); + } + + /** + * setPageData + * + * @param obj obj + */ + public void setPageData(AppFunc obj) { + if (DataPanel.analysisEnum.equals(AnalysisEnum.APP)) { + if (obj instanceof Func) { + Func appFunc = (Func) obj; + getAppTraceData(appFunc); + timeRange.setText(TimeUtils.getTimeFormatString(appFunc.getStartTs()) + "~" + TimeUtils + .getTimeFormatString(appFunc.getEndTs())); + dataType.setText("Trace Event"); + selectEventTable.dataSource.clear(); + selectEventTable.dataSource.add(initAppBean(appFunc)); + selectEventTable.freshData(); + } + } + } + + private void getAppTraceData(Func func) { + List collect = + AllData.funcMap.get(func.getTid()).stream() + .filter(filter -> filter.getFuncName().equals(func.getFuncName())) + .sorted(Comparator.comparingLong(Func::getDur).reversed()).collect(Collectors.toList()); + List longs = collect.stream().map(Func::getDur).collect(Collectors.toList()); + setStatisticsData(longs); + List dataSource = new ArrayList<>(); + collect.stream().limit(10).forEach(item -> { + dataSource.add(initAppBean(item)); + }); + funcTable.dataSource = dataSource; + funcTable.freshData(); + } + + private EventBean initAppBean(Func func) { + EventBean eventBean = new EventBean(); + eventBean.setName(func.getFuncName()); + eventBean.setStartTime(func.getStartTs()); + eventBean.setWallDuration(func.getDur()); + eventBean.setSelfTime(func.getDur() - AllData.funcMap.get(func.getTid()).stream() + .filter(filter -> filter.getDepth() != -1 && filter.getParentId().equals(func.getId())) + .mapToLong(Func::getDur).sum()); + eventBean.setCpuDuration(func.getRunning()); + eventBean.setCpuSelfTime(func.getRunning() - AllData.funcMap.get(func.getTid()).stream() + .filter(filter -> filter.getDepth() != -1 && filter.getParentId().equals(func.getId())) + .mapToLong(Func::getRunning).sum()); + return eventBean; + } + + private void setStatisticsData(List longs) { + topFuncPanel.setTitle("All Occurrences(" + longs.size() + ")"); + String countTxt = Integer.toString(longs.size()); + double averageNum = MathUtils.average(longs.stream().map(Long::doubleValue).collect(Collectors.toList())); + String averageTxt = TimeUtils.getTimeWithUnit(Double.valueOf(averageNum).longValue()); + count.setText(countTxt); + average.setText(averageTxt); + String maxTxt = TimeUtils.getTimeWithUnit(longs.stream().max(Long::compareTo).orElse(0L)); + max.setText(maxTxt); + String minTxt = TimeUtils.getTimeWithUnit(longs.stream().min(Long::compareTo).orElse(0L)); + min.setText(minTxt); + double stdDevNum = + MathUtils.standardDiviation(longs.stream().map(Long::doubleValue).collect(Collectors.toList())); + String stdDevTxt = TimeUtils.getTimeWithUnit(Double.valueOf(stdDevNum).longValue()); + stdDev.setText(stdDevTxt); + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + } + + @Override + public void change(long startNS, long endNS, long scale) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadPanel.java new file mode 100644 index 000000000..3369ed6d3 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadPanel.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; + +import java.util.Objects; + +/** + * The OtherThreadPanel + * + * @date 2021/04/22 12:25 + */ +public class OtherThreadPanel extends JBPanel { + private JBTabbedPane otherThreadTab; + private TopBottomPanel topBottomPanel; + private TopBottomPanel bottomUpPanel; + private FlameSearchChart flameSearchChart; + + /** + * structure + * + * @param analysisEnum analysisEnum + */ + public OtherThreadPanel(AnalysisEnum analysisEnum) { + setLayout(new MigLayout("inset 0", "[grow,fill]", "[grow,fill]")); + otherThreadTab = new JBTabbedPane(); + otherThreadTab.setBackground(JBColor.background().darker()); + if (Objects.equals(analysisEnum, AnalysisEnum.APP)) { + topBottomPanel = new TopBottomPanel(null, AllData::getFuncTreeTopDown); + bottomUpPanel = new TopBottomPanel(null, AllData::getFuncTreeBottomUp); + flameSearchChart = new FlameSearchChart(null, AllData::getFuncTreeFlameChart); + } + setBorder(JBUI.Borders.empty(5, 8)); + otherThreadTab.addTab("Summary", new OtherThreadSummaryPanel()); + otherThreadTab.addTab("Top Down", topBottomPanel); + otherThreadTab.addTab("Flame Chart", flameSearchChart); + otherThreadTab.addTab("Bottom Up", bottomUpPanel); + add(otherThreadTab); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadSummaryPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadSummaryPanel.java new file mode 100644 index 000000000..f0fd0fa68 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/OtherThreadSummaryPanel.java @@ -0,0 +1,113 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.DataPanel; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.ExpandPanel; +import ohos.devtools.views.trace.TracePanel; + +import java.util.List; + +/** + * The OtherThreadSummaryPanel + * + * @date 2021/04/22 12:25 + */ +public class OtherThreadSummaryPanel extends EventPanel { + private EventTable topFuncTable; + private ExpandPanel topFuncPanel; + private JBLabel timeRange = new JBLabel(); + private JBLabel duration = new JBLabel(); + private JBLabel thread = new JBLabel(); + private JBLabel idLable = new JBLabel("ID"); + private JBLabel id = new JBLabel(); + + /** + * structure + */ + public OtherThreadSummaryPanel() { + setLayout(new MigLayout("inset 0")); + setBackground(JBColor.background().brighter()); + setData(); + } + + private void setData() { + removeAll(); + setBorder(JBUI.Borders.empty(15, 15)); + add(new JBLabel("Time Range")); + add(timeRange, "growx,pushx,wrap"); + add(new JBLabel("Duration")); + add(duration, "growx,pushx,wrap"); + add(new JBLabel("Data Type")); + thread.setText("Thread"); + add(thread, "growx,pushx,wrap"); + add(idLable); + add(id, "growx,pushx,wrap"); + if (DataPanel.analysisEnum.equals(AnalysisEnum.APP)) { + StateTable stateTable = new StateTable(); + ExpandPanel stateTablePanel = new ExpandPanel("States"); + stateTablePanel.setBackground(JBColor.background().brighter()); + stateTablePanel.getContent().add(stateTable, "pushx,growx"); + add(stateTablePanel, "span 2,growx,growy,wrap"); + } + topFuncTable = new EventTable(title -> { + if (topFuncPanel != null) { + topFuncPanel.setVisible(true); + if (title == null) { + remove(topFuncPanel); + } else { + topFuncPanel.setTitle(title); + add(topFuncPanel, "span 2,growx,growy,wrap"); + } + } + }); + topFuncPanel = new ExpandPanel(""); + topFuncPanel.setBackground(JBColor.background().brighter()); + topFuncPanel.getContent().add(topFuncTable, "pushx,growx"); + add(topFuncPanel, "span 2,growx,growy,wrap"); + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + if (threadIds.size() == 1) { + id.setVisible(true); + idLable.setVisible(true); + id.setText(threadIds.get(0).toString()); + topFuncTable.getData(startNS, endNS, threadIds); + topFuncPanel.setVisible(true); + } else { + id.setVisible(false); + idLable.setVisible(false); + topFuncPanel.setVisible(false); + } + timeRange.setText(TimeUtils.getTimeFormatString(startNS) + "~" + TimeUtils.getTimeFormatString(endNS)); + duration.setText(TimeUtils.getTimeWithUnit(endNS - startNS)); + } + + @Override + public void change(long startNS, long endNS, long scale) { + if (TracePanel.rangeStartNS == null && TracePanel.rangeEndNS == null) { + change(startNS, endNS, TracePanel.currentSelectThreadIds); + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/StateTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/StateTable.java new file mode 100644 index 000000000..99926b5b3 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/StateTable.java @@ -0,0 +1,206 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.JBColor; +import com.intellij.ui.SideBorder; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.AllData; +import ohos.devtools.views.applicationtrace.bean.Thread; +import ohos.devtools.views.applicationtrace.bean.ThreadStateBean; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.TracePanel; +import ohos.devtools.views.trace.util.ComparatorUtils; +import org.apache.commons.collections.map.HashedMap; + +import javax.swing.ListSelectionModel; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableRowSorter; +import java.awt.Dimension; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * StateTable + * + * @version 1.0 + * @date: 2021/5/12 16:34 + */ +public class StateTable extends EventPanel { + /** + * table data source + */ + public List dataSource = new ArrayList<>(); + + private static final Map STATUS_MAP = new HashedMap() {{ + put("D", "Waiting"); + put("S", "Sleeping"); + put("R", "Runnable"); + put("Running", "Running"); + put("R+", "Runnable"); + put("DK", "Waiting"); + put("W", "Runnable"); + put("X", "Dead"); + put("Z", "Exit (Zombie)"); + put("K", "Wake Kill"); + put("P", "Parked"); + put("N", "No Load"); + }}; + private final int RowHeight = 25; + private final int RowHeadHeight = 30; + + private List> columnNames = new ArrayList<>() {{ + add(new EventTable.Col<>("Thread State", ThreadStateBean::getState)); + add(new EventTable.Col<>("Duration", ThreadStateBean::getDuration)); + add(new EventTable.Col<>("%", ThreadStateBean::getPercent)); + add(new EventTable.Col<>("Occurrences", ThreadStateBean::getOccurrences)); + }}; + private JBScrollPane jScrollPane; + private StateTableModel tableColumnModel; + private JBTable jbTable; + private TableRowSorter rowSorter; + + /** + * structure function + */ + public StateTable() { + setLayout(new MigLayout("insets 0", "[grow,fill]", "[grow,fill]")); + tableColumnModel = new StateTableModel(); + jbTable = new JBTable(tableColumnModel); + jbTable.setShowGrid(true); + JTableHeader tableHeader = jbTable.getTableHeader(); + tableHeader.setPreferredSize(new Dimension(tableHeader.getWidth(), RowHeadHeight)); + tableHeader.setBackground(JBColor.background()); + jbTable.setRowHeight(RowHeight); + jbTable.setShowGrid(false); + jbTable.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + jbTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + jbTable.setBackground(JBColor.background().darker()); + rowSorter = new TableRowSorter<>(tableColumnModel); + for (int i = 0; i < tableColumnModel.getColumnCount(); i++) { + if (i == 1) { + // set duration sorter + rowSorter.setComparator(i, (str1, str2) -> { + // change duration String to time ns + long time1 = TimeUtils.getNSByTimeString(String.valueOf(str1)); + long time2 = TimeUtils.getNSByTimeString(String.valueOf(str2)); + if (time1 < time2) { + return -1; + } else if (time1 == time2) { + return 0; + } else { + return 1; + } + }); + } else { + rowSorter.setComparator(i, ComparatorUtils.generateComparator("")); + } + } + jbTable.setRowSorter(rowSorter); // add row sorter + jScrollPane = new JBScrollPane(jbTable, javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, + javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + jScrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.NONE)); + add(jScrollPane); + } + + private void getAppData(long startNS, long endNS, List threadIds) { + List threads = new ArrayList<>(); + dataSource.clear(); + threadIds.forEach(threadId -> { + if (AllData.threadMap.containsKey(threadId)) { + threads.addAll(AllData.threadMap.get(threadId).stream().filter(thread -> TimeUtils + .isRangeCross(startNS, endNS, thread.getStartTime(), + thread.getStartTime() + thread.getDuration())) + .collect(Collectors.toList())); + } + }); + Map> collect = threads.stream().filter(filter -> STATUS_MAP.get(filter.getState()) != null) + .collect(Collectors.groupingBy(thread -> STATUS_MAP.get(thread.getState()))); + long totalDur = endNS - startNS; + collect.forEach((key, value) -> { + ThreadStateBean bean = new ThreadStateBean(); + long sum = value.stream().mapToLong(thread -> TimeUtils + .getNanoIntersection(startNS, endNS, thread.getStartTime(), + thread.getStartTime() + thread.getDuration())).sum(); + bean.setState(key); + bean.setOccurrences(Integer.toString(value.size())); + bean.setDuration(TimeUtils.getTimeWithUnit(sum)); + bean.setPercent(String.format(Locale.ENGLISH, "%.2f", sum * 1.0 / totalDur * 100)); + dataSource.add(bean); + }); + tableColumnModel.fireTableDataChanged(); + jScrollPane + .setPreferredSize(new Dimension(jScrollPane.getWidth(), dataSource.size() * RowHeight + RowHeadHeight)); + } + + private void getData(long startNS, long endNS, List threadIds) { + getAppData(startNS, endNS, threadIds); + tableColumnModel.fireTableDataChanged(); + jScrollPane + .setPreferredSize(new Dimension(jScrollPane.getWidth(), dataSource.size() * RowHeight + RowHeadHeight)); + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + getData(startNS, endNS, threadIds); + } + + @Override + public void change(long startNS, long endNS, long scale) { + if (TracePanel.rangeStartNS == null && TracePanel.rangeEndNS == null) { + getData(startNS, endNS, TracePanel.currentSelectThreadIds); + } + } + + /** + * class of state table model + */ + public class StateTableModel extends AbstractTableModel { + @Override + public int getRowCount() { + return dataSource.size(); + } + + @Override + public int getColumnCount() { + return columnNames.size(); + } + + @Override + public String getColumnName(int column) { + return columnNames.get(column).name; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + return columnNames.get(columnIndex).callable.apply(dataSource.get(rowIndex)); + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TabTitleBar.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TabTitleBar.java new file mode 100644 index 000000000..62ac150b5 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TabTitleBar.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.util.ui.JBUI; +import net.miginfocom.swing.MigLayout; +import org.jetbrains.annotations.NotNull; + +import javax.swing.JPanel; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +/** + * TabThreadStatesBean + */ +public class TabTitleBar extends JPanel { + private String title; + private int activeIndex = 0; + private Color backColor = JBColor.background(); + private Color focusColor = JBUI.CurrentTheme.Link.linkColor(); + + /** + * structure function + * + * @param title title + */ + public TabTitleBar(@NotNull String title) { + this.title = title; + setLayout(new MigLayout("inset 0")); + setBackground(backColor); + JBLabel titleLabel = new JBLabel(title); + add(titleLabel); + } + + /** + * add tab + * + * @param tabName tabName + * @param currentIndex currentIndex + */ + public void addTab(String tabName, int currentIndex) { + add(new NormalTab(tabName, currentIndex)); + } + + private class NormalTab extends JPanel { + private final int selectBorderHeight = 2; + private Color mouseEnterColor = JBColor.background().darker(); + private int currentIndex = 0; + private boolean isMouseEnter = false; + + /** + * NormalTab + * + * @param tabTitle tabTitle + * @param currentIndex currentIndex + */ + public NormalTab(String tabTitle, int currentIndex) { + setLayout(new MigLayout("inset 0")); + JBLabel tabTitleLabel = new JBLabel(tabTitle); + tabTitleLabel.setBorder(JBUI.Borders.empty(10, 15)); + add(tabTitleLabel); + addMouseListener(new MouseListener() { + @Override + public void mouseClicked(MouseEvent event) { + } + + @Override + public void mousePressed(MouseEvent event) { + activeIndex = currentIndex; + repaint(); + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + isMouseEnter = true; + repaint(); + } + + @Override + public void mouseExited(MouseEvent event) { + isMouseEnter = false; + repaint(); + } + }); + this.currentIndex = currentIndex; + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + graphics.setColor(backColor); + graphics.fillRect(0, 0, getWidth(), getHeight()); + if (currentIndex == activeIndex) { + graphics.setColor(focusColor); + graphics.fillRect(0, getHeight() - selectBorderHeight, getWidth(), getHeight()); + } + if (isMouseEnter) { + graphics.setColor(mouseEnterColor); + graphics.fillRect(0, 0, getWidth(), getHeight() - selectBorderHeight); + } + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TopBottomPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TopBottomPanel.java new file mode 100644 index 000000000..8386f7d37 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TopBottomPanel.java @@ -0,0 +1,412 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.NlsContexts; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBTextField; +import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; +import com.intellij.ui.treeStructure.treetable.TreeColumnInfo; +import com.intellij.util.ui.ColumnInfo; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.bean.TreeTableBean; +import ohos.devtools.views.applicationtrace.listener.IAllThreadDataListener; +import ohos.devtools.views.applicationtrace.listener.IOtherThreadDataListener; +import ohos.devtools.views.trace.EventPanel; +import ohos.devtools.views.trace.TracePanel; +import ohos.devtools.views.trace.util.Final; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.JTree; +import javax.swing.SortOrder; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeWillExpandListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.ExpandVetoException; +import javax.swing.tree.TreeNode; +import java.awt.Component; +import java.awt.Font; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +/** + * TopBottomPanel + * + * @date: 2021/5/24 11:57 + */ +public class TopBottomPanel extends EventPanel { + private JBTextField search = new JBTextField(); + private DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); + private ListTreeTableModelOnColumns tableModelOnColumns; + private int currentSortKey = 1; + private SortOrder currentOrder = SortOrder.DESCENDING; + private String searchText = ""; + private ColumnInfo[] columns = new ColumnInfo[] {new TreeColumnInfo("Name"), + new TreeTableColumn<>("Total(µs)", TreeTableBean.class, Long.class) { + @Override + @NotNull + Long getCompareValue(TreeTableBean nodeData) { + return nodeData.getTotalNum(); + } + }, new TreeTableColumn<>("%", TreeTableBean.class, Double.class) { + @Override + @NotNull + Double getCompareValue(TreeTableBean nodeData) { + return nodeData.getTotalPercentNum(); + } + }, new TreeTableColumn<>("Self(µs)", TreeTableBean.class, Long.class) { + @Override + @NotNull + Long getCompareValue(TreeTableBean nodeData) { + return nodeData.getSelfNum(); + } + }, new TreeTableColumn<>("%", TreeTableBean.class, Double.class) { + @Override + @NotNull + Double getCompareValue(TreeTableBean nodeData) { + return nodeData.getSelfPercentNum(); + } + }, new TreeTableColumn<>("Children(µs)", TreeTableBean.class, Long.class) { + @Override + @NotNull + Long getCompareValue(TreeTableBean nodeData) { + return nodeData.getChildrenNum(); + } + }, new TreeTableColumn<>("%", TreeTableBean.class, Double.class) { + @Override + @NotNull + Double getCompareValue(TreeTableBean nodeData) { + return nodeData.getChildrenPercentNum(); + } + }}; + private ExpandTreeTable jbTreeTable; + private IAllThreadDataListener iAllThreadDataListener; + private IOtherThreadDataListener iOtherThreadDataListener; + + /** + * constructor + */ + public TopBottomPanel() { + this(null, null); + } + + /** + * constructor with listener + * + * @param iAllThreadDataListener all thread listener + * @param iOtherThreadDataListener other thread listener + */ + public TopBottomPanel(IAllThreadDataListener iAllThreadDataListener, + IOtherThreadDataListener iOtherThreadDataListener) { + this.iAllThreadDataListener = iAllThreadDataListener; + this.iOtherThreadDataListener = iOtherThreadDataListener; + initPanel(); + } + + /** + * get node contains keyword + * Set node type 0 OK 1 based on keywords There are keywords 2 children there keywords 3 no keywords + * + * @param node node + * @param searchText keyword + * @return getNodeContainSearch + */ + public static boolean getNodeContainSearch(DefaultMutableTreeNode node, String searchText) { + boolean hasKeyWord = false; + if (searchText.isEmpty()) { + return false; + } + if (!node.isLeaf()) { + Enumeration children = node.children(); + while (children.hasMoreElements()) { + TreeNode treNode = children.nextElement(); + if (treNode instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode nextElement = (DefaultMutableTreeNode) treNode; + if (nextElement.getUserObject() instanceof TreeTableBean) { + TreeTableBean bean = (TreeTableBean) nextElement.getUserObject(); + if (getNodeContainSearch(nextElement, searchText)) { + if (!hasKeyWord) { + hasKeyWord = true; + } + bean.setContainType(2); + } else { + bean.setContainType(3); + } + if (nextElement.getUserObject().toString().toLowerCase(Locale.ENGLISH).contains(searchText)) { + hasKeyWord = true; + bean.setContainType(1); + } + } + } + } + } else { + if (node.getUserObject() instanceof TreeTableBean) { + TreeTableBean bean = (TreeTableBean) node.getUserObject(); + if (bean.getName().toLowerCase(Locale.ENGLISH).contains(searchText)) { + hasKeyWord = true; + bean.setContainType(1); + } else { + bean.setContainType(3); + } + } + } + return hasKeyWord; + } + + /** + * reset nodes + * + * @param node node + */ + public static void resetAllNode(DefaultMutableTreeNode node) { // Put all nodes in a healthy state of 0 + Enumeration enumeration = node.breadthFirstEnumeration(); + while (enumeration.hasMoreElements()) { + TreeNode treNode = enumeration.nextElement(); + if (treNode instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode nextElement = (DefaultMutableTreeNode) treNode; + if (nextElement.getUserObject() instanceof TreeTableBean) { + ((TreeTableBean) nextElement.getUserObject()).setContainType(0); + } + } + } + } + + private void initPanel() { + setLayout(new MigLayout("inset 10", "[grow,fill]", "[][grow,fill]")); + search.setTextToTriggerEmptyTextStatus("Search"); + search.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + searchText = search.getText().toLowerCase(Locale.ENGLISH); + getNodeContainSearch(root, searchText); + treeResort(root); + tableModelOnColumns.reload(); + jbTreeTable.freshTreeRowExpand(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + searchText = search.getText().toLowerCase(Locale.ENGLISH); + if (searchText.isEmpty()) { + resetAllNode(root); + } else { + getNodeContainSearch(root, searchText); + } + treeResort(root); + tableModelOnColumns.reload(); + jbTreeTable.freshTreeRowExpand(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }); + add(search, "wrap"); + setBackground(JBColor.background().brighter()); + initTree(); + } + + private void initTree() { + tableModelOnColumns = new ListTreeTableModelOnColumns(root, columns); + jbTreeTable = new ExpandTreeTable(tableModelOnColumns); + jbTreeTable.setColumnProportion(0.12F); + jbTreeTable.getTree().addTreeWillExpandListener(new TreeWillExpandListener() { + @Override + public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { + Object lpc = event.getPath().getLastPathComponent(); + if (lpc != null && lpc instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode) lpc; + treeResort(lastPathComponent); + } + } + + @Override + public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { + } + }); + TreeTableRowSorter sorter = new TreeTableRowSorter(jbTreeTable.getTable().getModel()); + sorter.setListener((columnIndex, sortOrder) -> { + if (columnIndex <= 0 || columnIndex > columns.length) { + return; + } + currentSortKey = columnIndex; + currentOrder = sortOrder; + treeResort(root); + tableModelOnColumns.reload(); + jbTreeTable.freshTreeExpand(); + + }); + jbTreeTable.getTree().setExpandsSelectedPaths(true); + jbTreeTable.getTable().setRowSorter(sorter); + jbTreeTable.getTree().setCellRenderer(new TableTreeCellRender()); + jbTreeTable.getTree().getExpandableItemsHandler().setEnabled(true); + add(jbTreeTable); + } + + private void treeResort(DefaultMutableTreeNode node) { + if (currentOrder == SortOrder.ASCENDING) { + TreeTableRowSorter.sortDescTree(node, columns[currentSortKey].getComparator(), jbTreeTable.getTree()); + } else { + TreeTableRowSorter.sortTree(node, columns[currentSortKey].getComparator(), jbTreeTable.getTree()); + } + } + + /** + * refresh tree data + * + * @param nodes nodes list + */ + public void freshTreeData(List nodes) { + if (Objects.isNull(nodes)) { + return; + } + root.removeAllChildren(); + nodes.forEach(item -> root.add(item)); + getNodeContainSearch(root, searchText); + treeResort(root); + tableModelOnColumns.reload(); + jbTreeTable.freshTreeRowExpand(); + } + + @Override + public void change(long startNS, long endNS, long scale) { + if (iAllThreadDataListener != null) { + freshTreeData(iAllThreadDataListener.getAllThreadData(startNS, endNS, scale)); + } + if (iOtherThreadDataListener != null && TracePanel.rangeStartNS == null && TracePanel.rangeEndNS == null) { + freshTreeData( + iOtherThreadDataListener.getOtherThreadData(startNS, endNS, TracePanel.currentSelectThreadIds)); + } + } + + @Override + public void change(long startNS, long endNS, List threadIds) { + if (threadIds.size() != 0) { + if (iOtherThreadDataListener != null) { + freshTreeData(iOtherThreadDataListener.getOtherThreadData(startNS, endNS, threadIds)); + } + } + } + + /** + * the class of tree table column + * + * @param type + * @param nType + */ + public abstract class TreeTableColumn extends ColumnInfo { + private final Class type; + private final Class nType; + + /** + * construction + * + * @param name name of table + * @param typeParameterClass param type + * @param nTypeParameterClass param type + */ + public TreeTableColumn(@NlsContexts.ColumnName String name, Class typeParameterClass, + Class nTypeParameterClass) { + super(name); + type = typeParameterClass; + nType = nTypeParameterClass; + } + + @Override + @Nullable + public String valueOf(DefaultMutableTreeNode defaultMutableTreeNode) { + if (type.isInstance(defaultMutableTreeNode.getUserObject())) { + T nodeData = type.cast(defaultMutableTreeNode.getUserObject()); + if (this.getCompareValue(nodeData) instanceof Double) { + return String.format(Locale.ENGLISH, "%.2f", this.getCompareValue(nodeData)); + } else { + return String.format(Locale.ENGLISH, "%0$,9d", this.getCompareValue(nodeData)); + } + } + return ""; + } + + @Override + @Nullable + public Comparator getComparator() { + return (o1, o2) -> { + if (type.isInstance(o1.getUserObject()) && type.isInstance(o2.getUserObject())) { + T start = type.cast(o1.getUserObject()); + T end = type.cast(o2.getUserObject()); + try { + if (this.getCompareValue(start) instanceof Double && this + .getCompareValue(end) instanceof Double) { + return Double + .compare((double) this.getCompareValue(start), (double) this.getCompareValue(end)); + } else if (this.getCompareValue(start) instanceof Long && this + .getCompareValue(end) instanceof Long) { + return Long.compare((long) this.getCompareValue(start), (long) this.getCompareValue(end)); + } else { + return 0; + } + } catch (ClassCastException e) { + return 0; + } + } + return 0; + }; + } + + @NotNull + abstract N getCompareValue(T nodeData); + } + + class TableTreeCellRender extends DefaultTreeCellRenderer { + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, + boolean leaf, int row, boolean hasFocus) { + JBLabel jbLabel = new JBLabel(); + jbLabel.setIcon(AllIcons.Nodes.Method); + jbLabel.setText(value.toString()); + if (value instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; + if (node.getUserObject() instanceof TreeTableBean) { + TreeTableBean tableBean = (TreeTableBean) node.getUserObject(); + switch (tableBean.getContainType()) { + case 0: + case 2: + jbLabel.setFont(new Font(Final.FONT_NAME, Font.PLAIN, Final.NORMAL_FONT_SIZE)); + jbLabel.setForeground(JBColor.foreground()); + break; + case 1: + jbLabel.setFont(new Font(Final.FONT_NAME, Font.BOLD, Final.NORMAL_FONT_SIZE)); + jbLabel.setForeground(JBColor.foreground()); + break; + case 3: + jbLabel.setFont(new Font(Final.FONT_NAME, Font.PLAIN, Final.NORMAL_FONT_SIZE)); + jbLabel.setForeground(JBColor.foreground().darker()); + break; + } + } + } + return jbLabel; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TreeTableRowSorter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TreeTableRowSorter.java new file mode 100644 index 000000000..8c5118d1c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/analysis/TreeTableRowSorter.java @@ -0,0 +1,220 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.analysis; + +import ohos.devtools.views.applicationtrace.bean.TreeTableBean; +import ohos.devtools.views.applicationtrace.listener.ITreeTableSortChangeListener; + +import javax.swing.DefaultRowSorter; +import javax.swing.JTree; +import javax.swing.SortOrder; +import javax.swing.table.TableModel; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** + * class of tree table row sorter + * + * @param model + * @version 1.0 + * @date: 2021/5/27 12:01 + */ +public class TreeTableRowSorter extends DefaultRowSorter { + private static Comparator nameComparator = (node1, node2) -> { + if (node1.getUserObject() instanceof TreeTableBean && node2.getUserObject() instanceof TreeTableBean) { + TreeTableBean userObject1 = (TreeTableBean) node1.getUserObject(); + TreeTableBean userObject2 = (TreeTableBean) node2.getUserObject(); + return Integer.compare(userObject1.getContainType(), userObject2.getContainType()); + } else { + return 0; + } + }; + + private int sorterColumn = -1; + private M treeTablemodel; + private TreeTableRowSorterModelWrapper modelWrapper; + private ITreeTableSortChangeListener listener; + + /** + * constructor with model + * + * @param mode model + */ + public TreeTableRowSorter(M mode) { + treeTablemodel = mode; + modelWrapper = new TreeTableRowSorterModelWrapper(); + setModelWrapper(modelWrapper); + } + + /** + * sort desc tree + * + * @param root root node + * @param condition sort condition + * @param jtree tree + */ + public static void sortDescTree(DefaultMutableTreeNode root, Comparator condition, JTree jtree) { + Consumer sort = parent -> { + Enumeration children = parent.children(); + List childs = new ArrayList<>(); + while (children.hasMoreElements()) { + TreeNode node = children.nextElement(); + if (node instanceof DefaultMutableTreeNode) { + childs.add((DefaultMutableTreeNode) node); + } + } + parent.removeAllChildren(); + childs.stream().sorted(nameComparator.thenComparing(condition)).collect(Collectors.toList()) + .forEach(parent::add); + }; + Enumeration enumeration = root.depthFirstEnumeration(); + while (enumeration.hasMoreElements()) { + Object nodeObj = enumeration.nextElement(); + if (nodeObj instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeObj; + TreePath path = new TreePath(node.getPath()); + boolean leafFlag = !node.isLeaf() && node.getChildCount() > 1; + boolean rootFlag = (node.isRoot() || jtree.isExpanded(jtree.getRowForPath(path)) || !root.isRoot()); + if (leafFlag && rootFlag) { + sort.accept(node); + } + } + } + } + + /** + * sort tree + * + * @param root root node + * @param condition sort condition + * @param jtree tree + */ + public static void sortTree(DefaultMutableTreeNode root, Comparator condition, JTree jtree) { + Consumer sort = parent -> { + Enumeration children = parent.children(); + List childs = new ArrayList<>(); + while (children.hasMoreElements()) { + TreeNode node = children.nextElement(); + if (node instanceof DefaultMutableTreeNode) { + childs.add((DefaultMutableTreeNode) node); + } + } + parent.removeAllChildren(); + childs.stream().sorted(nameComparator.thenComparing(condition.reversed())).collect(Collectors.toList()) + .forEach(parent::add); + }; + Enumeration enumeration = root.depthFirstEnumeration(); + while (enumeration.hasMoreElements()) { + Object nodeObj = enumeration.nextElement(); + if (nodeObj instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeObj; + TreePath path = new TreePath(node.getPath()); + boolean leafFlag = !node.isLeaf() && node.getChildCount() > 1; + boolean rootFlag = (node.isRoot() || jtree.isExpanded(jtree.getRowForPath(path)) || !root.isRoot()); + if (leafFlag && rootFlag) { + sort.accept(node); + } + } + } + } + + /** + * set sort change listener + * + * @param listener listener + */ + public void setListener(ITreeTableSortChangeListener listener) { + this.listener = listener; + } + + @Override + public void toggleSortOrder(int column) { + if (column < 0 || column > treeTablemodel.getColumnCount()) { + return; + } + sorterColumn = column; + List newKeys = new ArrayList<>(); + List sortKeys = getSortKeys(); + SortOrder sortOrder; + if (sortKeys.size() > 0) { + if (sortKeys.stream() + .anyMatch(item -> item.getColumn() == column && item.getSortOrder() == SortOrder.ASCENDING)) { + sortOrder = SortOrder.DESCENDING; + } else if (sortKeys.stream() + .anyMatch(item -> item.getColumn() == column && item.getSortOrder() == SortOrder.DESCENDING)) { + sortOrder = SortOrder.ASCENDING; + } else { + sortOrder = SortOrder.DESCENDING; + } + } else { + sortOrder = SortOrder.DESCENDING; + } + newKeys.add(new SortKey(column, sortOrder)); + setSortKeys(newKeys); + fireSortOrderChanged(); + if (listener != null) { + listener.reSort(column, sortOrder); + } + } + + @Override + public void sort() { + } + + private class TreeTableRowSorterModelWrapper extends ModelWrapper { + @Override + public M getModel() { + return treeTablemodel; + } + + @Override + public int getColumnCount() { + if (treeTablemodel == null) { + return 0; + } + return treeTablemodel.getColumnCount(); + } + + @Override + public int getRowCount() { + if (treeTablemodel == null) { + return 0; + } + return treeTablemodel.getRowCount(); + } + + @Override + public Object getValueAt(int row, int column) { + if (treeTablemodel == null) { + return Optional.of(null); + } + return treeTablemodel.getValueAt(row, column); + } + + @Override + public Integer getIdentifier(int row) { + return row; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/AppFunc.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/AppFunc.java new file mode 100644 index 000000000..878368f02 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/AppFunc.java @@ -0,0 +1,272 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.List; + +/** + * app function abstract class + */ +public abstract class AppFunc extends AbstractNode { + /** + * fun name + */ + @DField(name = "funName") + protected String funcName = ""; + + /** + * thread id + */ + @DField(name = "tid") + protected Integer tid; + + /** + * depth + */ + @DField(name = "depth") + protected Integer depth = 0; + + /** + * thread name + */ + @DField(name = "threadName") + protected String threadName = ""; + + /** + * start ts + */ + @DField(name = "startTs") + protected long startTs; + + /** + * duration + */ + @DField(name = "dur") + protected long dur; + + /** + * end ts + */ + protected long endTs = 0; + + /** + * blood id + */ + protected String bloodId = ""; + + /** + * parent blood id + */ + protected String parentBloodId = ""; + + /** + * Gets the value of funcName . + * + * @return the value of funcName . + */ + public String getFuncName() { + return funcName; + } + + /** + * Sets the funcName . + *

You can use getFuncName() to get the value of funcName.

+ * + * @param param . + */ + public void setFuncName(final String param) { + this.funcName = param; + } + + /** + * Gets the value of tid . + * + * @return the value of tid . + */ + public Integer getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid.

+ * + * @param param . + */ + public void setTid(final Integer param) { + this.tid = param; + } + + /** + * Gets the value of depth . + * + * @return the value of depth . + */ + public Integer getDepth() { + return depth; + } + + /** + * Sets the depth . + *

You can use getDepth() to get the value of depth.

+ * + * @param param . + */ + public void setDepth(final Integer param) { + this.depth = param; + } + + /** + * Gets the value of threadName . + * + * @return the value of threadName . + */ + public String getThreadName() { + return threadName; + } + + /** + * Sets the threadName . + *

You can use getThreadName() to get the value of threadName.

+ * + * @param param . + */ + public void setThreadName(final String param) { + this.threadName = param; + } + + /** + * Gets the value of startTs . + * + * @return the value of startTs . + */ + public long getStartTs() { + return startTs; + } + + /** + * Sets the startTs . + *

You can use getStartTs() to get the value of startTs.

+ * + * @param param . + */ + public void setStartTs(final long param) { + this.startTs = param; + } + + /** + * Gets the value of dur . + * + * @return the value of dur . + */ + public long getDur() { + return dur; + } + + /** + * Sets the dur . + *

You can use getDur() to get the value of dur.

+ * + * @param param . + */ + public void setDur(final Long param) { + this.dur = param; + } + + /** + * Gets the value of endTs . + * + * @return the value of endTs . + */ + public long getEndTs() { + return endTs; + } + + /** + * Sets the endTs . + *

You can use getEndTs() to get the value of endTs.

+ * + * @param param . + */ + public void setEndTs(final long param) { + this.endTs = param; + } + + /** + * Gets the value of bloodId . + * + * @return the value of bloodId . + */ + public String getBloodId() { + return bloodId; + } + + /** + * Sets the bloodId . + *

You can use getBloodId() to get the value of bloodId.

+ * + * @param param . + */ + public void setBloodId(final String param) { + this.bloodId = param; + } + + /** + * Gets the value of parentBloodId . + * + * @return the value of parentBloodId . + */ + public String getParentBloodId() { + return parentBloodId; + } + + /** + * Sets the parentBloodId . + *

You can use getParentBloodId() to get the value of parentBloodId.

+ * + * @param param . + */ + public void setParentBloodId(final String param) { + this.parentBloodId = param; + } + + /** + * create StackId by parentStackId、funcName and depth + */ + public void createBloodId() { + if (depth == 0) { + bloodId = Utils.md5String(threadName + funcName + depth); + parentBloodId = Utils.md5String(threadName); + } else { + bloodId = Utils.md5String(parentBloodId + funcName + depth); + } + } + + @Override + public void draw(Graphics2D paint) { + } + + @Override + public List getStringList(String time) { + return null; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Cpu.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Cpu.java new file mode 100644 index 000000000..e5c93584b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Cpu.java @@ -0,0 +1,342 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import com.intellij.ui.JBColor; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Cpu + * + * @version 1.0 + * @date: 2021/5/14 15:52 + */ +public class Cpu extends AbstractNode { + @DField(name = "cpu") + private Integer cpu; + @DField(name = "name") + private String name; + private ArrayList stats = new ArrayList<>(); + @DField(name = "end_state") + private String endState; + @DField(name = "priority") + private Integer priority; + @DField(name = "schedId") + private Integer schedId; + @DField(name = "startTime") + private long startTime; + @DField(name = "dur") + private long duration; + @DField(name = "type") + private String type; + @DField(name = "id") + private Integer id; + @DField(name = "tid") + private Integer tid; + @DField(name = "processCmdLine") + private String processCmdLine; + @DField(name = "processName") + private String processName; + @DField(name = "processId") + private Integer processId; + + /** + * get the number of cpu . + * + * @return Integer Returns the number of cpu + */ + public Integer getCpu() { + return cpu; + } + + /** + * set the value of cpu . + * + * @param cpu Set the number of cpu + */ + public void setCpu(final Integer cpu) { + this.cpu = cpu; + } + + /** + * get the name . + * + * @return String Get the name + */ + public String getName() { + return name; + } + + /** + * set the name . + * + * @param name Set name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * get the stats . + * + * @return java.util.ArrayList + */ + public ArrayList getStats() { + return stats; + } + + /** + * set the stats . + * + * @param stats stats + */ + public void setStats(final ArrayList stats) { + this.stats = stats; + } + + /** + * get the endState . + * + * @return String endState + */ + public String getEndState() { + return endState; + } + + /** + * get the endState . + * + * @param endState endState + */ + public void setEndState(final String endState) { + this.endState = endState; + } + + /** + * get the priority . + * + * @return Integer priority + */ + public Integer getPriority() { + return priority; + } + + /** + * set the priority . + * + * @param priority priority + */ + public void setPriority(final Integer priority) { + this.priority = priority; + } + + /** + * get the schedId . + * + * @return Integer + */ + public Integer getSchedId() { + return schedId; + } + + /** + * set the schedId . + * + * @param schedId schedId + */ + public void setSchedId(final Integer schedId) { + this.schedId = schedId; + } + + /** + * get the startTime . + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * set the startTime . + * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * get the duration . + * + * @return long + */ + public long getDuration() { + return duration; + } + + /** + * set the duration . + * + * @param duration duration + */ + public void setDuration(final long duration) { + this.duration = duration; + } + + /** + * get the type . + * + * @return String + */ + public String getType() { + return type; + } + + /** + * set the type . + * + * @param type type + */ + public void setType(final String type) { + this.type = type; + } + + /** + * get the id . + * + * @return Integer + */ + public Integer getId() { + return id; + } + + /** + * set the id . + * + * @param id id + */ + public void setId(final Integer id) { + this.id = id; + } + + /** + * get the tid . + * + * @return Integer + */ + public Integer getTid() { + return tid; + } + + /** + * set the tid . + * + * @param tid tid + */ + public void setTid(final Integer tid) { + this.tid = tid; + } + + /** + * get the processCmdLine . + * + * @return String + */ + public String getProcessCmdLine() { + return processCmdLine; + } + + /** + * set the processCmdLine . + * + * @param processCmdLine processCmdLine + */ + public void setProcessCmdLine(final String processCmdLine) { + this.processCmdLine = processCmdLine; + } + + /** + * get the processName . + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * set the processName . + * + * @param processName processName + */ + public void setProcessName(final String processName) { + this.processName = processName; + } + + /** + * get the processId . + * + * @return Integer + */ + public Integer getProcessId() { + return processId; + } + + /** + * set the processId . + * + * @param processId processId + */ + public void setProcessId(final Integer processId) { + this.processId = processId; + } + + @Override + public void draw(Graphics2D paint) { + if (isMouseIn) { + Common.setAlpha(paint, 0.7F); + } else { + Common.setAlpha(paint, 1.0F); + } + paint.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + Common.setAlpha(paint, 1.0F); + paint.setColor(JBColor.foreground().brighter()); + Common.drawStringCenter(paint, getName(), rect); + } + + @Override + public List getStringList(String time) { + return Arrays.asList( + time, + "Thread: " + name, + "Process: " + ((processName == null || processName.isBlank()) ? name : processName), + "Duration: " + TimeUtils.getTimeString(duration), + "CPU: " + cpu + ); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreq.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreq.java new file mode 100644 index 000000000..bce0fd09f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreq.java @@ -0,0 +1,208 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.List; + +/** + * cpu frequency data + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class CpuFreq extends AbstractNode { + @DField(name = "cpu") + private Integer cpu; + + @DField(name = "value") + private Long value; + + @DField(name = "startNS") + private Long startTime; + + private Long duration; + private JComponent root; + private boolean flagFocus; + private double max; + + /** + * Empty parameter construction method + */ + public CpuFreq() { + } + + /** + * Gets the value of cpu . + * + * @return the value of int + */ + public int getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(final int cpu) { + this.cpu = cpu; + } + + /** + * Gets the value of value . + * + * @return the value of long + */ + public long getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param value value + */ + public void setValue(final long value) { + this.value = value; + } + + /** + * Gets the value of startTime . + * + * @return the value of long + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * Gets the value of duration . + * + * @return the value of long + */ + public long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param duration duration + */ + public void setDuration(final long duration) { + this.duration = duration; + } + + /** + * Gets the value of root . + * + * @return the value of javax.swing.JComponent + */ + public JComponent getRoot() { + return root; + } + + /** + * Sets the root . + *

You can use getRoot() to get the value of root

+ * + * @param root root + */ + public void setRoot(final JComponent root) { + this.root = root; + } + + /** + * Gets the value of flagFocus . + * + * @return the value of boolean + */ + public boolean isFlagFocus() { + return flagFocus; + } + + /** + * Sets the flagFocus . + *

You can use getFlagFocus() to get the value of flagFocus

+ * + * @param flagFocus flagFocus + */ + public void setFlagFocus(final boolean flagFocus) { + this.flagFocus = flagFocus; + } + + /** + * Gets the value of max . + * + * @return the value of double + */ + public double getMax() { + return max; + } + + /** + * Sets the max . + *

You can use getMax() to get the value of max

+ * + * @param max max + */ + public void setMax(double max) { + this.max = max; + } + + /** + * Rewrite drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + double drawHeight = (value * (rect.height) * 1.0) / max; + graphics.setColor(ColorUtils.MD_PALETTE[cpu]); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect) + rect.height - (int) drawHeight, rect.width, + (int) drawHeight); + } + + @Override + public List getStringList(String time) { + return Arrays.asList( + time, + "CPU" + cpu + " Frequency: " + value + ); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreqMax.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreqMax.java new file mode 100644 index 000000000..e7a490e4d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuFreqMax.java @@ -0,0 +1,108 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * CpuFreqMax + * + * @date: 2021/5/27 12:29 + */ +public class CpuFreqMax { + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + @DField(name = "maxFreq") private Integer maxFreq; + private String name = "0 Ghz"; + private Double value = 0D; + + /** + * Gets the value of name . + * + * @return the value of java.lang.String + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name

+ * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the value of value . + * + * @return the value of java.lang.Long + */ + public Double getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param value value + */ + public void setValue(Double value) { + this.value = value; + } + + /** + * Gets the value of maxFreq . + * + * @return the value of java.lang.Integer + */ + public Integer getMaxFreq() { + return maxFreq; + } + + /** + * Sets the maxFreq .You can use getMaxFreq() to get the value of maxFreq + * + * @param maxFreq maxFreq + */ + public void setMaxFreq(Integer maxFreq) { + this.maxFreq = maxFreq; + } + + /** + * get the max cpu freq + * + * @return CpuFreqMax + */ + public CpuFreqMax math() { + StringBuilder sb = new StringBuilder(" "); + setName(" "); + if (maxFreq > 0) { + double log10 = Math.ceil(Math.log10(maxFreq)); + double pow10 = Math.pow(10, log10); + double afterCeil = Math.ceil(maxFreq / (pow10 / 4)) * (pow10 / 4); + setValue(afterCeil); + double unitIndex = Math.floor(log10 / 3); + sb.append(afterCeil / Math.pow(10, unitIndex * 3)); + sb.append(units[(int) unitIndex + 1]); + sb.append("hz"); + } + setName(sb.toString()); + return this; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuMax.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuMax.java new file mode 100644 index 000000000..4a414203b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuMax.java @@ -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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * CpuMax + * + * @version 1.0 + * @date: 2021/5/27 12:22 + */ +public class CpuMax { + @DField(name = "cpu") + private Integer cpu; + + /** + * Gets the value of cpu . + * + * @return the value of java.lang.Integer + */ + public Integer getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(Integer cpu) { + this.cpu = cpu; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuScale.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuScale.java new file mode 100644 index 000000000..c3e4820bb --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/CpuScale.java @@ -0,0 +1,192 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * cpu scale + * + * @version 1.0 + * @date: 2021/5/27 12:22 + */ +public class CpuScale { + @DField(name = "data") + private byte[] data; + @DField(name = "id") + private long id; + @DField(name = "session") + private long session; + @DField(name = "sessionId") + private long sessionId; + @DField(name = "timeStamp") + private long timeStamp; + private double scale; + private long startNs; + private long endNs; + + /** + * Gets the value of data . + * + * @return the value of data . + */ + public byte[] getData() { + return data; + } + + /** + * Sets the data . + *

You can use getData() to get the value of data.

+ * + * @param param . + */ + public void setData(final byte[] param) { + this.data = param; + } + + /** + * Gets the value of id . + * + * @return the value of id . + */ + public long getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id.

+ * + * @param param . + */ + public void setId(final long param) { + this.id = param; + } + + /** + * Gets the value of session . + * + * @return the value of session . + */ + public long getSession() { + return session; + } + + /** + * Sets the session . + *

You can use getSession() to get the value of session.

+ * + * @param param . + */ + public void setSession(final long param) { + this.session = param; + } + + /** + * Gets the value of sessionId . + * + * @return the value of sessionId . + */ + public long getSessionId() { + return sessionId; + } + + /** + * Sets the sessionId . + *

You can use getSessionId() to get the value of sessionId.

+ * + * @param param . + */ + public void setSessionId(final long param) { + this.sessionId = param; + } + + /** + * Gets the value of timeStamp . + * + * @return the value of timeStamp . + */ + public long getTimeStamp() { + return timeStamp; + } + + /** + * Sets the timeStamp . + *

You can use getTimeStamp() to get the value of timeStamp.

+ * + * @param param . + */ + public void setTimeStamp(final long param) { + this.timeStamp = param; + } + + /** + * Gets the value of scale . + * + * @return the value of scale . + */ + public double getScale() { + return scale; + } + + /** + * Sets the scale . + *

You can use getScale() to get the value of scale.

+ * + * @param param . + */ + public void setScale(final double param) { + this.scale = param; + } + + /** + * Gets the value of startNs . + * + * @return the value of startNs . + */ + public long getStartNs() { + return startNs; + } + + /** + * Sets the startNs . + *

You can use getStartNs() to get the value of startNs.

+ * + * @param param . + */ + public void setStartNs(final long param) { + this.startNs = param; + } + + /** + * Gets the value of endNs . + * + * @return the value of endNs . + */ + public long getEndNs() { + return endNs; + } + + /** + * Sets the endNs . + *

You can use getEndNs() to get the value of endNs.

+ * + * @param param . + */ + public void setEndNs(final long param) { + this.endNs = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/DisplayFunc.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/DisplayFunc.java new file mode 100644 index 000000000..ca6af575e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/DisplayFunc.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.List; + +/** + * DisplayFunc + * + * @version 1.0 + * @date: 2021/5/13 13:22 + */ +public class DisplayFunc extends Func { + /** + * Construction + * + * @param func function class + */ + public DisplayFunc(Func func) { + setCategory(func.getCategory()); + setDur(func.getDur()); + setDepth(func.getDepth()); + setFuncName(func.getFuncName()); + setTid(func.getTid()); + setParentId(func.getParentId()); + setStackId(func.getTrackId()); + setParentStackId(func.getParentStackId()); + setThreadName(func.getThreadName()); + setId(func.getId()); + setStartTs(func.getStartTs()); + } + + @Override + public void draw(Graphics2D graphics) { + if (isMouseIn) { + Common.setAlpha(graphics, 0.7F); + } else { + Common.setAlpha(graphics, 1.0F); + } + graphics.setColor(JBUI.CurrentTheme.Label.foreground()); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + Common.setAlpha(graphics, 1.0F); + } + + @Override + public List getStringList(String time) { + return Arrays.asList( + time, + "" + getFuncName(), + "", + TimeUtils.getTimeWithUnit(getDur()) + ); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Duration.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Duration.java new file mode 100644 index 000000000..7d1d1933b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Duration.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Duration + * + * @version 1.0 + * @date: 2021/5/27 12:01 + */ +public class Duration { + @DField(name = "total") + private Long total; + @DField(name = "start_ts") + private Long startTs; + @DField(name = "end_ts") + private Long endTs; + + /** + * Gets the value of total . + * + * @return the value of java.lang.Long + */ + public Long getTotal() { + return total; + } + + /** + * Sets the total . + *

You can use getTotal() to get the value of total

+ * + * @param total total + */ + public void setTotal(Long total) { + this.total = total; + } + + /** + * Gets the value of startTs . + * + * @return the value of java.lang.Long + */ + public Long getStartTs() { + return startTs; + } + + /** + * Sets the startTs . + *

You can use getStartTs() to get the value of startTs

+ * + * @param startTs startTs + */ + public void setStartTs(Long startTs) { + this.startTs = startTs; + } + + /** + * Gets the value of endTs . + * + * @return the value of java.lang.Long + */ + public Long getEndTs() { + return endTs; + } + + /** + * Sets the endTs . + *

You can use getEndTs() to get the value of endTs

+ * + * @param endTs endTs + */ + public void setEndTs(Long endTs) { + this.endTs = endTs; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/EventBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/EventBean.java new file mode 100644 index 000000000..e83a43b1f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/EventBean.java @@ -0,0 +1,145 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +/** + * EventBean + * + * @version 1.0 + * @date: 2021/5/27 12:01 + */ +public class EventBean { + private long startTime; + private String name; + private long wallDuration; + private long selfTime; + private long cpuDuration; + private long cpuSelfTime; + + /** + * Gets the value of startTime . + * + * @return the value of startTime . + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime.

+ * + * @param param . + */ + public void setStartTime(final long param) { + this.startTime = param; + } + + /** + * Gets the value of name . + * + * @return the value of name . + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name.

+ * + * @param param . + */ + public void setName(final String param) { + this.name = param; + } + + /** + * Gets the value of wallDuration . + * + * @return the value of wallDuration . + */ + public long getWallDuration() { + return wallDuration; + } + + /** + * Sets the wallDuration . + *

You can use getWallDuration() to get the value of wallDuration.

+ * + * @param param . + */ + public void setWallDuration(final long param) { + this.wallDuration = param; + } + + /** + * Gets the value of selfTime . + * + * @return the value of selfTime . + */ + public long getSelfTime() { + return selfTime; + } + + /** + * Sets the selfTime . + *

You can use getSelfTime() to get the value of selfTime.

+ * + * @param param . + */ + public void setSelfTime(final long param) { + this.selfTime = param; + } + + /** + * Gets the value of cpuDuration . + * + * @return the value of cpuDuration . + */ + public long getCpuDuration() { + return cpuDuration; + } + + /** + * Sets the cpuDuration . + *

You can use getCpuDuration() to get the value of cpuDuration.

+ * + * @param param . + */ + public void setCpuDuration(final long param) { + this.cpuDuration = param; + } + + /** + * Gets the value of cpuSelfTime . + * + * @return the value of cpuSelfTime . + */ + public long getCpuSelfTime() { + return cpuSelfTime; + } + + /** + * Sets the cpuSelfTime . + *

You can use getCpuSelfTime() to get the value of cpuSelfTime.

+ * + * @param param . + */ + public void setCpuSelfTime(final long param) { + this.cpuSelfTime = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Frame.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Frame.java new file mode 100644 index 000000000..6dae76c67 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Frame.java @@ -0,0 +1,260 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Frame chart node + * + * @version 1.0 + * @date: 2021/5/18 23:18 + */ +public class Frame extends AbstractNode { + /** + * one frame time + */ + public static final long ONE_FRAME_TIME = 16L; + + private long startNs = 0L; + private long dur = 0L; + private long mainThreadCpu = 0L; + private long mainThreadWall = 0L; + private long renderThreadWall = 0L; + private long renderThreadCpu = 0L; + private long total = 0L; + private List renderList; + + /** + * structure + * + * @param func func + */ + public Frame(Func func) { + startNs = func.getStartTs(); + dur = func.getDur(); + total = dur; + mainThreadWall = func.getDur(); + mainThreadCpu = func.getRunning(); + } + + /** + * Gets the value of startNs . + * + * @return the value of startNs . + */ + public long getStartNs() { + return startNs; + } + + /** + * Sets the startNs . + *

You can use getStartNs() to get the value of startNs.

+ * + * @param param . + */ + public void setStartNs(final long param) { + this.startNs = param; + } + + /** + * Gets the value of dur . + * + * @return the value of dur . + */ + public long getDur() { + return dur; + } + + /** + * Sets the dur . + *

You can use getDur() to get the value of dur.

+ * + * @param param . + */ + public void setDur(final long param) { + this.dur = param; + } + + /** + * Gets the value of mainThreadCpu . + * + * @return the value of mainThreadCpu . + */ + public long getMainThreadCpu() { + return mainThreadCpu; + } + + /** + * Sets the mainThreadCpu . + *

You can use getMainThreadCpu() to get the value of mainThreadCpu.

+ * + * @param param . + */ + public void setMainThreadCpu(final long param) { + this.mainThreadCpu = param; + } + + /** + * Gets the value of mainThreadWall . + * + * @return the value of mainThreadWall . + */ + public long getMainThreadWall() { + return mainThreadWall; + } + + /** + * Sets the mainThreadWall . + *

You can use getMainThreadWall() to get the value of mainThreadWall.

+ * + * @param param . + */ + public void setMainThreadWall(final long param) { + this.mainThreadWall = param; + } + + /** + * Gets the value of renderThreadWall . + * + * @return the value of renderThreadWall . + */ + public long getRenderThreadWall() { + return renderThreadWall; + } + + /** + * Sets the renderThreadWall . + *

You can use getRenderThreadWall() to get the value of renderThreadWall.

+ * + * @param param . + */ + public void setRenderThreadWall(final long param) { + this.renderThreadWall = param; + } + + /** + * Gets the value of renderThreadCpu . + * + * @return the value of renderThreadCpu . + */ + public long getRenderThreadCpu() { + return renderThreadCpu; + } + + /** + * Sets the renderThreadCpu . + *

You can use getRenderThreadCpu() to get the value of renderThreadCpu.

+ * + * @param param . + */ + public void setRenderThreadCpu(final long param) { + this.renderThreadCpu = param; + } + + /** + * Gets the value of total . + * + * @return the value of total . + */ + public long getTotal() { + return total; + } + + /** + * Sets the total . + *

You can use getTotal() to get the value of total.

+ * + * @param param . + */ + public void setTotal(final long param) { + this.total = param; + } + + /** + * setRenderList + * + * @return List of Func + */ + public List getRenderList() { + return renderList; + } + + /** + * setRenderList + * + * @param renderList renderList + */ + public void setRenderList(final List renderList) { + this.renderList = renderList; + long renderTotal = renderList.stream().filter( + func -> !(startNs <= func.getStartTs() && (startNs + dur) >= (func.getStartTs() + func.getDur()))) + .mapToLong(Func::getDur).sum(); + if (renderTotal > 0) { + long renderRuning = renderList.stream().mapToLong(Func::getRunning).sum(); + total = dur + renderTotal; + renderThreadWall = renderTotal; + renderThreadCpu = renderRuning; + } + } + + @Override + public void draw(Graphics2D graphics) { + if (isMouseIn) { + Common.setAlpha(graphics, 0.7F); + } else { + Common.setAlpha(graphics, 1.0F); + } + if (TimeUnit.NANOSECONDS.toMillis(total) >= ONE_FRAME_TIME) { + graphics.setColor(JBUI.CurrentTheme.Label.foreground()); + Common.drawStringCenter(graphics, TimeUtils.getTimeWithUnit(total), rect); + graphics.setColor(JBUI.CurrentTheme.Validator.errorBackgroundColor()); + } else { + graphics.setColor(JBUI.CurrentTheme.Label.foreground()); + } + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + Common.setAlpha(graphics, 1.0F); + } + + @Override + public List getStringList(String time) { + if (renderThreadWall == 0L && renderThreadCpu == 0L) { + return Arrays.asList(time, + "Main Thread", + "CPU Time: " + TimeUtils.getTimeWithUnit(mainThreadCpu), + "Wall Time: " + TimeUtils.getTimeWithUnit(mainThreadWall)); + } else { + return Arrays.asList(time, + "Total Time: " + TimeUtils.getTimeWithUnit(total), + "", + "Main Thread", "CPU Time: " + TimeUtils.getTimeWithUnit(mainThreadCpu), + "Wall Time: " + TimeUtils.getTimeWithUnit(mainThreadWall), + "", + "Render Thread", + "CPU Time: " + TimeUtils.getTimeWithUnit(renderThreadCpu), + "Wall Time: " + TimeUtils.getTimeWithUnit(renderThreadWall)); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Func.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Func.java new file mode 100644 index 000000000..e06617300 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Func.java @@ -0,0 +1,458 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.EventDispatcher; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.util.Arrays; +import java.util.List; + +/** + * Func + * + * @date: 2021/5/20 15:24 + */ +public class Func extends AppFunc { + /** + * parent blood id + */ + protected String parentBloodId = ""; + @DField(name = "stack_id") private long stackId; + @DField(name = "parent_stack_id") private long parentStackId; + @DField(name = "id") private Integer id; + @DField(name = "parent_id") private Integer parentId; + @DField(name = "is_main_thread") private Integer isMainThread; + @DField(name = "track_id") private Integer trackId; + @DField(name = "funName") private String funcName = ""; + @DField(name = "tid") private Integer tid; + @DField(name = "depth") private Integer depth = 0; + @DField(name = "threadName") private String threadName = ""; + @DField(name = "startTs") private long startTs; + @DField(name = "dur") private long dur; + private String category; + private long running; + private long idle; + private boolean isSelected; // Whether to be selected + + /** + * Gets the value of parentStackId . + * + * @return the value of int + */ + public long getParentStackId() { + return parentStackId; + } + + /** + * Sets the parentStackId . + *

You can use getParentStackId() to get the value of parentStackId

+ * + * @param parentStackId parentStackId + */ + public void setParentStackId(long parentStackId) { + this.parentStackId = parentStackId; + } + + /** + * Gets the value of stackId . + * + * @return the value of int + */ + public long getStackId() { + return stackId; + } + + /** + * Sets the stackId . + *

You can use getStackId() to get the value of stackId

+ * + * @param stackId stackId + */ + public void setStackId(Integer stackId) { + this.stackId = stackId; + } + + /** + * Gets the value of id . + * + * @return the value of int + */ + public Integer getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id

+ * + * @param id id + */ + public void setId(Integer id) { + this.id = id; + } + + /** + * Gets the value of parentId . + * + * @return the value of int + */ + public Integer getParentId() { + return parentId; + } + + /** + * Sets the parentId . + *

You can use getParentId() to get the value of parentId

+ * + * @param parentId parentId + */ + public void setParentId(Integer parentId) { + this.parentId = parentId; + } + + /** + * Gets the value of isMainThread . + * + * @return the value of int + */ + public Integer getIsMainThread() { + return isMainThread; + } + + /** + * Sets the isMainThread . + *

You can use getIsMainThread() to get the value of isMainThread

+ * + * @param mainThread mainThread + */ + public void setIsMainThread(final Integer mainThread) { + this.isMainThread = mainThread; + } + + /** + * Gets the value of trackId . + * + * @return the value of int + */ + public Integer getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId

+ * + * @param id id + */ + public void setTrackId(final Integer id) { + this.trackId = id; + } + + /** + * Gets the value of category . + * + * @return the value of java.lang.String + */ + public String getCategory() { + return category; + } + + /** + * Sets the category . + *

You can use getCategory() to get the value of category

+ * + * @param cate cate + */ + public void setCategory(final String cate) { + this.category = cate; + } + + /** + * Gets the value of isSelected . + * + * @return the value of boolean + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the isSelected . + *

You can use getSelected() to get the value of isSelected

+ * + * @param selected selected + */ + public void setSelected(final boolean selected) { + this.isSelected = selected; + } + + /** + * get depth + * + * @return depth + */ + public Integer getDepth() { + return depth; + } + + /** + * Set the depth . + * + * @param depth depth + */ + public void setDepth(final Integer depth) { + this.depth = depth; + } + + /** + * get the thread name + * + * @return thread name + */ + public String getThreadName() { + return threadName; + } + + /** + * set the thread name + * + * @param threadName thread name + */ + public void setThreadName(final String threadName) { + this.threadName = threadName; + } + + /** + * get start time + * + * @return start time + */ + public long getStartTs() { + return startTs; + } + + /** + * set start ts + * + * @param startTs start ts + */ + public void setStartTs(final long startTs) { + this.startTs = startTs; + } + + /** + * get parent blood id + * + * @return parent blood id + */ + public String getParentBloodId() { + return parentBloodId; + } + + /** + * set the parent blood id + * + * @param parentBloodId parent blood id + */ + public void setParentBloodId(final String parentBloodId) { + this.parentBloodId = parentBloodId; + } + + /** + * get the endTs + * + * @return endTs endTs + */ + public long getEndTs() { + return endTs; + } + + /** + * set the endTs + * + * @param endTs endTs + */ + public void setEndTs(final long endTs) { + this.endTs = endTs; + dur = endTs - startTs; + } + + /** + * get the funcName + * + * @return funcName funcName + */ + public String getFuncName() { + return funcName; + } + + /** + * set the funcName + * + * @param funcName funcName + */ + public void setFuncName(final String funcName) { + this.funcName = funcName; + } + + /** + * get duration + * + * @return duration + */ + public long getDur() { + return dur; + } + + /** + * set duration + * + * @param dur duration + */ + public void setDur(final long dur) { + this.dur = dur; + } + + /** + * get thread id + * + * @return thread id + */ + public Integer getTid() { + return tid; + } + + /** + * set thread id + * + * @param tid thread id + */ + public void setTid(final Integer tid) { + this.tid = tid; + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (depth == -1) { + return; + } + if (isMouseIn) { + Common.setAlpha(graphics, 0.7F); + } else { + Common.setAlpha(graphics, 1.0F); + } + if (isSelected) { + graphics.setColor(Color.black); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); + graphics.fillRect(Utils.getX(rect) + 1, Utils.getY(rect) + 1, rect.width - 2, rect.height - 2); + graphics.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + 1, rect.getY() + 1, rect.getWidth() - 2, rect.getHeight() - 2); + Common.drawStringCenter(graphics, funcName, rectangle); + } else { + graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(Color.white); + Common.drawStringCenter(graphics, funcName, rect); + } + Common.setAlpha(graphics, 1.0F); + } + + @Override + public List getStringList(final String time) { + return Arrays.asList( + time, + "" + getFuncName(), + "Running: " + TimeUtils.getTimeWithUnit(running), + "Idle: " + TimeUtils.getTimeWithUnit(idle), + "Total: " + TimeUtils.getTimeWithUnit(dur) + ); + } + + /** + * create StackId by parentStackId、funcName and depth + */ + @Override + public void createBloodId() { + if (depth == 0) { + bloodId = Utils.md5String(threadName + funcName + depth); + parentBloodId = Utils.md5String(threadName); + } else { + bloodId = Utils.md5String(parentBloodId + funcName + depth); + } + } + + /** + * Gets the value of idle . + * + * @return the value of long + */ + public long getIdle() { + return idle; + } + + /** + * Sets the setIdle . + *

You can use setIdle() to get the value of setIdle

+ * + * @param idle idle + */ + public void setIdle(final long idle) { + this.idle = idle; + running = dur - idle; + } + + /** + * get running time + * + * @return running time + */ + public long getRunning() { + return running; + } + + /** + * set running time + * + * @param running running time + */ + public void setRunning(final long running) { + this.running = running; + } + + @Override + public void onClick(MouseEvent event) { + super.onClick(event); + if (depth != -1) { + EventDispatcher.dispatcherClickListener(this); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Thread.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Thread.java new file mode 100644 index 000000000..b708e3bfc --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/Thread.java @@ -0,0 +1,365 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import ohos.devtools.views.applicationtrace.AllData; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.TracePanel; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.util.Arrays; +import java.util.List; + +import static ohos.devtools.views.trace.TracePanel.root; + +/** + * Thread + * + * @date: 2021/5/17 12:25 + */ +public class Thread extends AbstractNode { + private static Color runningColor = new Color(Final.RUNNING_COLOR); + private static Color rColor = new Color(Final.R_COLOR); + private static Color uninterruptibleSleepColor = new Color(Final.UNINTERRUPTIBLE_SLEEP_COLOR); + private static Color exitColor = new Color(Final.EXIT_COLOR); + private static Color sColor = new Color(Final.S_COLOR); + private final Integer padding1 = 5; + private final Integer padding2 = 10; + private final float alpha2 = 0.02f; + @DField(name = "upid") private Integer uPid; + @DField(name = "utid") private Integer uTid; + @DField(name = "pid") private Integer pid; // Process id + @DField(name = "tid") private Integer tid; // Thread id + @DField(name = "processName") private String processName; + @DField(name = "threadName") private String threadName; + @DField(name = "state") private String state; + @DField(name = "startTime") private Long startTime; + @DField(name = "dur") private Long duration; + @DField(name = "cpu") private Integer cpu; + private boolean isSelected; // Whether to be selected + + /** + * Gets the value of uPid . + * + * @return the value of uPid . + */ + public Integer getuPid() { + return uPid; + } + + /** + * Sets the uPid .You can use getuPid() to get the value of uPid. + * + * @param param param. + */ + public void setuPid(final Integer param) { + this.uPid = param; + } + + /** + * Gets the value of uTid . + * + * @return the value of uTid . + */ + public Integer getuTid() { + return uTid; + } + + /** + * Sets the uTid . You can use getuTid() to get the value of uTid.

+ * + * @param param param + */ + public void setuTid(final Integer param) { + this.uTid = param; + } + + /** + * Gets the value of pid . + * + * @return the value of pid . + */ + public Integer getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid.

+ * + * @param param param + */ + public void setPid(final Integer param) { + this.pid = param; + } + + /** + * Gets the value of tid . + * + * @return the value of tid . + */ + public Integer getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid.

+ * + * @param param param + */ + public void setTid(final Integer param) { + this.tid = param; + } + + /** + * Gets the value of processName . + * + * @return the value of processName . + */ + public String getProcessName() { + return processName; + } + + /** + * Sets the processName . + *

You can use getProcessName() to get the value of processName.

+ * + * @param param param + */ + public void setProcessName(final String param) { + this.processName = param; + } + + /** + * Gets the value of threadName . + * + * @return the value of threadName . + */ + public String getThreadName() { + return threadName; + } + + /** + * Sets the threadName . + *

You can use getThreadName() to get the value of threadName.

+ * + * @param param param + */ + public void setThreadName(final String param) { + this.threadName = param; + } + + /** + * Gets the value of state . + * + * @return the value of state . + */ + public String getState() { + return state; + } + + /** + * Sets the state . + *

You can use getState() to get the value of state.

+ * + * @param param param + */ + public void setState(final String param) { + this.state = param; + } + + /** + * Gets the value of startTime . + * + * @return the value of startTime . + */ + public Long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime.

+ * + * @param param param + */ + public void setStartTime(final Long param) { + this.startTime = param; + } + + /** + * Gets the value of duration . + * + * @return the value of duration . + */ + public Long getDuration() { + if (duration == -1) { + duration = TracePanel.DURATION - startTime; + } + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration.

+ * + * @param param param + */ + public void setDuration(final Long param) { + this.duration = param; + } + + /** + * Gets the value of cpu . + * + * @return the value of cpu . + */ + public Integer getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu.

+ * + * @param param param + */ + public void setCpu(final Integer param) { + this.cpu = param; + } + + /** + * Sets the isSelected .You can use getSelected() to get the value of isSelected. + * + * @param param param + */ + public void select(final boolean param) { + isSelected = param; + } + + /** + * repaint. + */ + public void repaint() { + root.repaint(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + } + + /** + * Draw the corresponding shape according to the brush + * + * @param paint graphics + */ + @Override + public void draw(Graphics2D paint) { + if (isMouseIn) { + Common.setAlpha(paint, 0.7F); + } else { + Common.setAlpha(paint, 1.0F); + } + paint.setFont(paint.getFont().deriveFont(9f)); + if (isSelected && !"S".equals(state)) { + paint.setColor(Color.BLACK); + paint.fillRect(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + drawSelected(paint); + } else { + drawUnSelected(paint); + } + paint.setFont(paint.getFont().deriveFont(12f)); + Common.setAlpha(paint, 1.0F); + } + + private void drawSelected(final Graphics2D paint) { + if ("S".equals(state)) { + paint.setColor(sColor); + Common.setAlpha(paint, alpha2); // transparency + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + Common.setAlpha(paint, 1f); // transparency + } else if ("R".equals(state) || "R+".equals(state)) { + paint.setColor(rColor); + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } else if ("D".equals(state)) { + paint.setColor(uninterruptibleSleepColor); + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } else if ("Running".equals(state)) { + paint.setColor(runningColor); + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + paint.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); + Common.drawStringCenter(paint, Utils.getEndState(state), rectangle); + } else { + paint.setColor(exitColor); + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + paint.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); + Common.drawStringCenter(paint, Utils.getEndState(state), rectangle); + } + } + + private void drawUnSelected(final Graphics2D paint) { + if ("S".equals(state)) { + paint.setColor(sColor); + Common.setAlpha(paint, alpha2); // transparency + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + Common.setAlpha(paint, 1f); // transparency + } else if ("R".equals(state)) { + paint.setColor(rColor); + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } else if ("D".equals(state)) { + paint.setColor(uninterruptibleSleepColor); + paint.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } else if ("Running".equals(state)) { + paint.setColor(runningColor); + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } else { + paint.setColor(exitColor); + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + paint.setColor(Color.white); + Common.drawStringCenter(paint, Utils.getEndState(state), rect); + } + } + + @Override + public List getStringList(String time) { + return Arrays.asList(time, + "Thread: " + (threadName == null || threadName.isEmpty() ? AllData.threadNames.get(tid) : threadName), + Utils.getEndState(state), TimeUtils.getTimeWithUnit(duration)); + } + + @Override + public void onClick(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/ThreadStateBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/ThreadStateBean.java new file mode 100644 index 000000000..45bce3e33 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/ThreadStateBean.java @@ -0,0 +1,104 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +/** + * Tab Thread States + * + * @date 2021/04/20 12:12 + */ +public class ThreadStateBean { + private String state; + private String duration; + private String percent; + private String occurrences; + + /** + * Gets the value of state . + * + * @return the value of state . + */ + public String getState() { + return state; + } + + /** + * Sets the state . + *

You can use getState() to get the value of state.

+ * + * @param param . + */ + public void setState(final String param) { + this.state = param; + } + + /** + * Gets the value of duration . + * + * @return the value of duration . + */ + public String getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration.

+ * + * @param param . + */ + public void setDuration(final String param) { + this.duration = param; + } + + /** + * Gets the value of percent . + * + * @return the value of percent . + */ + public String getPercent() { + return percent; + } + + /** + * Sets the percent . + *

You can use getPercent() to get the value of percent.

+ * + * @param param . + */ + public void setPercent(final String param) { + this.percent = param; + } + + /** + * Gets the value of occurrences . + * + * @return the value of occurrences . + */ + public String getOccurrences() { + return occurrences; + } + + /** + * Sets the occurrences . + *

You can use getOccurrences() to get the value of occurrences.

+ * + * @param param . + */ + public void setOccurrences(final String param) { + this.occurrences = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeNodeToTree.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeNodeToTree.java new file mode 100644 index 000000000..16c503df4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeNodeToTree.java @@ -0,0 +1,78 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * tree node to tree + * + * @param data type + */ +public abstract class TreeNodeToTree { + /** + * get key + * + * @param node node + * @return key + */ + protected abstract String getKey(T node); + + /** + * get parent node id + * + * @param node node + * @return parent id + */ + protected abstract String getParentId(T node); + + /** + * add childes + * + * @param node node + * @param parent parent node + */ + protected abstract void addChildrens(T node, T parent); + + /** + * add root node + * + * @param node root node + */ + protected abstract void addRootNode(T node); + + /** + * list to tree + * + * @param list data list + */ + public void listToTree(List list) { + Map newMap = new HashMap<>(); + for (T tree : list) { + newMap.put(getKey(tree), tree); + } + for (T tree : list) { + T parent = newMap.get(getParentId(tree)); + if (parent != null) { + addChildrens(tree, parent); + } else { + addRootNode(tree); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeTableBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeTableBean.java new file mode 100644 index 000000000..b832edf13 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/TreeTableBean.java @@ -0,0 +1,478 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import com.intellij.ui.JBColor; +import ohos.devtools.views.applicationtrace.DataPanel; +import ohos.devtools.views.applicationtrace.analysis.AnalysisEnum; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * TreeTableBean + * + * @version 1.0 + * @date: 2021/5/26 15:38 + */ +public class TreeTableBean extends AbstractNode { + /** + * PERF_FLAME_VENDOR color + */ + public static final Color PERF_FLAME_VENDOR = new JBColor(0xFFC56F, 0xFFC56F); + + private static final int PADDING_LEFT = 5; + private static final int PADDING_RIGHT = 5; + private long stackId; + private long parentStackId; + private String prefStackId; + private String prefParentStackId; + private String name; + private String total; + private long totalNum = 0; + private double totalPercentNum = 0; + private long selfNum = 0; + private String selfPercent = "0"; + private double selfPercentNum = 0; + private long childrenNum = 0; + private double childrenPercentNum = 0; + private long childrenNS; + private String childrenPercent; + private boolean isUserWrite = false; + private int containType = 0; // 0 OK 1 There are keywords 2 children there are keywords 3 there are no keywords + private List childrens = new ArrayList<>(); + private long threadDur = 0; + + /** + * constructor + */ + public TreeTableBean() { + this(0); + } + + /** + * constructor + * + * @param threadDur duration + */ + public TreeTableBean(final long threadDur) { + this.threadDur = threadDur; + } + + /** + * set current time + * + * @param timeBean timeBean + */ + public void setTime(TreeTableBean timeBean) { + setTotalNum(timeBean.getTotalNum()); + setSelfNum(timeBean.getTotalNum()); + setChildrenNum(timeBean.getSelfNum()); + } + + /** + * merge current time + * + * @param timeBean timeBean + */ + public void mergeTime(TreeTableBean timeBean) { + setTotalNum(getTotalNum() + timeBean.getTotalNum()); + setSelfNum(getSelfNum() + timeBean.getTotalNum()); + setChildrenNum(getChildrenNum() + timeBean.getSelfNum()); + } + + /** + * get pref stack id + * + * @return id + */ + public String getPrefStackId() { + return prefStackId; + } + + /** + * set stack id + * + * @param param stack id + */ + public void setPrefStackId(final String param) { + this.prefStackId = param; + } + + /** + * get parent stack id + * + * @return id + */ + public String getPrefParentStackId() { + return prefParentStackId; + } + + /** + * set parent stack id + * + * @param param id + */ + public void setPrefParentStackId(final String param) { + this.prefParentStackId = param; + } + + /** + * is user write + * + * @return boolean + */ + public boolean isUserWrite() { + return isUserWrite; + } + + /** + * set user write + * + * @param param user write + */ + public void setUserWrite(final boolean param) { + isUserWrite = param; + } + + /** + * get contain type + * + * @return type + */ + public int getContainType() { + return containType; + } + + /** + * set contain type + * + * @param param type + */ + public void setContainType(final int param) { + this.containType = param; + } + + /** + * get thread duration + * + * @return duration + */ + public long getThreadDur() { + return threadDur; + } + + /** + * set thread duration + * 此方法需要在set total children self之前设置 否则百分数数据不会计算 + * + * @param param duration + */ + public void setThreadDur(final long param) { + this.threadDur = param; + } + + /** + * get total percent + * + * @return percent + */ + public double getTotalPercentNum() { + return totalPercentNum; + } + + /** + * get self percent + * + * @return percent + */ + public double getSelfPercentNum() { + return selfPercentNum; + } + + /** + * get child percent + * + * @return percent + */ + public double getChildrenPercentNum() { + return childrenPercentNum; + } + + /** + * get total num + * + * @return num + */ + public long getTotalNum() { + return totalNum; + } + + /** + * set total num + * + * @param param num + */ + public void setTotalNum(final long param) { + this.totalNum = param; + if (threadDur != 0) { + totalPercentNum = param * 1.0 / threadDur * 100; + } + } + + /** + * get self num + * + * @return num + */ + public long getSelfNum() { + return selfNum; + } + + /** + * set self num + * + * @param param num + */ + public void setSelfNum(final long param) { + this.selfNum = param; + if (threadDur != 0) { + selfPercentNum = param * 1.0 / threadDur * 100; + } + } + + /** + * get child num + * + * @return num + */ + public long getChildrenNum() { + return childrenNum; + } + + /** + * set children num + * + * @param param num + */ + public void setChildrenNum(final long param) { + this.childrenNum = param; + if (threadDur != 0) { + childrenPercentNum = param * 1.0 / threadDur * 100; + } + } + + /** + * get children + * + * @return children list + */ + public List getChildrens() { + return childrens; + } + + /** + * set children list + * + * @param param list + */ + public void setChildrens(final List param) { + this.childrens = param; + } + + /** + * Gets the value of childrenNS . + * + * @return the value of long + */ + public long getChildrenNS() { + return childrenNS; + } + + /** + * Sets the childrenNS . + *

You can use getChildrenNS() to get the value of childrenNS

+ * + * @param param childrenNS + */ + public void setChildrenNS(final long param) { + this.childrenNS = param; + } + + /** + * get total + * + * @return total + */ + public String getTotal() { + return total; + } + + /** + * set total + * + * @param param total + */ + public void setTotal(final String param) { + this.total = param; + } + + /** + * get name + * + * @return name + */ + public String getName() { + return name; + } + + /** + * set name + * + * @param param name + */ + public void setName(final String param) { + this.name = param; + } + + /** + * Gets the value of stackId . + * + * @return the value of java.lang.Integer + */ + public long getStackId() { + return stackId; + } + + /** + * Sets the stackId . + *

You can use getStackId() to get the value of stackId

+ * + * @param param id + */ + public void setStackId(final long param) { + this.stackId = param; + } + + /** + * Gets the value of parentStackId . + * + * @return the value of java.lang.Integer + */ + public long getParentStackId() { + return parentStackId; + } + + /** + * Sets the parentStackId . + *

You can use getParentStackId() to get the value of parentStackId

+ * + * @param param id + */ + public void setParentStackId(final long param) { + this.parentStackId = param; + } + + /** + * get the self percent + * + * @return percent + */ + public String getSelfPercent() { + return selfPercent; + } + + /** + * set self percent + * + * @param param percent + */ + public void setSelfPercent(final String param) { + this.selfPercent = param; + } + + /** + * get children percent + * + * @return percent + */ + public String getChildrenPercent() { + return childrenPercent; + } + + /** + * set children percent + * + * @param param percent + */ + public void setChildrenPercent(final String param) { + this.childrenPercent = param; + } + + @Override + public String toString() { + return name; + } + + @Override + public void draw(Graphics2D paint) { + if (containType == 3) { + Common.setAlpha(paint, 0.2F); + } else { + if (isMouseIn) { + Common.setAlpha(paint, 0.7F); + } else { + Common.setAlpha(paint, 1.0F); + } + } + if (DataPanel.analysisEnum.equals(AnalysisEnum.APP)) { + paint.setColor(PERF_FLAME_VENDOR); + } + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + if (rect.width > 1) { + paint.setColor(JBColor.background().darker()); + paint.drawRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + } + Common.setAlpha(paint, 1.0f); + if (containType == 1) { + paint.setFont(new Font(Final.FONT_NAME, Font.BOLD, Final.NORMAL_FONT_SIZE)); + } else { + paint.setFont(new Font(Final.FONT_NAME, Font.PLAIN, Final.NORMAL_FONT_SIZE)); + } + Common.drawStringMiddleHeight(paint, name, + new Rectangle(Utils.getX(rect) + PADDING_LEFT, Utils.getY(rect), rect.width - PADDING_LEFT - PADDING_RIGHT, + rect.height)); + } + + @Override + public List getStringList(String time) { + return Arrays.asList( + "" + getName(), + "", + "Total: " + TimeUtils.getTimeWithUnit(totalNum * 1000) + ); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/VsyncAppBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/VsyncAppBean.java new file mode 100644 index 000000000..8057d3a5a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/bean/VsyncAppBean.java @@ -0,0 +1,181 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.bean; + +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.List; + +/** + * VsyncAppBean + * + * @version 1.0 + * @date: 2021/5/26 15:38 + */ +public class VsyncAppBean extends AbstractNode { + @DField(name = "id") + private Integer id; + @DField(name = "type") + private String type; + @DField(name = "track_id") + private Integer trackId; + @DField(name = "value") + private Double value; + @DField(name = "startTime") + private Long startTime; + private Long duration; + + /** + * Gets the value of duration . + * + * @return the value of java.lang.Long + */ + public Long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param dur duration + */ + public void setDuration(final Long dur) { + this.duration = dur; + } + + /** + * Gets the value of id . + * + * @return the value of java.lang.Integer + */ + public Integer getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id

+ * + * @param param id + */ + public void setId(final Integer param) { + this.id = param; + } + + /** + * Gets the value of type . + * + * @return the value of java.lang.String + */ + public String getType() { + return type; + } + + /** + * Sets the type . + *

You can use getType() to get the value of type

+ * + * @param param type + */ + public void setType(final String param) { + this.type = param; + } + + /** + * Gets the value of trackId . + * + * @return the value of java.lang.Integer + */ + public Integer getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId

+ * + * @param param track id + */ + public void setTrackId(final Integer param) { + this.trackId = param; + } + + /** + * Gets the value of value . + * + * @return the value of java.lang.Double + */ + public Double getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param param value + */ + public void setValue(final Double param) { + this.value = param; + } + + /** + * Gets the value of startTime . + * + * @return the value of java.lang.Integer + */ + public Long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param param start time + */ + public void setStartTime(final Long param) { + this.startTime = param; + } + + @Override + public void draw(Graphics2D paint) { + paint.setColor(JBUI.CurrentTheme.Link.linkColor().brighter()); + if (value == 0) { + paint.drawLine(Utils.getX(rect), Utils.getY(rect) + rect.height - 1, Utils.getX(rect) + rect.width, + Utils.getY(rect) + rect.height - 1); + } else { + paint.drawLine(Utils.getX(rect), Utils.getY(rect), Utils.getX(rect), Utils.getY(rect) + rect.height - 1); + paint.drawLine(Utils.getX(rect), Utils.getY(rect), Utils.getX(rect) + rect.width, Utils.getY(rect)); + paint.drawLine(Utils.getX(rect) + rect.width, Utils.getY(rect), Utils.getX(rect) + rect.width, + Utils.getY(rect) + rect.height - 1); + } + } + + @Override + public List getStringList(String time) { + return Arrays.asList( + time, + "Value: " + value.intValue() + ); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IAllThreadDataListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IAllThreadDataListener.java new file mode 100644 index 000000000..956a46663 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IAllThreadDataListener.java @@ -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. + */ + +package ohos.devtools.views.applicationtrace.listener; + +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.List; + +/** + * interface all thread listener + * + * @date: 2021/5/27 12:01 + */ +public interface IAllThreadDataListener { + /** + * getAllThreadData Calllback + * + * @param startNS start time + * @param endNS end time + * @param scale scale level + * @return List tree node + */ + List getAllThreadData(long startNS, long endNS, long scale); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherFunctionDataListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherFunctionDataListener.java new file mode 100644 index 000000000..afc783d8d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherFunctionDataListener.java @@ -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. + */ + +package ohos.devtools.views.applicationtrace.listener; + +import ohos.devtools.views.applicationtrace.bean.Func; + +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.List; + +/** + * interface other function data listener + * + * @date: 2021/5/27 12:01 + */ +public interface IOtherFunctionDataListener { + /** + * getOtherFunctionData Callback + * + * @param func function + * @return List tree node + */ + List getOtherFunctionData(T func); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherThreadDataListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherThreadDataListener.java new file mode 100644 index 000000000..628a79ec4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/IOtherThreadDataListener.java @@ -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. + */ + +package ohos.devtools.views.applicationtrace.listener; + +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.List; + +/** + * interface other thread listener + * + * @date: 2021/5/27 12:01 + */ +public interface IOtherThreadDataListener { + /** + * getOtherThreadData Callback + * + * @param startNS start time + * @param endNS end time + * @param threadIds thread id + * @return tree node + */ + List getOtherThreadData(long startNS, long endNS, List threadIds); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ProfilerMonitorItem.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/ITreeTableSortChangeListener.java similarity index 60% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/ProfilerMonitorItem.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/ITreeTableSortChangeListener.java index d66173d9e..0b9b6cae0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ProfilerMonitorItem.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/listener/ITreeTableSortChangeListener.java @@ -1,35 +1,33 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common; - -/** - * Profiler的监控项 - * - * @since 2021/2/26 9:41 - */ -public enum ProfilerMonitorItem { - CPU("Cpu"), MEMORY("Memory"), NETWORK("Network"), ENERGY("Energy"), DISK_IO("DiskIO"), UNRECOGNIZED("Unrecognized"); - - private final String name; - - ProfilerMonitorItem(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.listener; + +import javax.swing.SortOrder; + +/** + * interface tree table sort change listener + * + * @date: 2021/5/27 12:01 + */ +public interface ITreeTableSortChangeListener { + /** + * sort Callback + * + * @param columns table column index + * @param sortOrder type of sort + */ + void reSort(int columns, SortOrder sortOrder); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/MathUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/MathUtils.java new file mode 100644 index 000000000..46ee20a00 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/MathUtils.java @@ -0,0 +1,62 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.util; + +import java.util.List; + +/** + * The MathUtils + * + * @date 2021/04/22 12:25 + */ +public class MathUtils { + /** + * Incoming a series x calculates the average + * + * @param doubles List calculates x + * @return average value + */ + public static double average(List doubles) { + int size = doubles.size(); // The number of column elements + double sum = doubles.stream().mapToDouble(it -> it).sum(); + return sum / size; + } + + /** + * Pass in a series x to calculate variance + * Variance s^2=[(x1-x)^2+(x2-x)^2+......(xn-x)^2]/(n) (x is average) + * + * @param doubles List The number of columns to calculate + * @return variance variance + */ + public static double variance(List doubles) { + int size = doubles.size(); // The number of column elements + double avg = average(doubles); // Average + double varianceD = doubles.stream().mapToDouble(it -> (it - avg) * (it + avg)).sum(); + return varianceD / size; + } + + /** + * Pass in a number of columns x to calculate the standard deviation + * The standard deviation σ sqrt (s)2), which is the square root of the standard deviation s/a variance + * + * @param doubles List The number of columns to calculate + * @return standard deviation + */ + public static double standardDiviation(List doubles) { + return Math.sqrt(variance(doubles)); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/TimeUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/TimeUtils.java new file mode 100644 index 000000000..05f7e4647 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/applicationtrace/util/TimeUtils.java @@ -0,0 +1,298 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace.util; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static java.math.BigDecimal.ROUND_HALF_UP; + +/** + * TimeUtils + * + * @date: 2021/5/13 13:06 + */ +public class TimeUtils { + /** + * getTimeWithUnit function + * + * @param nsL nsL + * @return String time + */ + public static String getTimeWithUnit(final long nsL) { + long ns = nsL; + StringBuilder time = new StringBuilder(); + long hours = TimeUnit.NANOSECONDS.toHours(ns); + if (hours > 1) { + time.append(hours).append("h"); + return time.toString(); + } + long minute = TimeUnit.NANOSECONDS.toMinutes(ns); + long second; + if (minute > 0) { + ns = ns - TimeUnit.MINUTES.toNanos(minute); + long longTime = TimeUnit.NANOSECONDS.toMillis(ns); + BigDecimal value = new BigDecimal(longTime) + .divide(new BigDecimal(6D), 0, ROUND_HALF_UP).multiply(new BigDecimal(10)); + second = value.longValue(); + time.append(minute).append(".").append(String.format(Locale.ENGLISH, "%02d", second)).append("m"); + return time.toString(); + } + long millis; + second = TimeUnit.NANOSECONDS.toSeconds(ns); + if (second > 0) { + ns = ns - TimeUnit.SECONDS.toNanos(second); + long longTime = TimeUnit.NANOSECONDS.toMillis(ns); + BigDecimal divide = new BigDecimal(longTime).divide(new BigDecimal(10D), 0, ROUND_HALF_UP); + millis = divide.longValue(); + time.append(second).append(".").append(String.format(Locale.ENGLISH, "%02d", millis)).append("s"); + return time.toString(); + } + long micros; + millis = TimeUnit.NANOSECONDS.toMillis(ns); + if (millis > 0) { + ns = ns - TimeUnit.MILLISECONDS.toNanos(millis); + long longTime = TimeUnit.NANOSECONDS.toMicros(ns); + BigDecimal divide = new BigDecimal(longTime).divide(new BigDecimal(10D), 0, ROUND_HALF_UP); + micros = divide.longValue(); + time.append(millis).append(".").append(String.format(Locale.ENGLISH, "%02d", micros)).append("ms"); + return time.toString(); + } + micros = TimeUnit.NANOSECONDS.toMicros(ns); + if (micros > 0) { + ns = ns - TimeUnit.MICROSECONDS.toNanos(micros); + BigDecimal divide = new BigDecimal(ns).divide(new BigDecimal(1000D), 0, ROUND_HALF_UP); + long nanos = divide.longValue(); + if (nanos > 0) { + micros++; + } + time.append(micros).append("μs"); + return time.toString(); + } + return "0μs"; + } + + /** + * get the time range is in other range function + * + * @param startNs startNs + * @param endNs endNs + * @param startRNs startRNs + * @param endLNs endLNs + * @return boolean + */ + public static boolean isInRange(long startNs, long endNs, long startRNs, long endLNs) { + return endLNs >= startNs && startRNs <= endNs; + } + + /** + * get the time range is cross function + * + * @param startNs startNs + * @param endNs endNs + * @param startRNs startRNs + * @param endLNs endLNs + * @return boolean + */ + public static boolean isRangeCross(long startNs, long endNs, long startRNs, long endLNs) { + long leftMin = Math.max(startNs, startRNs); + long rightMax = Math.min(endNs, endLNs); + return rightMax > leftMin; + } + + /** + * get the time string format function + * + * @param nsL nsL + * @return String time + */ + public static String getTimeFormatString(final long nsL) { + long ns = nsL; + long hours = TimeUnit.NANOSECONDS.toHours(ns); + ns = ns - TimeUnit.HOURS.toNanos(hours); + long minute = TimeUnit.NANOSECONDS.toMinutes(ns); + ns = ns - TimeUnit.MINUTES.toNanos(minute); + long second = TimeUnit.NANOSECONDS.toSeconds(ns); // second + ns = ns - TimeUnit.SECONDS.toNanos(second); + long millis = TimeUnit.NANOSECONDS.toMillis(ns); + StringBuffer time = new StringBuffer(); + time.append(String.format(Locale.ENGLISH, "%02d", minute)); + time.append(":"); + time.append(String.format(Locale.ENGLISH, "%02d", second)); + time.append("."); + time.append(String.format(Locale.ENGLISH, "%03d", millis)); + return time.toString(); + } + + /** + * get Intersection function + * + * @param fStartNs fStartNs + * @param fEndNs fEndNs + * @param sStartNs sStartNs + * @param sEndNs sEndNs + * @return long time + */ + public static long getIntersection(long fStartNs, long fEndNs, long sStartNs, long sEndNs) { + long leftMin = Math.max(fStartNs, sStartNs); + long rightMax = Math.min(fEndNs, sEndNs); + if (rightMax > leftMin) { + return TimeUnit.NANOSECONDS.toMicros(rightMax) - TimeUnit.NANOSECONDS.toMicros(leftMin); + } + return 0L; + } + + /** + * get Intersection unit nanos function + * + * @param fStartNs fStartNs + * @param fEndNs fEndNs + * @param sStartNs sStartNs + * @param sEndNs sEndNs + * @return long time + */ + public static long getNanoIntersection(long fStartNs, long fEndNs, long sStartNs, long sEndNs) { + long leftMin = Math.max(fStartNs, sStartNs); + long rightMax = Math.min(fEndNs, sEndNs); + if (rightMax > leftMin) { + return rightMax - leftMin; + } + return 0L; + } + + /** + * Get the current formatting time + * + * @param nsL nsL + * @return String + */ + public static String getTimeString(final long nsL) { + long ns = nsL; + long hours = TimeUnit.NANOSECONDS.toHours(ns); + ns = ns - TimeUnit.HOURS.toNanos(hours); + long minutes = TimeUnit.NANOSECONDS.toMinutes(ns); + ns = ns - TimeUnit.MINUTES.toNanos(minutes); + long second = TimeUnit.NANOSECONDS.toSeconds(ns); // second + ns = ns - TimeUnit.SECONDS.toNanos(second); + long millis = TimeUnit.NANOSECONDS.toMillis(ns); // millisecond + ns = ns - TimeUnit.MILLISECONDS.toNanos(millis); + long micros = TimeUnit.NANOSECONDS.toMicros(ns); // microsecond + ns = ns - TimeUnit.MICROSECONDS.toNanos(micros); + List list = new ArrayList<>(); + if (hours > 0) { + list.add(hours + "h"); + } + if (minutes > 0) { + list.add(minutes + "m"); + } + if (second > 0) { + list.add(second + "s"); + } + if (millis > 0) { + list.add(millis + "ms"); + } + if (micros > 0) { + list.add(micros + "μs"); + } + long nanos = ns; + if (nanos > 0) { + list.add(nanos + "ns"); + } + return list.stream().collect(Collectors.joining(" ")); + } + + /** + * get time ns by time string + * + * @param timeStr time string + * @return long + */ + public static long getNSByTimeString(final String timeStr) { + try { + if (timeStr.contains("ns")) { + String timeString = timeStr.replaceAll("ns", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 1); + } else if (timeStr.contains("μs")) { + String timeString = timeStr.replaceAll("μs", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 1000); + } else if (timeStr.contains("ms")) { + String timeString = timeStr.replaceAll("ms", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 1000 * 1000); + } else if (timeStr.contains("s")) { + String timeString = timeStr.replaceAll("s", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 1000 * 1000 * 1000); + } else if (timeStr.contains("m")) { + String timeString = timeStr.replaceAll("m", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 60 * 1000 * 1000 * 1000); + } else if (timeStr.contains("h")) { + String timeString = timeStr.replaceAll("h", ""); + double timeDouble = Double.parseDouble(timeString); + return (long) (timeDouble * 3600 * 1000 * 1000 * 1000); + } else { + return 0; + } + } catch (NumberFormatException e) { + e.printStackTrace(); + return 0; + } + } + + /** + * Get the current formatting time + * + * @param nsL nsL + * @return String + */ + public static String getDistributedTotalTime(final long nsL) { + long ns = nsL; + long hours = TimeUnit.NANOSECONDS.toHours(ns); + ns = ns - TimeUnit.HOURS.toNanos(hours); + long minutes = TimeUnit.NANOSECONDS.toMinutes(ns); + ns = ns - TimeUnit.MINUTES.toNanos(minutes); + long second = TimeUnit.NANOSECONDS.toSeconds(ns); // second + ns = ns - TimeUnit.SECONDS.toNanos(second); + long millis = TimeUnit.NANOSECONDS.toMillis(ns); // millisecond + ns = ns - TimeUnit.MILLISECONDS.toNanos(millis); + long micros = TimeUnit.NANOSECONDS.toMicros(ns); // microsecond + ns = ns - TimeUnit.MICROSECONDS.toNanos(micros); + List list = new ArrayList<>(); + if (hours > 0) { + list.add(hours + ""); + } else { + list.add("00"); + } + if (minutes > 0) { + list.add(minutes + ""); + } else { + list.add("00"); + } + if (second > 0) { + list.add(second + ""); + } else { + list.add("00"); + } + return list.stream().collect(Collectors.joining(":")) + "." + millis; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/FilledLineChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/FilledLineChart.java index 8745653a3..6a0232477 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/FilledLineChart.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/FilledLineChart.java @@ -1,432 +1,202 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts; - -import ohos.devtools.views.charts.model.ChartDataModel; -import ohos.devtools.views.charts.model.ChartLegendColorRect; -import ohos.devtools.views.common.MonitorItemDetail; -import ohos.devtools.views.charts.tooltip.LegendTooltip; -import ohos.devtools.views.charts.tooltip.TooltipItem; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; - -import javax.swing.JComponent; -import javax.swing.JLabel; -import java.awt.Graphics; -import java.awt.Polygon; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import static ohos.devtools.views.charts.model.ChartType.FILLED_LINE; -import static ohos.devtools.views.charts.utils.ChartConstants.INITIAL_VALUE; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_1024; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_2; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_3; -import static ohos.devtools.views.charts.utils.ChartUtils.divide; -import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; -import static ohos.devtools.views.charts.utils.ChartUtils.multiply; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_CODE; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_GRAPHICS; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_JAVA; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_NATIVE; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_OTHERS; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_STACK; - -/** - * 已填充的折线图 - * - * @since 2021/1/27 16:05 - */ -public class FilledLineChart extends ProfilerChart { - private final JLabel total = new JLabel(); - - private final JLabel javaLabel = new JLabel(); - - private final JLabel nativeLabel = new JLabel(); - - private final JLabel graphicsLabel = new JLabel(); - - private final JLabel stackLabel = new JLabel(); - - private final JLabel codeLabel = new JLabel(); - - private final JLabel othersLabel = new JLabel(); - - private final JLabel allocated = new JLabel("-- Allocated:N/A"); - - private final ChartLegendColorRect javaColorRect = new ChartLegendColorRect(); - - private final ChartLegendColorRect nativeColorRect = new ChartLegendColorRect(); - - private final ChartLegendColorRect graphicsColorRect = new ChartLegendColorRect(); - - private final ChartLegendColorRect stackColorRect = new ChartLegendColorRect(); - - private final ChartLegendColorRect codeColorRect = new ChartLegendColorRect(); - - private final ChartLegendColorRect othersColorRect = new ChartLegendColorRect(); - - /** - * 构造函数 - * - * @param bottomPanel 最底层父级面板 - */ - public FilledLineChart(ProfilerChartsView bottomPanel) { - super(bottomPanel); - chartType = FILLED_LINE; - initLegendComponents(); - } - - /** - * 初始化图例 - */ - private void initLegendComponents() { - total.setOpaque(false); - allocated.setOpaque(false); - javaColorRect.setOpaque(false); - javaLabel.setOpaque(false); - nativeColorRect.setOpaque(false); - nativeLabel.setOpaque(false); - graphicsColorRect.setOpaque(false); - graphicsLabel.setOpaque(false); - stackColorRect.setOpaque(false); - stackLabel.setOpaque(false); - codeColorRect.setOpaque(false); - codeLabel.setOpaque(false); - othersColorRect.setOpaque(false); - othersLabel.setOpaque(false); - } - - /** - * 构建图例 - * - * @param lastModels 面板上最右侧的数据 - * @see "图例展示的是面板上最右侧X轴对应的Y值,而非鼠标悬停处" - */ - @Override - protected void buildLegends(List lastModels) { - if (lastModels.size() == 1 && ("Total").equals(lastModels.get(0).getName())) { - buildMonitorViewLegend(lastModels); - } else { - // 否则为二级界面 - buildStageViewLegend(lastModels); - } - } - - /** - * 构造一级界面的图例 - * - * @param models 数据集合 - */ - private void buildMonitorViewLegend(List models) { - if (legends.getComponents().length == 0) { - legends.add(total); - } - BigDecimal totalValue = divide(models.get(0).getValue(), NUM_1024); - total.setText(totalValue + axisLabelY); - } - - /** - * 构造二级界面的图例 - * - * @param models 数据集合 - */ - private void buildStageViewLegend(List models) { - if (legends.getComponents().length == 0) { - addLegendComponents(); - } - // 文本标签 - BigDecimal totalMB = divide(new BigDecimal(getListSum(models, 0)), new BigDecimal(NUM_1024)); - total.setText(String.format(Locale.ENGLISH, "Total:%s%s", totalMB, axisLabelY)); - - Map> allItemLegendMap = initItemLegends(); - models.forEach(model -> parseModelToLegend(model, allItemLegendMap)); - // Map中只剩下没有选择的监控项,需要隐藏 - allItemLegendMap.forEach((item, components) -> components.forEach(component -> component.setVisible(false))); - } - - /** - * 添加Legend组件 - */ - private void addLegendComponents() { - legends.add(total); - legends.add(javaColorRect); - legends.add(javaLabel); - legends.add(nativeColorRect); - legends.add(nativeLabel); - legends.add(graphicsColorRect); - legends.add(graphicsLabel); - legends.add(stackColorRect); - legends.add(stackLabel); - legends.add(codeColorRect); - legends.add(codeLabel); - legends.add(othersColorRect); - legends.add(othersLabel); - legends.add(allocated); - } - - /** - * 初始化一个全量的内存图例的Map - * - * @return Map<监控项, 对应的图例组件> - */ - private Map> initItemLegends() { - Map> map = new HashMap<>(); - map.put(MEM_JAVA, Arrays.asList(javaColorRect, javaLabel)); - map.put(MEM_NATIVE, Arrays.asList(nativeColorRect, nativeLabel)); - map.put(MEM_GRAPHICS, Arrays.asList(graphicsColorRect, graphicsLabel)); - map.put(MEM_STACK, Arrays.asList(stackColorRect, stackLabel)); - map.put(MEM_CODE, Arrays.asList(codeColorRect, codeLabel)); - map.put(MEM_OTHERS, Arrays.asList(othersColorRect, othersLabel)); - return map; - } - - /** - * 处理数据,转化为图例 - * - * @param model 数据 - * @param allItemLegendMap 内存图例的Map - */ - private void parseModelToLegend(ChartDataModel model, Map> allItemLegendMap) { - MonitorItemDetail item = MonitorItemDetail.getItemByName(model.getName()); - switch (item) { - case MEM_JAVA: - refreshColorText(javaColorRect, javaLabel, model); - // 如果model保存的为当前监控项,则显示其组件 - allItemLegendMap.get(MEM_JAVA).forEach(component -> component.setVisible(true)); - // 组件设置为显示后,从Map中移除,循环完成后,Map中就只剩下没有选择的监控项,需要隐藏 - allItemLegendMap.remove(MEM_JAVA); - break; - case MEM_NATIVE: - refreshColorText(nativeColorRect, nativeLabel, model); - allItemLegendMap.get(MEM_NATIVE).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(MEM_NATIVE); - break; - case MEM_GRAPHICS: - refreshColorText(graphicsColorRect, graphicsLabel, model); - allItemLegendMap.get(MEM_GRAPHICS).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(MEM_GRAPHICS); - break; - case MEM_STACK: - refreshColorText(stackColorRect, stackLabel, model); - allItemLegendMap.get(MEM_STACK).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(MEM_STACK); - break; - case MEM_CODE: - refreshColorText(codeColorRect, codeLabel, model); - allItemLegendMap.get(MEM_CODE).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(MEM_CODE); - break; - case MEM_OTHERS: - refreshColorText(othersColorRect, othersLabel, model); - allItemLegendMap.get(MEM_OTHERS).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(MEM_OTHERS); - break; - default: - break; - } - } - - /** - * 更新图例的颜色和文本 - * - * @param colorRect 图例色块 - * @param label 图例文本标签 - * @param model 数据 - */ - private void refreshColorText(ChartLegendColorRect colorRect, JLabel label, ChartDataModel model) { - // 文本标签 - String showValue = divide(model.getValue(), NUM_1024).toString(); - String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, axisLabelY); - colorRect.setColor(model.getColor()); - if (!label.getText().equals(text)) { - label.setText(text); - } - } - - /** - * 绘制图表 - * - * @param graphics Graphics - */ - @Override - protected void paintChart(Graphics graphics) { - if (dataMap == null || dataMap.size() == 0) { - return; - } - // 循环绘制多条折线 - List lines = dataMap.entrySet().iterator().next().getValue(); - lines.forEach((line) -> paintFilledLine(line.getIndex(), graphics)); - } - - /** - * 绘制填充的折线 - * - * @param index 折线的index - * @param graphics Graphics - * @see "堆叠方式:当前折线的点的y值是所有在当前折线之下的y值之和,y点添加完成后,还要从右向左添加他下面一条线的y点,构成闭合图形" - */ - private void paintFilledLine(int index, Graphics graphics) { - Polygon polygon = new Polygon(); - int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); - // 每条线的颜色是一样的,所以这里只需要获取一次,不需要在下面的Map循环中每次都获取 - graphics.setColor(getCurrentLineColor(index, dataMap.get(timeArray[0]))); - // 堆叠方案:从左向后添加当前index折线的点,然后再从右向左添加next index折线的点 - // 从左向后添加当前index折线的点 - for (int time : timeArray) { - int x = startXCoordinate + multiply(pixelPerX, time - startTime); - // 折线是堆叠方式,y值应该为当前折线的值加上他下面所有折线的值之和 - int sum = getListSum(dataMap.get(time), index); - // 更新Y轴最大值 - if (sum > maxUnitY) { - // 更新y最大值的占用比例 - maxUnitY = divideInt(sum * NUM_3, NUM_2); - } - int y = y0 + multiply(pixelPerY, sum); - polygon.addPoint(x, y); - } - // 绘制辅线 - paintAssistLine(index, polygon, timeArray); - // 使用画笔填充多边形,形成折线 - graphics.fillPolygon(polygon); - } - - private void paintAssistLine(int index, Polygon polygon, int[] timeArray) { - // 如果nextLine不存在,表明index是最后一条线,这直接添加首尾的y0点即可,不需要循环计算所有点 - int nextLineIndex = getNextLineIndex(index, dataMap.get(timeArray[0])); - if (nextLineIndex == INITIAL_VALUE) { - int endX = startXCoordinate + multiply(pixelPerX, timeArray[timeArray.length - 1] - startTime); - int startX = startXCoordinate + multiply(pixelPerX, timeArray[0] - startTime); - polygon.addPoint(endX, y0); - polygon.addPoint(startX, y0); - } else { - // 从右向左添加next index折线的点 - for (int i = timeArray.length - 1; i >= 0; i--) { - // 计算数据在折线图上的X和Y点 - int x = startXCoordinate + multiply(pixelPerX, timeArray[i] - startTime); - // 如果是堆叠方式,y值应该为当前折线的值加上他下面所有折线的值之和 - int sum = getListSum(dataMap.get(timeArray[i]), nextLineIndex); - // 更新Y轴最大值 - if (sum > maxUnitY) { - // 更新y最大值的占用比例 - maxUnitY = divideInt(sum * NUM_3, NUM_2); - } - int y = y0 + multiply(pixelPerY, sum); - polygon.addPoint(x, y); - } - } - } - - /** - * 获取下一条折线的index - * - * @param current 当前折线的index - * @param lineModels 所有折线的数据模型 - * @return 下一条折线的index - */ - private int getNextLineIndex(int current, List lineModels) { - int next = INITIAL_VALUE; - if (lineModels == null || lineModels.isEmpty()) { - return next; - } - int size = lineModels.size(); - for (int index = 0; index < size; index++) { - ChartDataModel lineModel = lineModels.get(index); - int newIndex = index + 1; - if (lineModel.getIndex() == current && newIndex < size) { - next = lineModels.get(index + 1).getIndex(); - break; - } - } - return next; - } - - /** - * 构造悬浮提示框的内容 - * - * @param showKey 要展示的Key - * @param actualKey 实际在数据集合中取值的Key - * @param isNewChart 是否为新Chart - */ - @Override - protected void buildTooltip(int showKey, int actualKey, boolean isNewChart) { - String totalValue = calcTotal(actualKey); - List tooltipItems = buildTooltipItems(actualKey); - LegendTooltip.getInstance().showTip(this, showKey + "", totalValue, tooltipItems, isNewChart); - } - - /** - * 计算某一时间的Total值 - * - * @param time 时间 - * @return Total值 - */ - private String calcTotal(int time) { - List models = dataMap.get(time); - if (models == null || models.size() == 0) { - return ""; - } - // 这里拿到是KB,要转为MB - int value = getListSum(models, 0); - return divide(value, NUM_1024).toString(); - } - - /** - * 构造Tooltip - * - * @param time 当前时间 - * @return List - */ - private List buildTooltipItems(int time) { - List tooltipItems = new ArrayList<>(); - if (dataMap == null || dataMap.size() == 0 || dataMap.get(time) == null) { - return tooltipItems; - } - for (ChartDataModel model : dataMap.get(time)) { - BigDecimal showValue = divide(model.getValue(), NUM_1024); - String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, axisLabelY); - TooltipItem tooltipItem = new TooltipItem(model.getColor(), text); - tooltipItems.add(tooltipItem); - } - return tooltipItems; - } - - /** - * 求集合中指定index之后的所有元素的Value的和 - * - * @param models 数据集合 - * @param index 指定index - * @return int - */ - private int getListSum(List models, int index) { - int sum = 0; - if (index == INITIAL_VALUE || models == null) { - return sum; - } - for (ChartDataModel model : models) { - if (model.getIndex() < index) { - continue; - } - sum += model.getValue(); - } - return sum; - } - -} +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; + +import java.awt.Graphics; +import java.awt.Polygon; +import java.awt.event.MouseEvent; +import java.util.Comparator; +import java.util.List; + +import static ohos.devtools.views.charts.model.ChartType.FILLED_LINE; +import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; +import static ohos.devtools.views.charts.utils.ChartUtils.multiply; +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; + +/** + * Filled line chart + */ +public class FilledLineChart extends ProfilerChart { + private static final int NUM_2 = 2; + private static final int NUM_3 = 3; + + /** + * Do line charts need to be stacked + */ + private final boolean stacked; + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + * @param name chart name + * @param stacked Do line charts need to be stacked + */ + public FilledLineChart(ProfilerChartsView bottomPanel, String name, boolean stacked) { + super(bottomPanel, name); + this.stacked = stacked; + chartType = FILLED_LINE; + } + + /** + * Init legends + */ + @Override + protected void initLegends() { + } + + /** + * Build legends of chart + * + * @param lastModels Data on the far right side of the panel + * @see "The legend shows the y value corresponding to the rightmost X axis, not the mouse hover position" + */ + @Override + protected void buildLegends(List lastModels) { + } + + /** + * Paint chart + * + * @param graphics Graphics + */ + @Override + protected void paintChart(Graphics graphics) { + if (dataMap == null || dataMap.size() == 0) { + return; + } + List lines = dataMap.entrySet().iterator().next().getValue(); + // Sort from small to large according to [index] + lines.sort(Comparator.comparingInt(ChartDataModel::getIndex)); + lines.forEach((line) -> paintFilledLine(line.getIndex(), graphics)); + } + + /** + * Draw filled poly line + * + * @param index index of line chart + * @param graphics Graphics + * @see "Stacked method: the y value of the current broken line point is the sum of all the Y values below + * the current broken line. After the Y point is added, the Y point of the line below it should be added from + * right to left to form a closed figure." + * @see "If line charts do not need to be stacked, The model should go from [small to large] according to the index, + * and the value should go from [large to small]. Otherwise, smaller values will be masked." + */ + private void paintFilledLine(int index, Graphics graphics) { + Polygon polygon = new Polygon(); + int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); + graphics.setColor(getCurrentLineColor(index, dataMap.get(timeArray[0]))); + /* + * Stacked scheme: add the point of the current index line from left to back, and then add the point of + * the next index line from right to left + */ + // Adds the point of the current polyline from left to right + for (int time : timeArray) { + int pointX = startXCoordinate + multiply(pixelPerX, time - startTime); + int valueY; + if (stacked) { + valueY = getListSum(dataMap.get(time), index); + } else { + valueY = getModelValueByIndex(dataMap.get(time), index); + } + // If the current value exceeds the maximum, the maximum update value is 1.5 times the current value + if (valueY > maxUnitY) { + maxUnitY = divideInt(valueY * NUM_3, NUM_2); + } + int pointY = y0 + multiply(pixelPerY, valueY); + polygon.addPoint(pointX, pointY); + } + // Draw the line below + paintAssistLine(index, polygon, timeArray); + // Use the brush to fill the polygon to form a filled poly line + graphics.fillPolygon(polygon); + } + + private void paintAssistLine(int index, Polygon polygon, int[] timeArray) { + // If nextLine does not exist, it indicates that index is the last line. You can directly add Y0 points + // at the beginning and end of the line. You don't need to cycle through all the points + int nextLineIndex = getNextLineIndex(index, dataMap.get(timeArray[0])); + if (nextLineIndex == INITIAL_VALUE || !stacked) { + int endX = startXCoordinate + multiply(pixelPerX, timeArray[timeArray.length - 1] - startTime); + int startX = startXCoordinate + multiply(pixelPerX, timeArray[0] - startTime); + polygon.addPoint(endX, y0); + polygon.addPoint(startX, y0); + } else { + // Add the point of the next index line from right to left + for (int time = timeArray.length - 1; time >= 0; time--) { + // Calculate the X and Y points of the data on the line chart + int pointX = startXCoordinate + multiply(pixelPerX, timeArray[time] - startTime); + int sum = getListSum(dataMap.get(timeArray[time]), nextLineIndex); + // If the current value exceeds the maximum, the maximum update value is 1.5 times the current value + if (sum > maxUnitY) { + maxUnitY = divideInt(sum * NUM_3, NUM_2); + } + int pointY = y0 + multiply(pixelPerY, sum); + polygon.addPoint(pointX, pointY); + } + } + } + + /** + * Build tooltip content + * + * @param showKey Key to show + * @param actualKey The actual value of the key in the data map + * @param newChart Is it a new chart + */ + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void leftMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void rightMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseDraggedEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseReleaseEvent(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/LineChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/LineChart.java index 26e452b94..b5f8fd5b4 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/LineChart.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/LineChart.java @@ -1,275 +1,180 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts; - -import ohos.devtools.views.charts.model.ChartDataModel; -import ohos.devtools.views.charts.model.ChartLegendColorRect; -import ohos.devtools.views.charts.tooltip.LegendTooltip; -import ohos.devtools.views.charts.tooltip.TooltipItem; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.MonitorItemDetail; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; - -import javax.swing.JComponent; -import javax.swing.JLabel; -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import static ohos.devtools.views.charts.model.ChartType.LINE; -import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_LINE_WIDTH; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_2; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_3; -import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; -import static ohos.devtools.views.charts.utils.ChartUtils.multiply; -import static ohos.devtools.views.common.MonitorItemDetail.NETWORK_CONN; -import static ohos.devtools.views.common.MonitorItemDetail.NETWORK_RCV; -import static ohos.devtools.views.common.MonitorItemDetail.NETWORK_SENT; - -/** - * @Description 折线图 - * @Date 2021/4/20 16:37 - **/ -public class LineChart extends ProfilerChart { - private final ChartLegendColorRect receivedColor = new ChartLegendColorRect(); - - private final JLabel receivedLabel = new JLabel(); - - private final ChartLegendColorRect sentColor = new ChartLegendColorRect(); - - private final JLabel sentLabel = new JLabel(); - - private final ChartLegendColorRect connectionsColor = new ChartLegendColorRect(); - - private final JLabel connectionsLabel = new JLabel(); - - /** - * 构造函数 - * - * @param bottomPanel 最底层父级面板 - */ - public LineChart(ProfilerChartsView bottomPanel) { - super(bottomPanel); - chartType = LINE; - initLegends(); - } - - /** - * 初始化图例 - */ - private void initLegends() { - receivedColor.setOpaque(false); - receivedLabel.setOpaque(false); - sentColor.setOpaque(false); - sentLabel.setOpaque(false); - connectionsColor.setOpaque(false); - connectionsLabel.setOpaque(false); - } - - /** - * 构建图例 - * - * @param lastModels 面板上最右侧的数据 - * @see "图例展示的是面板上最右侧X轴对应的Y值,而非鼠标悬停处" - */ - @Override - protected void buildLegends(List lastModels) { - if (legends.getComponents().length == 0) { - addLegendComponents(); - } - Map> allItemLegendMap = initItemLegends(); - lastModels.forEach(model -> parseModelToLegend(model, allItemLegendMap)); - // Map中只剩下没有选择的监控项,需要隐藏 - allItemLegendMap.forEach((item, components) -> components.forEach(component -> component.setVisible(false))); - } - - /** - * 添加Legend组件 - */ - private void addLegendComponents() { - legends.add(receivedColor); - legends.add(receivedLabel); - legends.add(sentColor); - legends.add(sentLabel); - legends.add(connectionsColor); - legends.add(connectionsLabel); - } - - /** - * 初始化一个全量的Network图例的Map - * - * @return Map<监控项, 对应的图例组件> - */ - private Map> initItemLegends() { - Map> map = new HashMap<>(); - map.put(NETWORK_RCV, Arrays.asList(receivedColor, receivedLabel)); - map.put(NETWORK_SENT, Arrays.asList(sentColor, sentLabel)); - map.put(NETWORK_CONN, Arrays.asList(connectionsColor, connectionsLabel)); - return map; - } - - /** - * 处理数据,转化为图例 - * - * @param model 数据 - * @param allItemLegendMap 内存图例的Map - */ - private void parseModelToLegend(ChartDataModel model, Map> allItemLegendMap) { - MonitorItemDetail item = MonitorItemDetail.getItemByName(model.getName()); - switch (item) { - case NETWORK_RCV: - refreshColorText(receivedColor, receivedLabel, model); - // 如果model保存的为当前监控项,则显示其组件 - allItemLegendMap.get(NETWORK_RCV).forEach(component -> component.setVisible(true)); - // 组件设置为显示后,从Map中移除,循环完成后,Map中就只剩下没有选择的监控项,需要隐藏 - allItemLegendMap.remove(NETWORK_RCV); - break; - case NETWORK_SENT: - refreshColorText(sentColor, sentLabel, model); - allItemLegendMap.get(NETWORK_SENT).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(NETWORK_SENT); - break; - case NETWORK_CONN: - refreshColorText(connectionsColor, connectionsLabel, model); - allItemLegendMap.get(NETWORK_CONN).forEach(component -> component.setVisible(true)); - allItemLegendMap.remove(NETWORK_CONN); - break; - default: - break; - } - } - - /** - * 更新图例的颜色和文本 - * - * @param colorRect 图例色块 - * @param label 图例文本标签 - * @param model 数据 - */ - private void refreshColorText(ChartLegendColorRect colorRect, JLabel label, ChartDataModel model) { - // 文本标签 - String showValue = String.valueOf(model.getValue()); - String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, axisLabelY); - colorRect.setColor(model.getColor()); - colorRect.setOpaque(false); - legends.add(colorRect); - if (!label.getText().equals(text)) { - label.setText(text); - } - // 重要!设置透明,否则标尺会被盖住 - label.setOpaque(false); - legends.add(label); - } - - /** - * 绘制图表 - * - * @param graphics Graphics - */ - @Override - protected void paintChart(Graphics graphics) { - if (dataMap == null || dataMap.size() == 0) { - return; - } - Graphics graphic = graphics.create(); - Graphics2D graphicD = null; - if (graphic instanceof Graphics2D) { - graphicD = (Graphics2D) graphic; - } - // 获取原始线条特征 - Stroke stroke = graphicD.getStroke(); - BasicStroke defaultStroke = null; - if (stroke instanceof BasicStroke) { - defaultStroke = (BasicStroke) stroke; - } - // 定义虚线条特征 - BasicStroke bs = new BasicStroke(DEFAULT_LINE_WIDTH); - graphicD.setColor(ColorConstants.RULER); - graphicD.setStroke(bs); - // 循环绘制多条折线 - List lines = dataMap.entrySet().iterator().next().getValue(); - lines.forEach((line) -> paintLine(line.getIndex(), graphics)); - // 绘制完成后,要把默认格式还原 - graphicD.setStroke(defaultStroke); - } - - /** - * 绘制折线 - * - * @param index 折线的index - * @param graphics Graphics - */ - private void paintLine(int index, Graphics graphics) { - int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); - int length = timeArray.length; - int[] pointX = new int[length]; - int[] pointY = new int[length]; - for (int i = 0; i < length; i++) { - int time = timeArray[i]; - pointX[i] = startXCoordinate + multiply(pixelPerX, time - startTime); - int value = dataMap.get(time).get(index).getValue(); // 更新Y轴最大值 - if (value > maxUnitY) { - // 更新y最大值的占用比例 - maxUnitY = divideInt(value * NUM_3, NUM_2); - } - int y = y0 + multiply(pixelPerY, value); - pointY[i] = y; - } - // 每条线的颜色是一样的,所以这里只需要获取一次,不需要在下面的Map循环中每次都获取 - graphics.setColor(getCurrentLineColor(index, dataMap.get(timeArray[0]))); - graphics.drawPolyline(pointX, pointY, length); - } - - /** - * 构造悬浮提示框的内容 - * - * @param showKey 要展示的Key - * @param actualKey 实际在数据集合中取值的Key - * @param isNewChart 是否为新Chart - */ - @Override - protected void buildTooltip(int showKey, int actualKey, boolean isNewChart) { - List tooltipItems = buildTooltipItems(actualKey); - LegendTooltip.getInstance().showTip(this, showKey + "", "", tooltipItems, isNewChart); - } - - /** - * 构造Tooltip - * - * @param time 当前时间 - * @return List - */ - private List buildTooltipItems(int time) { - List tooltipItems = new ArrayList<>(); - if (dataMap == null || dataMap.size() == 0 || dataMap.get(time) == null) { - return tooltipItems; - } - for (ChartDataModel model : dataMap.get(time)) { - String showValue = String.valueOf(model.getValue()); - String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, axisLabelY); - TooltipItem tooltipItem = new TooltipItem(model.getColor(), text); - tooltipItems.add(tooltipItem); - } - return tooltipItems; - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; + +import java.awt.BasicStroke; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Stroke; +import java.awt.event.MouseEvent; +import java.util.List; + +import static ohos.devtools.views.charts.model.ChartType.LINE; +import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_LINE_WIDTH; +import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; +import static ohos.devtools.views.charts.utils.ChartUtils.multiply; + +/** + * Line chart + */ +public class LineChart extends ProfilerChart { + private static final int NUM_2 = 2; + private static final int NUM_3 = 3; + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + * @param name chart name + */ + public LineChart(ProfilerChartsView bottomPanel, String name) { + super(bottomPanel, name); + chartType = LINE; + } + + /** + * Init legends + * + */ + @Override + protected void initLegends() { + } + + /** + * Build legends of chart + * + * @param lastModels Data on the far right side of the panel + * @see "The legend shows the y value corresponding to the rightmost X axis, not the mouse hover position" + */ + @Override + protected void buildLegends(List lastModels) { + } + + /** + * Paint chart + * + * @param graphics Graphics + */ + @Override + protected void paintChart(Graphics graphics) { + if (dataMap == null || dataMap.size() == 0) { + return; + } + Graphics2D graphicD = castGraphics2D(graphics); + if (graphicD == null) { + return; + } + graphicD.setColor(ColorConstants.RULER); + graphicD.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + // Define dashed bar features + BasicStroke bs = new BasicStroke(DEFAULT_LINE_WIDTH); + // Save original line features + Stroke stroke = graphicD.getStroke(); + graphicD.setStroke(bs); + // 循环绘制多条折线 + List lines = dataMap.entrySet().iterator().next().getValue(); + lines.forEach((line) -> paintLine(line.getIndex(), graphics)); + // After drawing, the default format should be restored, otherwise the graphics drawn later are dotted lines + BasicStroke defaultStroke = castBasicStroke(stroke); + graphicD.setStroke(defaultStroke); + } + + /** + * Paint poly line + * + * @param index index of line chart + * @param graphics Graphics + */ + private void paintLine(int index, Graphics graphics) { + int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); + int length = timeArray.length; + int[] pointX = new int[length]; + int[] pointY = new int[length]; + for (int i = 0; i < length; i++) { + int time = timeArray[i]; + pointX[i] = startXCoordinate + multiply(pixelPerX, time - startTime); + List chartDataModels = dataMap.get(time); + if (chartDataModels == null) { + return; + } + ChartDataModel chartDataModel = chartDataModels.get(index); + if (chartDataModel == null) { + return; + } + int value = chartDataModel.getValue(); + // Update Y-axis maximum + if (value > maxUnitY) { + maxUnitY = divideInt(value * NUM_3, NUM_2); + } + int y = y0 + multiply(pixelPerY, value); + pointY[i] = y; + } + graphics.setColor(getCurrentLineColor(index, dataMap.get(timeArray[0]))); + graphics.drawPolyline(pointX, pointY, length); + } + + /** + * Build tooltip content + * + * @param showKey Key to show + * @param actualKey The actual value of the key in the data map + * @param newChart Is it a new chart + */ + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void leftMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void rightMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseDraggedEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseReleaseEvent(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/ProfilerChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/ProfilerChart.java index 03ffe553a..81d030ae0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/ProfilerChart.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/ProfilerChart.java @@ -1,602 +1,1049 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts; - -import com.intellij.ui.JBColor; -import ohos.devtools.views.charts.model.ChartDataModel; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartType; -import ohos.devtools.views.charts.tooltip.LegendTooltip; -import ohos.devtools.views.charts.utils.ChartUtils; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; - -import javax.swing.JPanel; -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.math.BigDecimal; -import java.util.LinkedHashMap; -import java.util.List; - -import static java.awt.AlphaComposite.SRC_OVER; -import static java.awt.BasicStroke.CAP_BUTT; -import static java.awt.BasicStroke.JOIN_ROUND; -import static ohos.devtools.views.charts.utils.ChartConstants.CHART_HEADER_HEIGHT; -import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_CHART_COLOR; -import static ohos.devtools.views.charts.utils.ChartConstants.INITIAL_VALUE; -import static ohos.devtools.views.charts.utils.ChartConstants.OPAQUE_VALUE; -import static ohos.devtools.views.charts.utils.ChartConstants.SCALE_LINE_LEN; -import static ohos.devtools.views.charts.utils.ChartConstants.TRANSLUCENT_VALUE; -import static ohos.devtools.views.charts.utils.ChartConstants.UNIT; -import static ohos.devtools.views.charts.utils.ChartConstants.Y_AXIS_STR_OFFSET_X; -import static ohos.devtools.views.charts.utils.ChartConstants.Y_AXIS_STR_OFFSET_Y; -import static ohos.devtools.views.charts.utils.ChartUtils.divide; -import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; -import static ohos.devtools.views.charts.utils.ChartUtils.multiply; -import static ohos.devtools.views.common.LayoutConstants.FLOAT_VALUE; -import static ohos.devtools.views.common.ViewConstants.CHART_MAX_Y; -import static ohos.devtools.views.common.ViewConstants.CHART_SECTION_NUM_Y; - -/** - * Chart的抽象父类 - * - * @since 2021/2/1 9:30 - */ -public abstract class ProfilerChart extends JPanel implements MouseListener, MouseMotionListener { - /** - * 构建图例 - * - * @param lastModels 面板上最右侧的数据 - * @see "图例展示的是面板上最右侧X轴对应的Y值,而非鼠标悬停处" - */ - protected abstract void buildLegends(List lastModels); - - /** - * 绘制图表 - * - * @param graphics Graphics - */ - protected abstract void paintChart(Graphics graphics); - - /** - * 构造悬浮提示框的内容 - * - * @param showKey 要展示的Key - * @param actualKey 实际在数据集合中取值的Key - * @param isNewChart 是否为新Chart - */ - protected abstract void buildTooltip(int showKey, int actualKey, boolean isNewChart); - - /** - * 最底层父级面板 - */ - protected final ProfilerChartsView bottomPanel; - - /** - * 图表类型 - */ - protected ChartType chartType; - - /** - * 数据集合 - * - * @see "Key:时间, Value:所有Chart的值>" - */ - protected volatile LinkedHashMap> dataMap; - - /** - * 图例 - */ - protected JPanel legends; - - /** - * X轴上可以展示的最大数量 - */ - protected int maxDisplayX = 1; - - /** - * X轴刻度线上的最小刻度间隔 - */ - protected int minMarkIntervalX = 1; - - /** - * X轴标签 - */ - protected String axisLabelX = ""; - - /** - * Y轴标签 - */ - protected String axisLabelY = ""; - - /** - * Y轴最大单位 - */ - protected int maxUnitY = CHART_MAX_Y; - - /** - * Y轴坐标刻度分段数量 - */ - protected int sectionNumY = CHART_SECTION_NUM_Y; - - /** - * 绘图时X轴的开始点 - */ - protected int startTime; - - /** - * 绘图时X轴的结束点 - */ - protected int endTime; - - /** - * 当前Chart的顶部 - */ - protected int top = 0; - - /** - * 当前Chart的右侧 - */ - protected int right = 0; - - /** - * 绘制Chart时的坐标轴X0点 - * - * @see "是日常中绘图习惯的坐标轴X0点,非Swing绘图的坐标轴原点" - */ - protected int x0 = 0; - - /** - * 绘制Chart时的坐标轴Y0点 - * - * @see "是日常中绘图习惯的坐标轴Y0点,非Swing绘图的坐标轴原点" - */ - protected int y0 = 0; - - /** - * X轴起始绘图的坐标,因为动态Chart从右往左出现 - */ - protected int startXCoordinate = 0; - - /** - * 每个X轴单位占用的像素数 - */ - protected BigDecimal pixelPerX; - - /** - * 每个Y轴单位占用的像素数z - */ - protected BigDecimal pixelPerY; - - /** - * 鼠标是否进入Chart - * - * @see "这里是指进入绘制出来的Chart,而非Chart组件" - */ - protected boolean isEnterChart; - - /** - * 构造函数 - * - * @param bottomPanel 最底层父级面板 - */ - public ProfilerChart(ProfilerChartsView bottomPanel) { - this.bottomPanel = bottomPanel; - // 设置可透明显示 - this.setOpaque(false); - this.setLayout(new BorderLayout()); - // 添加图例组件的布局 - legends = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - legends.setOpaque(false); - this.add(legends, BorderLayout.NORTH); - this.addMouseListener(this); - this.addMouseMotionListener(this); - } - - /** - * 更新Chart的起始、结束时间以及数据集合,实现刷新Chart的功能 - * - * @param startTime 起始时间 - * @param endTime 结束时间 - * @param dataMap 数据集合 - */ - public void refreshChart(int startTime, int endTime, LinkedHashMap> dataMap) { - // 保存数据,并重绘界面 - this.startTime = startTime; - this.endTime = endTime; - this.dataMap = dataMap; - refreshLegends(); - this.repaint(); - this.revalidate(); - } - - /** - * 刷新图例 - */ - protected void refreshLegends() { - // 在时间的数组中,找到最接近的值 - int lastTime = getLastTime(); - List models = dataMap.get(lastTime); - if (models != null && !models.isEmpty()) { - buildLegends(models); - } - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - // 设置画笔颜色 - graphics.setColor(JBColor.GRAY); - Graphics2D graph = null; - if (graphics instanceof Graphics2D) { - graph = (Graphics2D) graphics; - } - // 设置两个目标重叠时的混合类型和透明度 - graph.setComposite(AlphaComposite.getInstance(SRC_OVER, OPAQUE_VALUE)); - // 初始化坐标和比例尺等信息 - initPoint(); - // 绘制Y轴 - drawYAxis(graphics); - // 记录当前Y轴最大值 - int crtMaxY = this.maxUnitY; - // 绘制图表 - paintChart(graphics); - // 如果在画线过程中maxUnitY刷新,这时需要重绘一次,否则当前仍然以旧值绘制,会导致最大值超过面板大小 - if (crtMaxY != this.maxUnitY) { - repaint(); - return; - } - // 绘制框选区域 - paintSelectedArea(graphics); - // 还原透明度 - graph.setComposite(AlphaComposite.getInstance(SRC_OVER, OPAQUE_VALUE)); - // 绘制跟随鼠标的标尺 - drawMouseRuler(graphics); - // 绘制框选时的标尺 - drawSelectedRuler(graphics); - if (isEnterChart) { - // 展示Tooltip提示框 - showTooltip(false); - } - } - - /** - * 初始化坐标和比例尺等信息 - */ - protected void initPoint() { - // 计算Panel内绘图区的上下左右边距 - int left = this.getX(); - top = this.getY() + CHART_HEADER_HEIGHT; - // 整体稍微往下移动一点 - right = left + this.getWidth(); - int bottom = this.getHeight(); - // 确定绘制出的坐标轴的原点 - // 绘制出的坐标轴的X0点 - x0 = left; - // 绘制出的坐标轴的Y0点 - y0 = bottom; - // 计算出X轴1个单位占用多少像素 - pixelPerX = divide(right - left, maxDisplayX); - // 计算出Y轴1个单位占用多少像素 - pixelPerY = divide(top - y0, maxUnitY); - // 如果时间铺满了面板并继续往前走,绘制图形的时候应该需要从x0开始绘制,不需要像画坐标轴刻度那样存在偏移 - if (endTime < maxDisplayX) { - startXCoordinate = right - multiply(pixelPerX, endTime); - } else { - startXCoordinate = x0; - } - } - - /** - * 绘制Y轴 - * - * @param graphics Graphics - */ - protected void drawYAxis(Graphics graphics) { - // 前2个参数为线段起点左边,后2个参数为线段结束坐标,从上向下。 - graphics.drawLine(x0, this.getY(), x0, y0); - // 计算每段刻度的长度,同时也是循环绘制时的像素增量 - int interval = divideInt(maxUnitY, sectionNumY); - for (int i = interval; i <= maxUnitY; i += interval) { - int y = y0 + multiply(pixelPerY, i); - // 绘制Y轴刻度,其实就是绘制一条短横线 - graphics.drawLine(x0, y, x0 + SCALE_LINE_LEN, y); - // 绘制Y轴刻度值 - String str = i == maxUnitY ? divide(i, UNIT) + " " + axisLabelY : divide(i, UNIT) + ""; - graphics.drawString(str, x0 + Y_AXIS_STR_OFFSET_X, y + Y_AXIS_STR_OFFSET_Y); - } - } - - /** - * 绘制框选区域,这里实际是绘制了两块半透明的矩形,盖在Chart上,随着鼠标拖动改变矩形大小实现框选 - * - * @param graphics Graphics - */ - protected void paintSelectedArea(Graphics graphics) { - if (this.bottomPanel.getObserver().getStandard().getSelectedRange() == null) { - return; - } - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - int endTimeX = selectedRange.getEndTime(); - int startTimeX = selectedRange.getStartTime(); - int startX = multiply(pixelPerX, startTimeX - this.startTime) + startXCoordinate; - int endX = multiply(pixelPerX, endTimeX - this.startTime) + startXCoordinate; - int height = this.bottomPanel.getHeight(); - // 这里把画笔透明降低绘制遮盖的矩形 - ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(SRC_OVER, TRANSLUCENT_VALUE)); - graphics.setColor(ColorConstants.CHART_BG); - graphics.fillRect(0, 0, startX, height); - graphics.fillRect(endX, 0, endTime, height); - } - - /** - * 绘制跟随鼠标的标尺 - * - * @param graphics Graphics - */ - protected void drawMouseRuler(Graphics graphics) { - int mouseX; - Point mousePoint = getMousePosition(); - if (mousePoint == null) { - // 没有鼠标位置时,绘制标尺的X坐标为0,或鼠标当前进入的组件为空,则不需要绘制 - if (this.bottomPanel.getRulerXCoordinate() == 0 || this.bottomPanel.getCurrentEntered() == null) { - return; - } - mouseX = this.bottomPanel.getRulerXCoordinate(); - } else { - mouseX = (int) mousePoint.getX(); - this.bottomPanel.setRulerXCoordinate(mouseX); - } - Graphics2D g2d = null; - if (graphics instanceof Graphics2D) { - g2d = (Graphics2D) graphics; - } - // 保存原始线条特征 - BasicStroke defaultStroke = null; - - Stroke stroke = g2d.getStroke(); - if (stroke instanceof BasicStroke) { - defaultStroke = (BasicStroke) stroke; - } - float[] dash = {FLOAT_VALUE, 0f, FLOAT_VALUE}; - // 定义虚线条特征 - BasicStroke bs = new BasicStroke(1, CAP_BUTT, JOIN_ROUND, 1.0f, dash, FLOAT_VALUE); - g2d.setColor(ColorConstants.RULER); - g2d.setStroke(bs); - g2d.drawLine(mouseX, this.getY(), mouseX, this.getHeight()); - // 绘制完成后,要把默认格式还原,否则后面绘制的图形都是虚线 - g2d.setStroke(defaultStroke); - // 把当前组件标记为已绘制,刷新其他组件的标尺 - this.bottomPanel.compRulerDrawn(this); - this.bottomPanel.refreshCompRuler(); - } - - /** - * 绘制框选时的标尺 - * - * @param graphics Graphics - */ - protected void drawSelectedRuler(Graphics graphics) { - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - if (selectedRange != null) { - graphics.setColor(ColorConstants.RULER); - int startX = startXCoordinate + multiply(pixelPerX, selectedRange.getStartTime() - startTime); - graphics.drawLine(startX, this.getY(), startX, this.getHeight()); - int endX = startXCoordinate + multiply(pixelPerX, selectedRange.getEndTime() - startTime); - graphics.drawLine(endX, this.getY(), endX, this.getHeight()); - } - } - - /** - * 检查鼠标位置,判断是否需要显示Tooltip - * - * @param mouseEvent MouseEvent - */ - protected void checkMouseForTooltip(MouseEvent mouseEvent) { - // 如果鼠标X坐标小于Chart的X起始坐标,则不需要Tooltip - if (mouseEvent.getX() < startXCoordinate) { - isEnterChart = false; - LegendTooltip.getInstance().hideTip(); - } else { - // 鼠标移动,Tooltip位置需要刷新 - LegendTooltip.getInstance().followWithMouse(mouseEvent); - if (!isEnterChart) { - isEnterChart = true; - showTooltip(true); - } - } - } - - /** - * 显示悬浮提示框 - * - * @param isNewChart 是否为新Chart - */ - protected void showTooltip(boolean isNewChart) { - Point mousePoint = getMousePosition(); - // 如果鼠标X坐标小于Chart的X起始坐标,则不需要Tooltip - if (mousePoint == null || mousePoint.getX() < startXCoordinate) { - LegendTooltip.getInstance().hideTip(); - return; - } - if (dataMap == null || dataMap.size() == 0) { - LegendTooltip.getInstance().hideTip(); - return; - } - int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); - if (timeArray.length == 0) { - return; - } - // 要展示的时间,也就是鼠标上对应的时间 = (鼠标X坐标 - 绘制Chart的X起始坐标) / X轴1个单位对应的像素数 + 起始时间 - int showKey = divide(mousePoint.getX() - startXCoordinate, pixelPerX) + startTime; - // 展示时间不一定就在dataMap的时间数组中,需要找到最接近的时间,然后通过这个时间拿到value - int actualKey = timeArray[ChartUtils.searchClosestIndex(timeArray, showKey)]; - buildTooltip(showKey, actualKey, isNewChart); - } - - /** - * 获取当前数据的颜色 - * - * @param index int - * @param models 数据集合 - * @return Color - */ - protected Color getCurrentLineColor(int index, List models) { - Color color = DEFAULT_CHART_COLOR; - if (models == null || models.size() == 0) { - LegendTooltip.getInstance().hideTip(); - return color; - } - for (ChartDataModel model : models) { - if (model.getIndex() == index && model.getColor() != null) { - color = model.getColor(); - } - } - return color; - } - - /** - * 获取当前Chart上的最后一个时间,因为Standard中的endTime,不一定有数据 - * - * @return int - */ - protected int getLastTime() { - // 获取endTime时刻的数值的集合 - int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); - if (timeArray.length == 0) { - return INITIAL_VALUE; - } - - // 在时间的数组中,找到最接近的值 - ChartDataRange range = bottomPanel.getObserver().getStandard().getDisplayRange(); - return timeArray[ChartUtils.searchClosestIndex(timeArray, range.getEndTime())]; - } - - /** - * 初始化Y轴最大单位 - */ - public void initMaxUnitY() { - this.maxUnitY = CHART_MAX_Y; - } - - @Override - public void mouseClicked(MouseEvent mouseEvent) { - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - } - - @Override - public void mouseReleased(MouseEvent mouseEvent) { - } - - @Override - public void mouseEntered(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标进入,则更新底层父级panel的currentEntered - this.bottomPanel.setCurrentEntered(this); - // 如果鼠标X坐标小于Chart的X起始坐标,则不需要Tooltip - if (mouseEvent.getX() < startXCoordinate) { - isEnterChart = false; - LegendTooltip.getInstance().hideTip(); - } else { - isEnterChart = true; - // 鼠标移动,Tooltip位置需要刷新 - LegendTooltip.getInstance().followWithMouse(mouseEvent); - showTooltip(true); - } - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标退出,则更新底层父级panel的currentEntered为null - this.bottomPanel.setCurrentEntered(null); - // 这里需要重绘一下当前界面,否则会残留有之前的ruler - this.bottomPanel.resetRulerDrawStatus(); - this.bottomPanel.refreshCompRuler(); - isEnterChart = false; - LegendTooltip.getInstance().hideTip(); - } - - @Override - public void mouseDragged(MouseEvent mouseEvent) { - } - - @Override - public void mouseMoved(MouseEvent mouseEvent) { - // 这为了防止鼠标从Row底部移上来时,仍然是双箭头resize状态引起用户误解,这里把鼠标置为默认状态 - this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - // 鼠标移动,则所有组件的标尺需要重新绘制 - this.bottomPanel.resetRulerDrawStatus(); - checkMouseForTooltip(mouseEvent); - this.repaint(); - } - - public ChartType getChartType() { - return chartType; - } - - public void setMaxDisplayX(int maxDisplayX) { - this.maxDisplayX = maxDisplayX; - } - - public void setMinMarkIntervalX(int minMarkIntervalX) { - this.minMarkIntervalX = minMarkIntervalX; - } - - public void setAxisLabelX(String axisLabelX) { - this.axisLabelX = axisLabelX; - } - - public void setAxisLabelY(String axisLabelY) { - this.axisLabelY = axisLabelY; - } - - public void setSectionNumY(int sectionNumY) { - this.sectionNumY = sectionNumY; - } - - public int getStartTime() { - return startTime; - } - - public void setStartTime(int startTime) { - this.startTime = startTime; - } - - public int getEndTime() { - return endTime; - } - - public void setEndTime(int endTime) { - this.endTime = endTime; - } - - public ProfilerChartsView getBottomPanel() { - return bottomPanel; - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.charts.model.ChartType; +import ohos.devtools.views.charts.tooltip.LegendTooltip; +import ohos.devtools.views.charts.utils.ChartUtils; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; + +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Polygon; +import java.awt.Stroke; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import static java.awt.AlphaComposite.SRC_OVER; +import static java.awt.BasicStroke.CAP_BUTT; +import static java.awt.BasicStroke.JOIN_ROUND; +import static ohos.devtools.views.charts.utils.ChartConstants.CHART_HEADER_HEIGHT; +import static ohos.devtools.views.charts.utils.ChartConstants.CHART_MAX_Y; +import static ohos.devtools.views.charts.utils.ChartConstants.CHART_SECTION_NUM_Y; +import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_CHART_COLOR; +import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_SELECT; +import static ohos.devtools.views.charts.utils.ChartConstants.SCALE_LINE_LEN; +import static ohos.devtools.views.charts.utils.ChartConstants.TRANSLUCENT_VALUE; +import static ohos.devtools.views.charts.utils.ChartConstants.Y_AXIS_STR_OFFSET_X; +import static ohos.devtools.views.charts.utils.ChartConstants.Y_AXIS_STR_OFFSET_Y; +import static ohos.devtools.views.charts.utils.ChartUtils.divide; +import static ohos.devtools.views.charts.utils.ChartUtils.divideInt; +import static ohos.devtools.views.charts.utils.ChartUtils.multiply; +import static ohos.devtools.views.common.ColorConstants.TIMELINE_SCALE; +import static ohos.devtools.views.common.LayoutConstants.FLOAT_VALUE; +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; + +/** + * Abstract parent class of all charts + */ +public abstract class ProfilerChart extends JBPanel implements MouseListener, MouseMotionListener { + private static final int NUM_5 = 5; + + /** + * The start time of the x-axis when drawing + */ + protected int startTime; + + /** + * The end time of the x-axis when drawing + */ + protected int endTime; + + /** + * Enable/disable select function + * + * @see "true: chart fold, false: chart expand" + * @see "chart expand: show ruler and tooltip" + */ + protected boolean fold; + + /** + * Enable/disable select function + */ + protected boolean enableSelect; + + /** + * Whether the mouse enters chart + * + * @see "Here is the entry into the paint chart, not the chart component" + */ + protected boolean enterChart; + + /** + * Chart name, used as key in selected map + */ + protected final String chartName; + + /** + * Right of chart + */ + protected int right = 0; + + /** + * Coordinate axis X0 point when drawing chart + * + * @see "It is the coordinate axis X0 point used in daily drawing, not the coordinate axis origin of Swing" + */ + protected int x0 = 0; + + /** + * Coordinate axis Y0 point when drawing chart + * + * @see "It is the coordinate axis Y0 point used in daily drawing, not the coordinate axis origin of Swing" + */ + protected int y0 = 0; + + /** + * The x-axis is the coordinate of the starting plot + * + * @see "The dynamic timeline and chart appear from right to left" + */ + protected int startXCoordinate = 0; + + /** + * The top of this panel + */ + protected int panelTop = 0; + + /** + * The maximum value that can be displayed on the x-axis + */ + protected int maxDisplayX = 1; + + /** + * Minimum scale interval on X-axis scale line + */ + protected int minMarkIntervalX = 1; + + /** + * Y-axis label + */ + protected String axisLabelY = ""; + + /** + * Y-axis maximum unit + */ + protected int maxUnitY = CHART_MAX_Y; + + /** + * Number of y-axis scale segments + */ + protected int sectionNumY = CHART_SECTION_NUM_Y; + + /** + * Top of chart + */ + protected int top = CHART_HEADER_HEIGHT; + + /** + * The anchor point of dragging box selection, that is, the fixed point + */ + protected int dragAnchorPoint = INITIAL_VALUE; + + /** + * The starting point of dragging and dropping box selection + */ + protected int dragStartPoint = INITIAL_VALUE; + + /** + * The ending point of dragging and dropping box selection + */ + protected int dragEndPoint = INITIAL_VALUE; + + /** + * Bottom parent panel + */ + protected final ProfilerChartsView bottomPanel; + + /** + * YAxisLable + */ + protected ArrayList yAxisList = new ArrayList<>(); + + /** + * Data map + * + * @see "Key: time, Value: The values of chart at this point in time>" + */ + protected volatile LinkedHashMap> dataMap; + + /** + * Legends + */ + protected JBPanel legends; + + /** + * Tooltip + */ + protected LegendTooltip tooltip; + + /** + * Chart type + */ + protected ChartType chartType; + + /** + * Number of pixels per X-axis unit + */ + protected BigDecimal pixelPerX; + + /** + * Number of pixels per Y-axis unit + */ + protected BigDecimal pixelPerY; + + /** + * Update when mouse moved + * + * @see "Use function getMousePosition() will be null sometime." + */ + private Point mousePoint; + + /** + * Whether the chart can be dragged or not + */ + private boolean canDragged = false; + + /** + * Whether the chart is being dragged or not + */ + private boolean dragging = false; + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + * @param name chart name + */ + ProfilerChart(ProfilerChartsView bottomPanel, String name) { + this.bottomPanel = bottomPanel; + this.chartName = name; + // 设置可透明显示 + this.setOpaque(false); + this.setLayout(new BorderLayout()); + this.addMouseListener(this); + this.addMouseMotionListener(this); + this.tooltip = new LegendTooltip(); + // 添加图例组件的布局 + legends = new JBPanel(new FlowLayout(FlowLayout.RIGHT)); + legends.setOpaque(false); + initLegends(); + this.add(legends, BorderLayout.NORTH); + } + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + * @param name chart name + */ + ProfilerChart(ProfilerChartsView bottomPanel, String name, ArrayList yAxisList) { + this.bottomPanel = bottomPanel; + this.chartName = name; + this.yAxisList = yAxisList; + // Set transparent display + this.setOpaque(false); + this.setLayout(new BorderLayout()); + this.addMouseListener(this); + this.addMouseMotionListener(this); + this.tooltip = new LegendTooltip(); + // 添加图例组件的布局 + legends = new JBPanel(new FlowLayout(FlowLayout.RIGHT)); + legends.setOpaque(false); + initLegends(); + this.add(legends, BorderLayout.NORTH); + } + + /** + * Init legends + */ + protected abstract void initLegends(); + + /** + * Build legends of chart + * + * @param lastModels Data on the far right side of the panel + */ + protected abstract void buildLegends(List lastModels); + + /** + * Paint chart + * + * @param graphics Graphics + */ + protected abstract void paintChart(Graphics graphics); + + /** + * Build tooltip content + * + * @param showKey Key to show + * @param actualKey The actual value of the key in the data map + * @param newChart Is it a new chart + */ + protected abstract void buildTooltip(int showKey, int actualKey, boolean newChart); + + /** + * User defined events + * + * @param event MouseEvent + */ + protected abstract void leftMouseClickEvent(MouseEvent event); + + /** + * User defined events + * + * @param event MouseEvent + */ + protected abstract void rightMouseClickEvent(MouseEvent event); + + /** + * User defined events + * + * @param event MouseEvent + */ + protected abstract void mouseDraggedEvent(MouseEvent event); + + /** + * User defined events + * + * @param event MouseEvent + */ + protected abstract void mouseReleaseEvent(MouseEvent event); + + /** + * Refresh chart + * + * @param startTime The start time of the x-axis when drawing + * @param endTime The end time of the x-axis when drawing + * @param dataMap Map of chart data + */ + public void refreshChart(int startTime, int endTime, LinkedHashMap> dataMap) { + this.startTime = startTime; + this.endTime = endTime; + this.dataMap = dataMap; + refreshLegends(); + this.repaint(); + this.revalidate(); + } + + /** + * Refresh legends + */ + protected void refreshLegends() { + // Find the closest value in the array of time + int lastTime = getLastTime(); + List models = dataMap.get(lastTime); + if (models != null && !models.isEmpty()) { + buildLegends(models); + } + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + graphics.setColor(JBColor.GRAY); + initPoint(); + // Save the maximum value of current y-axis + int crtMaxY = this.maxUnitY; + paintChart(graphics); + // If maxUnitY was update in the process of paint chart, it needs to be redrawn at this time. Otherwise, + // the current drawing is still based on the old value, which will cause the maximum value to exceed the panel + if (crtMaxY != this.maxUnitY) { + repaint(); + return; + } + drawYAxis(graphics); + if (enableSelect) { + paintSelectedArea(graphics); + drawSelectedRuler(graphics); + } + // chart expand: show ruler + if (!fold) { + drawMouseRuler(graphics); + } + // chart expand: show tooltip + if (enterChart && !fold) { + showTooltip(false); + } + } + + /** + * Initialization of points and scale information + */ + protected void initPoint() { + // Calculate the top, bottom, left and right margins of the drawing area in the panel + int left = 0; + right = left + this.getWidth(); + int bottom = this.getHeight(); + x0 = left; + y0 = bottom; + // How many pixels does one unit of x-axis occupy + pixelPerX = divide(right - left, maxDisplayX); + // How many pixels does one unit of y-axis occupy + pixelPerY = divide(top - y0, maxUnitY); + // If the time exceeds maxDisplayX and continues to move forward, the drawing should start from x0 + if (endTime < maxDisplayX) { + startXCoordinate = right - multiply(pixelPerX, endTime); + } else { + startXCoordinate = x0; + } + } + + /** + * Draw Y-axis + * + * @param graphics Graphics + */ + protected void drawYAxis(Graphics graphics) { + // Calculate the length of each scale segment and the pixel increment when drawing circularly + int interval = divideInt(maxUnitY, sectionNumY); + int index = 0; + for (int value = interval; value <= maxUnitY; value += interval) { + int y = y0 + multiply(pixelPerY, value); + // Draw Y-axis scale + graphics.setColor(TIMELINE_SCALE); + graphics.drawLine(x0, y, x0 + SCALE_LINE_LEN, y); + // Draw the string of Y-axis scale + String str = null; + if (yAxisList.size() > 0 && index < yAxisList.size()) { + str = yAxisList.get(index); + index ++; + }else { + str = getYaxisLabelStr(value); + } + graphics.setColor(JBColor.foreground()); + graphics.drawString(str, x0 + Y_AXIS_STR_OFFSET_X, y + Y_AXIS_STR_OFFSET_Y); + } + } + + /** + * Gets the string in Y-axis units + * + * @param value int + * @return String + */ + protected String getYaxisLabelStr(int value) { + return value == maxUnitY ? value + axisLabelY : value + ""; + } + + /** + * Draw the box selection area + * + * @param graphics Graphics + */ + protected void paintSelectedArea(Graphics graphics) { + if (this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName) == null) { + return; + } + ChartDataRange selectedRange = this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName); + int selectedStartTime = selectedRange.getStartTime(); + int selectedEndTime = selectedRange.getEndTime(); + int selectedStartX = multiply(pixelPerX, selectedStartTime - this.startTime) + startXCoordinate; + int selectedEndX = multiply(pixelPerX, selectedEndTime - this.startTime) + startXCoordinate; + int height = this.bottomPanel.getHeight(); + // Here, the brush is transparent, and the covered rectangle is drawn + Graphics2D g2d = castGraphics2D(graphics); + if (g2d != null) { + g2d.setComposite(AlphaComposite.getInstance(SRC_OVER, TRANSLUCENT_VALUE)); + } + graphics.setColor(ColorConstants.CHART_BG); + graphics.fillRect(0, 0, selectedStartX, height); + graphics.fillRect(selectedEndX, 0, right - selectedEndX, height); + } + + /** + * Draw a ruler that follows the mouse + * + * @param graphics Graphics + */ + protected void drawMouseRuler(Graphics graphics) { + if (mousePoint == null) { + return; + } + + Graphics2D g2d = castGraphics2D(graphics); + if (g2d == null) { + return; + } + // Define dashed bar features + float[] dash = {FLOAT_VALUE, 0f, FLOAT_VALUE}; + BasicStroke bs = new BasicStroke(1, CAP_BUTT, JOIN_ROUND, 1.0f, dash, FLOAT_VALUE); + // Save original line features + Stroke stroke = g2d.getStroke(); + BasicStroke defaultStroke = castBasicStroke(stroke); + g2d.setColor(ColorConstants.RULER); + g2d.setStroke(bs); + int mouseX = (int) mousePoint.getX(); + g2d.drawLine(mouseX, panelTop, mouseX, this.getHeight()); + // After drawing, the default format should be restored, otherwise the graphics drawn later are dotted lines + g2d.setStroke(defaultStroke); + } + + /** + * castGraphics2D + * + * @param graphics graphics + * @return Graphics2D + */ + protected Graphics2D castGraphics2D(Graphics graphics) { + Graphics2D graph = null; + if (graphics instanceof Graphics2D) { + graph = (Graphics2D) graphics; + } + return graph; + } + + /** + * castBasicStroke + * + * @param stroke stroke + * @return BasicStroke + */ + protected BasicStroke castBasicStroke(Stroke stroke) { + BasicStroke basicStroke = null; + if (stroke instanceof BasicStroke) { + basicStroke = (BasicStroke) stroke; + } + return basicStroke; + } + + /** + * Draw a ruler when the chart is being selected + * + * @param graphics Graphics + */ + protected void drawSelectedRuler(Graphics graphics) { + ChartDataRange selectedRange = this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName); + if (selectedRange != null) { + graphics.setColor(ColorConstants.RULER); + int startX = startXCoordinate + multiply(pixelPerX, selectedRange.getStartTime() - startTime); + graphics.drawLine(startX, panelTop, startX, this.getHeight()); + drawInvertedTriangle(startX, graphics); + int endX = startXCoordinate + multiply(pixelPerX, selectedRange.getEndTime() - startTime); + graphics.drawLine(endX, panelTop, endX, this.getHeight()); + drawInvertedTriangle(endX, graphics); + } + } + + /** + * Draw an inverted triangle + * + * @param bottomVertexX Vertex below inverted triangle + * @param graphics Graphics + */ + private void drawInvertedTriangle(int bottomVertexX, Graphics graphics) { + Polygon polygon = new Polygon(); + polygon.addPoint(bottomVertexX, panelTop + NUM_5); + polygon.addPoint(bottomVertexX - NUM_5, panelTop); + polygon.addPoint(bottomVertexX + NUM_5, panelTop); + polygon.addPoint(bottomVertexX, panelTop + NUM_5); + graphics.setColor(JBColor.foreground()); + graphics.fillPolygon(polygon); + } + + /** + * Check the position of the mouse to determine whether it is necessary to display the tool tip + * + * @param event MouseEvent + */ + protected void checkMouseForTooltip(MouseEvent event) { + // If the X coordinate of the mouse is less than the X starting coordinate of chart, the tooltip is not required + if (event.getX() < startXCoordinate) { + enterChart = false; + tooltip.hideTip(); + return; + } + if (!enterChart) { + enterChart = true; + } + if (!fold) { + // Tooltip position needs to be refreshed when mouse move + tooltip.followWithMouse(event); + showTooltip(true); + } + } + + /** + * Show tooltip + * + * @param newChart Is it a new chart + */ + protected void showTooltip(boolean newChart) { + if (dragging) { + tooltip.hideTip(); + return; + } + // If the X coordinate of the mouse is less than the X starting coordinate of chart, the tooltip is not required + if (mousePoint == null || mousePoint.getX() < startXCoordinate) { + tooltip.hideTip(); + return; + } + if (dataMap == null || dataMap.size() == 0) { + tooltip.hideTip(); + return; + } + int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); + if (timeArray.length == 0) { + return; + } + // The time to display + // the time corresponding to the mouse = (mouse X coordinate - x start coordinate of drawing chart) / the + // number of pixels corresponding to 1 unit of X axis + start time + int showKey = divide(mousePoint.getX() - startXCoordinate, pixelPerX) + startTime; + // The display time is not necessarily in the dataMap time array, and the closest time needs to be found, + // and then the value is obtained through this time + int actualKey = timeArray[ChartUtils.searchClosestIndex(timeArray, showKey)]; + buildTooltip(showKey, actualKey, newChart); + } + + /** + * Gets the chart color of the current data + * + * @param index chart data index + * @param models Data list + * @return Color + */ + protected Color getCurrentLineColor(int index, List models) { + Color color = DEFAULT_CHART_COLOR; + if (models == null || models.size() == 0) { + tooltip.hideTip(); + return color; + } + for (ChartDataModel model : models) { + if (model.getIndex() == index && model.getColor() != null) { + color = model.getColor(); + } + } + return color; + } + + /** + * Get the index of the next chart data + * + * @param current Index of current chart data + * @param models All chart's data models + * @return Next chart's index + */ + protected int getNextLineIndex(int current, List models) { + int next = INITIAL_VALUE; + if (models == null || models.isEmpty()) { + return next; + } + int size = models.size(); + for (int index = 0; index < size; index++) { + ChartDataModel model = models.get(index); + int newIndex = index + 1; + if (model.getIndex() == current && newIndex < size) { + next = models.get(index + 1).getIndex(); + break; + } + } + return next; + } + + /** + * Find the sum of the values of all elements in the collection after the index is specified + * + * @param models Data list + * @param index Specify index + * @return int + */ + public int getListSum(List models, int index) { + int sum = 0; + if (index == INITIAL_VALUE || models == null) { + return sum; + } + for (ChartDataModel model : models) { + if (model.getIndex() < index) { + continue; + } + sum += model.getValue(); + } + return sum; + } + + /** + * Find the value of ChartDataModel in the list by index + * + * @param models Data list + * @param index Specify index + * @return int + */ + protected int getModelValueByIndex(List models, int index) { + int value = 0; + if (index == INITIAL_VALUE || models == null) { + return value; + } + for (ChartDataModel model : models) { + if (model.getIndex() == index) { + value = model.getValue(); + break; + } + } + return value; + } + + /** + * Get the last time on the current chart, because End time in standard does not necessarily have data + * + * @return int + */ + protected int getLastTime() { + // Gets the set of values for End time time + int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); + if (timeArray.length == 0) { + return INITIAL_VALUE; + } + + // In the array of time, find the closest value + ChartDataRange range = bottomPanel.getPublisher().getStandard().getDisplayRange(); + return timeArray[ChartUtils.searchClosestIndex(timeArray, range.getEndTime())]; + } + + /** + * Initialize Y-axis maximum units + */ + public void initMaxUnitY() { + this.maxUnitY = CHART_MAX_Y; + } + + @Override + public void mouseClicked(MouseEvent event) { + if (!enableSelect) { + return; + } + int button = event.getButton(); + // If the left click point is less than the starting point, it will not be updated + if (button == MouseEvent.BUTTON1 && event.getX() < startXCoordinate) { + return; + } + if (button == MouseEvent.BUTTON1) { + // Left click trigger box to select scene + this.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); + mouseLeftClick(event); + } else { + // Right click to cancel the selection and clear the selection range + this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + mouseRightClick(event); + } + } + + private void mouseLeftClick(MouseEvent event) { + int mouseX = event.getX(); + // By default, 10px is selected in the back box of the mouse position. + // If it exceeds the far right, 10px is selected from the starting point to the left + int mouseXNumber = mouseX + DEFAULT_SELECT; + if (mouseXNumber < right) { + dragStartPoint = mouseX; + dragEndPoint = mouseX + DEFAULT_SELECT; + } else { + dragStartPoint = right - DEFAULT_SELECT; + dragEndPoint = right; + } + int selectStart = getTimeByMouseX(dragStartPoint); + int selectEnd = getTimeByMouseX(dragEndPoint); + this.bottomPanel.getPublisher().getStandard().updateSelectedStart(chartName, selectStart); + this.bottomPanel.getPublisher().getStandard().updateSelectedEnd(chartName, selectEnd); + // Pause refreshing data + this.bottomPanel.getPublisher().pauseRefresh(); + // Refresh the interface manually once, otherwise the interface will not darken + ChartDataRange range = bottomPanel.getPublisher().getStandard().getDisplayRange(); + bottomPanel.getPublisher().notifyRefresh(range.getStartTime(), range.getEndTime()); + // Call the method to be override + leftMouseClickEvent(event); + } + + private void mouseRightClick(MouseEvent event) { + dragStartPoint = INITIAL_VALUE; + dragEndPoint = INITIAL_VALUE; + this.bottomPanel.getPublisher().getStandard().clearSelectedRange(chartName); + // Manually refresh the interface once + ChartDataRange range = bottomPanel.getPublisher().getStandard().getDisplayRange(); + bottomPanel.getPublisher().notifyRefresh(range.getStartTime(), range.getEndTime()); + // Call the method to be override + rightMouseClickEvent(event); + } + + @Override + public void mousePressed(MouseEvent event) { + if (!enableSelect) { + return; + } + // If the pressed point is less than the starting point, it will not be updated + if (event.getX() < startXCoordinate) { + return; + } + ChartDataRange selectedRange = this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName); + // selectedRange is null, which means that there is no click and the drag starts directly. + // This scene is not considered for the moment + if (selectedRange == null) { + return; + } + int mouseX = event.getX(); + // After dragging the scroll bar, the value of dragStartPoint will change, + // so we get point by time from select range + dragStartPoint = getPointXByTime(selectedRange.getStartTime()); + dragEndPoint = getPointXByTime(selectedRange.getEndTime()); + if (Math.abs(mouseX - dragStartPoint) > NUM_5 && Math.abs(mouseX - dragEndPoint) > NUM_5) { + canDragged = false; + return; + } + // Determine the anchor point when dragging + boolean isCloseToStart = Math.abs(mouseX - dragStartPoint) < NUM_5; + if (isCloseToStart) { + dragAnchorPoint = dragEndPoint; + canDragged = true; + } + boolean isCloseToEnd = Math.abs(mouseX - dragEndPoint) < NUM_5; + if (isCloseToEnd) { + dragAnchorPoint = dragStartPoint; + canDragged = true; + } + } + + @Override + public void mouseReleased(MouseEvent event) { + if (!enableSelect) { + return; + } + // Release event not processed with non left key + if (event.getButton() != MouseEvent.BUTTON1) { + return; + } + /* + * The trigger sequence of drag events is: press > drag > release + * The trigger sequence of click events is: press > release > click + */ + if (!dragging) { + return; + } + // Call the method to be override + mouseReleaseEvent(event); + dragging = false; + } + + @Override + public void mouseEntered(MouseEvent event) { + mousePoint = event.getPoint(); + // If the X coordinate of the mouse is less than the X starting coordinate of chart, the tooltip is not required + if (event.getX() < startXCoordinate) { + enterChart = false; + tooltip.hideTip(); + return; + } + + enterChart = true; + if (!fold) { + // Tooltip position needs to be refreshed when mouse move + tooltip.followWithMouse(event); + showTooltip(true); + } + } + + @Override + public void mouseExited(MouseEvent event) { + mousePoint = null; + enterChart = false; + tooltip.hideTip(); + this.repaint(); + } + + @Override + public void mouseDragged(MouseEvent event) { + if (!enableSelect || !canDragged) { + // Call repaint, mainly to update the ruler following the mouse movement + this.repaint(); + return; + } + dragging = true; + ChartDataRange selectedRange = this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName); + if (selectedRange == null) { + // Call repaint, mainly to update the ruler following the mouse movement + this.repaint(); + return; + } + int mouseX = event.getX(); + if (mouseX > dragAnchorPoint) { + // If the mouse position is larger than the anchor position, it means that you drag it on the right side of + // the anchor and update end to the mouse point + dragRightRuler(mouseX); + } else { + // If the mouse position is smaller than the anchor position, it means that it is dragging on the left side + // of the anchor, then update end to the anchor and start to the mouse point + dragLeftRuler(mouseX); + } + checkCursorStyle(mouseX); + // Call the method to be override + mouseDraggedEvent(event); + this.repaint(); + } + + private void dragLeftRuler(int mouseX) { + dragStartPoint = mouseX; + ChartStandard standard = this.bottomPanel.getPublisher().getStandard(); + if (dragAnchorPoint != INITIAL_VALUE) { + dragEndPoint = dragAnchorPoint; + standard.updateSelectedEnd(chartName, getTimeByMouseX(dragAnchorPoint)); + } + standard.updateSelectedStart(chartName, getTimeByMouseX(mouseX)); + } + + private void dragRightRuler(int mouseX) { + dragEndPoint = mouseX; + ChartStandard standard = this.bottomPanel.getPublisher().getStandard(); + if (dragAnchorPoint != INITIAL_VALUE) { + dragStartPoint = dragAnchorPoint; + standard.updateSelectedStart(chartName, getTimeByMouseX(dragAnchorPoint)); + } + standard.updateSelectedEnd(chartName, getTimeByMouseX(mouseX)); + } + + @Override + public void mouseMoved(MouseEvent event) { + mousePoint = event.getPoint(); + checkCursorStyle(event.getX()); + checkMouseForTooltip(event); + this.repaint(); + } + + /** + * Through the X coordinate of the mouse, calculate the corresponding time + * + * @param mouseX X coordinate of mouse + * @return Corresponding X-axis time + * @see "Note that the time corresponding to the time x axis calculated here is not necessarily in the keyset of + * the datamap drawing chart. It may be between two values. When using it, you need to find the closest value to + * the keyset of the datamap" + */ + private int getTimeByMouseX(int mouseX) { + // Time corresponding to mouse = (mouse X coordinate - x start coordinate of drawing chart) / number + // of pixels corresponding to 1 unit of X axis + start time + return ChartUtils.divide(mouseX - startXCoordinate, pixelPerX) + startTime; + } + + /** + * Calculate the corresponding X-axis coordinate through time + * + * @param time Current time + * @return Corresponding X-axis coordinate value + */ + private int getPointXByTime(int time) { + // Corresponding coordinates on the mouse = number of pixels corresponding to 1 unit of X axis * + // (current time - x start time of drawing chart) + X start coordinates of drawing chart + return ChartUtils.multiply(pixelPerX, time - startTime) + startXCoordinate; + } + + /** + * Update the mouse style according to the coordinates of the mouse + * + * @param crtMouseX X-axis coordinates of mouse + */ + private void checkCursorStyle(int crtMouseX) { + ChartDataRange selectedRange = this.bottomPanel.getPublisher().getStandard().getSelectedRange(chartName); + if (selectedRange == null) { + return; + } + + int selectStart = startXCoordinate + ChartUtils.multiply(pixelPerX, selectedRange.getStartTime() - startTime); + int selectEnd = startXCoordinate + ChartUtils.multiply(pixelPerX, selectedRange.getEndTime() - startTime); + // When the mouse is close to the ruler, the mouse will be reset + if (Math.abs(selectStart - crtMouseX) < NUM_5) { + this.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR)); + } else if (Math.abs(selectEnd - crtMouseX) < NUM_5) { + this.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); + } else { + this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + } + + public LegendTooltip getTooltip() { + return tooltip; + } + + public void setMaxDisplayX(int maxDisplayX) { + this.maxDisplayX = maxDisplayX; + } + + public void setMinMarkIntervalX(int minMarkIntervalX) { + this.minMarkIntervalX = minMarkIntervalX; + } + + public String getAxisLabelY() { + return axisLabelY; + } + + public void setAxisLabelY(String axisLabelY) { + this.axisLabelY = axisLabelY; + } + + public void setMaxUnitY(int maxUnitY) { + this.maxUnitY = maxUnitY; + } + + public void setSectionNumY(int sectionNumY) { + this.sectionNumY = sectionNumY; + } + + public int getStartTime() { + return startTime; + } + + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + public int getEndTime() { + return endTime; + } + + public void setEndTime(int endTime) { + this.endTime = endTime; + } + + public ProfilerChartsView getBottomPanel() { + return bottomPanel; + } + + public void setEnableSelect(boolean enableSelect) { + this.enableSelect = enableSelect; + } + + public void setFold(boolean fold) { + this.fold = fold; + } + + public int getMinMarkIntervalX() { + return minMarkIntervalX; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/RectChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/RectChart.java new file mode 100644 index 000000000..2b1b6328d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/RectChart.java @@ -0,0 +1,225 @@ +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import com.intellij.ui.JBColor; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; + +import java.awt.*; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.List; + +import static ohos.devtools.views.charts.model.ChartType.RECT; +import static ohos.devtools.views.charts.utils.ChartUtils.multiply; + +/** + * RectChart chart + */ +public class RectChart extends ProfilerChart { + /** + * thread unspecified + */ + private static final int THREAD_UNSPECIFIED = 0; + + /** + * thread running + */ + private static final int THREAD_RUNNING = 1; + + /** + * thread sleeping + */ + private static final int THREAD_SLEEPING = 2; + + /** + * thread stopped + */ + private static final int THREAD_STOPPED = 3; + + /** + * thread waiting + */ + private static final int THREAD_WAITING = 4; + + private int threadId; + + public void setThreadId(int threadId) { + this.threadId = threadId; + } + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + * @param name chart name + */ + public RectChart(ProfilerChartsView bottomPanel, String name) { + super(bottomPanel, name); + chartType = RECT; + top = 0; + } + + /** + * Init legends + */ + @Override + protected void initLegends() { + } + + /** + * Build legends of chart + * + * @param lastModels Data on the far right side of the panel + * @see "The legend shows the y value corresponding to the rightmost X axis, not the mouse hover position" + */ + @Override + protected void buildLegends(List lastModels) { + } + + /** + * Paint chart + * + * @param graphics Graphics + */ + @Override + protected void paintChart(Graphics graphics) { + if (dataMap == null || dataMap.size() == 0) { + return; + } + int[] timeArray = dataMap.keySet().stream().mapToInt(Integer::valueOf).toArray(); + int pointX = 0; + int lastValue = 0; + int endX = 0; + for (int time : timeArray) { + List chartDataModelList = dataMap.get(time); + ArrayList splitList = new ArrayList(); + if (chartDataModelList != null && !chartDataModelList.isEmpty()) { + for (ChartDataModel chartDataModel : chartDataModelList) { + if (chartDataModel.getIndex() == threadId) { + int currentValue = chartDataModel.getValue(); + pointX = startXCoordinate + multiply(pixelPerX, time - startTime); + endX = startXCoordinate + multiply(pixelPerX, timeArray[timeArray.length - 1] - startTime); + if (currentValue != lastValue) { + splitList.add(new RectDataModel(pointX, currentValue)); + lastValue = currentValue; + } + } + } + for (int i = 0; i < splitList.size(); i++) { + switch (splitList.get(i).getThreadStatus()) { + case THREAD_RUNNING: + graphics.setColor(JBColor.GREEN); + break; + case THREAD_SLEEPING: + graphics.setColor(JBColor.background().darker()); + break; + case THREAD_WAITING: + graphics.setColor(JBColor.YELLOW); + break; + default: + graphics.setColor(null); + } + graphics.fillRect(splitList.get(i).getPointX(), 0, endX, y0); + } + } + } + } + + /** + * Build tooltip content + * + * @param showKey Key to show + * @param actualKey The actual value of the key in the data map + * @param newChart Is it a new chart + */ + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void leftMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void rightMouseClickEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseDraggedEvent(MouseEvent event) { + } + + /** + * User defined events + * + * @param event MouseEvent + */ + @Override + protected void mouseReleaseEvent(MouseEvent event) { + } + + @Override + protected void drawYAxis(Graphics graphics) { + } + + private class RectDataModel { + private int pointX; + private int threadStatus; + + /** + * Constructor + * + * @param pointX pointX + * @param threadStatus threadStatus + */ + RectDataModel(int pointX, int threadStatus) { + this.pointX = pointX; + this.threadStatus = threadStatus; + } + + public int getPointX() { + return pointX; + } + + public void setPointX(int pointX) { + this.pointX = pointX; + } + + public int getThreadStatus() { + return threadStatus; + } + + public void setThreadStatus(int threadStatus) { + this.threadStatus = threadStatus; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataModel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataModel.java index d40ab1dde..79765fd6b 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataModel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataModel.java @@ -1,65 +1,79 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts.model; - -import java.awt.Color; - -/** - * Chart数据的模型 - * - * @since 2021/3/2 11:26 - */ -public class ChartDataModel { - private int index; - - private String name; - - private Color color; - - private int value; - - public int getIndex() { - return index; - } - - public void setIndex(int index) { - this.index = index; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Color getColor() { - return color; - } - - public void setColor(Color color) { - this.color = color; - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts.model; + +import java.awt.Color; + +/** + * Chart data model + */ +public class ChartDataModel { + private int index; + + private String name; + + private double cpuPercent; + + private Color color; + + private int value; + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Color getColor() { + return color; + } + + public void setColor(Color color) { + this.color = color; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public double getCpuPercent() { + return cpuPercent; + } + + public void setCpuPercent(double cpuPercent) { + this.cpuPercent = cpuPercent; + } + + @Override + public String toString() { + return "ChartDataModel{" + "index=" + index + ", name='" + name + '\'' + ", cpuPercent=" + cpuPercent + + ", color=" + color + ", value=" + value + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataRange.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataRange.java index e68143463..a0e757512 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataRange.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartDataRange.java @@ -1,54 +1,52 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.charts.model; - -/** - * Timeline和Chart数据的时间范围 - * - * @since 2021/1/29 9:26 - */ -public class ChartDataRange { - /** - * 起始时间 - */ - private int startTime = Integer.MIN_VALUE; - - /** - * 结束时间 - */ - private int endTime = Integer.MAX_VALUE; - - public int getStartTime() { - return startTime; - } - - public void setStartTime(int startTime) { - this.startTime = startTime; - } - - public int getEndTime() { - return endTime; - } - - public void setEndTime(int endTime) { - this.endTime = endTime; - } - - @Override - public String toString() { - return "ChartDataRange{" + "startTime=" + startTime + ", endTime=" + endTime + '}'; - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts.model; + +/** + * Time range of chart data + */ +public class ChartDataRange { + /** + * Start time + */ + private int startTime = Integer.MIN_VALUE; + + /** + * End time + */ + private int endTime = Integer.MAX_VALUE; + + public int getStartTime() { + return startTime; + } + + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + public int getEndTime() { + return endTime; + } + + public void setEndTime(int endTime) { + this.endTime = endTime; + } + + @Override + public String toString() { + return "ChartDataRange{" + "startTime=" + startTime + ", endTime=" + endTime + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartLegendColorRect.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartLegendColorRect.java index 4e04e96ca..0b9aa5850 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartLegendColorRect.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartLegendColorRect.java @@ -15,7 +15,8 @@ package ohos.devtools.views.charts.model; -import javax.swing.JComponent; +import com.intellij.ui.components.JBPanel; + import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; @@ -25,11 +26,15 @@ import java.awt.Graphics; * * @since 2021/3/1 9:48 */ -public class ChartLegendColorRect extends JComponent { +public class ChartLegendColorRect extends JBPanel { /** - * legend Color Block Size + * legend Color Block Default Size */ - private static final int SIZE = 10; + private static final int DEFAULT_SIZE = 10; + + private int rectWidth; + + private int rectHeight; /** * color @@ -40,6 +45,19 @@ public class ChartLegendColorRect extends JComponent { * Chart Legend Color Rect */ public ChartLegendColorRect() { + this(DEFAULT_SIZE, DEFAULT_SIZE); + } + + /** + * Chart Legend Color Rect + * + * @param rectWidth rectWidth + * @param rectHeight rectHeight + */ + public ChartLegendColorRect(int rectWidth, int rectHeight) { + this.rectWidth = rectWidth; + this.rectHeight = rectHeight; + this.setOpaque(false); fillColor(); } @@ -47,7 +65,7 @@ public class ChartLegendColorRect extends JComponent { * fillColor */ private void fillColor() { - this.setPreferredSize(new Dimension(SIZE, SIZE)); + this.setPreferredSize(new Dimension(rectWidth, rectHeight)); super.repaint(); super.validate(); } @@ -64,7 +82,7 @@ public class ChartLegendColorRect extends JComponent { color = Color.GRAY; } graphics.setColor(color); - graphics.fillRect(0, 0, SIZE, SIZE); + graphics.fillRect(0, 0, rectWidth, rectHeight); } public void setColor(Color color) { diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartStandard.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartStandard.java index b6808c621..3a243fb16 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartStandard.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartStandard.java @@ -15,8 +15,11 @@ package ohos.devtools.views.charts.model; -import static ohos.devtools.views.common.ViewConstants.DEFAULT_MAX_MILLIS; -import static ohos.devtools.views.common.ViewConstants.DEFAULT_TIME_UNIT; +import java.util.HashMap; +import java.util.Map; + +import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_MAX_MILLIS; +import static ohos.devtools.views.charts.utils.ChartConstants.DEFAULT_TIME_UNIT; /** * Chart绘制标准,用于统一Timeline和Chart @@ -24,16 +27,18 @@ import static ohos.devtools.views.common.ViewConstants.DEFAULT_TIME_UNIT; * @since 2021/1/26 15:10 */ public class ChartStandard { - /** - * sizeTime - */ - public static int sizeTime; - /** * sessionId */ private final long sessionId; + /** + * 用户框选时间范围的集合 + * + * @see "Key: 区别各个Chart的key, value: 框选的时间范围" + */ + private final Map selectedRangeMap = new HashMap<>(); + /** * 窗体上可以展示的最大毫秒数,单位为毫秒 */ @@ -59,11 +64,6 @@ public class ChartStandard { */ private ChartDataRange displayRange; - /** - * 用户框选的时间范围 - */ - private ChartDataRange selectedRange; - /** * 构造函数 * @@ -75,15 +75,6 @@ public class ChartStandard { minMarkInterval = DEFAULT_TIME_UNIT; } - /** - * 修改Chart展示的时间刻度间隔长度 - * - * @param sizeTimed 时间刻度间隔 - */ - public void updateSizeTime(int sizeTimed) { - sizeTime = sizeTimed; - } - /** * 修改Chart展示的时间范围 * @@ -98,35 +89,60 @@ public class ChartStandard { displayRange.setEndTime(end); } + /** + * 根据Key获取对应的框选时间范围 + * + * @param key 区别各个Chart的key + * @return ChartDataRange + */ + public ChartDataRange getSelectedRange(String key) { + return selectedRangeMap.get(key); + } + /** * 更新用户框选的起始时间和坐标点 * + * @param key 区别各个Chart的key * @param startTime 用户新框选的时间范围 */ - public void updateSelectedStart(int startTime) { - if (selectedRange == null) { - selectedRange = new ChartDataRange(); + public void updateSelectedStart(String key, int startTime) { + ChartDataRange range = selectedRangeMap.get(key); + if (range == null) { + range = new ChartDataRange(); + selectedRangeMap.put(key, range); } - selectedRange.setStartTime(startTime); + range.setStartTime(startTime); } /** * 更新用户框选的起始时间和坐标点 * + * @param key 区别各个Chart的key * @param endTime 用户新框选的时间范围 */ - public void updateSelectedEnd(int endTime) { - if (selectedRange == null) { - selectedRange = new ChartDataRange(); + public void updateSelectedEnd(String key, int endTime) { + ChartDataRange range = selectedRangeMap.get(key); + if (range == null) { + range = new ChartDataRange(); + selectedRangeMap.put(key, range); } - selectedRange.setEndTime(endTime); + range.setEndTime(endTime); } /** - * 清空框选的时间范围 + * 清空所有Chart的框选时间范围 */ - public void clearSelectedRange() { - selectedRange = null; + public void clearAllSelectedRanges() { + selectedRangeMap.clear(); + } + + /** + * 清空指定Chart的框选时间范围 + * + * @param key 区别各个Chart的key + */ + public void clearSelectedRange(String key) { + selectedRangeMap.remove(key); } public long getSessionId() { @@ -168,8 +184,4 @@ public class ChartStandard { public ChartDataRange getDisplayRange() { return displayRange; } - - public ChartDataRange getSelectedRange() { - return selectedRange; - } } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartType.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartType.java index 5ed9752d3..9ecb02605 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartType.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/model/ChartType.java @@ -16,28 +16,33 @@ package ohos.devtools.views.charts.model; /** - * Chart类型的枚举类 + * Enumeration class of chart type * * @since 2021/2/1 9:31 */ public enum ChartType { /** - * 已填充的折线图 + * Filled poly line chart */ FILLED_LINE, /** - * 折线图 + * Poly line chart */ LINE, /** - * 柱状图/条形图 + * Bar chart */ BAR, /** - * 未知类型 + * Bar chart + */ + RECT, + + /** + * unknown type */ UNRECOGNIZED } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/LegendTooltip.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/LegendTooltip.java index 2fb766623..acddf40d0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/LegendTooltip.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/LegendTooltip.java @@ -1,282 +1,382 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts.tooltip; - -import com.intellij.ui.components.JBLabel; - -import ohos.devtools.views.charts.utils.ChartUtils; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.JComponent; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.SwingUtilities; -import javax.swing.border.LineBorder; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.util.List; -import java.util.regex.Pattern; - -import static ohos.devtools.views.common.ColorConstants.TOOLTIP; -import static ohos.devtools.views.common.ViewConstants.NUM_2; - -/** - * @Description 自定义可以跟随鼠标移动Tooltip作为图例 - * @Date 2021/1/19 21:35 - **/ -public final class LegendTooltip extends JComponent { - private static final Logger LOGGER = LogManager.getLogger(LegendTooltip.class); - - /** - * 常量1,距离鼠标常量,防止鼠标遮挡 - */ - private static final Point CONST_POINT = new Point(12, 5); - - /** - * 常量2,防止离鼠标太近,触发mouse exit事件 - */ - private static final Point CONST_POINT2 = new Point(30, 75); - - /** - * Grid布局的默认行数 - */ - private static final int DEFAULT_ROWS = 2; - - /** - * Grid布局的行高 - */ - private static final int ROW_HEIGHT = 36; - - /** - * Tooltip默认宽度 - */ - private static final int DEFAULT_WIDTH = 170; - - /** - * 单例 - */ - private static volatile LegendTooltip singleton; - - /** - * 当前Tooltip的主面板 - */ - private JPanel mainPanel; - - /** - * 当前Tooltip的父组件的根面板 - */ - private JRootPane parentRootPane; - - /** - * 窗口的遮罩层,不能随便修改,只作父对象应用 - */ - private JLayeredPane mask; - - /** - * 当前Tooltip中Grid布局的行数 - */ - private int rows = DEFAULT_ROWS; - - /** - * 单例,外部不允许初始化 - */ - private LegendTooltip() { - super(); - initTip(); - } - - /** - * 获取单例 - * - * @return 单例 - */ - public static LegendTooltip getInstance() { - if (singleton == null) { - synchronized (LegendTooltip.class) { - if (singleton == null) { - singleton = new LegendTooltip(); - } - } - } - return singleton; - } - - /** - * 初始化Tooltip - */ - private void initTip() { - this.setLayout(new FlowLayout()); - // false为控件透明,true为不透明 - this.setOpaque(false); - this.setVisible(false); - mainPanel = new JPanel(new GridLayout(rows, 1)); - mainPanel.setBackground(TOOLTIP); - } - - /** - * 隐藏组件 - */ - public void hideTip() { - this.setVisible(false); - } - - /** - * 为某个组件设置tip - * - * @param parent 显示tooltip的对象 - * @param timeline 显示的时间Tip - * @param totalValue Total值 - * @param tooltipItems 要显示的图例 - * @param isCharting boolean - */ - public void showTip(JComponent parent, String timeline, String totalValue, List tooltipItems, - boolean isCharting) { - if (parent != null && parent.getRootPane() != null) { - this.rows = tooltipItems.size() + NUM_2; - // 重新组建Tooltip - if (isCharting) { - rebuild(parent); - resize(); - return; - } - - // 动态添加和绘制图例 - addLegends(timeline, totalValue, tooltipItems); - this.validate(); - this.setVisible(true); - } - } - - /** - * 重新组建Tooltip - * - * @param parent 显示tooltip的对象 - */ - private void rebuild(JComponent parent) { - parentRootPane = parent.getRootPane(); - JLayeredPane layerPane = parentRootPane.getLayeredPane(); - - // 先从旧面板中移除tip - if (mask != null && mask != layerPane) { - mask.remove(this); - } - mask = layerPane; - - // 防止还有没有移除监听的组件 - layerPane.remove(this); - - // 由于每次要重绘mainPanel,所以也要先移除mainPanel - this.remove(mainPanel); - - // 放置tip在遮罩窗口顶层 - layerPane.add(this, JLayeredPane.POPUP_LAYER); - // 窗口遮罩层添加监听 - - // 根据传入的TooltipItem集合大小,重新创建mainPanel - mainPanel = new JPanel(new GridLayout(rows, 1)); - mainPanel.setBorder(new LineBorder(Color.BLACK)); - mainPanel.setBackground(TOOLTIP); - this.add(mainPanel); - } - - /** - * Tooltip中添加图例 - * - * @param timeline 时间 - * @param totalValue Total值 - * @param tooltipItems 图例集合 - */ - private void addLegends(String timeline, String totalValue, List tooltipItems) { - mainPanel.removeAll(); - // 添加时间 - JBLabel timeLabel = new JBLabel(); - long ms = 0; - String pattern = "^\\d{0,20}$"; - boolean isMatch = Pattern.matches(pattern, timeline); - if (isMatch) { - ms = Long.parseLong(timeline); - } else { - LOGGER.error("Time format error:{}", timeline); - } - timeLabel.setText(ChartUtils.formatTime(ms)); - timeLabel.setOpaque(false); - mainPanel.add(timeLabel); - - // 添加悬浮框的total值 - JBLabel totalLabel = new JBLabel(); - totalLabel.setOpaque(false); - totalLabel.setText("Total:" + totalValue + "MB"); - mainPanel.add(totalLabel); - - // 添加图例 - for (TooltipItem tooltipItem : tooltipItems) { - JPanel single = new JPanel(new FlowLayout(FlowLayout.LEFT)); - single.setOpaque(false); - - Color color = tooltipItem.getColor(); - if (color != null) { - single.add(new TooltipColorRect(tooltipItem.getColor())); - } - JBLabel nameLabel = new JBLabel(); - nameLabel.setOpaque(false); - nameLabel.setText(tooltipItem.getText()); - single.add(nameLabel); - mainPanel.add(single); - } - } - - /** - * 坐标转换,标签跟随鼠标移动 - * - * @param mouseEvent MouseEvent - */ - public void followWithMouse(MouseEvent mouseEvent) { - if (mask == null) { - return; - } - - this.setVisible(true); - Point screenPoint = mouseEvent.getLocationOnScreen(); - SwingUtilities.convertPointFromScreen(screenPoint, mask); - - int newLocationX = (int) (screenPoint.getX() + CONST_POINT.getX()); - int newLocationY = (int) (screenPoint.getY() + CONST_POINT.getY()); - - Dimension tipSize = mainPanel.getPreferredSize(); - if (newLocationX + tipSize.width > parentRootPane.getWidth()) { - newLocationX = (int) (screenPoint.getX() - tipSize.width - CONST_POINT2.getX()); - } - if (newLocationY + tipSize.height > parentRootPane.getHeight()) { - newLocationY = (int) (screenPoint.getY() - tipSize.height - CONST_POINT2.getY()); - } - - this.setLocation(newLocationX, newLocationY); - } - - /** - * 重新调整大小 - */ - private void resize() { - this.setSize(DEFAULT_WIDTH, this.rows * ROW_HEIGHT); - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts.tooltip; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; + +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.charts.utils.ChartUtils; + +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.JComponent; +import javax.swing.JLayeredPane; +import javax.swing.JPanel; +import javax.swing.JRootPane; +import javax.swing.SwingUtilities; +import javax.swing.border.EmptyBorder; +import javax.swing.border.LineBorder; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.regex.Pattern; + +/** + * Customize the tooltip that can follow the mouse as a legend + */ +public final class LegendTooltip extends JComponent { + private static final Logger LOGGER = LogManager.getLogger(LegendTooltip.class); + + private static final int MIN_SIZE = 2; + + private static final int NUM_2 = 2; + + private static final int NUM_3 = 4; + + /** + * 常量1,距离鼠标常量,防止鼠标遮挡 + */ + private static final Point CONST_POINT = new Point(12, 5); + + /** + * 常量2,防止离鼠标太近,触发mouse exit事件 + */ + private static final Point CONST_POINT2 = new Point(30, 75); + + /** + * Grid布局的默认行数 + */ + private static final int DEFAULT_ROWS = 2; + + /** + * Grid布局的行高 + */ + private static final int ROW_HEIGHT = 36; + + /** + * Tooltip默认宽度 + */ + private static final int DEFAULT_WIDTH = 170; + + /** + * thread unspecified + */ + private static final int THREAD_UNSPECIFIED = 0; + + /** + * thread running + */ + private static final int THREAD_RUNNING = 1; + + /** + * thread sleeping + */ + private static final int THREAD_SLEEPING = 2; + + /** + * thread stopped + */ + private static final int THREAD_STOPPED = 3; + + /** + * thread waiting + */ + private static final int THREAD_WAITING = 4; + + /** + * 当前Tooltip的主面板 + */ + private JPanel mainPanel; + + /** + * 当前Tooltip的父组件的根面板 + */ + private JRootPane parentRootPane; + + /** + * 窗口的遮罩层,不能随便修改,只作父对象应用 + */ + private JLayeredPane mask; + + /** + * 当前Tooltip中Grid布局的行数 + */ + private int rows = DEFAULT_ROWS; + + /** + * Constructor + */ + public LegendTooltip() { + initTip(); + } + + /** + * 初始化Tooltip + */ + private void initTip() { + this.setLayout(new FlowLayout()); + // false为控件透明,true为不透明 + this.setOpaque(false); + this.setVisible(false); + mainPanel = new JPanel(new GridLayout(rows, 1)); + mainPanel.setBackground(JBColor.background().darker()); + } + + /** + * 隐藏组件 + */ + public void hideTip() { + this.setVisible(false); + } + + /** + * 为某个组件设置tip + * + * @param parent 显示tooltip的对象 + * @param timeline 显示的时间Tip + * @param totalValue Total值 + * @param tooltipItems 要显示的图例 + * @param isCharting boolean + * @param axisYUnit axisYUnit + */ + public void showTip(JComponent parent, String timeline, String totalValue, List tooltipItems, + boolean isCharting, String axisYUnit) { + if (parent != null && parent.getRootPane() != null) { + this.rows = tooltipItems.size() + NUM_2; + // 重新组建Tooltip + if (isCharting) { + rebuild(parent); + resize(); + return; + } + + // 动态添加和绘制图例 + addLegends(timeline, totalValue, tooltipItems, axisYUnit); + this.validate(); + this.setVisible(true); + } + } + + /** + * 重新组建Tooltip + * + * @param parent 显示tooltip的对象 + */ + private void rebuild(JComponent parent) { + parentRootPane = parent.getRootPane(); + JLayeredPane layerPane = parentRootPane.getLayeredPane(); + + // 先从旧面板中移除tip + if (mask != null && mask != layerPane) { + mask.remove(this); + } + mask = layerPane; + + // 防止还有没有移除监听的组件 + layerPane.remove(this); + + // 由于每次要重绘mainPanel,所以也要先移除mainPanel + this.remove(mainPanel); + + // 放置tip在遮罩窗口顶层 + layerPane.add(this, JLayeredPane.POPUP_LAYER); + // 窗口遮罩层添加监听 + + // 根据传入的TooltipItem集合大小,重新创建mainPanel + mainPanel = new JPanel(new GridLayout(rows, 1)); + mainPanel.setBorder(new LineBorder(Color.BLACK)); + mainPanel.setBackground(JBColor.background().darker()); + this.add(mainPanel); + } + + /** + * Tooltip中添加图例 + * + * @param timeline 时间 + * @param totalValue Total值 + * @param tooltipItems 图例集合 + * @param axisYUnit axisYUnit + */ + private void addLegends(String timeline, String totalValue, List tooltipItems, String axisYUnit) { + mainPanel.removeAll(); + // 添加时间 + JBLabel timeLabel = new JBLabel(); + timeLabel.setBorder(new EmptyBorder(5, 5, 5, 5)); + long ms = 0; + String pattern = "^\\d{0,20}$"; + boolean isMatch = Pattern.matches(pattern, timeline); + if (isMatch) { + ms = Long.parseLong(timeline); + } else { + LOGGER.error("Time format error:{}", timeline); + } + timeLabel.setText(ChartUtils.formatTime(ms)); + timeLabel.setOpaque(false); + mainPanel.add(timeLabel); + if (StringUtils.isNotBlank(totalValue)) { + // 添加悬浮框的total值 + JBLabel totalLabel = new JBLabel(); + totalLabel.setBorder(new EmptyBorder(0, 5, 5, 5)); + totalLabel.setOpaque(false); + totalLabel.setText("Total:" + totalValue + axisYUnit); + mainPanel.add(totalLabel); + } + // 添加图例 + for (TooltipItem tooltipItem : tooltipItems) { + JPanel single = new JPanel(new FlowLayout(FlowLayout.LEFT)); + single.setOpaque(false); + + Color color = tooltipItem.getColor(); + if (color != null) { + single.add(new TooltipColorRect(tooltipItem.getColor())); + } + JBLabel nameLabel = new JBLabel(); + nameLabel.setOpaque(false); + nameLabel.setText(tooltipItem.getText()); + single.add(nameLabel); + mainPanel.add(single); + } + } + + /** + * 坐标转换,标签跟随鼠标移动 + * + * @param mouseEvent MouseEvent + */ + public void followWithMouse(MouseEvent mouseEvent) { + if (mask == null) { + return; + } + + if (this.getWidth() < MIN_SIZE || this.getHeight() < MIN_SIZE) { + this.setVisible(false); + return; + } + + this.setVisible(true); + Point screenPoint = mouseEvent.getLocationOnScreen(); + SwingUtilities.convertPointFromScreen(screenPoint, mask); + + int newLocationX = (int) (screenPoint.getX() + CONST_POINT.getX()); + int newLocationY = (int) (screenPoint.getY() + CONST_POINT.getY()); + + Dimension tipSize = mainPanel.getPreferredSize(); + if (newLocationX + tipSize.width > parentRootPane.getWidth()) { + newLocationX = (int) (screenPoint.getX() - tipSize.width - CONST_POINT2.getX()); + } + if (newLocationY + tipSize.height > parentRootPane.getHeight()) { + newLocationY = (int) (screenPoint.getY() - tipSize.height - CONST_POINT2.getY()); + } + + this.setLocation(newLocationX, newLocationY); + } + + /** + * 重新调整大小 + */ + private void resize() { + this.setSize(DEFAULT_WIDTH, this.rows * ROW_HEIGHT); + } + + /** + * showThreadStatusTip + * + * @param parent parent + * @param timeline timeline + * @param chartDataModel chartDataModel + * @param isCharting isCharting + */ + public void showThreadStatusTip(JComponent parent, String timeline, ChartDataModel chartDataModel, + boolean isCharting) { + if (parent != null && parent.getRootPane() != null) { + if (isCharting) { + this.rows = NUM_3; + rebuild(parent); + resize(); + return; + } + addThreadStatusLegends(timeline, chartDataModel.getName(), chartDataModel.getValue(), + chartDataModel.getCpuPercent()); + this.validate(); + this.setVisible(true); + } + } + + /** + * addThreadStatusLegends + * + * @param timeline timeline + * @param threadName threadName + * @param threadStatus threadStatus + * @param threadUsage threadUsage + */ + private void addThreadStatusLegends(String timeline, String threadName, int threadStatus, double threadUsage) { + mainPanel.removeAll(); + // 添加时间 + JBLabel timeLabel = new JBLabel(); + timeLabel.setBorder(new EmptyBorder(5, 5, 5, 5)); + long ms = 0; + String pattern = "^\\d{0,20}$"; + boolean isMatch = Pattern.matches(pattern, timeline); + if (isMatch) { + ms = Long.parseLong(timeline); + } else { + LOGGER.error("Time format error:{}", timeline); + } + timeLabel.setText(ChartUtils.formatTime(ms)); + timeLabel.setOpaque(false); + mainPanel.add(timeLabel); + + JBLabel nameLabel = new JBLabel(); + nameLabel.setBorder(new EmptyBorder(0, 5, 5, 5)); + nameLabel.setOpaque(false); + nameLabel.setText("Thread:" + threadName); + mainPanel.add(nameLabel); + + JBLabel statusLabel = new JBLabel(); + statusLabel.setBorder(new EmptyBorder(0, 5, 5, 5)); + statusLabel.setOpaque(false); + switch (threadStatus) { + case THREAD_RUNNING: + statusLabel.setText("RUNNING");; + break; + case THREAD_SLEEPING: + statusLabel.setText("SLEEPING");; + break; + case THREAD_STOPPED: + statusLabel.setText("STOPPED");; + break; + case THREAD_WAITING: + statusLabel.setText("WAITING");; + break; + default: + statusLabel.setText("UNSPECIFIED");; + } + mainPanel.add(statusLabel); + JBLabel usageLabel = new JBLabel(); + usageLabel.setBorder(new EmptyBorder(0, 5, 5, 5)); + usageLabel.setOpaque(false); + usageLabel.setText("OccRate:" + threadUsage); + mainPanel.add(usageLabel); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipColorRect.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipColorRect.java index 050a6a4fd..0f1469158 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipColorRect.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipColorRect.java @@ -1,70 +1,68 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.charts.tooltip; - -import javax.swing.JComponent; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; - -/** - * Tooltip中的图例色块 - * - * @since 2021/1/19 21:35 - */ -public class TooltipColorRect extends JComponent { - /** - * 图例色块大小 - */ - private static final int SIZE = 15; - - /** - * 颜色 - */ - private final Color color; - - /** - * 构造函数 - * - * @param color 图例色块的颜色 - */ - public TooltipColorRect(Color color) { - this.color = color; - this.setOpaque(false); - fillColor(); - } - - /** - * 填充颜色 - */ - private void fillColor() { - this.setPreferredSize(new Dimension(SIZE, SIZE)); - super.repaint(); - super.validate(); - } - - /** - * paintComponent - * - * @param graphics graphics - */ - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - graphics.setColor(color); - graphics.fillRect(0, 0, SIZE, SIZE); - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts.tooltip; + +import javax.swing.JComponent; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; + +/** + * Legend color block in tooltip + */ +public class TooltipColorRect extends JComponent { + /** + * Color block size + */ + private static final int SIZE = 15; + + /** + * Color + */ + private final Color color; + + /** + * Constructor + * + * @param color Color + */ + public TooltipColorRect(Color color) { + this.color = color; + this.setOpaque(false); + fillColor(); + } + + /** + * Fill color + */ + private void fillColor() { + this.setPreferredSize(new Dimension(SIZE, SIZE)); + super.repaint(); + super.validate(); + } + + /** + * Paint component + * + * @param graphics graphics + */ + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + graphics.setColor(color); + graphics.fillRect(0, 0, SIZE, SIZE); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipItem.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipItem.java index bc0f5aa6c..181915fe3 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipItem.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/tooltip/TooltipItem.java @@ -31,7 +31,7 @@ public class TooltipItem { /** * 文本 */ - private final String text; + private String text; /** * 构造函数 @@ -44,21 +44,19 @@ public class TooltipItem { this.text = text; } - /** - * Getter - * - * @return Color - */ public Color getColor() { return color; } - /** - * Getter - * - * @return String - */ + public void setColor(Color color) { + this.color = color; + } + public String getText() { return text; } + + public void setText(String text) { + this.text = text; + } } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartConstants.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartConstants.java index 8a9afde2b..429e6d274 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartConstants.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartConstants.java @@ -15,7 +15,7 @@ package ohos.devtools.views.charts.utils; -import java.awt.Color; +import com.intellij.ui.JBColor; /** * Chart相关的常量类 @@ -23,21 +23,11 @@ import java.awt.Color; * @since 2021/1/21 11:33 */ public final class ChartConstants { - /** - * 初始值 - */ - public static final int INITIAL_VALUE = -1; - /** * 默认半透明度的值 */ public static final float TRANSLUCENT_VALUE = 0.8F; - /** - * 不透明时的值 - */ - public static final float OPAQUE_VALUE = 1.0F; - /** * Chart绘制区域离顶部的偏移量(页眉高度) */ @@ -58,31 +48,16 @@ public final class ChartConstants { */ public static final int Y_AXIS_STR_OFFSET_Y = 5; - /** - * KB,MB转换时的单位 - */ - public static final int UNIT = 1024; - /** * 默认Chart绘制颜色 */ - public static final Color DEFAULT_CHART_COLOR = Color.GRAY; + public static final JBColor DEFAULT_CHART_COLOR = JBColor.GRAY; /** * 折线图线条默认宽度 */ public static final int DEFAULT_LINE_WIDTH = 3; - /** - * 数字 - */ - public static final int NUM_2 = 2; - - /** - * 数字 - */ - public static final int NUM_3 = 3; - /** * 数字 */ @@ -98,16 +73,36 @@ public final class ChartConstants { */ public static final int NUM_1000 = 1000; - /** - * 数字 - */ - public static final int NUM_1024 = 1024; - /** * 计算时默认保留的小数位数 */ public static final int DECIMAL_COUNTS = 5; + /** + * Default time range selected after clicking chart + */ + public static final int DEFAULT_SELECT = 10; + + /** + * Chart的Y轴最大单位 + */ + public static final int CHART_MAX_Y = 2; + + /** + * Chart的Y轴坐标刻度分段数量 + */ + public static final int CHART_SECTION_NUM_Y = 2; + + /** + * 时间线上的默认最大毫秒数 + */ + public static final int DEFAULT_MAX_MILLIS = 10000; + + /** + * 时间线上的默认最小时间单位,单位为毫秒 + */ + public static final int DEFAULT_TIME_UNIT = 200; + /** * 构造函数 */ diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartUtils.java index 772369b7a..b88f1c578 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/charts/utils/ChartUtils.java @@ -1,210 +1,207 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts.utils; - -import java.math.BigDecimal; - -import static java.math.BigDecimal.ROUND_HALF_UP; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_1000; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_60; -import static ohos.devtools.views.charts.utils.ChartConstants.NUM_24; -import static ohos.devtools.views.charts.utils.ChartConstants.DECIMAL_COUNTS; -import static ohos.devtools.views.common.ViewConstants.INITIAL_VALUE; - -/** - * Chart相关的工具类 - * - * @since 2021/3/3 10:41 - */ -public final class ChartUtils { - /** - * 二分法计算时除以2的常量 - */ - private static final int HALF_VALUE = 2; - - /** - * init number - */ - private static final long INIT_NUMBER = -1L; - - /** - * 构造函数 - */ - private ChartUtils() { - } - - /** - * 在有序数组中找到与目标值最接近的值的index - * - * @param arr 有序数组 - * @param value 目标值 - * @return 数组中与目标值最接近的值的index - */ - public static int searchClosestIndex(int[] arr, int value) { - // 开始位置 - int low = 0; - // 结束位置 - int high = arr.length - 1; - // 先判断下是不是大于最大值或者小于最小值,是的话直接返回 - if (value <= arr[low]) { - return low; - } - if (value >= arr[high]) { - return high; - } - int index = INITIAL_VALUE; - while (low <= high) { - int middle = (low + high) / HALF_VALUE; - - // 如果值正好相等,则直接返回查询到的索引 - if (value == arr[middle]) { - index = middle; - break; - } - // 如果已经是最后一个数据,则返回其索引 - if (middle == arr.length - 1) { - index = middle; - break; - } - // 大于当前index的值,小于下一个index的值,表明落在该区间内,取最接近的索引 - if (value > arr[middle] && value < arr[middle + 1]) { - int dif1 = value - arr[middle]; - int dif2 = arr[middle + 1] - value; - // 返回查询到的索引 - index = dif1 < dif2 ? middle : middle + 1; - break; - } - if (value > arr[middle]) { - low = middle + 1; - } - if (value < arr[middle]) { - high = middle - 1; - } - } - return index; - } - - /** - * 乘法运算 - * - * @param num1 数字1 - * @param num2 数字2 - * @return int结果 - */ - public static int multiply(BigDecimal num1, int num2) { - return num1.multiply(new BigDecimal(num2)).intValue(); - } - - /** - * 除法运算,返回BigDecimal - * - * @param num1 数字1 - * @param num2 数字2 - * @return BigDecimal结果 - */ - public static BigDecimal divide(double num1, double num2) { - return new BigDecimal(num1).divide(new BigDecimal(num2), DECIMAL_COUNTS, ROUND_HALF_UP); - } - - /** - * 除法运算,返回BigDecimal - * - * @param num1 数字1 - * @param num2 数字2 - * @return BigDecimal结果 - */ - public static BigDecimal divide(BigDecimal num1, BigDecimal num2) { - return num1.divide(num2, DECIMAL_COUNTS, ROUND_HALF_UP); - } - - /** - * 除法运算,返回int - * - * @param num1 数字1 - * @param num2 数字2 - * @return int结果 - */ - public static int divideInt(double num1, double num2) { - return new BigDecimal(num1).divide(new BigDecimal(num2), DECIMAL_COUNTS, ROUND_HALF_UP).intValue(); - } - - /** - * 除法运算,返回int - * - * @param num1 数字1 - * @param num2 数字2 - * @return int结果 - */ - public static int divide(double num1, BigDecimal num2) { - return new BigDecimal(num1).divide(num2, DECIMAL_COUNTS, ROUND_HALF_UP).intValue(); - } - - /** - * 将毫秒转换为分:秒:毫秒的格式 - * - * @param ms 处理的毫秒数 - * @return java.lang.String 转换为 分:秒:毫秒的格式 - * @date 2021/3/17 15:24 - */ - public static String formatTime(Long ms) { - int ss = NUM_1000; - int mi = ss * NUM_60; - int hh = mi * NUM_60; - int dd = hh * NUM_24; - - long day = INIT_NUMBER; - if (dd != 0) { - day = ms / dd; - } - long hour = INIT_NUMBER; - if (hh != 0) { - hour = (ms - day * dd) / hh; - } - long minute = INIT_NUMBER; - if (mi != 0) { - minute = (ms - day * dd - hour * hh) / mi; - } - long second = INIT_NUMBER; - if (ss != 0) { - second = (ms - day * dd - hour * hh - minute * mi) / ss; - } - long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss; - - StringBuilder sb = new StringBuilder(); - if (day > 0) { - sb.append(day).append(":"); - } - if (hour > 0) { - sb.append(hour).append(":"); - } - if (minute > 0) { - sb.append(minute).append(":"); - } else { - sb.append("00:"); - } - if (second > 0) { - sb.append(second).append(":"); - } else { - sb.append("00:"); - } - if (milliSecond > 0) { - sb.append(milliSecond).append(" "); - } else { - sb.append("00:"); - } - return sb.toString(); - } -} +/* + * 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. + */ + +package ohos.devtools.views.charts.utils; + +import java.math.BigDecimal; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static ohos.devtools.views.charts.utils.ChartConstants.NUM_1000; +import static ohos.devtools.views.charts.utils.ChartConstants.NUM_60; +import static ohos.devtools.views.charts.utils.ChartConstants.NUM_24; +import static ohos.devtools.views.charts.utils.ChartConstants.DECIMAL_COUNTS; +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; + +/** + * Chart相关的工具类 + */ +public final class ChartUtils { + /** + * 二分法计算时除以2的常量 + */ + private static final int HALF_VALUE = 2; + + /** + * init number + */ + private static final long INIT_NUMBER = -1L; + + /** + * 构造函数 + */ + private ChartUtils() { + } + + /** + * 在有序数组中找到与目标值最接近的值的index + * + * @param arr 有序数组 + * @param value 目标值 + * @return 数组中与目标值最接近的值的index + */ + public static int searchClosestIndex(int[] arr, int value) { + // 开始位置 + int low = 0; + // 结束位置 + int high = arr.length - 1; + // 先判断下是不是大于最大值或者小于最小值,是的话直接返回 + if (value <= arr[low]) { + return low; + } + if (value >= arr[high]) { + return high; + } + int index = INITIAL_VALUE; + while (low <= high) { + int middle = (low + high) / HALF_VALUE; + + // 如果值正好相等,则直接返回查询到的索引 + if (value == arr[middle]) { + index = middle; + break; + } + // 如果已经是最后一个数据,则返回其索引 + if (middle == arr.length - 1) { + index = middle; + break; + } + // 大于当前index的值,小于下一个index的值,表明落在该区间内,取最接近的索引 + if (value > arr[middle] && value < arr[middle + 1]) { + int dif1 = value - arr[middle]; + int dif2 = arr[middle + 1] - value; + // 返回查询到的索引 + index = dif1 < dif2 ? middle : middle + 1; + break; + } + if (value > arr[middle]) { + low = middle + 1; + } + if (value < arr[middle]) { + high = middle - 1; + } + } + return index; + } + + /** + * 乘法运算 + * + * @param num1 数字1 + * @param num2 数字2 + * @return int结果 + */ + public static int multiply(BigDecimal num1, int num2) { + return num1.multiply(new BigDecimal(num2)).intValue(); + } + + /** + * 除法运算,返回BigDecimal + * + * @param num1 数字1 + * @param num2 数字2 + * @return BigDecimal结果 + */ + public static BigDecimal divide(double num1, double num2) { + return new BigDecimal(num1).divide(new BigDecimal(num2), DECIMAL_COUNTS, ROUND_HALF_UP); + } + + /** + * 除法运算,返回BigDecimal + * + * @param num1 数字1 + * @param num2 数字2 + * @return BigDecimal结果 + */ + public static BigDecimal divide(BigDecimal num1, BigDecimal num2) { + return num1.divide(num2, DECIMAL_COUNTS, ROUND_HALF_UP); + } + + /** + * 除法运算,返回int + * + * @param num1 数字1 + * @param num2 数字2 + * @return int结果 + */ + public static int divideInt(double num1, double num2) { + return new BigDecimal(num1).divide(new BigDecimal(num2), DECIMAL_COUNTS, ROUND_HALF_UP).intValue(); + } + + /** + * 除法运算,返回int + * + * @param num1 数字1 + * @param num2 数字2 + * @return int结果 + */ + public static int divide(double num1, BigDecimal num2) { + return new BigDecimal(num1).divide(num2, DECIMAL_COUNTS, ROUND_HALF_UP).intValue(); + } + + /** + * 将毫秒转换为分:秒:毫秒的格式 + * + * @param ms 处理的毫秒数 + * @return java.lang.String 转换为 分:秒:毫秒的格式 + */ + public static String formatTime(Long ms) { + int ss = NUM_1000; + int mi = ss * NUM_60; + int hh = mi * NUM_60; + int dd = hh * NUM_24; + + long day = INIT_NUMBER; + if (dd != 0) { + day = ms / dd; + } + long hour = INIT_NUMBER; + if (hh != 0) { + hour = (ms - day * dd) / hh; + } + long minute = INIT_NUMBER; + if (mi != 0) { + minute = (ms - day * dd - hour * hh) / mi; + } + long second = INIT_NUMBER; + if (ss != 0) { + second = (ms - day * dd - hour * hh - minute * mi) / ss; + } + long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss; + + StringBuilder sb = new StringBuilder(); + if (day > 0) { + sb.append(day).append(":"); + } + if (hour > 0) { + sb.append(hour).append(":"); + } + if (minute > 0) { + sb.append(minute).append(":"); + } else { + sb.append("00:"); + } + if (second > 0) { + sb.append(second).append(":"); + } else { + sb.append("00:"); + } + if (milliSecond > 0) { + sb.append(milliSecond).append(" "); + } else { + sb.append("00:"); + } + return sb.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ColorConstants.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ColorConstants.java index 459e7bdde..a195974ed 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ColorConstants.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/ColorConstants.java @@ -1,291 +1,260 @@ -/* - * 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. - */ - -package ohos.devtools.views.common; - -import java.awt.Color; - -/** - * 颜色常量类 - * - * @since 2021/2/27 14:26 - */ -public final class ColorConstants { - /** - * color RGB 12 14 18 - */ - public static final Color BLACK_COLOR = new Color(13, 14, 19); - - /** - * color RGB 37 37 45 - */ - public static final Color BLACK_COLOR_JBUTTON = new Color(37, 37, 45); - - /** - * 文本组件的背景色 - */ - public static final Color BG_GRAY = new Color(0xEEEEEE); - - /** - * The color white. In the default sRGB space. - */ - public static final Color WHITE = new Color(255, 255, 255); - - /** - * The color lightGray. In the default sRGB space. - */ - public static final Color LIGHTGRAY = new Color(192, 192, 192); - - /** - * The color gray. In the default sRGB space. - */ - public static final Color GRAY = new Color(128, 128, 128); - - /** - * The color dark gray. In the default sRGB space. - */ - public static final Color DARKGRAY = new Color(64, 64, 64); - - /** - * The color black. In the default sRGB space. - */ - public static final Color BLACK = new Color(0, 0, 0); - - /** - * The color red. In the default sRGB space. - */ - public static final Color RED = new Color(255, 0, 0); - - /** - * The color pink. In the default sRGB space. - */ - public static final Color PINK = new Color(255, 175, 175); - - /** - * The color orange. In the default sRGB space. - */ - public static final Color ORANGE = new Color(255, 200, 0); - - /** - * The color yellow. In the default sRGB space. - */ - public static final Color YELLOW = new Color(255, 255, 0); - - /** - * The color green. In the default sRGB space. - */ - public static final Color GREEN = new Color(0, 255, 0); - - /** - * The color magenta. In the default sRGB space. - */ - public static final Color MAGENTA = new Color(255, 0, 255); - - /** - * The color cyan. In the default sRGB space. - */ - public static final Color CYAN = new Color(0, 255, 255); - - /** - * The color blue. In the default sRGB space. - */ - public static final Color BLUE = new Color(0, 0, 255); - - /** - * CHOOSE_BUTTON的颜色 - */ - public static final Color CHOOSE_BUTTON = new Color(91, 190, 212); - - /** - * DEVICE_PROCESS_PANEL颜色 - */ - public static final Color DEVICE_PROCESS_PANEL = new Color(40, 40, 48); - - /** - * SCROLL_PANE颜色 - */ - public static final Color SCROLL_PANE = new Color(13, 14, 19); - - /** - * HOME_PANE颜色 - */ - public static final Color HOME_PANE = new Color(48, 50, 52); - - /** - * SCENE_BUT颜色 - */ - public static final Color SCENE_BUT = new Color(37, 37, 45); - - /** - * SELECT_PANEL颜色 - */ - public static final Color SELECT_PANEL = new Color(69, 73, 74); - - /** - * ADD_DEVICE_BUN的颜色 - */ - public static final Color ADD_DEVICE_BUN = new Color(91, 190, 212); - - /** - * TOP_PANEL的颜色 - */ - public static final Color TOP_PANEL = new Color(13, 14, 19); - - /** - * TOP_PANEL_APPLICATION的颜色 - */ - public static final Color TOP_PANEL_APPLICATION = new Color(177, 177, 177); - - /** - * Chart背景色 - */ - public static final Color CHART_BG = new Color(0x0D0E13); - - /** - * 竖线标尺颜色 - */ - public static final Color RULER = new Color(0x757784); - - /** - * 时间线刻度颜色 - */ - public static final Color TIMELINE_SCALE = new Color(0x35353E); - - /** - * 时间线背景色 - */ - public static final Color TIMELINE_BG = new Color(0X18181D); - - /** - * Tooltip背景色 - */ - public static final Color TOOLTIP = new Color(0X18181D); - - /** - * 时间线背景色 - */ - public static final Color SCROLLBAR = new Color(0x66FFFFFF, true); - - /** - * Chart上方的指标项标题背景色 - */ - public static final Color ITEM_PANEL = new Color(0X18181D); - - /** - * 一级界面内存指标项颜色 - */ - public static final Color MEMORY = new Color(0x805BBED4, true); - - /** - * 内存:Java颜色 - */ - public static final Color MEM_JAVA = new Color(0x805BBED4, true); - - /** - * 内存:Native颜色 - */ - public static final Color MEM_NATIVE = new Color(0x80C3FFCA, true); - - /** - * 内存:Graphics颜色 - */ - public static final Color MEM_GRAPHICS = new Color(0x80FFA9A9, true); - - /** - * 内存:Stack颜色 - */ - public static final Color MEM_STACK = new Color(0x809E6EDA, true); - - /** - * 内存:Code颜色 - */ - public static final Color MEM_CODE = new Color(0x80FF9167, true); - - /** - * 内存:OTHERS颜色 - */ - public static final Color MEM_OTHERS = new Color(0x8050B4F3, true); - - /** - * 内存:OTHERS颜色 - */ - public static final Color NETWORK_RCV = new Color(0x80557EBE, true); - - /** - * 内存:OTHERS颜色 - */ - public static final Color NETWORK_SENT = new Color(0x80FEC08C, true); - - /** - * 内存:OTHERS颜色 - */ - public static final Color NETWORK_CONN = new Color(0x807D6B65, true); - - /** - * SYSTEM_TUNNING_SETTING_BACK颜色 - */ - public static final Color SYSTEM_TUNNING_SETTING_BACK = new Color(12, 14, 18); - - /** - * SYSTEM_TUNNING_SETTING_CENTER颜色 - */ - public static final Color SYSTEM_TUNNING_SETTING_CENTER = new Color(60, 63, 65); - - /** - * SYSTEM_TUNNING_WEST_LABEL颜色 - */ - public static final Color SYSTEM_TUNNING_WEST_LABEL = new Color(41, 41, 42); - - /** - * 构造函数 - */ - private ColorConstants() { - } - - /** - * 首页背景 - */ - public static final Color TOP_COLOR = new Color(41, 41, 48); - - /** - * 首页背景 - */ - public static final Color CENTER_COLOR = new Color(13, 14, 19); - - /** - * BORDER背景 - */ - public static final Color BORDER_COLOR = new Color(117, 119, 132); - - /** - * APPLYTUN_COLOR背景 - */ - public static final Color APPLYTUN_COLOR = new Color(53, 53, 62); - - /** - * SYSTEM_COLOR背景 - */ - public static final Color SYSTEM_COLOR = new Color(38, 38, 45); - - /** - * trace table COlOR - */ - public static final Color TRACE_TABLE_COLOR = new Color(20, 21, 25); - - /** - * table selected background - */ - public static final Color SELECTED_TABLE_COLOR = new Color(67, 67, 79); -} +/* + * 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. + */ + +package ohos.devtools.views.common; + +import com.intellij.ui.Gray; +import com.intellij.ui.JBColor; + +import java.awt.Color; + +/** + * ColorConstants + */ +public final class ColorConstants { + /** + * 构造函数 + */ + private ColorConstants() { + } + + /** + * color RGB 12 14 18 + */ + public static final Color BLACK_COLOR = new Color(13, 14, 19); + + /** + * The color black. In the default sRGB space. + */ + public static final Color BLACK = new Color(0, 0, 0); + + /** + * The color cyan. In the default sRGB space. + */ + public static final Color CYAN = new Color(0, 255, 255); + + /** + * HOME_PANE颜色 + */ + public static final Color HOME_PANE = new Color(48, 50, 52); + + /** + * SELECT_PANEL颜色 + */ + public static final Color SELECT_PANEL = new Color(69, 73, 74); + + /** + * Chart background color + */ + public static final Color CHART_BG = new Color(0x0D0E13); + + /** + * Vertical ruler color + */ + public static final Color RULER = new Color(0x757784); + + /** + * Timeline scale color + */ + public static final Color TIMELINE_SCALE = new Color(0x35353E); + + /** + * Scrollbar background color + */ + public static final Color SCROLLBAR = new Color(0x66FFFFFF, true); + + /** + * Font color + */ + public static final Color FONT_COLOR = new Color(0xFFE6E6E6, true); + + /** + * 1st level interface memory item chart color + */ + public static final Color MEMORY = new Color(0xFF3391FF, true); + + /** + * 1st level interface CPU item chart color + */ + public static final Color CPU = new Color(0xFF3391FF, true); + + /** + * 2nd level interface memory item chart color: Java + */ + public static final Color MEM_JAVA = new Color(0xFF5BBED4, true); + + /** + * 2nd level interface memory item chart color: Native + */ + public static final Color MEM_NATIVE = new Color(0xFFC3FFCA, true); + + /** + * 2nd level interface memory item chart color: Graphics + */ + public static final Color MEM_GRAPHICS = new Color(0xFFFFA9A9, true); + + /** + * 2nd level interface memory item chart color: Stack + */ + public static final Color MEM_STACK = new Color(0xFF9E6EDA, true); + + /** + * 2nd level interface memory item chart color: Code + */ + public static final Color MEM_CODE = new Color(0xFFFF9167, true); + + /** + * 2nd level interface memory item chart color: Others + */ + public static final Color MEM_OTHERS = new Color(0xFF50B4F3, true); + + /** + * Network Legend color: Received + */ + public static final Color NETWORK_RCV = new Color(0xFF66ADFF, true); + + /** + * Network Legend color: Sent + */ + public static final Color NETWORK_SENT = new Color(0xFFFF9201, true); + + /** + * Network Legend color: Connections + */ + public static final Color NETWORK_CONN = new Color(0xFF7D6B64, true); + + /** + * Energy Legend color: CPU + */ + public static final Color ENERGY_CPU = new Color(0xFF535DA6, true); + + /** + * Energy Legend color: Network + */ + public static final Color ENERGY_NETWORK = new Color(0xFF878FCA, true); + + /** + * Energy Legend color: Location + */ + public static final Color ENERGY_LOCATION = new Color(0xFFB9BFE8, true); + + /** + * Energy Legend color: System event Location + */ + public static final Color ENERGY_EVENT_LOCATION = new Color(65, 155, 249); + + /** + * Energy Legend color: System event Wake Locks + */ + public static final Color ENERGY_EVENT_LOCKS = new Color(0xFFC15A65, true); + + /** + * Energy Legend color: System event Alarms&Jobs + */ + public static final Color ENERGY_EVENT_ALARMS_JOBS = new Color(0xFFFFC880, true); + + /** + * DISK_IO_READ + */ + public static final Color DISK_IO_READ = new Color(0xFFDD9A16, true); + + /** + * DISK_IO_WRITE + */ + public static final Color DISK_IO_WRITE = new Color(0xFF04A9AC, true); + + /** + * trace table COlOR + */ + public static final Color TRACE_TABLE_COLOR = new Color(20, 21, 25); + + /** + * native record border color + */ + public static final Color NATIVE_RECORD_BORDER = new Color(0x474F59); + + /** + * JComBoBox border color + */ + public static final Color COMBOBOX_BORDER = new Color(71, 79, 89); + + /** + * Hyperlinks color + */ + public static final Color HYPERLINK = new Color(0, 118, 255); + + /** + * selected color + */ + public static final Color SELECTED_COLOR = new Color(12, 101, 209); + + /** + * url color + */ + public static final JBColor URL_COLOR = new JBColor(new Color(0x0076FF, true), + new Color(0, 118, 255)); + + /** + * ability background color + */ + public static final Color ABILITY_COLOR = new JBColor(new Color(0xFF494E52, true), + new Color(73, 78, 82)); + + /** + * ability active color + */ + public static final Color ABILITY_ACTIVE_COLOR = new JBColor(new Color(0xFF0C65D1, true), + new Color(12, 101, 209)); + + /** + * ability initial color + */ + public static final Color ABILITY_INITIAL_COLOR = + new JBColor(new Color(0xFFAEB1B3, true), new Color(174, 177, 179)); + + /** + * network request color + */ + public static final Color NETWORK_REQUEST_COLOR = new JBColor(new Color(0xFF9201), + new Color(255, 146, 1)); + + /** + * network response color + */ + public static final Color NETWORK_RESPONSE_COLOR = new JBColor(new Color(0x3391FF, true), + new Color(51, 145, 255)); + + /** + * network overview text color + */ + public static final Color NETWORK_OVER_VIEW_COLOR = new JBColor(new Color(0xFF999999, true), Gray._153); + + /** + * ability home color + */ + public static final Color ABILITY_HOME_COLOR = new JBColor(new Color(0xE88FAE, true), + new Color(232, 143, 174)); + + /** + * ability home other color + */ + public static final Color ABILITY_HOME_OTHER_COLOR = + new JBColor(new Color(0xECA5BF, true), new Color(236, 165, 191)); + + /** + * ability back event color + */ + public static final Color ABILITY_BACK_COLOR = new JBColor(new Color(0xACACAC), Gray._172); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Common.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Common.java deleted file mode 100644 index a7f836d17..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Common.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import java.awt.Component; - -/** - * 公共方法类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class Common { - public Common() { - } - - /** - * updateNum - * - * @param jTabbedPane jTabbedPane - */ - public void updateNum(JTabbedPane jTabbedPane) { - // 更新所有的run -- of -- - for (int index = 0; index < jTabbedPane.getTabCount(); index++) { - Component component = jTabbedPane.getComponentAt(index); - JPanel jScrollPanelCom = (JPanel) component; - JPanel jScrollPanelComChart = null; - Object componentsObj = jScrollPanelCom.getComponents()[0]; - if (componentsObj instanceof JPanel) { - jScrollPanelComChart = (JPanel) componentsObj; - // 定位到chart监测页面 - if (jScrollPanelComChart.getComponentCount() == LayoutConstants.DEVICES_Y) { - JPanel componentComAll = null; - Object compObj = jScrollPanelComChart.getComponents()[0]; - if (compObj instanceof JPanel) { - componentComAll = (JPanel) compObj; - if (componentComAll.getComponents()[0] instanceof JLabel) { - continue; - } else { - JPanel componentComAllJpanelJlabel = (JPanel) componentComAll.getComponents()[0]; - for (Component componentAll : componentComAllJpanelJlabel.getComponents()) { - if (componentAll instanceof JLabel) { - JLabel jcb = (JLabel) componentAll; - jcb.setText("Run " + (index + 1) + " of " + jTabbedPane.getTabCount()); - } - } - } - } - } - } - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Constant.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Constant.java index 94ee723b0..f54e0ac1e 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Constant.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/Constant.java @@ -1,130 +1,69 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; - -import javax.swing.JTabbedPane; -import java.util.HashMap; -import java.util.Map; - -/** - * @Description Constants - * @version 1.0 - * @date 2021/3/4 10:55 - **/ -public class Constant { - /** - * Default polling frequency. - */ - public static final String POLLING_FREQUEBCY_DEFAULT = "0/1 * * * * ?"; - - /** - * The source file path pushed by the plugin - */ - public static final String SOURCE_FILEPATH = "src/main/resources/"; - - /** - * Cpu plugin file name - */ - public static final String CPU_PLUG_NAME = "Cpu"; - - /** - * Gpu plugin file name - */ - public static final String GPU_PLUG_NAME = "Gpu"; - - /** - * Memory plugin file name - */ - public static final String MEMORY_PLUG_NAME = "Memory"; - - /** - * Process plugin file name - */ - public static final String PROCESS_PLUG_NAME = "Process"; - - /** - * The target file path of the plug-in push - */ - public static final String TARGET_PLUG_PATH = "/data/local/tmp/hiprofiler/bin/"; - - /** - * File suffix pushed by the plugin - */ - public static final String FILE_SUFFIX = ".so"; - - /** - * The default value of SAMPLE INTERVAL - */ - public static final int SAMPLE_INTERVAL_DEFAULT = 1000; - - /** - * STATUS - */ - public static final int NORMAL_STATUS = 0; - - /** - * Real-time scene - */ - public static final int REALTIME_SCENE = 1; - - /** - * File import scene - */ - public static final int FILE_IMPORT_SCENE = 2; - - /** - * MB - */ - public static final int MB = 1024; - - /** - * Abnormal state - */ - public static final Long ABNORMAL = -1L; - - /** - * Common tab - */ - public static JTabbedPane jtasksTab = null; - - /** - * Real-time refresh task name in the device selection box - */ - public static final String DEVICEREFRESH = "deviceRefresh"; - - /** - * Maps stored in all process devices - */ - public static Map> map = new HashMap<>(); - - /** - * File suffix pushed by the plugin - */ - public static final String TRACE_SUFFIX = ".trace"; - - /** - * trace file path - */ - public static String path = ""; - - /** - * trace文件保存路径 - */ - public static String tracePath = ""; -} +/* + * 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. + */ + +package ohos.devtools.views.common; + +import com.intellij.ui.components.JBTabbedPane; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * Constants + */ +public class Constant { + /** + * develop mode + */ + public static final boolean IS_DEVELOP_MODE = false; + + /** + * IS_SUPPORT_NEW_HDC + */ + public static final boolean IS_SUPPORT_NEW_HDC = true; + + /** + * Common tab + */ + public static JBTabbedPane jtasksTab = null; + + /** + * Real-time refresh task name in the device selection box + */ + public static final String DEVICE_REFRESH = "deviceRefresh"; + + /** + * Real-time refresh task name in the device selection box + */ + public static final String DISTRIBUTED_REFRESH = "DistributedRefresh"; + + /** + * Maps stored in all process devices + */ + public static Map> map = new HashMap<>(); + + /** + * File suffix pushed by the plugin + */ + public static final String TRACE_SUFFIX = ".trace"; + + /** + * treeTable init count + */ + public static int MEMORY_AGENT_INIT_COUNT = 1000; + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/LayoutConstants.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/LayoutConstants.java index 5e084deba..0fed6e436 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/LayoutConstants.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/LayoutConstants.java @@ -1,1933 +1,873 @@ -/* - * 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. - */ - -package ohos.devtools.views.common; - -/** - * 主界面相关的常量值 - * - * @version 1.0 - * @date 2021/03/02 16:33 - **/ -public final class LayoutConstants { - /** - * 构造函数 - */ - private LayoutConstants() { - } - - /** - * Chart延迟启动的时长,单位为毫秒 - */ - public static final int CHART_START_DELAY = 2000; - - /** - * Chart loading图的大小 - */ - public static final int LOADING_SIZE = 60; - - /** - * 界面布局宽度 - */ - public static final int WINDOW_WIDTH = 1200; - - /** - * 界面布局高度 - */ - public static final int WINDOW_HEIGHT = 800; - - /** - * 字体大小 - */ - public static final int FONT_SIZE = 14; - - /** - * 二级欢迎界面按钮宽度 - */ - public static final int BUTTON_WIDTH = 125; - - /** - * 进程框大小 - */ - public static final int PRECCE_WIDTH = 560; - - /** - * 二级欢迎界面按钮高度 - */ - public static final int BUTTON_HEIGHT = 25; - - /** - * 多配置界面选项卡窗体宽度 - */ - public static final int OPT_WIDTH = 1200; - - /** - * 多配置界面选项卡窗体高度 - */ - public static final int OPT_HEIGHT = 800; - - /** - * 多配置界面选项卡标签宽度 - */ - public static final int JPA_LABEL_WIDTH = 135; - - /** - * 多配置界面选项卡标签高度 - */ - public static final int JP_LABEL_HEIGHT = 20; - - /** - * 多配置界面选项卡标签左侧宽 - */ - public static final int JP_LEFT_WIDTH = 118; - - /** - * 多配置界面选项卡标签左侧宽 - */ - public static final int JP_LEFT_HEIGHT = 20; - - /** - * 多配置界面选项卡标签右侧宽 - */ - public static final int JP_RIGHT_WIDTH = 10; - - /** - * 多配置界面选项卡标签右侧宽 - */ - public static final int JP_RIGHT_HEIGHT = 20; - - /** - * 配置界面选项卡标签宽度 - */ - public static final int JP_SET_WIDTH = 118; - - /** - * 配置界面选项卡标签宽度 - */ - public static final int JP_SET_HEIGHT = 20; - - /** - * 应用场景标签X值 - */ - public static final int APP_LABEL_X = 30; - - /** - * 应用场景标签Y1值 - */ - public static final int APP_LABEL_Y1 = 550; - - /** - * 高度 - */ - public static final int APP_LABEL_HIGHT = 55; - - /** - * 应用场景标签Y1值 - */ - public static final int APP_LABEL_Y2 = 580; - - /** - * 应用场景标签宽度 - */ - public static final int APP_LABEL_WIDTH = 2500; - - /** - * 应用场景标签高度 - */ - public static final int APP_LABEL_HEIGHT = 20; - - /** - * 应用场景标签字体大小 - */ - public static final int APP_LABEL_FONT = 15; - - /** - * 应用场景描述字体大小 - */ - public static final int TUN_LABEL_FONT = 12; - - /** - * 选择按钮X值 - */ - public static final int CHOOSE_X = 900; - - /** - * 选择按钮Y值 - */ - public static final int CHOOSE_Y = 670; - - /** - * 选择按钮宽度 - */ - public static final int CHOOSE_WIDTH = 150; - - /** - * 选择按钮高度 - */ - public static final int CHOOSE_HEIGHT = 40; - - /** - * 场景类型标签X值 - */ - public static final int TASK_SCENE_X = 30; - - /** - * 场景类型标签Y值 - */ - public static final int TASK_SCENE_Y = 30; - - /** - * 设备框大小 - */ - public static final int HEIGHT_PRESSE = 451; - - /** - * 场景类型标签宽度 - */ - public static final int TASK_WIDTH = 300; - - /** - * 场景类型标签高度 - */ - public static final int TASK_HEIGHT = 20; - - /** - * 场景类型标签字体 - */ - public static final int TASK_FONT = 25; - - /** - * 选择场景类型标签X值 - */ - public static final int CH_TASK_X = 190; - - /** - * 选择场景类型标签Y值 - */ - public static final int CH_TASK_Y = 33; - /** - * 选择场景类型标签宽度 - */ - public static final int CH_TASK_WIDTH = 250; - - /** - * 选择场景类型标签高度 - */ - public static final int CH_TASK_HEIGHT = 20; - - /** - * 选择场景类型字体 - */ - public static final int CH_TASK_FONT = 15; - - /** - * 应用场景按钮X值 - */ - public static final int APP_BUT_X = 50; - - /** - * 应用场景按钮Y值 - */ - public static final int APP_BUT_Y = 80; - - /** - * 应用场景按钮宽度 - */ - public static final int APP_BUT_WIDTH = 157; - - /** - * 应用场景按钮高度 - */ - public static final int APP_BUT_HEIGHT = 95; - - /** - * 应用场景按钮字体大小 - */ - public static final int APP_BUT_FONT = 12; - - /** - * 系统场景按钮X值 - */ - public static final int SYS_BUT_X = 247; - - /** - * 系统场景按钮Y值 - */ - public static final int SYS_BUT_Y = 80; - - /** - * 系统场景按钮宽度 - */ - public static final int SYS_BUT_WIDTH = 157; - - /** - * 系统场景按钮高度 - */ - public static final int SYS_BUT_HEIGHT = 95; - - /** - * 系统场景按钮字体大小 - */ - public static final int SYS_BUT_FONT = 12; - - /** - * 分布式场景按钮X值 - */ - public static final int EMB_BUT_X = 444; - - /** - * 分布式场景按钮Y值 - */ - public static final int EMB_BUT_Y = 80; - - /** - * 分布式场景按钮宽度 - */ - public static final int EMB_BUT_WIDTH = 157; - - /** - * 分布式场景按钮高度 - */ - public static final int EMB_BUT_HEIGHT = 95; - - /** - * 设备进程面板X值 - */ - public static final int DEVICE_PRO_X = 35; - - /** - * 设备进程面板Y值--num - */ - public static final int DEVICE_PRO_Y = 0; - - /** - * 设备进程面板宽度 - */ - public static final int DEVICE_PRO_WIDTH = 700; - - /** - * 设备进程面板高度 - */ - public static final int DEVICE_PRO_HEIGHT = 150; - - /** - * 每一台设备对应X值 - */ - public static final int DEVICES_X = 40; - - /** - * 每一台设备对应Y值 - */ - public static final int DEVICES_Y = 2; - - /** - * 每一台设备对标签宽度 - */ - public static final int DEVICES_WIDTH = 100; - - /** - * 每一台设备对标签高度 - */ - public static final int DEVICES_HEIGHT = 20; - - /** - * 每一台设备对标签字体大小 - */ - public static final int DEVICES_FONT = 13; - - /** - * 设备信息标签对应X值 - */ - public static final int DEVICE_X = 40; - - /** - * 每设备信息标签对应Y值 - */ - public static final int DEVICE_Y = 30; - - /** - * 每设备信息标签宽度 - */ - public static final int DEVICE_WIDTH = 50; - - /** - * 每设备信息标签高度 - */ - public static final int DEVICE_HEIGHT = 20; - - /** - * 设备连接方式下拉框对应X值 - */ - public static final int CON_BOX_X = 85; - - /** - * 设备连接方式下拉框对应Y值 - */ - public static final int CON_BOX_Y = 30; - - /** - * 设备连接方式下拉框宽度 - */ - public static final int CON_BOX_WIDTH = 100; - - /** - * 设备连接方式下拉框高度 - */ - public static final int CON_BOX_HEIGHT = 20; - - /** - * 设备名称下拉框对应X值 - */ - public static final int DEVICE_NAME_X = 200; - - /** - * 设备名称下拉框对应Y值 - */ - public static final int DEVICE_NAME_Y = 30; - - /** - * 设备名称下拉框宽度 - */ - public static final int DEVICE_NAME_WIDTH = 300; - - /** - * 设备名称下拉框高度 - */ - public static final int DEVICE_NAME_HEIGHT = 20; - - /** - * 进程名称下拉框对应X值 - */ - public static final int APP_NAME_X = 40; - - /** - * 进程名称下拉框对应Y值 - */ - public static final int APP_NAME_Y = 90; - - /** - * 进程名称下拉框宽度 - */ - public static final int APP_NAME_WIDTH = 80; - - /** - * 进程名称下拉框高度 - */ - public static final int APP_NAME_HEIGHT = 20; - - /** - * 选择面板对应X值 - */ - public static final int SE_PANEL_X = 115; - - /** - * Y轴高度 - */ - public static final int SE_PANEL_Y_TWO = 110; - - /** - * 选择面板对应Y值 - */ - public static final int SE_PANEL_Y = 90; - - /** - * 选择面板宽度 - */ - public static final int SE_PANEL_WIDTH = 300; - - /** - * 选择面板高度 - */ - public static final int SE_PANEL_HEIGHT = 20; - - /** - * 进程框y轴距离 - */ - public static final int PRECCE_HEIGHT_Y = 155; - - /** - * 标签名称文本框宽度 - */ - public static final int LABEL_NAME_WIDTH = 280; - - /** - * 标签名称文本框高度 - */ - public static final int LABEL_NAME_HEIGHT = 20; - - /** - * 标签名称文本框宽度 - */ - public static final int LABEL_SVG_WIDTH = 20; - - /** - * 标签名称文本框高度 - */ - public static final int LABEL_SVG_HEIGHT = 20; - - /** - * 设备添加按钮对应X值 - */ - public static final int DEVICE_ADD_X = 5; - - /** - * 设备添加按钮对应Y值 - */ - public static final int DEVICE_ADD_Y = 5; - - /** - * 设备添加按钮宽度 - */ - public static final int DEVICE_ADD_WIDTH = 100; - - /** - * 设备添加按钮高度 - */ - public static final int DEVICE_ADD_HEIGHT = 30; - - /** - * Center容器左边部分top面板宽度 - */ - public static final int LEFT_TOP_WIDTH = 700; - - /** - * Center容器左边部分top面板高度 - */ - public static final int LEFT_TOP_HEIGHT = 540; - - /** - * Center容器左边部分center面板宽度 - */ - public static final int LEFT_CENTER_WIDTH = 700; - - /** - * Center容器左边部分center面板高度 - */ - public static final int LEFT_CENTER_HEIGHT = 100; - - /** - * Center容器左边部分按钮面板高度 - */ - public static final int LEFT_BUN_WIDTH = 550; - - /** - * Center容器左边部分按钮面板高度 - */ - public static final int LEFT_BUN_HEIGHT = 100; - - /** - * Center容器右边部分按钮面板高度 - */ - public static final int RIGHT_BUN_WIDTH = 150; - - /** - * Center容器右边部分按钮面板高度 - */ - public static final int RIGHT_BUN_HEIGHT = 100; - - /** - * 监控按钮面板对应X值 - */ - public static final int MONITOR_PANEL_X = 20; - - /** - * 设备添加按钮对应Y值 - */ - public static final int MONITOR_PANEL_Y = 0; - - /** - * 设备添加按钮宽度 - */ - public static final int MONITOR_PANEL_WIDTH = 450; - - /** - * 设备添加按钮高度 - */ - public static final int MONITOR_PANEL_HEIGHT = 50; - - /** - * 监控按钮标签对应X值 - */ - public static final int MONITOR_BUN_X = 20; - - /** - * 监控按钮标签对应Y值 - */ - public static final int MONITOR_BUN_Y = 15; - - /** - * 监控按钮标签宽度 - */ - public static final int MONITOR_BUN_WIDTH = 450; - - /** - * 监控按钮标签高度 - */ - public static final int MONITOR_BUN_HEIGHT = 20; - - /** - * 监控按钮标签字体大小 - */ - public static final int MONITOR_BUN_FONT = 15; - - /** - * 监控项复选框对应X值 - */ - public static final int MONITOR_OPT_X = 20; - - /** - * 监控项复选框对应Y值 - */ - public static final int MONITOR_OPT_Y = 50; - - /** - * 监控项复选框宽度 - */ - public static final int MONITOR_OPT_WIDTH = 450; - - /** - * 监控项复选框高度 - */ - public static final int MONITOR_OPT_HEIGHT = 200; - - /** - * Center容器左边面板宽度 - */ - public static final int WEST_LABEL_WIDTH = 700; - - /** - * Center容器左边面板高度 - */ - public static final int WEST_LABEL_HEIGHT = 80; - - /** - * Center容器右边面板宽度 - */ - public static final int EAST_LABEL_WIDTH = 500; - - /** - * 多场景页面y轴距离 - */ - public static final int EAST_LABEL_Y = 520; - - /** - * Center容器右边面板高度 - */ - public static final int EAST_LABEL_HEIGHT = 80; - - /** - * top、south容器面板宽度 - */ - public static final int TOP_SOUTH_WIDTH = 100; - - /** - * top、south容器面板高度 - */ - public static final int TOP_SOUTH_HEIGHT = 80; - - /** - * 应用场景标签对应X值 - */ - public static final int TASK_LABEL_X = 30; - - /** - * 应用场景标签对应Y值 - */ - public static final int TASK_LABEL_Y = 30; - - /** - * 应用场景标签宽度 - */ - public static final int TASK_LABEL_WIDTH = 250; - - /** - * 应用场景标签高度 - */ - public static final int TASK_LABEL_HEIGHT = 20; - - /** - * 应用场景标签字体大小 - */ - public static final int TASK_LABEL_FONT = 20; - - /** - * 应用场景标签字体大小 - */ - public static final int SYSTEM_TUNNING_LABEL_FONT = 14; - - /** - * 应用场景描述对应X值 - */ - public static final int TASK_DEC_X = 270; - - /** - * number计算 - */ - public static final int TASK_DEC_NUM = 27; - - /** - * 应用场景描述对应Y值 - */ - public static final int TASK_DEC_Y = 33; - - /** - * 应用场景描述宽度 - */ - public static final int TASK_DEC_WIDTH = 200; - - /** - * 应用场景描述高度 - */ - public static final int TASK_DEC_HEIGHT = 20; - - /** - * 应用场景描述字体大小 - */ - public static final int TASK_DEC_FONT = 12; - - /** - * SYSTEM TUNNING JCheckBox 字体大小 - */ - public static final int SYSTEM_TUNNING_JCHECKBOX_FONT = 14; - - /** - * 监控项内存标签对应X值 - */ - public static final int MEMORY_X = 20; - - /** - * 监控项内存标签对应Y值 - */ - public static final int MEMORY_Y = 10; - - /** - * 内存添加标签对应MemoryX值 - */ - public static final int MEMORY_X_TESTING = 32; - - /** - * 内存添加标签对应MemoryY值 - */ - public static final int MEMORY_Y_TESTING = 32; - - /** - * 监控项内存标签宽度 - */ - public static final int MEMORY_WIDTH = 50; - - /** - * 监控项内存标签高度 - */ - public static final int MEMORY_HEIGHT = 20; - - /** - * 全部选择复选框对应X值 - */ - public static final int SELECT_ALL_X = 20; - - /** - * 全部选择复选框对应Y值 - */ - public static final int SELECT_ALL_Y = 40; - - /** - * 监测页面内存添加全部选择复选框对应X值 - */ - public static final int SELECT_ALL_X_TESTING = 34; - - /** - * 监测页面内存添加全部选择复选框对应Y值 - */ - public static final int SELECT_ALL_Y_TESTING = 90; - - /** - * 全部选择复选框宽度 - */ - public static final int SELECT_ALL_WIDTH = 100; - - /** - * 全部选择复选框高度 - */ - public static final int SELECT_ALL_HEIGHT = 20; - - /** - * java选择框对应X值 - */ - public static final int JAVA_X = 250; - - /** - * java选择框对应Y值 - */ - public static final int JAVA_Y = 40; - - /** - * 监测页面内存添加java选择框对应X值 - */ - public static final int JAVA_X_TESTING = 240; - - /** - * 监测页面内存添加java选择框对应Y值 - */ - public static final int JAVA_Y_TESTING = 90; - - /** - * java选择框宽度 - */ - public static final int JAVA_WIDTH = 120; - - /** - * java选择框高度 - */ - public static final int JAVA_HEIGHT = 20; - - /** - * native选择框对应X值 - */ - public static final int NATIVE_X = 20; - - /** - * native选择框对应Y值 - */ - public static final int NATIVE_Y = 70; - - /** - * 检测页面内存添加native选择框对应X值 - */ - public static final int NATIVE_X_TESTING = 34; - - /** - * 检测页面内存添加native选择框对应Y值 - */ - public static final int NATIVE_Y_TESTING = 128; - - /** - * native选择框宽度 - */ - public static final int NATIVE_WIDTH = 100; - - /** - * native选择框高度 - */ - public static final int NATIVE_HEIGHT = 20; - - /** - * graphics选择框对应X值 - */ - public static final int GRAPHICS_X = 250; - - /** - * graphics选择框对应Y值 - */ - public static final int GRAPHICS_Y = 70; - - /** - * 检测页面内存添加graphics选择框对应X值 - */ - public static final int GRAPHICS_X_TESTING = 240; - - /** - * 检测页面内存添加graphics选择框对应Y值 - */ - public static final int GRAPHICS_Y_TESTING = 128; - - /** - * graphics选择框宽度 - */ - public static final int GRAPHICS_WIDTH = 100; - - /** - * graphics选择框高度 - */ - public static final int GRAPHICS_HEIGHT = 20; - - /** - * stack选择框对应X值 - */ - public static final int STACK_X = 20; - - /** - * stack选择框对应Y值 - */ - public static final int STACK_Y = 100; - - /** - * 检测页面内存添加stack选择框对应X值 - */ - public static final int STACK_X_TESTING = 34; - - /** - * 检测页面内存添加stack选择框对应Y值 - */ - public static final int STACK_Y_TESTING = 166; - - /** - * stack选择框宽度 - */ - public static final int STACK_WIDTH = 120; - - /** - * stack选择框高度 - */ - public static final int STACK_HEIGHT = 20; - - /** - * code选择框对应X值 - */ - public static final int CODE_X = 250; - - /** - * code选择框对应Y值 - */ - public static final int CODE_Y = 100; - - /** - * 检测页面内存添加code选择框对应X值 - */ - public static final int CODE_X_TESTING = 240; - - /** - * 检测页面内存添加code选择框对应Y值 - */ - public static final int CODE_Y_TESTING = 166; - - /** - * code选择框宽度 - */ - public static final int CODE_WIDTH = 100; - - /** - * code选择框高度 - */ - public static final int CODE_HEIGHT = 20; - - /** - * others选择框对应X值 - */ - public static final int OTHERS_X = 20; - - /** - * others选择框对应Y值 - */ - public static final int OTHERS_Y = 130; - - /** - * 检测页面内存添加others选择框对应X值 - */ - public static final int OTHERS_X_TESTING = 34; - - /** - * 检测页面内存添加others选择框对应Y值 - */ - public static final int OTHERS_Y_TESTING = 204; - - /** - * others选择框宽度 - */ - public static final int OTHERS_WIDTH = 100; - - /** - * others选择框高度 - */ - public static final int OTHERS_HEIGHT = 20; - - /** - * 滚轮滚动速度 - */ - public static final int SCROLL_UNIT_INCREMENT = 10; - - /** - * 数组索引 - */ - public static final int INDEX_ZERO = 0; - - /** - * 数组索引 - */ - public static final int INDEX_ONE = 1; - - /** - * 数组索引 - */ - public static final int INDEX_TWO = 2; - - /** - * 数组索引 - */ - public static final int INDEX_THREE = 3; - - /** - * 数组索引 - */ - public static final int INDEX_FOUR = 4; - - /** - * 数组索引 - */ - public static final int INDEX_FIVE = 5; - - /** - * 数组索引 - */ - public static final int INDEX_SIX = 6; - - /** - * 数组索引 - */ - public static final int INDEX_SEVEN = 7; - - /** - * X轴距离 - */ - public static final int NUMBER_X = 160; - - /** - * X轴距离 - */ - public static final int NUMBER_X_ADD = 165; - - /** - * 多场景按钮宽度 - */ - public static final int WIDTHS = 250; - - /** - * Y轴距离 - */ - public static final int NUMBER_Y = 4; - - /** - * 高度 - */ - public static final int HEIGHT = 45; - - /** - * 用于Y轴位置计算 - */ - public static final int HEIGHT_Y = 150; - - /** - * X轴位置 - */ - public static final int POSITION_X = 150; - - /** - * X轴位置 - */ - public static final int POSITION_TASK_X = 1070; - - /** - * 计数/y轴高度 - */ - public static final int NUMBER_TWO = 2; - - /** - * X轴位置 - */ - public static final int NUMBER_STEP = 950; - - /** - * 秒数计数 - */ - public static final int NUMBER_SECONDS = 59; - - /** - * 秒数计数 - */ - public static final int NUMBER_SLEEEP = 50; - - /** - * 循环计数 - */ - public static final int NUMBER_FOR = 220; - - /** - * Thread interval time - */ - public static final int NUMBER_THREAD = 1000; - - /** - * CHOOSE按钮X轴距离 - */ - public static final int CHOSSE_X = 1070; - - /** - * 滚东条计数 - */ - public static final int SCROPNUM = 360; - - /** - * 多场景描述面板大小 - */ - public static final int JLABEL_SIZE = 60; - - /** - * 宽度 - */ - public static final int WIDTH = 145; - - /** - * 分割线宽度 - */ - public static final int SPLITWIDTH = 9; - - /** - * 图片宽度 - */ - public static final int SVGWIDTH_ONE = 16; - - /** - * 图片宽度 - */ - public static final int SVGWIDTH_TWO = 24; - - /** - * 图片宽度 - */ - public static final int SVGWIDTH_THREE = 32; - - /** - * 图片宽度 - */ - public static final int SVGWIDTH_FOUR = 48; - - /** - * 图片宽度 - */ - public static final int SVGWIDTH_FIVE = 64; - - /** - * SVG宽度 - */ - public static final int SVGWIDTHONE = -1; - - /** - * SVG高度 - */ - public static final int SVGWIDTHTWO = 1; - - /** - * SVG计数 - */ - public static final int SVGNUMBER = 16; - - /** - * SVG计数 - */ - public static final int SVGNUMBERXXONE = 0xffffff; - - /** - * SVG计数 - */ - public static final int SVGNUMBERXTWO = 0x00ffffff; - - /** - * SVG计数 - */ - public static final int SVGNUMBERXTHREE = 0xff000000; - - /** - * 定位chart页面 - */ - public static final int INTNUMBER = 3; - - /** - * 宽度 - */ - public static final int WIDTHSUPEN = 400; - - /** - * 场景描述框大小 - */ - public static final int HIGTHSCEECS = 65; - - /** - * 字体大小 - */ - public static final int FONT = 11; - - /** - * 二级界面的按钮大小 - */ - public static final int BUTTON_SIZE = 28; - - /** - * 二级界面的run和stop按钮宽度 - */ - public static final int BUTTON_WIDTHS = 45; - - /** - * memory对话框宽度 - */ - public static final int MEMORY_WIDTH_SIZE = 484; - - /** - * memory对话框高度 - */ - public static final int MEMORY_HEIGHT_SIZE = 339; - - /** - * memory配置项按钮宽度 - */ - public static final int ITERM_BUT_WIDTH_SIZE = 78; - - /** - * memory配置项按钮高度 - */ - public static final int ITERM_BUT_HEIGHT_SIZE = 32; - - /** - * memory配置项取消按钮X轴 - */ - public static final int CANCEL_BUT_X = 296; - - /** - * memory配置项取消/确定按钮Y轴 - */ - public static final int CANCEL_BUT_Y = 275; - - /** - * memory配置项取消按钮X轴 - */ - public static final int OK_BUT_X = 390; - - /** - * 检测页面内存添加关闭按钮 - */ - public static final int CLOSE_BUT_WIDTH = 16; - - /** - * 检测页面内存添加关闭按钮X轴 - */ - public static final int CLOSE_BUT_X = 452; - - /** - * 检测页面内存添加关闭按钮Y轴 - */ - public static final int CLOSE_BUT_Y = 16; - - /** - * 检测页面内存添加选项字体 - */ - public static final int OPTION_FONT = 14; - - /** - * 数字1000 - */ - public static final int THOUSAND = 1000; - - /** - * 数字500 - */ - public static final int FIVE_HUNDRED = 500; - - /** - * 数字2 - */ - public static final int TWO = 2; - - /** - * 数字25 - */ - public static final int TWENTY_FIVE = 25; - - /** - * 数字1100 - */ - public static final int THOUSAND_ONE = 1100; - - /** - * 数字69 - */ - public static final int SIXTY_NINE = 69; - - /** - * 数字73 - */ - public static final int SEVENTY_THREE = 73; - - /** - * 数字74 - */ - public static final int SEVENTY_FOUR = 74; - - /** - * 数字300 - */ - public static final int THREE_HUNDRED = 300; - - /** - * 数字122 - */ - public static final int HUNDRED_TWENTY_TWO = 122; - - /** - * 数字133 - */ - public static final int HUNDRED_THIRTY_THREE = 133; - - /** - * 数字144 - */ - public static final int HUNDRED_FORTY_FOUR = 144; - - /** - * 数字145 - */ - public static final int HUNDRED_FORTY_FIVE = 145; - - /** - * 数字146 - */ - public static final int HUNDRED_FORTY_SIX = 146; - - /** - * 数字155 - */ - public static final int HUNDRED_FIFTY_FIVE = 155; - - /** - * 数字100 - */ - public static final int HUNDRED = 100; - - /** - * 数字40 - */ - public static final int FORTY = 40; - - /** - * 数字20 - */ - public static final int TWENTY = 20; - - /** - * 数字-1 - */ - public static final int NEGATIVE_ONE = -1; - - /** - * 数字400 - */ - public static final int FOUR_HUNDRED = 400; - - /** - * 数字260 - */ - public static final int TWO_HUNDRED_SIXTY = 260; - - /** - * 数字10 - */ - public static final int TEN = 10; - - /** - * 数字30 - */ - public static final int THIRTY = 30; - - /** - * 数字70 - */ - public static final int SEVENTY = 70; - - /** - * 数字90 - */ - public static final int NINETY = 90; - - /** - * 数字220 - */ - public static final int TWO_HUNDRED_TWENTY = 220; - - /** - * 数字91 - */ - public static final int NINETY_ONE = 91; - - /** - * 数字218 - */ - public static final int TWO_HUNDRED_EIGHTEEN = 213; - - /** - * 数字60 - */ - public static final int SIXTY = 60; - - /** - * 数字320 - */ - public static final int THREE_HUNDRED_TWENTY = 320; - - /** - * 数字180 - */ - public static final int HUNDRED_EIGHTY = 180; - - /** - * 数字80 - */ - public static final int EIGHTY = 80; - - /** - * 数字160 - */ - public static final int HUNDRED_SIXTY = 160; - - /** - * 数字150 - */ - public static final int HUNDRED_FIFTY = 150; - - /** - * 数字800 - */ - public static final int EIGHT_HUNDRED = 800; - - /** - * 数字210 - */ - public static final int TWO_HUNDRED_TEN = 210; - - /** - * 数字1024 - */ - public static final int THOUSAND_TWENTY_FOUR = 1024; - - /** - * 数字0.75f - */ - public static final float LOAD_FACTOR = 0.75F; - - /** - * 数字2f - */ - public static final float FLOAT_VALUE = 2F; - - /** - * 数字3 - */ - public static final int THREE = 3; - - /** - * 数字16 - */ - public static final int SIXTEEN = 16; - - /** - * 数字1500 - */ - public static final int THOUSAND_FIVE_HUNDRED = 1500; - - /** - * 数字31 - */ - public static final int THIRTY_ONE = 31; - - /** - * 数字32 - */ - public static final int THIRTY_TWO = 32; - - /** - * 数字5 - */ - public static final int FIVE = 5; - - /** - * 端口号 - */ - public static final int PORT = 65535; - - /** - * 数字50 - */ - public static final int FIFTY = 50; - - /** - * 数字32947L - */ - public static final long NUM_L = 32947L; - - /** - * 数字32947 - */ - public static final int NUM_BER = 32947; - - /** - * SYSTEM tun center左右宽度 - */ - public static final int SYSTEM_TUNNING_CENTER_LEFT_AND_RIGHT_X = 40; - - /** - * 默认值 - */ - public static final int DEFAULT_NUMBER = 0; - - /** - * 默认值 - */ - public static final int SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER = 10; - - /** - * 默认值 - */ - public static final int SYSTEM_TUNNING_RECORD_SETTING_MAXDURATION_DEFAULT_NUMBER = 1; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_LABEL_INTT_X = 50; - - /** - * SYSTEM TUNNING 单选按钮的初始化x轴 - */ - public static final int SYSTEM_TUNNING_LABLE_RADIO_INTT_X = 50; - - /** - * SYSTEM TUNNING 单选按钮的初始化x轴 - */ - public static final int SYSTEM_TUNNING_LABLE_RADIO_DECOND_INTT_X = 210; - - /** - * SYSTEM TUNNING 单选按钮的初始化x轴 - */ - public static final int SYSTEM_TUNNING_LABLE_RADIO_THREE_INTT_X = 370; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_RIGHT_X = 521; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_LABLE_INTT_RIGHT_X = 500; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_RECORD_MODEL_LABLE_INTT_Y = 13; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_LABLE_INTT_Y = 50; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_LABLE_SPACING_Y = 50; - - /** - * SYSTEM TUNNING SLIDE自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_SLIDE_LABLE_SPACING_Y = 70; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_SPACING_Y = 90; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_SCHEDULING_SPACING_Y = 80; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_CPU_SPACING_Y = 170; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_SYSCALLS_SPACING_Y = 260; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_BOARD_SPACING_Y = 350; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_DOUBLE_SPACING_Y = 180; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_THREE_SPACING_Y = 270; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 - */ - public static final int SYSTEM_TUNNING_PROBES_FOUR_SPACING_Y = 360; - - /** - * SYSTEM TUNNING 复选框High frequency memory label的Y轴 - */ - public static final int SYSTEM_TUNNING_PROBES_HIGH_FREQUENCY_MEMORY_LABEL_INIT_Y = 95; - - /** - * SYSTEM TUNNING 复选框LOW MEMORY KILLER label的Y轴 - */ - public static final int SYSTEM_TUNNING_PROBES_LOW_MEMORY_KILLER_LABEL_INIT_Y = 185; - - /** - * SYSTEM TUNNING 复选框ATRACE USERSPACE ANNOTATIONS label的Y轴 - */ - public static final int SYSTEM_TUNNING_PROBES_ATRACE_USERSPACE_ANNOTATIONS_LABEL_INIT_Y = 360; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 * 2 - */ - public static final int SYSTEM_TUNNING_LABLE_SPACING_TWO_TIMES_Y = 2 * 50; - - /** - * SYSTEM TUNNING 自定义布局label的默认Y值 - 之间间距 * 3 - */ - public static final int SYSTEM_TUNNING_LABLE_SPACING_THREE_TIMES_Y = 3 * 50; - - /** - * SYSTEM TUNNING 自定义布局label的默认宽度 - */ - public static final int SYSTEM_TUNNING_LABLE_WIDTH = 200; - - /** - * SYSTEM TUNNING JCHECKBOX自定义布局label的默认宽度 - */ - public static final int SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH = 250; - - /** - * SYSTEM TUNNING 自定义布局label的默认高度 - */ - public static final int SYSTEM_TUNNING_LABLE_HEIGHT = 50; - - /** - * SYSTEM TUNNING CHECKBOX自定义布局label的默认高度 - */ - public static final int SYSTEM_TUNNING_CHECKBOX_LABLE_HEIGHT = 60; - - /** - * SYSTEM TUNNING SLIDE HEIGHT 自定义布局label的默认高度 - */ - public static final int SYSTEM_TUNNING_SLIDE_LABLE_HEIGHT = 70; - - /** - * SYSTEM TUNNING ,label 的描述 - */ - public static final int SYSTEM_TUNNING_LABLE_DESCRIBE = 350; - - /** - * SYSTEM TUNNING 自定义布局label的默认初始化Y值 - */ - public static final int SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_X = 71; - - /** - * SYSTEM TUNNING TRACE COMMAND TEXTAREA 初始化X位置 - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_TEXT_AREA_INTT_X = 40; - - /** - * SYSTEM TUNNING TRACE COMMAND TEXTAREA 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_TEXT_AREA_INTT_Y = 40; - - /** - * SYSTEM TUNNING SETTING RECORD RADIO 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SPACEING_Y = 130; - - /** - * SYSTEM TUNNING SETTING RECORD RADIO 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_INTI_Y = 200; - - /** - * SYSTEM TUNNING SETTING RECORD RADIO 初始化X位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_X = 700; - - /** - * SYSTEM TUNNING SETTING RECORD IN MEMORY 滚动条触发的label框的显示 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_IN_MEMORY_INTI_Y = 150; - - /** - * SYSTEM TUNNING SETTING RECORD 滚动条触发的label框的显示 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_Y = 250; - - /** - * SYSTEM TUNNING SETTING RECORD 滚动条触发的label框的长度 初始化width位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_WIDTH = 110; - - /** - * SYSTEM TUNNING SETTING SLIDE 初始化X位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_X = 45; - - /** - * SYSTEM TUNNING SETTING SLIDE 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_Y = 140; - - /** - * SYSTEM TUNNING SETTING SLIDE RIGHT LABEL初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_RIGHT_LABEL_INT_Y = 135; - - /** - * SYSTEM TUNNING SETTING SLIDE SPCING 初始化SLIDE 的垂直间距位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_LABEL = 190; - - /** - * SYSTEM TUNNING SETTING SLIDE SPCING 初始化SLIDE 的垂直间距位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_LABEL_INIT_Y = 225; - - /** - * SYSTEM TUNNING SETTING MAX FILE SIZE SLIDE LABEL初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_FILE_SIZE_SLIDE_INT_LABEL_Y = 280; - - /** - * SYSTEM TUNNING SETTING MAX FILE SIZE SLIDE LABEL初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_FILE_SIZE_SLIDE_LABEL_INT_LABEL_Y = 315; - - /** - * SYSTEM TUNNING SETTING MAX FILE SIZE SLIDE 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_FLUSH_ON_DISK_SLIDE_INT_Y = 370; - - /** - * SYSTEM TUNNING SETTING MAX FILE SIZE SLIDE LABEL 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_FLUSH_ON_DISK_SLIDE_LABEL_INT_Y = 405; - - /** - * SYSTEM TUNNING SETTING SLIDE SPCING 初始化SLIDE and label的垂直间距位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_AND_LABEL_SPACING_Y = 40; - - /** - * SYSTEM TUNNING TABBEDPANE TRACE CONFIG WIDETH 初始化tabbedPane 的宽度 - */ - public static final int SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_WIDTH_INIT = 100; - - /** - * SYSTEM TUNNING TABBEDPANE TRACE CONFIG HEIGHT 初始化tabbedPane 的高度 - */ - public static final int SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_HEIGHT_INIT = 50; - - /** - * SYSTEM TUNNING TABBEDPANE TRACE CONFIG 字体大小 - */ - public static final int SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_FONT = 16; - /** - * SYSTEM TUNNING SETTING SLIDE 初始化WIDTH位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_WIDTH = 600; - - /** - * SYSTEM TUNNING SETTING SLIDE 初始化HIGHT位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_HIGHT = 30; - - /** - * SYSTEM TUNNING SETTING RECORD 滚动条触发的label框的长度 初始化width位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_IN_MEMORY_NUMBER = 100; - - /** - * SYSTEM TUNNING SETTING RECORD 滚动条触发的label框的长度 初始化width位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MIN_DURATION_NUMBER = 10; - - /** - * SYSTEM TUNNING SETTING RECORD 滚动条触发的label框的长度 初始化width位置 - */ - public static final int SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_DURATION_NUMBER = 600; - - /** - * SYSTEM TUNNING DEVICE COMBOX 初始化Y位置 - */ - public static final int SYSTEM_TUNNING_DEVICE_COMBOX_EQUIPMENT_INIT_Y = 40; - - /** - * SYSTEM TUNNING LABEL 默认高度HEIGTH - */ - public static final int SYSTEM_TUNNING_ALL_LABEL_INIT_HEIGHT = 28; - - /** - * SYSTEM TUNNING LABEL TRACE CONFIG & PROBES INIT Y 默认Y - */ - public static final int SYSTEM_TUNNING_TRACE_CONFIG_AND_PROBES_INIT_Y = 90; - - /** - * SYSTEM TUNNING LABEL TASK SECEN:SYSTEM TUNNING INIT Y 默认Y - */ - public static final int SYSTEM_TUNNING_SAMLL_TASH_SCENEINIT_Y = 98; - - /** - * SYSTEM TUNNING TRACE COMMAND COPY FUNCTION CURSOR NUMBER 复制功能小手图标 - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_CURSOR = 12; - - /** - * SYSTEM TUNNING TRACE COMMAND COPY FUNCTION INIT X 初始化复制图片的X位置 - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_INIT_X = 900; - - /** - * SYSTEM TUNNING TRACE COMMAND COPY FUNCTION WIDTH OR HEIGHT 初始化复制图片的HEIGHT || HEIGHT位置 - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_INIT_WIDTH = 64; - - /** - * SYSTEM TUNNING TRACE COMMAND TextArea WIDTH - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_TEXTAREA_WIDTH = 600; - - /** - * SYSTEM TUNNING TRACE COMMAND TextArea HEIGHT - */ - public static final int SYSTEM_TUNNING_TRACE_COMMAND_TEXTAREA_HEIGHT = 400; - - /** - * SYSTEM TUNNING RECORD SETTING SLIDE LABEL 初始化滚动条右侧label的高度 - */ - public static final int SYSTEM_TUNNING_RECORD_SETTING_SLIDE_LABEL = 45; - - /** - * SYSTEM TUNNING RECORD SETTING radio width 单选按钮的宽度 - */ - public static final int SYSTEM_TUNNING_RECORD_SETTING_RADIO_WIDTH = 160; - - /** - * SYSTEM TUNNING RECORD SETTING radio width 单选按钮的宽度 - */ - public static final int SYSTEM_TUNNING_DURATION_MINUTE = 9; - - /** - * serialVersionUID - */ - public static final long SERIALVERSIONUID = -5172589582171358319L; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_WIDTH = 300; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_HEIGHT = 150; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INITLINE_ONE_X = 120; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INIT_LINE_TWO_X = 190; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INIT_INITLINE_ONE_Y = 30; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INIT_INITLINE_TWO_Y = 60; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING WIDTH LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH = 70; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING HEIGHT LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT = 20; - - /** - * SYSTEM TUNNING GET TRACE DATA LOADING HEIGHT LOAD框 - */ - public static final int SYSTEM_TUNNING_LOADING_BUTTON_Y = 110; - - /** - * 数字2000 - */ - public static final int TWO_THOUSAND = 2000; - - /** - * 数字2000 - */ - public static final int EIGHT_NUM = 8; - - /** - * ASC - */ - public static final String ASC = "ASCENDING"; - - /** - * 数字980 - */ - public static final int SEARCH_NUM = 980; - - /** - * 数字0 - */ - public static final int NUM_0 = 0; - - /** - * 数字1 - */ - public static final int NUM_1 = 1; - - /** - * 数字2 - */ - public static final int NUM_2 = 2; - - /** - * 数字3 - */ - public static final int NUM_3 = 3; - - /** - * 数字4 - */ - public static final int NUM_4 = 4; - - /** - * device number - */ - public static final int DEVICE_NUMBER = 1085; - - /** - * description number - */ - public static final int DESCRIPTION_NUMBER = 430; -} +/* + * 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. + */ + +package ohos.devtools.views.common; + +/** + * 主界面相关的常量值 + */ +public final class LayoutConstants { + /** + * 构造函数 + */ + private LayoutConstants() { + } + + /** + * 初始值 + */ + public static final int INITIAL_VALUE = -1; + + /** + * 界面布局宽度 + */ + public static final int WINDOW_WIDTH = 1200; + + /** + * 界面布局高度 + */ + public static final int WINDOW_HEIGHT = 800; + + /** + * 字体大小 + */ + public static final int FONT_SIZE = 14; + + /** + * 二级欢迎界面按钮高度 + */ + public static final int BUTTON_HEIGHT = 25; + + /** + * 多配置界面选项卡标签宽度 + */ + public static final int JPA_LABEL_WIDTH = 135; + + /** + * 多配置界面选项卡标签左侧宽 + */ + public static final int JP_LEFT_WIDTH = 118; + + /** + * 多配置界面选项卡标签左侧宽 + */ + public static final int JP_LEFT_HEIGHT = 20; + + /** + * 多配置界面选项卡标签右侧宽 + */ + public static final int JP_RIGHT_WIDTH = 10; + + /** + * 多配置界面选项卡标签右侧宽 + */ + public static final int JP_RIGHT_HEIGHT = 20; + + /** + * 配置界面选项卡标签宽度 + */ + public static final int JP_SET_WIDTH = 118; + + /** + * 配置界面选项卡标签宽度 + */ + public static final int JP_SET_HEIGHT = 20; + + /** + * 应用场景标签X值 + */ + public static final int APP_LABEL_X = 28; + + /** + * 应用场景标签Y1值 + */ + public static final int APP_LABEL_Y2 = 580; + + /** + * 应用场景标签宽度 + */ + public static final int APP_LABEL_WIDTH = 2500; + + /** + * 应用场景描述字体大小 + */ + public static final int TUN_LABEL_FONT = 12; + + /** + * 场景类型标签Y值 + */ + public static final int TASK_SCENE_Y = 30; + + /** + * 设备框大小 + */ + public static final int HEIGHT_PRESSE = 451; + + /** + * 场景类型标签字体 + */ + public static final int TASK_FONT = 25; + + /** + * 选择场景类型标签宽度 + */ + public static final int CH_TASK_WIDTH = 250; + + /** + * 应用场景按钮字体大小 + */ + public static final int APP_BUT_FONT = 12; + + /** + * top panel east width + */ + public static final int TOP_PANEL_EAST_WIDTH = 250; + + /** + * 设备进程面板X值 + */ + public static final int DEVICE_PRO_X = 35; + + /** + * 设备进程面板宽度 + */ + public static final int DEVICE_PRO_WIDTH = 700; + + /** + * top panel height + */ + public static final int TOP_PANEL_HEIGHT = 30; + + /** + * 每一台设备对应X值 + */ + public static final int DEVICES_X = 40; + + /** + * 每一台设备对应Y值 + */ + public static final int DEVICES_Y = 2; + + /** + * 每一台设备对标签宽度 + */ + public static final int DEVICES_WIDTH = 100; + + /** + * 每一台设备对标签高度 + */ + public static final int DEVICES_HEIGHT = 20; + + /** + * 每一台设备对标签字体大小 + */ + public static final int DEVICES_FONT = 13; + + /** + * 每设备信息标签高度 + */ + public static final int DEVICE_HEIGHT = 20; + + /** + * 设备连接方式下拉框宽度 + */ + public static final int CON_BOX_WIDTH = 100; + + /** + * 设备名称下拉框对应Y值 + */ + public static final int DEVICE_NAME_Y = 30; + + /** + * Y轴高度 + */ + public static final int SE_PANEL_Y_TWO = 110; + + /** + * 标签名称文本框宽度 + */ + public static final int LABEL_NAME_WIDTH = 280; + + /** + * 标签名称文本框高度 + */ + public static final int LABEL_NAME_HEIGHT = 20; + + /** + * 设备添加按钮对应Y值 + */ + public static final int DEVICE_ADD_Y = 5; + + /** + * 设备添加按钮宽度 + */ + public static final int DEVICE_ADD_WIDTH = 100; + + /** + * 设备添加按钮高度 + */ + public static final int DEVICE_ADD_HEIGHT = 30; + + /** + * Center容器左边部分top面板宽度 + */ + public static final int LEFT_TOP_WIDTH = 700; + + /** + * 设备添加按钮高度 + */ + public static final int MONITOR_PANEL_HEIGHT = 50; + + /** + * Center容器右边面板宽度 + */ + public static final int EAST_LABEL_WIDTH = 500; + + /** + * 应用场景标签对应X值 + */ + public static final int TASK_LABEL_X = 30; + + /** + * 应用场景标签对应Y值 + */ + public static final int TASK_LABEL_Y = 30; + + /** + * number计算 + */ + public static final int TASK_DEC_NUM = 27; + + /** + * 监控项内存标签对应Y值 + */ + public static final int MEMORY_Y = 10; + + /** + * 监控项内存标签宽度 + */ + public static final int MEMORY_WIDTH = 50; + + /** + * java选择框宽度 + */ + public static final int JAVA_WIDTH = 120; + + /** + * java选择框高度 + */ + public static final int JAVA_HEIGHT = 20; + + /** + * others选择框对应Y值 + */ + public static final int OTHERS_Y = 130; + + /** + * 滚轮滚动速度 + */ + public static final int SCROLL_UNIT_INCREMENT = 10; + + /** + * 数组索引 + */ + public static final int INDEX_ZERO = 0; + + /** + * 数组索引 + */ + public static final int INDEX_ONE = 1; + + /** + * 数组索引 + */ + public static final int INDEX_TWO = 2; + + /** + * 数组索引 + */ + public static final int INDEX_THREE = 3; + + /** + * 数组索引 + */ + public static final int INDEX_FOUR = 4; + + /** + * 数组索引 + */ + public static final int INDEX_FIVE = 5; + + /** + * 数组索引 + */ + public static final int INDEX_SIX = 6; + + /** + * 数组索引 + */ + public static final int INDEX_SEVEN = 7; + + /** + * X轴距离 + */ + public static final int NUMBER_X = 160; + + /** + * X轴距离 + */ + public static final int NUMBER_X_ADD = 165; + + /** + * Y轴距离 + */ + public static final int NUMBER_Y = 4; + + /** + * 高度 + */ + public static final int HEIGHT = 80; + + /** + * 用于Y轴位置计算 + */ + public static final int HEIGHT_Y = 150; + + /** + * 秒数计数 + */ + public static final int NUMBER_SECONDS = 59; + + /** + * 秒数计数 + */ + public static final int NUMBER_SLEEEP = 50; + + /** + * 循环计数 + */ + public static final int NUMBER_FOR = 220; + + /** + * Thread interval time + */ + public static final int NUMBER_THREAD = 1000; + + /** + * 滚东条计数 + */ + public static final int SCROPNUM = 360; + + /** + * 多场景描述面板大小 + */ + public static final int JLABEL_SIZE = 60; + + /** + * 宽度 + */ + public static final int WIDTHSUPEN = 400; + + /** + * 场景描述框大小 + */ + public static final int HIGTHSCEECS = 65; + + /** + * 二级界面的按钮大小 + */ + public static final int BUTTON_SIZE = 28; + + /** + * 检测页面内存添加选项字体 + */ + public static final int OPTION_FONT = 14; + + /** + * 数字1000 + */ + public static final int THOUSAND = 1000; + + /** + * 数字500 + */ + public static final int FIVE_HUNDRED = 500; + + /** + * 数字2 + */ + public static final int TWO = 2; + + /** + * 数字300 + */ + public static final int THREE_HUNDRED = 300; + + /** + * 数字122 + */ + public static final int HUNDRED_TWENTY_TWO = 122; + + /** + * 数字100 + */ + public static final int HUNDRED = 100; + + /** + * 数字40 + */ + public static final int FORTY = 40; + + /** + * 数字20 + */ + public static final int TWENTY = 20; + + /** + * 数字-1 + */ + public static final int NEGATIVE_ONE = -1; + + /** + * 数字400 + */ + public static final int FOUR_HUNDRED = 400; + + /** + * 数字260 + */ + public static final int TWO_HUNDRED_SIXTY = 260; + + /** + * 数字10 + */ + public static final int TEN = 10; + + /** + * 数字30 + */ + public static final int THIRTY = 30; + + /** + * 数字90 + */ + public static final int NINETY = 90; + + /** + * 数字60 + */ + public static final int SIXTY = 60; + + /** + * 数字180 + */ + public static final int HUNDRED_EIGHTY = 180; + + /** + * 数字150 + */ + public static final int HUNDRED_FIFTY = 150; + + /** + * 数字800 + */ + public static final int EIGHT_HUNDRED = 800; + + /** + * 数字1024 + */ + public static final int THOUSAND_TWENTY_FOUR = 1024; + + /** + * 数字0.75f + */ + public static final float LOAD_FACTOR = 0.75F; + + /** + * 数字2f + */ + public static final float FLOAT_VALUE = 2F; + + /** + * 数字3 + */ + public static final int THREE = 3; + + /** + * 数字16 + */ + public static final int SIXTEEN = 16; + + /** + * 数字1500 + */ + public static final int THOUSAND_FIVE_HUNDRED = 1500; + + /** + * 数字31 + */ + public static final int THIRTY_ONE = 31; + + /** + * 数字32 + */ + public static final int THIRTY_TWO = 32; + + /** + * 数字5 + */ + public static final int FIVE = 5; + + /** + * 端口号 + */ + public static final int PORT = 65535; + + /** + * 数字50 + */ + public static final int FIFTY = 50; + + /** + * 数字32947L + */ + public static final long NUM_L = 32947L; + + /** + * 默认值 + */ + public static final int DEFAULT_NUMBER = 0; + + /** + * serialVersionUID + */ + public static final long SERIALVERSIONUID = -5172589582171358319L; + + /** + * 数字2000 + */ + public static final int TWO_THOUSAND = 2000; + + /** + * 数字2000 + */ + public static final int EIGHT_NUM = 8; + + /** + * 数字1 + */ + public static final int NUM_1 = 1; + + /** + * 数字2 + */ + public static final int NUM_2 = 2; + + /** + * 数字4 + */ + public static final int NUM_4 = 4; + + + /** + * description number + */ + public static final int DESCRIPTION_NUMBER = 430; + + /** + * description device connect Type + */ + public static final String USB = "USB"; + + /** + * record native number 50 + */ + public static final int NUM_50 = 50; + + /** + * record native number 110 + */ + public static final int NUM_110 = 110; + + /** + * record native number 222 + */ + public static final int NUM_222 = 222; + + /** + * record native number 142 + */ + public static final int NUM_142 = 142; + + /** + * record native number 96 + */ + public static final int NUM_96 = 96; + + /** + * record native number 40 + */ + public static final int NUM_40 = 40; + + /** + * record native number 20 + */ + public static final int NUM_20 = 20; + + /** + * record native left width + */ + public static final int RECORD_LEFT_PANEL_WIDTH = 56; + + /** + * record native left width + */ + public static final int RECORD_RIGHT_PANEL_WIDTH = 176; + + /** + * record native pointX 161 + */ + public static final int RECORD_UP_POINT_NUMBER = 161; + + /** + * record native left pointY + */ + public static final int RECORD_LEFT_POINT_NUMBER = 76; + + /** + * native_hook_recording + */ + public static final String NATIVE_HOOK_RECORDING = "Native Hook Recording"; + + /** + * Drop down options trace app calls + */ + public static final String TRACE_SYSTEM_CALLS = "Trace App Calls"; + + /** + * System Trace Recording tips + */ + public static final String TRACE_SYSTEM_CALLS_TIPS = "System Trace"; + + /** + * Sample Perf Data Recording tips + */ + public static final String SAMPLE_PERF_DATA_TIPS = "Sample Perf Data"; + + /** + * heap_dump + */ + public static final String HEAP_DUMP = "Heap Dump"; + + /** + * The number of milliseconds in the one-hour time zone + */ + public static final int ONE_HOURS_MILLISECONDS = 60 * 60 * 1000; + + /** + * The number of 200 + */ + public static final int NUM_200 = 200; + + /** + * The record table width + */ + public static final int RECORD_TABLE_WIDTH = 1152; + + /** + * The record table height + */ + public static final int RECORD_TABLE_HEIGHT = 736; + + /** + * The record search height + */ + public static final int RECORD_SEARCH_HEIGHT = 28; + + /** + * The record search width + */ + public static final int RECORD_SEARCH_WIDTH = 230; + + /** + * The record combo box width + */ + public static final int RECORD_COMBO_BOX_WIDTH = 240; + + /** + * The record features space + */ + public static final int RECORD_FEATURES_SPACE = 14; + + /** + * The record tabbed height + */ + public static final int RECORD_FEATURES_HEIGHT = 48; + + /** + * The record tabbed border space + */ + public static final int RECORD_BORDER_SPACE = 54; + + /** + * The record tabbed bounds width + */ + public static final int RECORD_TABBED_BOUNDS_WIDTH = 135; + + /** + * The record tabbed bounds point + */ + public static final int RECORD_TABBED_BOUNDS_POINT = 155; + + /** + * The record tabbed border + */ + public static final int RECORD_TABBED_BORDER = 35; + + /** + * The record tabbed title space + */ + public static final int RECORD_TABBED_TITLE_SPACE = 7; + + /** + * The record tabbed height + */ + public static final int RECORD_TABBED_HEIGHT = 42; + + /** + * session list width + */ + public static final int SESSION_LIST_WIDTH = 210; + + /** + * session list height + */ + public static final int SESSION_LIST_HEIGHT = 60; + + /** + * save dialog SAVE_LOCATION width + */ + public static final int SAVE_LOCATION_WIDTH = 348; + + /** + * heap dummp or native hook list width + */ + public static final int LIST_WIDTH = 240; + + /** + * session list DividerLocation width + */ + public static final int SESSION_LIST_DIVIDER_WIDTH = 220; + + /** + * number 12 + */ + public static final int TWELVE = 12; + + /** + * jComboBox Filter width + */ + public static final int ARRAY_WIDTH = 188; + + /** + * heap dummp or native hook timelable list width + */ + public static final int TIMELABLE_XY = 15; + + /** + * export dialog component margin left + */ + public static final int MARGIN_LEFT = 15; + + /** + * export file select y + */ + public static final int FILE_SELECT_Y = 125; + + /** + * export file type y + */ + public static final int FILE_TYPE_Y = 165; + + /** + * export file type box y + */ + public static final int FILE_TYPE_BOX_Y = 200; + + /** + * export dialog width + */ + public static final int DIALOG_WIDTH = 380; + + /** + * export dialog height + */ + public static final int DIALOG_HEIGHT = 260; + + /** + * NUM 34 + */ + public static final int NUM_34 = 34; + + /** + * NUM 65 + */ + public static final int NUM_65 = 65; + + /** + * NUM 650 + */ + public static final int NUM_650 = 650; + + /** + * NUM 52 + */ + public static final int NUM_52 = 52; + + /** + * Splitter PROPORTION + */ + public static final float PROPORTION_SEGMENT = 0.6f; + + /** + * session list DividerLocation width + */ + public static final int INSTANCE_LIST_WIDTH = 470; + + /** + * number 21 + */ + public static final int TWENTY_ONE = 21; + + /** + * number 48 + */ + public static final int FORTY_EIGHT = 48; + + /** + * Instance list label height + */ + public static final int LABEL_HEIGHT = 22; + + /** + * CPU grap data kind button , init y coordinate + */ + public static final int CPU_GRAP_TYPE_Y = 90; + + /** + * CPU grap data kind button width + */ + public static final int CPU_GRAP_TYPE_WIDTH = 200; +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/SystemTunningProbesCheckbox.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/SystemTunningProbesCheckbox.java deleted file mode 100644 index 8e4beb715..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/SystemTunningProbesCheckbox.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common; - -/** - * SystemTunningProbesCheckbox - * - * @version 1.0 - * @date 2021/04/14 20:13 - **/ -public final class SystemTunningProbesCheckbox { - private static final String TRACE_EVENT = " ftrace_events:"; - - /** - * SYSTEM_TUNNING_PROBES_NO_SELECT_HEAD - */ - public static final String SYSTEM_TUNNING_PROBES_NO_SELECT_HEAD = - "hdc shell hiprofiler_cmd \\\n" + " -c - \\\n" + "< maxDisplayTime && minMarkInterval != 0) { - startCoordinate = x0; - // 判断是否有偏移时间 - if (endTime % minMarkInterval == 0) { - offsetTime = 0; - } else { - // 如果当前时间和minMarkInterval取余不为0,则计算偏移量:最小间隔 - 当前时间 % 最小间隔 - offsetTime = minMarkInterval - endTime % minMarkInterval; - } - } else { - // 如果当前时间小于最大时间,则需要从中间绘制时间轴,偏移量为0 - offsetTime = 0; - startCoordinate = x0 + right - OperationUtils.multiply(pixelPerTime, endTime); - } - } - - /** - * 绘制时间线的坐标轴 - * - * @param graphics Graphics - */ - private void drawAxis(Graphics graphics) { - graphics.setColor(TIMELINE_SCALE); - // 绘制Timeline左侧的竖线 - graphics.drawLine(x0, top, x0, y0); - // 绘制Timeline的横线 - graphics.drawLine(x0, y0, right, y0); - // 时间轴是否绘满界面 - boolean flag = endTime > maxDisplayTime; - // 从offsetTime开始绘制时间线(其实是画刻度),绘制时间范围其实也是从0到max - for (int drawTime = offsetTime; drawTime <= maxDisplayTime; drawTime += this.minMarkInterval) { - int x = startCoordinate + ChartUtils.multiply(pixelPerTime, drawTime); - // 计算出实际要展示的时间 - int showTime; - if (flag) { - showTime = startTime + drawTime; - } else { - showTime = drawTime; - } - double result = (showTime / this.minMarkInterval) % TIMELINE_MARK_COUNTS; - // 每隔N个minMarkInterval绘制坐标轴数字和大刻度 - if (result == 0) { - // 绘制长刻度 - graphics.setColor(TIMELINE_SCALE); - graphics.drawLine(x, y0, x, top); - graphics.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, TIMELINE_FONT_SIZE)); - // 转换后的时间 - String str = millisecondToTime(showTime); - graphics.setColor(RULER); - graphics.drawString(str, x + NUM_5, y0 - NUM_10); - } else { - graphics.setColor(TIMELINE_SCALE); - graphics.drawLine(x, top, x, top + NUM_6); - } - } - } - - /** - * 绘制时间线的坐标数字 - * - * @param time time - * @return String - */ - private String millisecondToTime(int time) { - String timeStr; - int hour; - int minute; - int second; - int millisecond; - int num60 = NUM_6 * NUM_10; - if (time <= 0) { - return "0s"; - } else { - second = time / NUM_1000; - minute = second / num60; - millisecond = time % NUM_1000; - if (second < num60) { - timeStr = secondFormat(second) + "." + millisecondFormat(millisecond) + "s"; - } else if (minute < num60) { - second = second % num60; - timeStr = - secondFormat(minute) + ":" + secondFormat(second) + "." + millisecondFormat(millisecond) + "s"; - } else { - hour = minute / num60; - minute = minute % num60; - int num3600 = num60 * num60; - second = second - hour * num3600 - minute * num60; - timeStr = secondFormat(hour) + ":" + secondFormat(minute) + ":" + secondFormat(second) + "." - + millisecondFormat(millisecond) + "s"; - } - } - return timeStr; - } - - /** - * 时分秒的格式转换 - * - * @param secondTime secondTime - * @return String - */ - private String secondFormat(int secondTime) { - String retStr; - if (secondTime == 0) { - retStr = "00"; - } else if (secondTime > 0 && secondTime < NUM_10) { - retStr = Integer.toString(secondTime); - } else { - retStr = "" + secondTime; - } - return retStr; - } - - /** - * 毫秒的格式转换 - * - * @param millisecondTime millisecondTime - * @return String - */ - private String millisecondFormat(int millisecondTime) { - String retStr; - if (millisecondTime == 0) { - retStr = "000"; - } else if (millisecondTime > 0 && millisecondTime < NUM_10) { - retStr = Integer.toString(millisecondTime); - } else if (millisecondTime >= NUM_10 && millisecondTime < NUM_10 * NUM_10) { - retStr = Integer.toString(millisecondTime); - } else { - retStr = "" + millisecondTime; - } - return retStr; - } - - /** - * 绘制Timeline框选的标记 - * - * @param graphics Graphics - */ - private void drawSelectedMark(Graphics graphics) { - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - if (selectedRange == null) { - return; - } - if (selectedRange.getStartTime() != Integer.MIN_VALUE) { - int selectStartX = - startCoordinate + OperationUtils.multiply(pixelPerTime, selectedRange.getStartTime() - startTime); - drawInvertedTriangle(selectStartX, graphics); - } - if (selectedRange.getEndTime() != Integer.MAX_VALUE) { - int selectEndX = - startCoordinate + OperationUtils.multiply(pixelPerTime, selectedRange.getEndTime() - startTime); - drawInvertedTriangle(selectEndX, graphics); - } - } - - /** - * 画一个倒三角形 - * - * @param bottomVertexX 倒三角形下方的顶点 - * @param graphics Graphics - */ - private void drawInvertedTriangle(int bottomVertexX, Graphics graphics) { - // 创建一个多边形对象 - Polygon polygon = new Polygon(); - polygon.addPoint(bottomVertexX, y0); - polygon.addPoint(bottomVertexX - NUM_5, y0 - NUM_5); - polygon.addPoint(bottomVertexX + NUM_5, y0 - NUM_5); - polygon.addPoint(bottomVertexX, y0); - graphics.fillPolygon(polygon); - } - - /** - * 更新标尺的坐标点 - */ - private void updateRulerPoint() { - // Timeline上不画标尺,但是鼠标移动时,要更新坐标点,通知其他组件绘制标尺 - Point mousePoint = getMousePosition(); - if (mousePoint != null) { - this.bottomPanel.setRulerXCoordinate((int) mousePoint.getX()); - } - } - - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseClicked(MouseEvent mouseEvent) { - // 鼠标点击事件,单击后停止刷新数据,等待用户框选数据 - int button = mouseEvent.getButton(); - int mouseX = mouseEvent.getX(); - // 如果左键点击的点小于起始点,则不更新 - if (button == MouseEvent.BUTTON1 && mouseX < startCoordinate) { - return; - } - // 目前仅左键单击触发框选场景 - if (button == MouseEvent.BUTTON1) { - this.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); - // start和end同时更新 - mouseLeftClick(mouseX); - } else { - // 右键取消选择,清空框选范围 - this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - mouseRightClick(); - } - // 鼠标点击后,也需要组件的标尺需要重新绘制(主要是将Chart绘制为半透明状态) - this.bottomPanel.resetRulerDrawStatus(); - } - - private void mouseLeftClick(int mouseX) { - dragStartPoint = mouseX; - dragEndPoint = mouseX; - this.bottomPanel.getObserver().getStandard().updateSelectedStart(getTimeByMouseX(mouseX)); - this.bottomPanel.getObserver().getStandard().updateSelectedEnd(getTimeByMouseX(mouseX)); - checkLevelTablePanel(); - // 停止刷新数据,手动刷新界面,否则界面不会变暗 - doNotifyRefresh(bottomPanel.isChartLevel()); - bottomPanel.setAbleUnfoldTable(true); - // 增加chart点击和暂停开始按钮的事件联动 - // 修改OhosProfiler应用任务停止后连续左击和右击时间线时“暂停/恢复”按钮会相应变化 - if (!bottomPanel.isStopFlag()) { - taskScenePanelChart.getjButtonStop() - .setIcon(new ImageIcon(ProfilerTimeline.class.getClassLoader().getResource("images/suspended.png"))); - } - if (!bottomPanel.isFlagDown() && bottomPanel.isChartLevel()) { - taskScenePanelChart.getjButtonBottom().setIcon( - new ImageIcon(ProfilerTimeline.class.getClassLoader().getResource("images/button_bottom_bar.png"))); - } - } - - private void checkLevelTablePanel() { - if (levelTablePanel == null) { - long sessionId = this.bottomPanel.getSessionId(); - levelTablePanel = new LevelTablePanel(jpanelSupen, sessionId); - levelTablePanel.setPreferredSize(new Dimension(DEVICES_WIDTH, LABEL_NAME_WIDTH)); - } - } - - void mouseRightClick() { - dragStartPoint = INITIAL_VALUE; - dragEndPoint = INITIAL_VALUE; - this.bottomPanel.getObserver().getStandard().clearSelectedRange(); - removeTablePanel(); - // 恢复刷新数据 - this.bottomPanel.getObserver().restartRefresh(); - bottomPanel.setAbleUnfoldTable(false); - // 修改OhosProfiler应用任务停止后连续左击和右击时间线时“暂停/恢复”按钮会相应变化 - if (!bottomPanel.isStopFlag()) { - taskScenePanelChart.getjButtonStop() - .setIcon(new ImageIcon(ProfilerTimeline.class.getClassLoader().getResource("images/button_stop.png"))); - } - taskScenePanelChart.getjButtonBottom().setIcon( - new ImageIcon(ProfilerTimeline.class.getClassLoader().getResource("images/button_bottom_bar_grey.png"))); - bottomPanel.setFlagDown(false); - // 手动刷新界面,否则界面不会变亮 - ChartDataRange range = bottomPanel.getObserver().getStandard().getDisplayRange(); - bottomPanel.getObserver().notifyRefresh(range.getStartTime(), range.getEndTime()); - } - - /** - * 鼠标左键点击事件 - */ - public void addTablePanel() { - checkLevelTablePanel(); - this.bottomPanel.add(levelTablePanel, BorderLayout.SOUTH); - this.bottomPanel.setFlagDown(false); - } - - /** - * 鼠标右键点击事件 - */ - public void removeTablePanel() { - if (levelTablePanel != null) { - // 点击右键去除层级table - this.bottomPanel.remove(levelTablePanel); - levelTablePanel = null; - } - jpanelSupen.setVisible(false); - this.bottomPanel.setFlagDown(true); - } - - /** - * doNotifyRefresh 停止刷新数据,手动刷新界面,否则界面不会变暗 - * - * @param secondFlag secondFlag - */ - private void doNotifyRefresh(boolean secondFlag) { - if (secondFlag) { - this.bottomPanel.add(levelTablePanel, BorderLayout.SOUTH); - this.bottomPanel.setFlagDown(false); - } - // 停止刷新数据 - this.bottomPanel.getObserver().pauseRefresh(); - // 手动刷新界面,否则界面不会变暗 - ChartDataRange range = bottomPanel.getObserver().getStandard().getDisplayRange(); - bottomPanel.getObserver().notifyRefresh(range.getStartTime(), range.getEndTime()); - } - - /** - * 通过鼠标的X坐标,计算当前坐标对应的Timeline的X轴时间 - * - * @param mouseX 鼠标的X坐标 - * @return 对应的Timeline的X轴时间 - * @see "注意这里算出来的时间,Timeline的X轴上对应的时间,这个时间点不一定在绘制Chart的dataMap的keyset里, - *

- * 有可能是出于某2个值中间,使用时需要找到与dataMap的keyset最接近的值" - */ - private int getTimeByMouseX(int mouseX) { - // 计算公式为:鼠标上对应的时间 = (鼠标X坐标 - 绘制Chart的X起始坐标) / X轴1个单位对应的像素数 + 起始时间 - return OperationUtils.divide(mouseX - startCoordinate, pixelPerTime) + startTime; - } - - /** - * 通过时间,计算当前时间对应的Timeline的X轴坐标 - * - * @param time 当前时间 - * @return 对应的Timeline的X轴坐标值 - */ - private int getPointXByTime(int time) { - // 计算公式为:鼠标上对应的坐标 = X轴1个单位对应的像素数 * (当前时间 - 绘制Chart的X起始时间) + 绘制Chart的X起始坐标 - return OperationUtils.multiply(pixelPerTime, time - startTime) + startCoordinate; - } - - /** - * 鼠标按下事件 - * - * @param mouseEvent MouseEvent - * @see "drag之前会先触发一次press,press时就可以确定拖拽时的锚点(即拖拽时不动的那一条竖线标尺)" - */ - @Override - public void mousePressed(MouseEvent mouseEvent) { - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - int mouseX = mouseEvent.getX(); - // dragStartPoint在滚动条拖动后 数值可能发生了变化 优化: 将最后框选的时间确定下来 不按照坐标去得到dragStartPoint,而是按照最后框选 - // 时刻的时间作为标准 只是在最终将标准时间又转为坐标去判断 - if (selectedRange != null) { - dragStartPoint = getPointXByTime(selectedRange.getStartTime()); - dragEndPoint = getPointXByTime(selectedRange.getEndTime()); - } - // selectedRange为null,说明是没有click,直接开始拖拽,暂时不考虑这种场景 - if (Math.abs(mouseX - dragStartPoint) > NUM_10 && Math.abs(mouseX - dragEndPoint) > NUM_10) { - canDragged = false; - } - if (selectedRange == null) { - return; - } - boolean isCloseToStart = Math.abs(mouseX - dragStartPoint) < NUM_10; - boolean isCloseToEnd = Math.abs(mouseX - dragEndPoint) < NUM_10; - - if (isCloseToStart) { - dragAnchorPoint = dragEndPoint; - canDragged = true; - } - if (isCloseToEnd) { - dragAnchorPoint = dragStartPoint; - canDragged = true; - } - } - - /** - * mouseReleased - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseReleased(MouseEvent mouseEvent) { - // 非左键的release事件不处理 - if (mouseEvent.getButton() != MouseEvent.BUTTON1) { - return; - } - /* - * 拖拽的触发顺序为:press -> drag -> release,而点击为:press -> release -> click - * 拖拽时SelectRange在drag步骤更新,所以release时拿到的range是更新后的 - * 点击时SelectRange在click步骤更新,release时还未更新,所以这里需要手动set一下 ↓↓↓ - */ - if (!isDragging) { - int mouseX = mouseEvent.getX(); - this.bottomPanel.getObserver().getStandard().updateSelectedStart(getTimeByMouseX(mouseX)); - this.bottomPanel.getObserver().getStandard().updateSelectedEnd(getTimeByMouseX(mouseX)); - } - if (bottomPanel.isChartLevel()) { - new SwingWorker() { - @Override - protected AgentDataModel doInBackground() { - // treeTable这时还未初始化完成,这里等待一下 - while (levelTablePanel == null || levelTablePanel.getTreeTable() == null) { - try { - TimeUnit.MILLISECONDS.sleep(10); - } catch (InterruptedException exception) { - LOGGER.error("Drag swing work done error."); - } - } - long sessionId = bottomPanel.getSessionId(); - return levelTablePanel.getTreeDataModel(sessionId); - } - - @Override - protected void done() { - try { - AgentDataModel model = get(); - if (model == null) { - return; - } - if (levelTablePanel == null || levelTablePanel.getTreeTable() == null) { - return; - } - levelTablePanel.getTreeTable().setTreeTableModel(model); - } catch (InterruptedException | ExecutionException | NullPointerException exception) { - LOGGER.error("Drag swing work done error.", exception); - } - } - }.execute(); - } - isDragging = false; - } - - /** - * mouseEntered - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseEntered(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标进入,则更新底层父级panel的currentEntered - this.bottomPanel.setCurrentEntered(this); - } - - /** - * mouseExited - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseExited(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标退出,则更新底层父级panel的currentEntered为null - this.bottomPanel.setCurrentEntered(null); - // 这里需要手动调用重绘一下所有Panel,否则会残留有之前的ruler - this.bottomPanel.resetRulerDrawStatus(); - this.bottomPanel.refreshCompRuler(); - } - - /** - * mouseDragged - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseDragged(MouseEvent mouseEvent) { - isDragging = true; - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - if (selectedRange == null || !canDragged) { - return; - } - int mouseX = mouseEvent.getX(); - if (mouseX > dragAnchorPoint) { - // 鼠标位置大于锚点位置,说明是在锚点右侧拖拽,更新end为鼠标的点即可 - dragEndPoint = mouseX; - if (dragAnchorPoint != INITIAL_VALUE) { - dragStartPoint = dragAnchorPoint; - this.bottomPanel.getObserver().getStandard().updateSelectedStart(getTimeByMouseX(dragAnchorPoint)); - } - this.bottomPanel.getObserver().getStandard().updateSelectedEnd(getTimeByMouseX(mouseX)); - } else { - // 鼠标位置小于锚点位置,说明是在锚点左侧拖拽,则更新end为锚点,start为鼠标的点 - dragStartPoint = mouseX; - if (dragAnchorPoint != INITIAL_VALUE) { - dragEndPoint = dragAnchorPoint; - this.bottomPanel.getObserver().getStandard().updateSelectedEnd(getTimeByMouseX(dragAnchorPoint)); - } - this.bottomPanel.getObserver().getStandard().updateSelectedStart(getTimeByMouseX(mouseX)); - } - // 鼠标移动,则所有组件的标尺需要重新绘制 - this.bottomPanel.resetRulerDrawStatus(); - // 如果鼠标在框选的标尺附近,样式要变为可拉伸 - checkCursorStyle(mouseEvent.getX(), mouseEvent.getY()); - this.repaint(); - this.revalidate(); - } - - /** - * mouseMoved - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseMoved(MouseEvent mouseEvent) { - // 鼠标移动,则所有组件的标尺需要重新绘制 - this.bottomPanel.resetRulerDrawStatus(); - // 如果鼠标在框选的标尺附近,样式要变为可拉伸 - checkCursorStyle(mouseEvent.getX(), mouseEvent.getY()); - this.repaint(); - this.revalidate(); - } - - /** - * mouseWheelMoved - * - * @param mouseWheelEvent mouseWheelEvent - */ - @Override - public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) { - if (true) { - return; - } - ChartDataRange zoomRange = this.bottomPanel.getObserver().getStandard().getDisplayRange(); - if (zoomRange == null || startTime == 0) { - return; - } - // 缩放的char动静判断 - boolean moveDecide = false; - // 缩放前的的开始和结束时间 - int startTimed = zoomRange.getStartTime(); - int endTimed = zoomRange.getEndTime(); - // 计算x轴缩放前显示的时间长度 - int lengthX = endTimed - startTimed; - // 计算比例尺 - BigDecimal divide = OperationUtils.divide(lengthX, maxDisplayTime); - // 是否允许缩放的判断 - boolean zoomAllow = true; - // 缩放的判断 - int zoomDecide = mouseWheelEvent.getWheelRotation(); - if (zoomDecide == 1) { - moveDecide = true; - if (maxDisplayTime < ZOOM_IN_MIN) { - zoomAllow = false; - } - if (zoomAllow) { - // zoomIn向后放大 放大增加判断:放大到一定程度玖不能放大了 - maxDisplayTime = maxDisplayTime - ZOOM_TIME; - } - } else if (-zoomDecide == 1) { - moveDecide = false; - if (maxDisplayTime > ZOOM_OUT_MAX) { - zoomAllow = false; - } - if (zoomAllow) { - // zoomOut 向前缩小 缩小增加判断:缩小到一定程度玖不能放大了 - maxDisplayTime = maxDisplayTime + ZOOM_TIME; - } - } else { - zoomAllow = false; - } - // x轴缩放后的总时间 之后计算鼠标落点的比例 - int multiply = OperationUtils.multiply(divide, maxDisplayTime); - // 缩放的增减时间长度 - int changeLength = OperationUtils.divideInt(multiply - lengthX, NUM_2); - // 调用界面刷新 - zoomRefresh(changeLength, startTimed, endTimed, moveDecide, zoomDecide); - } - - /** - * 根据鼠标的坐标,更新鼠标样式 - * - * @param changeLength 改变的刻度值 - * @param startTimed 新的开始时间 - * @param endTimed 新的结束时间 - * @param moveDecide 是否可以缩放判断 - * @param zoomDecide 滚轮缩放的程度值 - */ - private void zoomRefresh(int changeLength, int startTimed, int endTimed, boolean moveDecide, int zoomDecide) { - // 缩放后的起始和结束时间 - int newStartTime = 0; - int newEndTime = 0; - // 根据缩放选择获取开始结束时间 - if (zoomDecide == 1) { - // 放大后的起始和结束时间 - newStartTime = startTimed - changeLength; - newEndTime = endTimed + changeLength; - - } else if (-zoomDecide == 1) { - // 缩小后的起始和结束时间 - newStartTime = startTimed + changeLength; - newEndTime = endTimed - changeLength; - } else { - newStartTime = startTimed; - newEndTime = endTimed; - } - ChartStandard standard = this.bottomPanel.getObserver().getStandard(); - int currentTime = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - // 当前展示的时间大于最大展示时间,则不刷新 - int maxDisplay = this.bottomPanel.getObserver().getStandard().getMaxDisplayMillis(); - if (currentTime <= maxDisplay) { - return; - } - // 缩放变化放入观察者去刷新 - this.bottomPanel.getObserver().charZoom(newStartTime, newEndTime, maxDisplayTime); - if (moveDecide) { - // 调用观察者的停止刷新方法 - this.bottomPanel.getObserver().stopRefresh(false); - } else { - // 恢复刷新数据 - this.bottomPanel.getObserver().restartRefresh(); - } - // 调用重绘方法 - this.repaint(); - this.revalidate(); - } - - /** - * 根据鼠标的坐标,更新鼠标样式 - * - * @param crtMouseX 鼠标X轴坐标 - * @param crtMouseY 鼠标Y轴坐标 - */ - private void checkCursorStyle(int crtMouseX, int crtMouseY) { - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - if (selectedRange == null) { - return; - } - // Y轴是否也接近倒三角的标记点 - boolean isCloseToCoordinateY = Math.abs(this.getHeight() - crtMouseY) < NUM_8; - int selectStart = - startCoordinate + OperationUtils.multiply(pixelPerTime, selectedRange.getStartTime() - startTime); - int selectEnd = startCoordinate + OperationUtils.multiply(pixelPerTime, selectedRange.getEndTime() - startTime); - // X轴和Y轴坐标,都靠近倒三角的标记点时,鼠标变为resize状态 - if (Math.abs(selectStart - crtMouseX) < NUM_5 && isCloseToCoordinateY) { - this.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR)); - } else if (Math.abs(selectEnd - crtMouseX) < NUM_5 && isCloseToCoordinateY) { - this.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); - } else { - this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - } - - /** - * setMaxDisplayTime - * - * @param maxDisplayTime maxDisplayTime - */ - public void setMaxDisplayTime(int maxDisplayTime) { - this.maxDisplayTime = maxDisplayTime; - } - - /** - * setMinMarkInterval - * - * @param minMarkInterval minMarkInterval - */ - public void setMinMarkInterval(int minMarkInterval) { - this.minMarkInterval = minMarkInterval; - } - - /** - * getStartTime - * - * @return int - */ - public int getStartTime() { - return startTime; - } - - /** - * setStartTime - * - * @param startTime startTime - */ - public void setStartTime(int startTime) { - this.startTime = startTime; - } - - /** - * getEndTime - * - * @return int - */ - public int getEndTime() { - return endTime; - } - - /** - * setEndTime - * - * @param endTime endTime - */ - public void setEndTime(int endTime) { - this.endTime = endTime; - } - - /** - * getLevelTablePanel - * - * @return LevelTablePanel - */ - public LevelTablePanel getLevelTablePanel() { - return levelTablePanel; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/AgentDataModel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/AgentDataModel.java deleted file mode 100644 index fc83f109c..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/AgentDataModel.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.event.EventListenerList; -import javax.swing.event.TreeModelListener; -import javax.swing.tree.TreePath; - -import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; -import static ohos.devtools.views.common.LayoutConstants.NUM_0; -import static ohos.devtools.views.common.LayoutConstants.NUM_1; -import static ohos.devtools.views.common.LayoutConstants.NUM_2; -import static ohos.devtools.views.common.LayoutConstants.NUM_3; -import static ohos.devtools.views.common.LayoutConstants.NUM_4; - -/** - * agentDataModel class. - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class AgentDataModel implements TreeTableModel { - private static final Logger LOGGER = LogManager.getLogger(AgentDataModel.class); - - /** - * Names of the columns. - */ - protected static String[] cNames = {"Class Name", "Allocations", "Deallocations", "Total Count", "Shallow Size"}; - - /** - * cTypes Types of the columns. - */ - protected static Class[] cTypes = {TreeTableModel.class, Integer.class, Integer.class, Integer.class, Long.class}; - - /** - * listenerList - */ - protected EventListenerList listenerList = new EventListenerList(); - - private DataNode dataNode; - - /** - * FileSystemModel - * - * @param dataNode dataNode - */ - public AgentDataModel(DataNode dataNode) { - this.dataNode = dataNode; - } - - /** - * getDataNode - * - * @return DataNode - */ - public DataNode getDataNode() { - return dataNode; - } - - /** - * getClassObject - * - * @param node node - * @return DataNode - */ - protected DataNode getClassObject(Object node) { - return (DataNode) node; - } - - /** - * getChildren - * - * @param node node - * @return Object[] - */ - protected Object[] getChildren(Object node) { - DataNode digitalNode = null; - if (node instanceof DataNode) { - digitalNode = (DataNode) node; - } - if (digitalNode == null) { - return new DataNode[0]; - } - if (digitalNode.getChildren() != null) { - return digitalNode.getChildren().toArray(); - } else { - return new DataNode[0]; - } - } - - /** - * 获取子节点数量 - * - * @param node node - * @return int - */ - public int getChildCount(Object node) { - Object[] children = getChildren(node); - return (children == null) ? 0 : children.length; - } - - /** - * getRootNode - * - * @return dataNode dataNode - */ - @Override - public Object getRoot() { - return dataNode; - } - - /** - * 获取子节点 - * - * @param node node - * @param number number - * @return Object - */ - public Object getChild(Object node, int number) { - return getChildren(node)[number]; - } - - /** - * isLeaf - * - * @param node node - * @return boolean - */ - public boolean isLeaf(Object node) { - return getChildCount(node) <= 0; - } - - /** - * valueForPathChanged Not implemented - * - * @param path path - * @param newValue newValue - */ - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - } - - /** - * 获取子节点序列 - * - * @param parent parent - * @param child child - * @return int - */ - @Override - public int getIndexOfChild(Object parent, Object child) { - for (int index = 0; index < getChildCount(parent); index++) { - if (getChild(parent, index).equals(child)) { - return index; - } - } - return NEGATIVE_ONE; - } - - /** - * addTreeModelListener - * - * @param listener listener - */ - @Override - public void addTreeModelListener(TreeModelListener listener) { - listenerList.add(TreeModelListener.class, listener); - } - - /** - * removeTreeModelListener - * - * @param listener listener - */ - @Override - public void removeTreeModelListener(TreeModelListener listener) { - listenerList.remove(TreeModelListener.class, listener); - } - - /** - * getColumnCount - * - * @return int - */ - public int getColumnCount() { - return cNames.length; - } - - /** - * 获取列名 - * - * @param column column - * @return String - */ - public String getColumnName(int column) { - return cNames[column]; - } - - /** - * getColumnClass - * - * @param column column - * @return Class - */ - public Class getColumnClass(int column) { - return cTypes[column]; - } - - /** - * 获取数据 - * - * @param node node - * @param column column - * @return Object - */ - public Object getValueAt(Object node, int column) { - Object object = null; - DataNode digitalNode = getClassObject(node); - try { - switch (column) { - case NUM_0: - object = digitalNode.getClassName(); - break; - case NUM_1: - object = digitalNode.getAllocations(); - break; - case NUM_2: - object = digitalNode.getDeallocations(); - break; - case NUM_3: - object = digitalNode.getTotalCount(); - break; - case NUM_4: - object = digitalNode.getShallowSize(); - break; - default: - break; - } - } catch (SecurityException exception) { - LOGGER.error("SecurityException error: {}", exception.getMessage()); - } - return object; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNode.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNode.java deleted file mode 100644 index c95887c16..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNode.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import java.util.ArrayList; -import java.util.Objects; - -/** - * DataNode - * - * @version 1.0 - * @date 2021/03/15 10:07 - **/ -public class DataNode { - private Integer id; - private Integer cId; - private Integer heapId; - private Long sessionId; - private String className; - private Integer allocations; - private Integer deallocations; - private Integer totalCount; - private Long shallowSize; - ArrayList children; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getcId() { - return cId; - } - - public void setcId(Integer cId) { - this.cId = cId; - } - - public Integer getHeapId() { - return heapId; - } - - public void setHeapId(Integer heapId) { - this.heapId = heapId; - } - - public Long getSessionId() { - return sessionId; - } - - public void setSessionId(Long sessionId) { - this.sessionId = sessionId; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Integer getAllocations() { - return allocations; - } - - public void setAllocations(Integer allocations) { - this.allocations = allocations; - } - - public Integer getDeallocations() { - return deallocations; - } - - public void setDeallocations(Integer deallocations) { - this.deallocations = deallocations; - } - - public Integer getTotalCount() { - return totalCount; - } - - public void setTotalCount(Integer totalCount) { - this.totalCount = totalCount; - } - - public Long getShallowSize() { - return shallowSize; - } - - public void setShallowSize(Long shallowSize) { - this.shallowSize = shallowSize; - } - - public ArrayList getChildren() { - return children; - } - - public void setChildren(ArrayList children) { - this.children = children; - } - - /** - * addChildren - * - * @param children children - */ - public void addChildren(DataNode children) { - if (this.children == null) { - this.children = new ArrayList(); - } - this.children.add(children); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - - DataNode dataNode = null; - if (object instanceof DataNode) { - dataNode = (DataNode) object; - } - return Objects.equals(id, dataNode.id) && Objects.equals(cId, dataNode.cId) && Objects - .equals(heapId, dataNode.heapId) && Objects.equals(sessionId, dataNode.sessionId) && Objects - .equals(className, dataNode.className) && Objects.equals(allocations, dataNode.allocations) && Objects - .equals(deallocations, dataNode.deallocations) && Objects.equals(totalCount, dataNode.totalCount) && Objects - .equals(shallowSize, dataNode.shallowSize) && Objects.equals(children, dataNode.children); - } - - @Override - public int hashCode() { - return Objects - .hash(id, cId, heapId, sessionId, className, allocations, deallocations, totalCount, shallowSize, children); - } - - /** - * toStr - * - * @return String - */ - public String toStr() { - return className + ',' + allocations + ',' + deallocations + ',' + totalCount + ',' + shallowSize; - } - - @Override - public String toString() { - return className; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNodeCompares.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNodeCompares.java deleted file mode 100644 index ca5148941..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/DataNodeCompares.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import java.util.Comparator; - -import static ohos.devtools.views.common.LayoutConstants.ASC; - -/** - * @Description dataPoller回调类 - * @Date 2021/4/20 13:30 - **/ -public class DataNodeCompares { - /** - * classNameString - */ - public static Comparator classNameString = new Comparator() { - @Override - public int compare(String o1, String o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.compareTo(o2); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - private static Comparator classNameCompareDsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.getClassName().compareTo(o2.getClassName()); - if (res == 0) { - return 0; - } - return res < 0 ? 1 : -1; - } - }; - - private static Comparator shallowSizeCompareAsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - long res = o1.getShallowSize() - o2.getShallowSize(); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - private static Comparator shallowSizeCompareDsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return 1; - } - if (o2 == null) { - return -1; - } - long res = o1.getShallowSize() - o2.getShallowSize(); - if (res == 0) { - return 0; - } - return res < 0 ? 1 : -1; - } - }; - - private static Comparator totalCompareAsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.getTotalCount() - o2.getTotalCount(); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - private static Comparator totalCompareDsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return 1; - } - if (o2 == null) { - return -1; - } - int res = o1.getTotalCount() - o2.getTotalCount(); - if (res == 0) { - return 0; - } - return res < 0 ? 1 : -1; - } - }; - - private static Comparator allocationsCompareAsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.getAllocations() - o2.getAllocations(); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - private static Comparator allocationsCompareDsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return 1; - } - if (o2 == null) { - return -1; - } - int res = o1.getAllocations() - o2.getAllocations(); - if (res == 0) { - return 0; - } - return res < 0 ? 1 : -1; - } - }; - - private static Comparator deallocationsCompareAsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.getDeallocations() - o2.getDeallocations(); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - private static Comparator deallocationsCompareDsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return 1; - } - if (o2 == null) { - return -1; - } - int res = o1.getDeallocations() - o2.getDeallocations(); - if (res == 0) { - return 0; - } - return res < 0 ? 1 : -1; - } - }; - - /** - * classNameCompareAsc - */ - private Comparator classNameCompareAsc = new Comparator() { - @Override - public int compare(DataNode o1, DataNode o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int res = o1.getClassName().compareTo(o2.getClassName()); - if (res == 0) { - return 0; - } - return res > 0 ? 1 : -1; - } - }; - - /** - * 选择出比较器 - * - * @param keyColumn keyColumn - * @param sortOrder sortOrder - * @return Comparator - */ - public Comparator chooseCompare(int keyColumn, String sortOrder) { - Comparator comparator = null; - if (ASC.equals(sortOrder)) { - switch (keyColumn) { - case 0: - comparator = classNameCompareAsc; - break; - case 1: - comparator = allocationsCompareAsc; - break; - case 2: - comparator = deallocationsCompareAsc; - break; - case 3: - comparator = totalCompareAsc; - break; - case 4: - comparator = shallowSizeCompareAsc; - break; - default: - break; - } - } else { - switch (keyColumn) { - case 0: - comparator = classNameCompareDsc; - break; - case 1: - comparator = allocationsCompareDsc; - break; - case 2: - comparator = deallocationsCompareDsc; - break; - case 3: - comparator = totalCompareDsc; - break; - case 4: - comparator = shallowSizeCompareDsc; - break; - default: - break; - } - } - return comparator; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/JTreeTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/JTreeTable.java deleted file mode 100644 index 15613ef01..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/JTreeTable.java +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.JTable; -import javax.swing.JTree; -import javax.swing.RowSorter; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; -import javax.swing.text.Position; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Graphics; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; - -import static ohos.devtools.views.common.LayoutConstants.NEGATIVE_ONE; - -/** - * JTreeTable - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class JTreeTable extends JTable { - private static final Logger LOGGER = LogManager.getLogger(JTreeTable.class); - - /** - * 数字220 - */ - public static final int NUM_220 = 220; - - /** - * TreeTableCellRenderer对象 - */ - public TreeTableCellRenderer treeTableCellRenderer; - - /** - * TreeTableModel类 - */ - public TreeTableModel treeTableModel; - - /** - * getTreeTableModel - * - * @return TreeTableModel - */ - public TreeTableModel getTreeTableModel() { - return treeTableModel; - } - - /** - * setTreeTableModel - * - * @param treeTableModel treeTableModel - */ - public void setTreeTableModel(TreeTableModel treeTableModel) { - this.treeTableModel = treeTableModel; - if (treeTableCellRenderer == null) { - treeTableCellRenderer = new TreeTableCellRenderer(treeTableModel); - } else { - treeTableCellRenderer.setModel(treeTableModel); - treeTableCellRenderer.setShowsRootHandles(true); - } - TreeTableModelAdapter model = new TreeTableModelAdapter(treeTableModel, treeTableCellRenderer); - super.setModel(model); - treeTableCellRenderer.setRowHeight(getRowHeight()); - setDefaultRenderer(TreeTableModel.class, treeTableCellRenderer); - TableRowSorter sorter = new TableRowSorter(this.getModel()); - sorter.setComparator(0, DataNodeCompares.classNameString); - sorter.addRowSorterListener(event -> { - try { - if (!sorter.getSortKeys().isEmpty()) { - List keys = sorter.getSortKeys(); - AgentDataModel treeTableModels = null; - TreeTableModel treeTModel = JTreeTable.this.treeTableModel; - if (treeTModel instanceof AgentDataModel) { - treeTableModels = (AgentDataModel) treeTModel; - } - DataNode rootNode = treeTableModels.getDataNode(); - ArrayList datNode = rootNode.getChildren(); - RowSorter.SortKey key = keys.get(0); - String sortOrder = key.getSortOrder().name(); - Comparator comparator = new DataNodeCompares().chooseCompare(key.getColumn(), sortOrder); - if (comparator != null) { - Collections.sort(datNode, comparator); - } - rootNode.setChildren(datNode); - AgentDataModel agentDataModel = new AgentDataModel(rootNode); - JTreeTable.this.treeTableModel = agentDataModel; - treeTableCellRenderer = new TreeTableCellRenderer(agentDataModel); - treeTableCellRenderer.setRowHeight(getRowHeight()); - setDefaultRenderer(TreeTableModel.class, treeTableCellRenderer); - } - } catch (IndexOutOfBoundsException | ClassCastException | UnsupportedOperationException - | IllegalArgumentException exception) { - LOGGER.error("reflush Exception {}", exception.getMessage()); - } - }); - this.setRowSorter(sorter); - } - - /** - * JTreeTable - * - * @param treeTableModel treeTableModel - */ - public JTreeTable(TreeTableModel treeTableModel) { - super(); - this.treeTableModel = treeTableModel; - treeTableCellRenderer = new TreeTableCellRenderer(treeTableModel); - super.setModel(new TreeTableModelAdapter(treeTableModel, treeTableCellRenderer)); - treeTableCellRenderer.setSelectionModel(new DefaultTreeSelectionModel() { - { - setSelectionModel(listSelectionModel); - } - }); - treeTableCellRenderer.setRowHeight(getRowHeight()); - setDefaultRenderer(TreeTableModel.class, treeTableCellRenderer); - setShowGrid(false); - getColumnModel().getColumn(0).setPreferredWidth(NUM_220); - setIntercellSpacing(new Dimension(0, 0)); - } - - /** - * TreeTableCellRenderer - */ - public class TreeTableCellRenderer extends JTree implements TableCellRenderer { - /** - * visibleRow - */ - protected int visibleRow; - - /** - * TreeTableCellRenderer - * - * @param model model - */ - public TreeTableCellRenderer(TreeModel model) { - super(model); - this.setShowsRootHandles(true); - } - - /** - * setBounds - * - * @param pointX pointX - * @param pointY pointY - * @param width width - * @param height height - */ - @Override - public void setBounds(int pointX, int pointY, int width, int height) { - super.setBounds(pointX, 0, width, JTreeTable.this.getHeight()); - } - - /** - * paint - * - * @param graphics graphics - */ - @Override - public void paint(Graphics graphics) { - graphics.translate(0, -visibleRow * getRowHeight()); - super.paint(graphics); - } - - /** - * 获取表单元格渲染器组件 - * - * @param table table - * @param value value - * @param isSelected isSelected - * @param hasFocus hasFocus - * @param row row - * @param column column - * @return Component - */ - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, - int row, int column) { - if (isSelected) { - setBackground(table.getSelectionBackground()); - } else { - setBackground(table.getBackground()); - } - visibleRow = row; - return this; - } - - /** - * getNextMatch - * - * @param prefix prefix - * @param startingRow startingRow - * @param bias bias - * @return TreePath - */ - @Override - public synchronized TreePath getNextMatch(String prefix, int startingRow, Position.Bias bias) { - String newPrefix = prefix; - int max = getRowCount(); - int row = 0; - if (newPrefix == null) { - return null; - } - if (startingRow < 0 || (startingRow + 1) == getRowCount()) { - row = 0; - } else { - row = startingRow + 1; - } - - if (startingRow >= max) { - return null; - } - newPrefix = newPrefix.toUpperCase(Locale.ENGLISH); - TreePath andExpand = null; - if (startingRow < 0) { - andExpand = findAndExpand(newPrefix, row, bias, NEGATIVE_ONE); - } else { - andExpand = findAndExpand(newPrefix, row, bias, getSelectedRow()); - } - if (andExpand == null && startingRow >= 0) { - TreePath path = getPathForRow(startingRow); - String text = - convertRowToText(path.getLastPathComponent(), isRowSelected(startingRow), isExpanded(startingRow), - true, startingRow, false); - if (text.toUpperCase(Locale.ENGLISH).indexOf(newPrefix) > NEGATIVE_ONE) { - return path; - } else { - return null; - } - } else { - return andExpand; - } - } - - /** - * 查找并扩展 - * - * @param prefix prefix - * @param row row - * @param bias bias - * @param currentSelectedRow currentSelectedRow - * @return TreePath - */ - public TreePath findAndExpand(String prefix, int row, Position.Bias bias, int currentSelectedRow) { - TreePath treePath = getPathForRow(row); - String text = - convertRowToText(treePath - .getLastPathComponent(), isRowSelected(row), isExpanded(row), true, row, false); - if (text.toUpperCase(Locale.ENGLISH).indexOf(prefix) > NEGATIVE_ONE) { - return treePath; - } else { - DataNode node = null; - Object objComponent = treePath.getLastPathComponent(); - if (objComponent instanceof DataNode) { - node = (DataNode) objComponent; - } - if (node != null && node.getChildren() != null && node.getChildren().size() > 0 && !isExpanded(row)) { - // expand current row - expandRow(row); - TreePath pathTem = findAndExpand(prefix, row + 1, bias, currentSelectedRow); - if (pathTem == null) { - collapseRow(row); - } else { - if (!isSubPath(treePath, pathTem)) { - collapseRow(row); - } - } - return pathTem; - } else { - if (getRowCount() == row + 1) { - if (currentSelectedRow <= 0) { - return null; - } else { - return findAndExpand(prefix, 0, bias, currentSelectedRow); - } - } - if (currentSelectedRow == row + 1) { - return null; - } - return findAndExpand(prefix, row + 1, bias, currentSelectedRow); - } - } - } - - /** - * isSubPath - * - * @param parentPath parentPath - * @param childPath childPath - * @return boolean - */ - public boolean isSubPath(TreePath parentPath, TreePath childPath) { - TreePath parent = childPath; - if (parentPath.getPathCount() >= childPath.getPathCount()) { - return false; - } - for (int index = 0; index < childPath.getPathCount() - parentPath.getPathCount(); index++) { - parent = childPath.getParentPath(); - } - if (parent == parentPath) { - return true; - } - return false; - } - - /** - * convertValueToText - * - * @param value value - * @param selected selected - * @param expanded expanded - * @param leaf leaf - * @param row row - * @param hasFocus hasFocus - * @return String - */ - @Override - public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, - boolean hasFocus) { - if (value != null && value instanceof DataNode) { - String strValue = ((DataNode) value).toString(); - if (strValue != null) { - return strValue; - } - } - return ""; - } - - /** - * convertRowToText - * - * @param value value - * @param selected selected - * @param expanded expanded - * @param leaf leaf - * @param row row - * @param hasFocus hasFocus - * @return String - */ - public String convertRowToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, - boolean hasFocus) { - if (value != null && value instanceof DataNode) { - String strValue = ((DataNode) value).toStr(); - if (strValue != null) { - return strValue; - } - } - return ""; - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModel.java deleted file mode 100644 index 1237db038..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModel.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import javax.swing.tree.TreeModel; - -/** - * TreeTableModel类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public interface TreeTableModel extends TreeModel { - /** - * Returns the number ofs available column. - * - * @return int - */ - int getColumnCount(); - - /** - * getColumnName Returns the name for column number column. - * - * @param column column - * @return String - */ - String getColumnName(int column); - - /** - * getColumnClass Returns the type for column number column. - * - * @param column column - * @return Class - */ - Class getColumnClass(int column); - - /** - * Returns the value to be displayed for node node, at column number column. - * - * @param node node - * @param column column - * @return Object - */ - Object getValueAt(Object node, int column); -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModelAdapter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModelAdapter.java deleted file mode 100644 index 54eada37d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/treetable/TreeTableModelAdapter.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import javax.swing.JTree; -import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeExpansionListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.tree.TreePath; - -/** - * 表模型适配器 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class TreeTableModelAdapter extends AbstractTableModel { - private JTree jTree; - private TreeTableModel treeTableModel; - - public TreeTableModelAdapter(TreeTableModel treeTableModel, JTree jTree) { - this.jTree = jTree; - this.treeTableModel = treeTableModel; - jTree.addTreeExpansionListener(new TreeExpansionListener() { - /** - * 树展开 - * - * @param event event - */ - public void treeExpanded(TreeExpansionEvent event) { - fireTableDataChanged(); - } - - /** - * 表数据更改 - * - * @param event event - */ - public void treeCollapsed(TreeExpansionEvent event) { - fireTableDataChanged(); - } - }); - } - - /** - * getColumnCount - * - * @return int - */ - @Override - public int getColumnCount() { - return treeTableModel.getColumnCount(); - } - - /** - * getColumnName - * - * @param column column - * @return String - */ - @Override - public String getColumnName(int column) { - return treeTableModel.getColumnName(column); - } - - /** - * getColumnClass - * - * @param column column - * @return Class - */ - @Override - public Class getColumnClass(int column) { - return treeTableModel.getColumnClass(column); - } - - /** - * getRowCount - * - * @return int - */ - @Override - public int getRowCount() { - return jTree.getRowCount(); - } - - /** - * getValueAt - * - * @param row row - * @param column column - * @return Object - */ - @Override - public Object getValueAt(int row, int column) { - TreePath treePath = jTree.getPathForRow(row); - Object rowNode = treePath.getLastPathComponent(); - return treeTableModel.getValueAt(rowNode, column); - } - - /** - * 单元格可编辑 - * - * @param row row - * @param column column - * @return boolean - */ - @Override - public boolean isCellEditable(int row, int column) { - return false; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJComboBox.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomComboBox.java similarity index 85% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJComboBox.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomComboBox.java index f4a95e640..043f6c83a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJComboBox.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomComboBox.java @@ -1,47 +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. - */ - -package ohos.devtools.views.common.hoscomp; - -import ohos.devtools.datasources.utils.session.entity.SessionInfo; - -import javax.swing.JComboBox; - -/** - * HosJComboBox - * - * @since 2021/3/16 10:36 - */ -public class HosJComboBox extends JComboBox { - private SessionInfo sessionInfo; - - private long sessionId; - - public SessionInfo getSessionInfo() { - return sessionInfo; - } - - public void setSessionInfo(SessionInfo sessionInfo) { - this.sessionInfo = sessionInfo; - } - - public long getSessionId() { - return sessionId; - } - - public void setSessionId(long sessionId) { - this.sessionId = sessionId; - } -} +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import ohos.devtools.datasources.utils.session.entity.SessionInfo; + +import javax.swing.*; + +/** + * CustomComboBox + */ +public class CustomComboBox extends JComboBox { + private SessionInfo sessionInfo; + + private long sessionId; + + public SessionInfo getSessionInfo() { + return sessionInfo; + } + + public void setSessionInfo(SessionInfo sessionInfo) { + this.sessionInfo = sessionInfo; + } + + public long getSessionId() { + return sessionId; + } + + public void setSessionId(long sessionId) { + this.sessionId = sessionId; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBComboBoxUI.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBComboBoxUI.java new file mode 100644 index 000000000..1c773e186 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBComboBoxUI.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.icons.AllIcons; +import com.intellij.util.ui.components.JBComponent; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.ListCellRenderer; +import javax.swing.UIManager; +import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.basic.BasicComboBoxUI; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Rectangle; + +/** + * Hos JBComboBox + */ +public class CustomJBComboBoxUI extends BasicComboBoxUI { + /** + * createUI + * + * @param component JComponent + * @return ComponentUI + */ + public static ComponentUI createUI(JBComponent component) { + return new CustomJBComboBoxUI(); + } + + /** + * createArrowButton + * + * @return JButton + */ + @Override + protected JButton createArrowButton() { + JButton dropDownButton = new JButton(); + dropDownButton.setContentAreaFilled(false); + dropDownButton.setFocusPainted(false); + dropDownButton.setBorder(BorderFactory.createEmptyBorder()); + dropDownButton.setOpaque(true); + dropDownButton.setIcon(AllIcons.Actions.FindAndShowNextMatchesSmall); + return dropDownButton; + } + + @Override + public void paintCurrentValue(Graphics graphics, Rectangle bounds, boolean hasFocus) { + ListCellRenderer renderer = comboBox.getRenderer(); + Component component; + + if (hasFocus && !isPopupVisible(comboBox)) { + component = renderer.getListCellRendererComponent(listBox, comboBox.getSelectedItem(), -1, true, false); + } else { + component = renderer.getListCellRendererComponent(listBox, comboBox.getSelectedItem(), -1, false, false); + component.setBackground(UIManager.getColor("ComboBox.background")); + } + component.setFont(comboBox.getFont()); + if (hasFocus && !isPopupVisible(comboBox)) { + component.setBackground(UIManager.getColor("ComboBox.background")); + } else { + if (comboBox.isEnabled()) { + component.setBackground(UIManager.getColor("ComboBox.background")); + } else { + component.setBackground(UIManager.getColor("ComboBox.background")); + } + } + boolean shouldValidate = false; + if (component instanceof JPanel) { + shouldValidate = true; + } + int boundX = (int) bounds.getX(); + int boundY = (int) bounds.getY(); + int boundW = bounds.width; + int boundH = bounds.height; + if (padding != null) { + boundX = (int) (bounds.getX() + padding.left); + boundY = (int) (bounds.getY() + padding.top); + boundW = bounds.width - (padding.left + padding.right); + boundH = bounds.height - (padding.top + padding.bottom); + } + currentValuePane.paintComponent(graphics, component, comboBox, boundX, boundY, boundW, boundH, shouldValidate); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBTextField.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBTextField.java new file mode 100644 index 000000000..5ec36879a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJBTextField.java @@ -0,0 +1,62 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.icons.AllIcons; +import com.intellij.ui.components.JBTextField; +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.common.LayoutConstants; + +import javax.swing.Icon; +import java.awt.Graphics; +import java.awt.Insets; + +/** + * Custom TextField + */ +public class CustomJBTextField extends JBTextField { + private final Icon icon; + private int width; + + /** + * HosJBTextField + */ + public CustomJBTextField() { + icon = AllIcons.Actions.Search; + Insets insets = JBUI.insetsLeft(LayoutConstants.NUM_20); + // Set text input distance + this.setMargin(insets); + } + + /** + * paintComponent + * + * @param graphics graphics + */ + @Override + public void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + int iconHeight = icon.getIconHeight(); + int height = this.getHeight(); + width = this.getWidth() - LayoutConstants.THIRTY; + // Draw the previous picture + icon.paintIcon(this, graphics, width, (height - iconHeight) / LayoutConstants.NUM_2); + } + + public void setWidth(int width) { + this.width = width; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJButton.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJButton.java similarity index 62% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJButton.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJButton.java index 47020aaaa..37096fbcd 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJButton.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJButton.java @@ -1,80 +1,131 @@ -/* - * 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. - */ - -package ohos.devtools.views.common.hoscomp; - -import ohos.devtools.datasources.utils.session.entity.SessionInfo; -import ohos.devtools.views.common.LayoutConstants; - -import javax.swing.Icon; -import javax.swing.JButton; -import java.awt.Dimension; - -/** - * @Description HosJButton - * @Date 2021/3/10 20:50 - **/ -public class HosJButton extends JButton { - private SessionInfo sessionInfo; - - private long sessionId; - - private String deviceName; - - private String processName; - - public HosJButton(Icon icon, String message) { - super(icon); - this.setPreferredSize(new Dimension(LayoutConstants.BUTTON_SIZE, LayoutConstants.BUTTON_SIZE)); - this.setToolTipText(message); - } - - public HosJButton(String text, String message) { - super(text); - this.setToolTipText(message); - } - - public SessionInfo getSessionInfo() { - return sessionInfo; - } - - public void setSessionInfo(SessionInfo sessionInfo) { - this.sessionInfo = sessionInfo; - } - - public long getSessionId() { - return sessionId; - } - - public void setSessionId(long sessionId) { - this.sessionId = sessionId; - } - - public String getDeviceName() { - return deviceName; - } - - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - public String getProcessName() { - return processName; - } - - public void setProcessName(String processName) { - this.processName = processName; - } -} +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.views.common.LayoutConstants; + +import javax.swing.Icon; +import javax.swing.JButton; +import java.awt.Dimension; + +/** + * CustomJButton + */ +public class CustomJButton extends JButton { + private SessionInfo sessionInfo; + + private long sessionId; + + private String deviceName; + + private String processName; + + /** + * CustomJButton + * + * @param icon icon + * @param message message + */ + public CustomJButton(Icon icon, String message) { + super(icon); + this.setPreferredSize(new Dimension(LayoutConstants.BUTTON_SIZE, LayoutConstants.BUTTON_SIZE)); + this.setToolTipText(message); + } + + /** + * CustomJButton + * + * @param text text + * @param message message + */ + public CustomJButton(String text, String message) { + super(text); + this.setToolTipText(message); + } + + /** + * getSessionInfo + * + * @return SessionInfo + */ + public SessionInfo getSessionInfo() { + return sessionInfo; + } + + /** + * setSessionInfo + * + * @param sessionInfo + */ + public void setSessionInfo(SessionInfo sessionInfo) { + this.sessionInfo = sessionInfo; + } + + /** + * getSessionId + * + * @return long + */ + public long getSessionId() { + return sessionId; + } + + /** + * setSessionId + * + * @param sessionId sessionId + */ + public void setSessionId(long sessionId) { + this.sessionId = sessionId; + } + + /** + * getDeviceName + * + * @return String + */ + public String getDeviceName() { + return deviceName; + } + + /** + * setDeviceName + * + * @param deviceName deviceName + */ + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + /** + * getProcessName + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * setProcessName + * + * @param processName + */ + public void setProcessName(String processName) { + this.processName = processName; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJLabel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJLabel.java new file mode 100644 index 000000000..3298520df --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJLabel.java @@ -0,0 +1,243 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.ui.components.JBLabel; + +/** + * HosJLabel + */ +public class CustomJLabel extends JBLabel { + private long sessionId; + private String deviceName; + private String processName; + private String message; + private String connectType; + private boolean isOnline = true; + private long startTime; + private long endTime; + private CustomJLabel left; + private String fileType; + + /** + * isOnline + * + * @return boolean + */ + public boolean isOnline() { + return isOnline; + } + + /** + * setOnline + * + * @param deviceType deviceType + */ + public void setOnline(boolean deviceType) { + this.isOnline = deviceType; + } + + /** + * getStartTime + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * setStartTime + * + * @param startTime startTime + */ + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + /** + * getEndTime + * + * @return long + */ + public long getEndTime() { + return endTime; + } + + /** + * setEndTime + * + * @param endTime endTime + */ + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + /** + * CustomJLabel + * + * @param text text + */ + public CustomJLabel(String text) { + super(text); + } + + /** + * CustomJLabel + */ + public CustomJLabel() { + super("", null, LEADING); + } + + /** + * getMessage + * + * @return String + */ + public String getMessage() { + return message; + } + + /** + * setMessage + * + * @param message message + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * getSessionId + * + * @return long + */ + public long getSessionId() { + return sessionId; + } + + /** + * setSessionId + * + * @param sessionId sessionId + */ + public void setSessionId(long sessionId) { + this.sessionId = sessionId; + } + + /** + * getDeviceName + * + * @return String + */ + public String getDeviceName() { + return deviceName; + } + + /** + * setDeviceName + * + * @param deviceName deviceName + */ + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + /** + * getProcessName + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * setProcessName + * + * @param processName processName + */ + public void setProcessName(String processName) { + this.processName = processName; + } + + /** + * getConnectType + * + * @return String + */ + public String getConnectType() { + return connectType; + } + + /** + * setConnectType + * + * @param connectType connectType + */ + public void setConnectType(String connectType) { + this.connectType = connectType; + } + + /** + * getLeft + * + * @return CustomJLabel + */ + public CustomJLabel getLeft() { + return left; + } + + /** + * setLeft + * + * @param left left + */ + public void setLeft(CustomJLabel left) { + this.left = left; + } + + /** + * getFileType + * + * @return String + */ + public String getFileType() { + return fileType; + } + + /** + * setFileType + * + * @param fileType fileType + */ + public void setFileType(String fileType) { + this.fileType = fileType; + } + + /** + * toString + * + * @return String + */ + @Override + public String toString() { + return "CustomJLabel{" + "sessionId=" + sessionId + ", deviceName='" + deviceName + '\'' + ", processName='" + + processName + '\'' + ", message='" + message + '\'' + ", connectType='" + connectType + '\'' + + ", isOnline=" + isOnline + ", startTime=" + startTime + ", endTime=" + endTime + ", left=" + left + + ", fileType='" + fileType + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJUnderLineLabel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJUnderLineLabel.java new file mode 100644 index 000000000..eb156ac59 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomJUnderLineLabel.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.ui.components.JBLabel; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Rectangle; + +import static java.awt.BasicStroke.CAP_BUTT; + +/** + * CustomJ UnderLine Label + */ +public class CustomJUnderLineLabel extends JBLabel { + private Color underLineColor; + + /** + * CustomJUnderLineLabel + * + * @param text text + */ + public CustomJUnderLineLabel(String text) { + super(text); + } + + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + Rectangle rectangle = graphics.getClipBounds(); + int texX = 0; + int texY = 0; + if (this.getBorder() != null && this.getBorder().getBorderInsets(this) != null) { + Insets inserts = this.getBorder().getBorderInsets(this); + texX = inserts.left; + texY = inserts.bottom; + } + int pointX = 0; + int pointY = 0; + pointX = texX; + pointY = rectangle.height - texY - getFontMetrics(getFont()).getDescent(); + + int point2X = 0; + int point2Y = 0; + point2Y = pointY; + point2X = pointX + getFontMetrics(getFont()).stringWidth(getText()); + if (underLineColor != null) { + graphics.setColor(underLineColor); + } + if (graphics instanceof Graphics2D) { + Graphics2D graphics2D = (Graphics2D) graphics; + // The array shows the length of each dotted line + float[] typeArray = {point2X - pointX}; + BasicStroke dottedLIne = new BasicStroke(1, CAP_BUTT, 1, 1, typeArray, 1); + graphics2D.setStroke(dottedLIne); + graphics2D.drawLine(pointX, pointY, point2X, point2Y); + } + } + + public void setUnderLineColor(Color underLineColor) { + this.underLineColor = underLineColor; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomListFilerModel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomListFilerModel.java new file mode 100644 index 000000000..410e39e38 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomListFilerModel.java @@ -0,0 +1,327 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import org.apache.commons.lang.StringUtils; + +import javax.swing.AbstractListModel; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Vector; + +/** + * CustomListFilerModel + */ +public class CustomListFilerModel extends AbstractListModel { + private Vector items = new Vector(); + private Vector filterItems = new Vector(); + private boolean defaultFilterItems = true; + + /** + * getSize + * + * @return int + */ + public int getSize() { + return defaultFilterItems ? items.size() : filterItems.size(); + } + + /** + * getElementAt + * + * @param index index + * @return E + */ + public E getElementAt(int index) { + return defaultFilterItems ? items.elementAt(index) : filterItems.elementAt(index); + } + + /** + * size + * + * @return int + */ + public int size() { + return defaultFilterItems ? items.size() : filterItems.size(); + } + + /** + * isEmpty + * + * @return boolean + */ + public boolean isEmpty() { + return defaultFilterItems ? items.isEmpty() : filterItems.isEmpty(); + } + + /** + * elements + * + * @return Enumeration + */ + public Enumeration elements() { + return items.elements(); + } + + /** + * contains + * + * @param elem elem + * @return boolean + */ + public boolean contains(Object elem) { + return items.contains(elem); + } + + /** + * indexOf + * + * @param elem elem + * @return int + */ + public int indexOf(Object elem) { + return items.indexOf(elem); + } + + /** + * indexOf + * + * @param elem elem + * @param index index + * @return int + */ + public int indexOf(Object elem, int index) { + return items.indexOf(elem, index); + } + + /** + * lastIndexOf + * + * @param elem elem + * @return int + */ + public int lastIndexOf(Object elem) { + return items.lastIndexOf(elem); + } + + /** + * lastIndexOf + * + * @param elem elem + * @param index index + * @return int + */ + public int lastIndexOf(Object elem, int index) { + return items.lastIndexOf(elem, index); + } + + /** + * elementAt + * + * @param index index + * @return E + */ + public E elementAt(int index) { + return items.elementAt(index); + } + + /** + * firstElement + * + * @return E + */ + public E firstElement() { + return items.firstElement(); + } + + /** + * lastElement + * + * @return E + */ + public E lastElement() { + return items.lastElement(); + } + + /** + * setElementAt + * + * @param element element + * @param index index + */ + public void setElementAt(E element, int index) { + items.setElementAt(element, index); + fireContentsChanged(this, index, index); + } + + /** + * removeElementAt + * + * @param index index + */ + public void removeElementAt(int index) { + items.removeElementAt(index); + fireIntervalRemoved(this, index, index); + } + + /** + * insertElementAt + * + * @param element element + * @param index index + */ + public void insertElementAt(E element, int index) { + items.insertElementAt(element, index); + fireIntervalAdded(this, index, index); + } + + /** + * addElement + * + * @param element element + */ + public void addElement(E element) { + int index = items.size(); + items.addElement(element); + fireIntervalAdded(this, index, index); + } + + /** + * removeElement + * + * @param obj obj + * @return boolean + */ + public boolean removeElement(Object obj) { + int index = indexOf(obj); + boolean rv = items.removeElement(obj); + if (index >= 0) { + fireIntervalRemoved(this, index, index); + } + return rv; + } + + /** + * removeAllElements + */ + public void removeAllElements() { + int index1 = items.size() - 1; + items.removeAllElements(); + if (index1 >= 0) { + fireIntervalRemoved(this, 0, index1); + } + } + + /** + * toString + * + * @return String + */ + public String toString() { + return items.toString(); + } + + /** + * toArray + * + * @return Object[] + */ + public Object[] toArray() { + Object[] rv = new Object[items.size()]; + items.copyInto(rv); + return rv; + } + + /** + * get + * + * @param index index + * @return E + */ + public E get(int index) { + return items.elementAt(index); + } + + /** + * clear + */ + public void clear() { + int index1; + if (defaultFilterItems) { + index1 = filterItems.size() - 1; + } else { + index1 = items.size() - 1; + } + items.removeAllElements(); + filterItems.removeAllElements(); + defaultFilterItems = true; + if (index1 >= 0) { + fireIntervalRemoved(this, 0, index1); + } + } + + /** + * addAll + * + * @param c c + */ + public void addAll(Collection c) { + if (c.isEmpty()) { + return; + } + int startIndex = getSize(); + items.addAll(c); + fireIntervalAdded(this, startIndex, getSize() - 1); + } + + /** + * addAll + * + * @param index index + * @param c c + */ + public void addAll(int index, Collection c) { + if (index < 0 || index > getSize()) { + throw new ArrayIndexOutOfBoundsException("index out of range: " + index); + } + if (c.isEmpty()) { + return; + } + items.addAll(index, c); + fireIntervalAdded(this, index, index + c.size() - 1); + } + + /** + * refilter + * + * @param text text + */ + public void refilter(String text) { + if (StringUtils.isBlank(text)) { + defaultFilterItems = true; + } else { + defaultFilterItems = false; + filterItems.clear(); + String term = text; + for (int i = 0; i < items.size(); i++) { + if (items.get(i).toString().indexOf(term, 0) != -1) { + filterItems.add(items.get(i)); + } + } + } + fireContentsChanged(this, 0, getSize()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TransferringWindow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomProgressBar.java similarity index 61% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TransferringWindow.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomProgressBar.java index 4af96249b..f62847e66 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TransferringWindow.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomProgressBar.java @@ -1,52 +1,44 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; - -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -/** - * @Description TransferringWindow - * @Date 2021/3/25 15:58 - **/ -public class TransferringWindow extends JProgressBar { - /** - * TransferringWindow - * - * @param owner owner - */ - public TransferringWindow(JPanel owner) { - this.setBounds(LayoutConstants.TEN, owner.getHeight() - LayoutConstants.FORTY, - owner.getWidth() - LayoutConstants.TWENTY, LayoutConstants.THIRTY); - this.setMinimum(0); - this.setMaximum(LayoutConstants.HUNDRED); - this.setValue(0); - this.setStringPainted(true); - this.setForeground(ColorConstants.CYAN); - this.setBackground(ColorConstants.BLACK); - this.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent event) { - } - }); - owner.add(this); - } -} +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; + +import javax.swing.JPanel; +import javax.swing.JProgressBar; + +/** + * CustomProgressBar + */ +public class CustomProgressBar extends JProgressBar { + /** + * TransferringWindow + * + * @param parentPanel parentPanel + */ + public CustomProgressBar(JPanel parentPanel) { + this.setBounds(LayoutConstants.TEN, parentPanel.getHeight() - LayoutConstants.FORTY, + parentPanel.getWidth() - LayoutConstants.TWENTY, LayoutConstants.THIRTY); + this.setMinimum(0); + this.setMaximum(LayoutConstants.HUNDRED); + this.setValue(0); + this.setStringPainted(true); + this.setForeground(ColorConstants.CYAN); + this.setBackground(ColorConstants.BLACK); + parentPanel.add(this); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomSearchComBox.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomSearchComBox.java new file mode 100644 index 000000000..b48253c52 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomSearchComBox.java @@ -0,0 +1,185 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBList; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import org.apache.commons.lang.StringUtils; + +import javax.swing.BorderFactory; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; + +/** + * CustomSearchComBox + */ +public class CustomSearchComBox extends JBPanel { + private CustomTextField selectedProcessName; + private CustomTextField searchField; + private JBList processList; + private JBScrollPane processScrollPane; + private SelectedTextFileLister selectedTextFileListener; + private CustomListFilerModel myListModel = new CustomListFilerModel(); + + /** + * CustomSearchComBox + */ + public CustomSearchComBox() { + this.setLayout(new BorderLayout()); + selectedProcessName = new CustomTextField("device"); + selectedProcessName.setBackground(JBColor.background()); + selectedProcessName.setOpaque(true); + selectedProcessName.setForeground(JBColor.foreground().brighter()); + selectedProcessName.setEditable(false); + selectedProcessName.setBorder(BorderFactory.createLineBorder(JBColor.background().darker(), 1)); + this.add(selectedProcessName, BorderLayout.NORTH); + searchField = new CustomTextField("press"); + searchField.setBackground(JBColor.background()); + searchField.setOpaque(true); + searchField.setForeground(JBColor.foreground().brighter()); + searchField.setVisible(false); + this.add(searchField, BorderLayout.CENTER); + processList = new JBList(myListModel); + processList.setBackground(JBColor.background()); + processList.setOpaque(true); + processList.setForeground(JBColor.foreground().brighter()); + processList.setVisible(false); + processList.setFont(new Font("PingFang SC", Font.PLAIN, 14)); + processScrollPane = new JBScrollPane(processList); + processScrollPane.setVisible(false); + this.add(processScrollPane, BorderLayout.SOUTH); + selectedProcessName.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + if (mouseEvent.getClickCount() == 1) { + if (searchField.isShowing() && processList.isShowing()) { + hidden(); + return; + } else { + selectedTextFileListener.textFileClick(); + showProcess(); + } + } + } + }); + addProcessListListen(); + addProcessPanelEvent(); + } + + private void hidden() { + myListModel.clear(); + searchField.setVisible(false); + processScrollPane.setVisible(false); + processList.setVisible(false); + this.revalidate(); + this.repaint(); + } + + private void showProcess() { + searchField.setVisible(true); + processList.setVisible(true); + processScrollPane.setVisible(true); + this.revalidate(); + this.repaint(); + } + + private void addProcessListListen() { + processList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + Object selectedValue = processList.getSelectedValue(); + if (selectedValue instanceof String) { + String value = (String) selectedValue; + if (StringUtils.isNotBlank(value)) { + selectedProcessName.setText(value); + hidden(); + } + } + if (processList.getSelectedIndex() == 0) { + processList.setSelectedValue(null, true); + } + } + }); + } + + private void addProcessPanelEvent() { + searchField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent documentEvent) { + String text = searchField.getText(); + myListModel.refilter(text); + } + + @Override + public void removeUpdate(DocumentEvent documentEvent) { + String text = searchField.getText(); + myListModel.refilter(text); + } + + @Override + public void changedUpdate(DocumentEvent exception) { + } + }); + } + + /** + * setSelectedTextFileListener + * + * @param selectedTextFileListener selectedTextFileListener + */ + public void setSelectedTextFileListener(SelectedTextFileLister selectedTextFileListener) { + this.selectedTextFileListener = selectedTextFileListener; + } + + /** + * Refresh process information + * + * @param processNames processNames + */ + public void refreshProcess(List processNames) { + myListModel.clear(); + myListModel.addAll(processNames); + } + + /** + * getSelectedProcessName + * + * @return String + */ + public String getSelectedProcessName() { + return selectedProcessName.getText(); + } + + /** + * clearSelectedName + */ + public void clearSelectedName() { + selectedProcessName.setText(""); + if (!myListModel.isEmpty()) { + myListModel.clear(); + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/JTextFieldTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomTextField.java similarity index 73% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/JTextFieldTable.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomTextField.java index 796898cf3..6b512f8d1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/JTextFieldTable.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/CustomTextField.java @@ -1,94 +1,92 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; - -import javax.swing.BorderFactory; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JTextField; -import javax.swing.border.Border; -import javax.swing.border.CompoundBorder; -import javax.swing.border.EmptyBorder; -import java.awt.Graphics; -import java.awt.Insets; - -/** - * JTextFieldTable - * - * @version 1.0 - * @date: 2021/4/14 15:35 - */ -public class JTextFieldTable extends JTextField { - private Icon icon; - - private String type; - - private Border line = BorderFactory.createLineBorder(ColorConstants.TOP_COLOR); - - private CompoundBorder border; - - private Border empty; - - public JTextFieldTable(String name) { - type = name; - - // 获取当前路径下的图片 - icon = new ImageIcon(JTextFieldTable.class.getClassLoader().getResource("images/search.png")); - if ("level".equals(type)) { - this.setBackground(ColorConstants.TRACE_TABLE_COLOR); - empty = new EmptyBorder(0, LayoutConstants.TASK_LABEL_Y, 0, 0); - } - if ("press".equals(type)) { - empty = new EmptyBorder(0, LayoutConstants.TASK_LABEL_Y, 0, 0); - } - if ("Analysis".equals(type)) { - empty = new EmptyBorder(0, LayoutConstants.DEVICE_ADD_Y, 0, LayoutConstants.TASK_LABEL_Y); - } - if ("device".equals(type)) { - icon = new ImageIcon(DeviceProcessJpanel.class.getClassLoader().getResource("images/down.png")); - empty = new EmptyBorder(0, LayoutConstants.DEVICE_ADD_Y, 0, LayoutConstants.TASK_LABEL_Y); - } - border = new CompoundBorder(line, empty); - this.setBorder(border); - } - - @Override - public void paintComponent(Graphics graphics) { - Insets insets = getInsets(); - super.paintComponent(graphics); - int iconWidth = icon.getIconWidth(); - int iconHeight = icon.getIconHeight(); - int height = this.getHeight(); - // 在文本框中画上之前图片 - if ("level".equals(type) || "press".equals(type)) { - icon.paintIcon(this, graphics, (insets.left - iconWidth) / LayoutConstants.DEVICES_Y, - (height - iconHeight) / LayoutConstants.DEVICES_Y); - } - if ("Analysis".equals(type)) { - icon.paintIcon(this, graphics, - LayoutConstants.LEFT_TOP_WIDTH / LayoutConstants.DEVICES_Y, - (height - iconHeight) / LayoutConstants.DEVICES_Y); - } - if ("device".equals(type)) { - icon.paintIcon(this, graphics, - LayoutConstants.DEVICE_NUMBER / LayoutConstants.DEVICES_Y, - (height - iconHeight) / LayoutConstants.DEVICES_Y); - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; + +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JTextField; +import javax.swing.border.Border; +import javax.swing.border.CompoundBorder; +import javax.swing.border.EmptyBorder; +import java.awt.Graphics; +import java.awt.Insets; + +/** + * CustomTextField + */ +public class CustomTextField extends JTextField { + private Icon icon; + + private String type; + + private Border line = BorderFactory.createLineBorder(JBColor.background().darker()); + + private CompoundBorder border; + + private Border empty; + + /** + * CustomTextField + * + * @param name name + */ + public CustomTextField(String name) { + type = name; + icon = AllIcons.Actions.Find; + if ("level".equals(type)) { + this.setBackground(ColorConstants.TRACE_TABLE_COLOR); + empty = new EmptyBorder(0, LayoutConstants.TASK_LABEL_Y, 0, 0); + } + if ("press".equals(type)) { + empty = new EmptyBorder(0, LayoutConstants.TASK_LABEL_Y, 0, 0); + } + if ("Analysis".equals(type)) { + empty = new EmptyBorder(0, LayoutConstants.DEVICE_ADD_Y, 0, LayoutConstants.TASK_LABEL_Y); + } + if ("device".equals(type)) { + icon = IconLoader.getIcon(("/images/down.png"), getClass()); + empty = new EmptyBorder(0, LayoutConstants.DEVICE_ADD_Y, 0, LayoutConstants.TASK_LABEL_Y); + } + border = new CompoundBorder(line, empty); + this.setBorder(border); + } + + @Override + public void paintComponent(Graphics graphics) { + Insets insets = getInsets(); + super.paintComponent(graphics); + int iconWidth = icon.getIconWidth(); + int iconHeight = icon.getIconHeight(); + int height = this.getHeight(); + if ("level".equals(type) || "press".equals(type)) { + icon.paintIcon(this, graphics, (insets.left - iconWidth) / LayoutConstants.DEVICES_Y, + (height - iconHeight) / LayoutConstants.DEVICES_Y); + } + if ("Analysis".equals(type)) { + icon.paintIcon(this, graphics, LayoutConstants.LEFT_TOP_WIDTH / LayoutConstants.DEVICES_Y, + (height - iconHeight) / LayoutConstants.DEVICES_Y); + } + if ("device".equals(type)) { + icon.paintIcon(this, graphics, getWidth() - 20, (height - iconHeight) / LayoutConstants.DEVICES_Y); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/DottedLine.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/DottedLine.java new file mode 100644 index 000000000..05f54d2f0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/DottedLine.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.common.ColorConstants; + +import java.awt.BasicStroke; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; + +import static java.awt.BasicStroke.CAP_BUTT; +import static java.awt.BasicStroke.JOIN_ROUND; + +/** + * Draw a vertical dotted line + */ +public class DottedLine extends JBPanel { + private static final int DEFAULT_WIDTH = 10; + private static final int DEFAULT_HEIGHT = 20; + private static final int DEFAULT_POINT_X = 5; + + /** + * DottedLine + */ + public DottedLine() { + this.setOpaque(false); + this.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT)); + repaint(); + } + + /** + * paintComponent + * + * @param graphics graphics + */ + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + Graphics2D g2d = castGraphics2D(graphics); + if (g2d == null) { + return; + } + float[] dash = {1.0f, 0f, 1.0f}; + BasicStroke bs = new BasicStroke(1, CAP_BUTT, JOIN_ROUND, 1.0f, dash, 1.0f); + g2d.setColor(ColorConstants.RULER); + g2d.setStroke(bs); + g2d.drawLine(DEFAULT_POINT_X, 0, DEFAULT_POINT_X, this.getHeight()); + } + + private Graphics2D castGraphics2D(Graphics graphics) { + Graphics2D graph = null; + if (graphics instanceof Graphics2D) { + graph = (Graphics2D) graphics; + } + return graph; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/GraphicsLinePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/GraphicsLinePanel.java new file mode 100644 index 000000000..07a5c3e3e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/GraphicsLinePanel.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.customcomp; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Line2D; + +/** + * GraphicsLinePanel + */ +public class GraphicsLinePanel extends JBPanel { + /** + * GraphicsJpanel + * + */ + public GraphicsLinePanel() { + this.setOpaque(false); + this.setLayout(null); + } + + /** + * draw line + * + * @param graphics graphics + */ + public void paint(Graphics graphics) { + super.paint(graphics); + graphics.setColor(JBColor.background().brighter()); + if (graphics instanceof Graphics2D) { + Graphics2D lineGraphics = (Graphics2D) graphics; + Line2D linTop = new Line2D.Float(0, 0, this.getWidth(), 0); + lineGraphics.draw(linTop); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioDao.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/SelectedTextFileLister.java similarity index 74% rename from host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioDao.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/SelectedTextFileLister.java index 11f6089cd..b8ea5fd3d 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/services/diskio/DiskioDao.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/customcomp/SelectedTextFileLister.java @@ -1,23 +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. - */ - -package ohos.devtools.services.diskio; - -/** - * @Description Diskio与数据库交互的类 - * @Date 2021/2/7 13:59 - **/ -public class DiskioDao { -} +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +/** + * SelectedTextFileLister + */ +public interface SelectedTextFileLister { + /** + * textFileClick + */ + void textFileClick(); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosDialog.java deleted file mode 100644 index 8c0c6ee78..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosDialog.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.hoscomp; - -import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; -import ohos.devtools.datasources.utils.session.entity.SessionInfo; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.chartview.observer.ProfilerChartsViewObserver; -import ohos.devtools.views.layout.swing.SampleDialogWrapper; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import java.awt.Dimension; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -/** - * Memory指标项添加复选框 - * - * @version 1.0 - * @date 2021/03/24 09:33 - **/ -public class HosDialog { - /** - * sessionInfo信息 - */ - private SessionInfo sessionInfo; - private JPanel jPanel; - /** - * Items项复选框容器 - */ - private JPanel jCheckPanel = new JPanel(null); - /** - * 复选框存放集合 - */ - private ArrayList jCheckBoxes = new ArrayList<>(); - - private ProfilerChartsView profilerView; - - /** - * Items页面复选框内容 - */ - private JLabel jLabelMemory = new JLabel("Memory"); - private JCheckBox checkBoxSelectAll = new JCheckBox("Select All"); - private JCheckBox checkBoxMemoryJava = new JCheckBox("Java"); - private JCheckBox checkBoxGpuMemoryNative = new JCheckBox("Native"); - private JCheckBox checkBoxGraphics = new JCheckBox("Graphics"); - private JCheckBox checkBoxStack = new JCheckBox("Stack"); - private JCheckBox checkBoxCode = new JCheckBox("Code"); - private JCheckBox checkBoxOthers = new JCheckBox("Others"); - - /** - * HosDialog Constructor - * - * @param sessionId session Id - * @param profilerView profiler View - */ - public HosDialog(long sessionId, ProfilerChartsView profilerView) { - addItem(); - this.profilerView = profilerView; - jCheckBoxes.add(checkBoxSelectAll); - jCheckBoxes.add(checkBoxMemoryJava); - jCheckBoxes.add(checkBoxGpuMemoryNative); - jCheckBoxes.add(checkBoxGraphics); - jCheckBoxes.add(checkBoxStack); - jCheckBoxes.add(checkBoxCode); - jCheckBoxes.add(checkBoxOthers); - // 设置对话框的宽高 - jCheckPanel - .setPreferredSize(new Dimension(LayoutConstants.MEMORY_WIDTH_SIZE, LayoutConstants.MEMORY_HEIGHT_SIZE)); - ConcurrentHashMap>> configData = MonitorConfigManager.dataMap; - Map> configMap = configData.get(sessionId); - - LinkedList configList = null; - if (configMap != null) { - configList = configMap.get("Memory"); - } - // 让初始选中的Iterm默认选中 - for (String str : configList) { - for (int index = 0; index < jCheckBoxes.size(); index++) { - if (jCheckBoxes.get(index).getText().equals(str)) { - jCheckBoxes.get(index).setSelected(true); - continue; - } - } - } - // 弹框 - SampleDialogWrapper sampleDialog = new SampleDialogWrapper("Select Add Items", jCheckPanel); - boolean flag = sampleDialog.showAndGet(); - if (flag) { - // 获取选中的指标项 - List collect = HosDialog.this.jCheckBoxes.stream().filter(jCheckBox -> jCheckBox.isSelected()) - .collect(Collectors.toList()); - if (collect.size() == 0) { - new SampleDialogWrapper("Reminder Msg", "Please Select Items !").show(); - return; - } - // 便利选中项,构建Memory的value - LinkedList memoryFlushed = new LinkedList<>(); - for (JCheckBox jc : collect) { - memoryFlushed.add(jc.getText()); - } - configMap.remove("Memory"); - configMap.put("Memory", memoryFlushed); - MonitorConfigManager.dataMap.put(sessionId, configMap); - ProfilerChartsViewObserver bottomPanel = ProfilerChartsView.sessionMap.get(sessionId).getObserver(); - ChartDataRange range = bottomPanel.getStandard().getDisplayRange(); - bottomPanel.notifyRefresh(range.getStartTime(), range.getEndTime()); - profilerView.setAddItemFlag(false); - } else { - profilerView.setAddItemFlag(false); - } - } - - private void addItem() { - jLabelMemory.setBounds(LayoutConstants.MEMORY_X, LayoutConstants.MEMORY_Y, LayoutConstants.MEMORY_WIDTH, - LayoutConstants.MEMORY_HEIGHT); - checkBoxSelectAll - .setBounds(LayoutConstants.SELECT_ALL_X, LayoutConstants.SELECT_ALL_Y, LayoutConstants.SELECT_ALL_WIDTH, - LayoutConstants.SELECT_ALL_HEIGHT); - checkBoxMemoryJava.setBounds(LayoutConstants.JAVA_X, LayoutConstants.JAVA_Y, LayoutConstants.JAVA_WIDTH, - LayoutConstants.JAVA_HEIGHT); - checkBoxGpuMemoryNative - .setBounds(LayoutConstants.NATIVE_X, LayoutConstants.NATIVE_Y, LayoutConstants.NATIVE_WIDTH, - LayoutConstants.NATIVE_HEIGHT); - checkBoxGraphics - .setBounds(LayoutConstants.GRAPHICS_X, LayoutConstants.GRAPHICS_Y, LayoutConstants.GRAPHICS_WIDTH, - LayoutConstants.GRAPHICS_HEIGHT); - checkBoxStack.setBounds(LayoutConstants.STACK_X, LayoutConstants.STACK_Y, LayoutConstants.STACK_WIDTH, - LayoutConstants.STACK_HEIGHT); - checkBoxCode.setBounds(LayoutConstants.CODE_X, LayoutConstants.CODE_Y, LayoutConstants.CODE_WIDTH, - LayoutConstants.CODE_HEIGHT); - checkBoxOthers.setBounds(LayoutConstants.OTHERS_X, LayoutConstants.OTHERS_Y, LayoutConstants.OTHERS_WIDTH, - LayoutConstants.OTHERS_HEIGHT); - jCheckPanel.add(jLabelMemory); - jCheckPanel.add(checkBoxSelectAll); - jCheckPanel.add(checkBoxMemoryJava); - jCheckPanel.add(checkBoxGpuMemoryNative); - jCheckPanel.add(checkBoxGraphics); - jCheckPanel.add(checkBoxStack); - jCheckPanel.add(checkBoxCode); - jCheckPanel.add(checkBoxOthers); - checkBoxSelectAll.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent exception) { - if (HosDialog.this.checkBoxSelectAll.isSelected()) { - HosDialog.this.checkBoxMemoryJava.setSelected(true); - HosDialog.this.checkBoxGpuMemoryNative.setSelected(true); - HosDialog.this.checkBoxGraphics.setSelected(true); - HosDialog.this.checkBoxStack.setSelected(true); - HosDialog.this.checkBoxCode.setSelected(true); - HosDialog.this.checkBoxOthers.setSelected(true); - } else { - HosDialog.this.checkBoxMemoryJava.setSelected(false); - HosDialog.this.checkBoxGpuMemoryNative.setSelected(false); - HosDialog.this.checkBoxGraphics.setSelected(false); - HosDialog.this.checkBoxStack.setSelected(false); - HosDialog.this.checkBoxCode.setSelected(false); - HosDialog.this.checkBoxOthers.setSelected(false); - } - } - }); - } - - public SessionInfo getSessionInfo() { - return sessionInfo; - } - - public void setSessionInfo(SessionInfo sessionInfo) { - this.sessionInfo = sessionInfo; - } - - public JPanel getjPanel() { - return jPanel; - } - - public void setjPanel(JPanel jPanel) { - this.jPanel = jPanel; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJLabel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJLabel.java deleted file mode 100644 index a775db47b..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJLabel.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.hoscomp; - -import ohos.devtools.datasources.utils.session.entity.SessionInfo; - -import javax.swing.JLabel; - -/** - * @Description HosJLabel - * @Date 2021/3/11 13:12 - **/ -public class HosJLabel extends JLabel { - private SessionInfo sessionInfo; - - private long sessionId; - - private String deviceName; - - private String processName; - - private String message; - - private Long firstStamp; - - private boolean deviceType = false; - private long startTime; - private long endTime; - - public boolean getDeviceType() { - return deviceType; - } - - public void setDeviceType(boolean deviceType) { - this.deviceType = deviceType; - } - - public long getStartTime() { - return startTime; - } - - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - public long getEndTime() { - return endTime; - } - - public void setEndTime(long endTime) { - this.endTime = endTime; - } - - public HosJLabel(String text) { - super(text); - } - - public HosJLabel() { - super("", null, LEADING); - } - - public SessionInfo getSessionInfo() { - return sessionInfo; - } - - public void setSessionInfo(SessionInfo sessionInfo) { - this.sessionInfo = sessionInfo; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public long getSessionId() { - return sessionId; - } - - public void setSessionId(long sessionId) { - this.sessionId = sessionId; - } - - public String getDeviceName() { - return deviceName; - } - - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - public String getProcessName() { - return processName; - } - - public void setProcessName(String processName) { - this.processName = processName; - } - - public Long getFirstStamp() { - return firstStamp; - } - - public void setFirstStamp(Long firstStamp) { - this.firstStamp = firstStamp; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJTabbedPane.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJTabbedPane.java deleted file mode 100644 index 63fed7e9f..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/hoscomp/HosJTabbedPane.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.hoscomp; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @Description 自定义选项卡 - * @Date 2021/3/29 10:36 - **/ -public class HosJTabbedPane extends JPanel { - // tab选项卡容器 - private JPanel tabJPanel = new JPanel(null); - - // 当前选中的tab。 - private JPanel tab; - - // 所有tab的集合 - private List tabLists; - - // content选项卡对应内容的容器 - private JPanel tabContentJPanel; - - // 所有内容面板的集合 - private Map tabContentLists = new HashMap<>(); - private int count = 0; - - /** - * HosJTabbedPane - * - * @param tab tab - * @param tabContentJPanel tabContentJPanel - */ - public HosJTabbedPane(JPanel tab, JPanel tabContentJPanel) { - this.tab = tab; - this.tab.setPreferredSize(new Dimension(100, 20)); - this.tabJPanel.setBackground(Color.lightGray); - this.tabJPanel.add(tab); - this.tabJPanel.setBackground(new Color(41, 41, 48)); - this.tab.setBackground(new Color(13, 14, 19)); - this.tabContentJPanel = tabContentJPanel; - this.tabContentJPanel.setBackground(new Color(13, 14, 19)); - this.tabContentLists.put(count, tabContentJPanel); - this.setLayout(new BorderLayout()); - this.add(this.tabJPanel, BorderLayout.NORTH); - this.add(this.tabContentJPanel, BorderLayout.CENTER); - this.tab.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - super.mouseClicked(event); - } - }); - } - - /** - * hosAdd - * - * @param tab tab - * @param tabContentJPanel tabContentJPanel - */ - public void hosAdd(JPanel tab, JPanel tabContentJPanel) { - this.count++; - this.tab = tab; - this.tab.setBackground(new Color(13, 14, 19)); - this.tab.setPreferredSize(new Dimension(100, 20)); - this.tabJPanel.add(tab); - this.tabContentJPanel = tabContentJPanel; - this.tabContentJPanel.setBackground(new Color(13, 14, 19)); - this.tabContentLists.put(this.count, this.tabContentJPanel); - } - - public JPanel getTabJPanel() { - return tabJPanel; - } - - public void setTabJPanel(JPanel tabJPanel) { - this.tabJPanel = tabJPanel; - } - - public JPanel getTab() { - return tab; - } - - public void setTab(JPanel tab) { - this.tab = tab; - } - - public List getTabLists() { - return tabLists; - } - - public void setTabLists(List tabLists) { - this.tabLists = tabLists; - } - - public JPanel getTabContentJPanel() { - return tabContentJPanel; - } - - public void setTabContentJPanel(JPanel tabContentJPanel) { - this.tabContentJPanel = tabContentJPanel; - } - - public Map getTabContentLists() { - return tabContentLists; - } - - public void setTabContentLists(Map tabContentLists) { - this.tabContentLists = tabContentLists; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } -} - -class HosTab { - private Integer id; - private JPanel tab; - - public HosTab(Integer id, JPanel tab) { - this.id = id; - this.tab = tab; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public JPanel getTab() { - return tab; - } - - public void setTab(JPanel tab) { - this.tab = tab; - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/DataFilter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/DataFilter.java new file mode 100644 index 000000000..02103c860 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/DataFilter.java @@ -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. + */ + +package ohos.devtools.views.common.treetable; + +import javax.swing.tree.TreeNode; + +/** + * DataFilter + */ +public class DataFilter { + boolean aBoolean = true; + String strFilter; + + /** + * passTreeNode + * + * @param treeNode treeNode + * @param textValue textValue + * @return boolean + */ + public boolean passTreeNode(TreeNode treeNode, String textValue) { + if (aBoolean) { + return true; + } + if (treeNode.isLeaf() == false) { + return true; + } + String treeString = treeNode.toString(); + return treeString.contains(textValue); + } + + /** + * setFilter + * + * @param aBoolean aBoolean + * @param str str + */ + public void setFilter(boolean aBoolean, String str) { + this.aBoolean = aBoolean; + strFilter = str; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ExpandTreeTable.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ExpandTreeTable.java new file mode 100644 index 000000000..290df1f9c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ExpandTreeTable.java @@ -0,0 +1,162 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.treetable; + +import com.intellij.ui.JBColor; +import com.intellij.ui.OnePixelSplitter; +import com.intellij.ui.components.JBTreeTable; +import com.intellij.ui.treeStructure.treetable.TreeTableModel; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeExpansionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.util.Vector; + + +/** + * ExpandTreeTable + */ +public class ExpandTreeTable extends JBTreeTable { + private static final Logger LOGGER = LogManager.getLogger(ExpandTreeTable.class); + private final Vector expandList = new Vector<>(); + private final Vector expandRowList = new Vector<>(); + private long firstTime; + private JScrollBar verticalScrollBar; + private int count = 100; + private int nextIndex = 0; + + /** + * ExpandTreeTable + * + * @param model model + */ + public ExpandTreeTable(@NotNull TreeTableModel model) { + super(model); + this.getTree().setBackground(JBColor.background()); + Component[] components = super.getComponents(); + for (Component component : components) { + if (component instanceof OnePixelSplitter) { + OnePixelSplitter splitter = (OnePixelSplitter) component; + JScrollPane firstComponent = null; + Object componentObject = splitter.getFirstComponent(); + if (componentObject instanceof JScrollPane) { + firstComponent = (JScrollPane) componentObject; + verticalScrollBar = firstComponent.getVerticalScrollBar(); + } + } + } + getTree().addTreeExpansionListener(new TreeExpansionListener() { + @Override + public void treeExpanded(TreeExpansionEvent event) { + if (event.getPath() != null && !expandList.contains(event.getPath())) { + expandList.add(event.getPath()); + } + if (event.getPath() != null && !expandRowList.contains(getTree().getRowForPath(event.getPath()))) { + expandRowList.add(getTree().getRowForPath(event.getPath())); + } + } + + @Override + public void treeCollapsed(TreeExpansionEvent event) { + if (event.getPath() != null && expandList.contains(event.getPath())) { + expandList.remove(event.getPath()); + } + if (event.getPath() != null && expandRowList.contains(getTree().getRowForPath(event.getPath()))) { + Object rowForPathObject = getTree().getRowForPath(event.getPath()); + if (rowForPathObject instanceof Integer) { + expandRowList.remove((Integer) rowForPathObject); + } + } + loadNodeCollapse(event); + } + }); + } + + public JScrollBar getVerticalScrollBar() { + return verticalScrollBar; + } + + /** + * freshTreeExpand + */ + public void freshTreeExpand() { + // Two executions are not allowed within 200 ms + firstTime = System.currentTimeMillis(); + expandList.forEach(item -> { + if (!getTree().isExpanded(item)) { + getTree().expandPath(item); + } + }); + } + + /** + * freshTreeRowExpand + */ + public void freshTreeRowExpand() { + expandRowList.forEach(item -> { + getTree().expandRow(item); + }); + } + + /** + * setTreeTableModel + * + * @param treeTableModel treeTableModel + */ + public void setTreeTableModel(TreeTableModel treeTableModel) { + super.setModel(treeTableModel); + expandList.clear(); + getTree().addTreeExpansionListener(new TreeExpansionListener() { + @Override + public void treeExpanded(TreeExpansionEvent event) { + if (event.getPath() != null && !expandList.contains(event.getPath())) { + expandList.add(event.getPath()); + } + } + + @Override + public void treeCollapsed(TreeExpansionEvent event) { + if (event.getPath() != null) { + expandList.remove(event.getPath()); + } + } + }); + } + + /** + * loadNodeCollapse + * + * @param event event + */ + private void loadNodeCollapse(TreeExpansionEvent event) { + DefaultMutableTreeNode currentNode = null; + Object lastPathComponentObject = event.getPath().getLastPathComponent(); + if (lastPathComponentObject instanceof DefaultMutableTreeNode) { + currentNode = (DefaultMutableTreeNode) lastPathComponentObject; + Object userObj = currentNode.getUserObject(); + currentNode.removeAllChildren(); + // add None to proved node can expand + currentNode.add(new DefaultMutableTreeNode()); + count = 0; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/FieldsTreeTableColumn.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/FieldsTreeTableColumn.java new file mode 100644 index 000000000..454b90f6f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/FieldsTreeTableColumn.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.treetable; + +import com.intellij.util.ui.ColumnInfo; + +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.Comparator; + +/** + * FieldsTreeTableColumn + */ +public abstract class FieldsTreeTableColumn extends ColumnInfo { + private final Class type; + + /** + * TreeTableColumn + * + * @param name name + * @param typeParameterClass typeParameterClass + */ + public FieldsTreeTableColumn(String name, Class typeParameterClass) { + super(name); + type = typeParameterClass; + } + + @Override + public String valueOf(DefaultMutableTreeNode defaultMutableTreeNode) { + if (type.isInstance(defaultMutableTreeNode.getUserObject())) { + T nodeData = type.cast(defaultMutableTreeNode.getUserObject()); + return this.getColumnValue(nodeData); + } + return ""; + } + + @Override + public Comparator getComparator() { + return (o1, o2) -> { + if (type.isInstance(o1.getUserObject()) && type.isInstance(o2.getUserObject())) { + T start = type.cast(o1.getUserObject()); + T end = type.cast(o2.getUserObject()); + try { + String columnValue = this.getColumnValue(start); + if ("-".equals(columnValue)) { + columnValue = "" + Integer.MAX_VALUE; + } + String columnValue1 = this.getColumnValue(end); + if ("-".equals(columnValue)) { + columnValue1 = "" + Integer.MAX_VALUE; + } + if ("--".equals(columnValue) || "--".equals(columnValue)) { + return 0; + } + long startL = Long.parseLong(columnValue); + long endL = Long.parseLong(columnValue1); + return Long.compare(startL, endL); + } catch (NumberFormatException e) { + return this.getColumnValue(start).compareTo(this.getColumnValue(end)); + } + } + return 0; + }; + } + + /** + * get Column Value + * + * @param nodeData nodeData + * @return String + */ + public abstract String getColumnValue(T nodeData); +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/HeapDumpTreeTableColumn.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/HeapDumpTreeTableColumn.java new file mode 100644 index 000000000..7289fb397 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/HeapDumpTreeTableColumn.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.treetable; + +import com.intellij.util.ui.ColumnInfo; +import org.jetbrains.annotations.Nullable; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeNode; +import java.util.Comparator; +import java.util.Enumeration; + +/** + * HeapDumpTreeTableColumn + */ +public abstract class HeapDumpTreeTableColumn extends ColumnInfo { + private final Class type; + + /** + * HeapDumpTreeTableColum + * + * @param name name + * @param typeParameterClass typeParameterClass + */ + public HeapDumpTreeTableColumn(String name, Class typeParameterClass) { + super(name); + type = typeParameterClass; + } + + @Override + public @Nullable + String valueOf(DefaultMutableTreeNode defaultMutableTreeNode) { + if (type.isInstance(defaultMutableTreeNode.getUserObject())) { + if (defaultMutableTreeNode.isLeaf()) { + T nodeData = type.cast(defaultMutableTreeNode.getUserObject()); + return this.getColumnValue(nodeData); + } else { + long parentNodeData = 0L; + Enumeration children = defaultMutableTreeNode.children(); + while (children.hasMoreElements()) { + DefaultMutableTreeNode treeNode = null; + Object nextElementObject = children.nextElement(); + if (nextElementObject instanceof DefaultMutableTreeNode) { + treeNode = (DefaultMutableTreeNode) nextElementObject; + T nodeData = type.cast(treeNode.getUserObject()); + parentNodeData = Long.parseLong(this.getColumnValue(nodeData)) + parentNodeData; + } + } + return String.valueOf(parentNodeData); + } + } + return ""; + } + + @Override + public Comparator getComparator() { + return (o1, o2) -> { + if (type.isInstance(o1.getUserObject()) && type.isInstance(o2.getUserObject())) { + T start = type.cast(o1.getUserObject()); + T end = type.cast(o2.getUserObject()); + try { + long startL = Long.parseLong(this.valueOf(o1)); + long endL = Long.parseLong(this.valueOf(o2)); + return Long.compare(startL, endL); + } catch (NumberFormatException numberFormatException) { + return this.getColumnValue(start).compareTo(this.getColumnValue(end)); + } + } + return 0; + }; + } + + /** + * get Column Value + * + * @param nodeData nodeData + * @return String + */ + public abstract String getColumnValue(T nodeData); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LayoutView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ITreeTableSortChangeListener.java similarity index 65% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LayoutView.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ITreeTableSortChangeListener.java index db2ee9014..a21f3fc7e 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LayoutView.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/ITreeTableSortChangeListener.java @@ -1,37 +1,32 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.swing; - -/** - * 界面构造类 - * - * @version 1.0 - * @date 2021/02/27 15:31 - **/ -public class LayoutView { - private LayoutView() { - } - - /** - * 页面启动方法 - * - * @return HomeWindow - */ - public static HomeWindow init() { - HomeWindow homeWindow = new HomeWindow(); - return homeWindow; - } -} +/* + * 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. + */ + +package ohos.devtools.views.common.treetable; + +import javax.swing.SortOrder; + +/** + * ITreeTableSortChangeListener + */ +public interface ITreeTableSortChangeListener { + + /** + * reSort + * + * @param columns columns + * @param sortOrder sortOrder + */ + void reSort(int columns, SortOrder sortOrder); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/TreeTableColumn.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/TreeTableColumn.java new file mode 100644 index 000000000..add6aa8e4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/common/treetable/TreeTableColumn.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.treetable; + +import com.intellij.util.ui.ColumnInfo; + +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.Comparator; + +/** + * TreeTableColumn + */ +public abstract class TreeTableColumn extends ColumnInfo { + private final Class type; + + /** + * TreeTableColumn + * + * @param name name + * @param typeParameterClass typeParameterClass + */ + public TreeTableColumn(String name, Class typeParameterClass) { + super(name); + type = typeParameterClass; + } + + @Override + public String valueOf(DefaultMutableTreeNode defaultMutableTreeNode) { + if (type.isInstance(defaultMutableTreeNode.getUserObject())) { + T nodeData = type.cast(defaultMutableTreeNode.getUserObject()); + return this.getColumnValue(nodeData); + } + return ""; + } + + @Override + public Comparator getComparator() { + return (o1, o2) -> { + if (type.isInstance(o1.getUserObject()) && type.isInstance(o2.getUserObject())) { + T start = type.cast(o1.getUserObject()); + T end = type.cast(o2.getUserObject()); + try { + long startL = Long.parseLong(this.getColumnValue(start)); + long endL = Long.parseLong(this.getColumnValue(end)); + return Long.compare(startL, endL); + } catch (NumberFormatException e) { + return this.getColumnValue(start).compareTo(this.getColumnValue(end)); + } + } + return 0; + }; + } + + /** + * get Column Value + * + * @param nodeData nodeData + * @return String + */ + public abstract String getColumnValue(T nodeData); +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/ApplicationConfigPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/ApplicationConfigPanel.java new file mode 100644 index 000000000..31d0382dc --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/ApplicationConfigPanel.java @@ -0,0 +1,427 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.alibaba.fastjson.JSONObject; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBCheckBox; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomJLabel; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import ohos.devtools.views.layout.dialog.SampleDialog; + +import javax.swing.JButton; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import static ohos.devtools.views.common.Constant.DEVICE_REFRESH; + +/** + * TaskScenePanel + */ +public class ApplicationConfigPanel extends JBPanel implements MouseListener, ItemListener { + private static final String SCENE_TITLE_STR = "Devices & Applications"; + private static final String SCENE_DES_STR = "Task scene: Application tuning"; + private static final String ADD_DEVICE_STR = "Add Device"; + private static final String MONITOR_ITEMS_STR = "Monitor Items"; + private static final String MEMORY_STR = "Memory"; + private static final String CHECKBOX_ALL_STR = "Select All"; + private static final String CHECKBOX_JAVA_STR = "Java"; + private static final String CHECKBOX_NATIVE_STR = "Native"; + private static final String CHECKBOX_GRAPHICS_STR = "Graphics"; + private static final String CHECKBOX_STACK_STR = "Stack"; + private static final String CHECKBOX_CODE_STR = "Code"; + private static final String CHECKBOX_OTHER_STR = "Others"; + private static final String LAST_STEP_BTN_STR = "Last Step"; + private static final String START_TASK_BTN_STR = "Start Task"; + + private TaskPanel taskPanel; + private JBPanel northPanel; + private JBLabel sceneTitlePanel; + private JBLabel sceneDesPanel; + private JBPanel centerPanel; + private JBPanel deviceConnectPanel; + private DeviceProcessPanel deviceProcessPanel; + private JButton addDeviceBtn; + private JBPanel dataSourceConfigPanel; + private JBCheckBox[] memoryCheckBoxItems; + private JBCheckBox allCheckBox; + private JBCheckBox memoryJavaCheckBox; + private JBCheckBox memoryNativeCheckBox; + private JBCheckBox memoryGraphicsCheckBox; + private JBCheckBox memoryStackCheckBox; + private JBCheckBox memoryCodeCheckBox; + private JBCheckBox memoryOthersCheckBox; + private JBPanel scrollContainer; + private JBScrollPane deviceConfigScrollPane; + private JBPanel southPanel; + private JButton lastStepBtn; + private JButton startTaskBtn; + + private int deviceNum = 1; + private int scrollContainerHeight = 0; + + /** + * Task Scene Panel + */ + public ApplicationConfigPanel() { + } + + /** + * TaskScenePanel + * + * @param taskPanel taskPanel + */ + public ApplicationConfigPanel(TaskPanel taskPanel) { + this.taskPanel = taskPanel; + initComponents(); + addEventListener(); + } + + /** + * initComponents + */ + private void initComponents() { + this.setLayout(new MigLayout("insets 0", "15[grow,fill]", + "15[fill,fill]")); + // init northPanel + initNorthPanelItems(); + // init centerPanel + initCenterPanelItems(); + // init southPanel + initSouthPanelItems(); + // add the panel + addPanels(); + } + + /** + * initCenterPanelItems + */ + private void initNorthPanelItems() { + northPanel = new JBPanel(new MigLayout("insets 0")); + sceneTitlePanel = new JBLabel(SCENE_TITLE_STR); + sceneTitlePanel.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); + sceneTitlePanel.setForeground(JBColor.foreground().brighter()); + sceneDesPanel = new JBLabel(SCENE_DES_STR); + sceneDesPanel.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + } + + /** + * initCenterPanelItems + */ + private void initCenterPanelItems() { + centerPanel = new JBPanel(new MigLayout("insets 0", "[grow,fill]20", + "[fill,fill]")); + scrollContainer = new JBPanel(new MigLayout("insets 0", "[grow,fill]", + "[fill,fill]")); + scrollContainer.setOpaque(false); + scrollContainer.setBackground(JBColor.background()); + deviceConfigScrollPane = new JBScrollPane(scrollContainer, JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + deviceConfigScrollPane.setBorder(null); + // set the scroll rat + deviceConfigScrollPane.getVerticalScrollBar().setUnitIncrement(LayoutConstants.SCROLL_UNIT_INCREMENT); + deviceConnectPanel = new JBPanel(new MigLayout("insets 0", "[grow,fill]", + "[fill,fill]")); + deviceConnectPanel.setOpaque(false); + deviceConnectPanel.add(deviceConfigScrollPane, "wrap, span"); + deviceConnectPanel.setBackground(JBColor.background()); + addDeviceBtn = new JButton(ADD_DEVICE_STR); + addDeviceBtn.setName(ADD_DEVICE_STR); + addDeviceBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT)); + addDeviceBtn.setOpaque(false); + addDeviceBtn.setPreferredSize(new Dimension(140, 40)); + deviceProcessPanel = new DeviceProcessPanel(scrollContainer, deviceNum, scrollContainerHeight); + scrollContainer.add(deviceProcessPanel, "wrap, span"); + initDataSourceConfig(); + } + + /** + * initDataSourceConfig + */ + private void initDataSourceConfig() { + dataSourceConfigPanel = new JBPanel(new MigLayout("insets 0", "20[]80[]", + "20[]14[]14[]14[]14[]")); + dataSourceConfigPanel.setOpaque(false); + dataSourceConfigPanel.setPreferredSize(new Dimension(400, 450)); + dataSourceConfigPanel.setBackground(JBColor.background()); + allCheckBox = new JBCheckBox(CHECKBOX_ALL_STR); + memoryJavaCheckBox = new JBCheckBox(CHECKBOX_JAVA_STR); + memoryNativeCheckBox = new JBCheckBox(CHECKBOX_NATIVE_STR); + memoryGraphicsCheckBox = new JBCheckBox(CHECKBOX_GRAPHICS_STR); + memoryStackCheckBox = new JBCheckBox(CHECKBOX_STACK_STR); + memoryCodeCheckBox = new JBCheckBox(CHECKBOX_CODE_STR); + memoryOthersCheckBox = new JBCheckBox(CHECKBOX_OTHER_STR); + JBLabel monitorTitleLabel = new JBLabel(MONITOR_ITEMS_STR); + monitorTitleLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 16)); + monitorTitleLabel.setForeground(JBColor.foreground().brighter()); + memoryCheckBoxItems = new JBCheckBox[LayoutConstants.INDEX_SEVEN]; + memoryCheckBoxItems[LayoutConstants.INDEX_ZERO] = allCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_ONE] = memoryJavaCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_TWO] = memoryNativeCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_THREE] = memoryGraphicsCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_FOUR] = memoryStackCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_FIVE] = memoryCodeCheckBox; + memoryCheckBoxItems[LayoutConstants.INDEX_SIX] = memoryOthersCheckBox; + // select all + allCheckBox.setSelected(true); + memoryJavaCheckBox.setSelected(true); + memoryNativeCheckBox.setSelected(true); + memoryGraphicsCheckBox.setSelected(true); + memoryStackCheckBox.setSelected(true); + memoryCodeCheckBox.setSelected(true); + memoryOthersCheckBox.setSelected(true); + allCheckBox.setOpaque(false); + memoryJavaCheckBox.setOpaque(false); + memoryNativeCheckBox.setOpaque(false); + memoryGraphicsCheckBox.setOpaque(false); + memoryStackCheckBox.setOpaque(false); + memoryCodeCheckBox.setOpaque(false); + memoryOthersCheckBox.setOpaque(false); + dataSourceConfigPanel.add(monitorTitleLabel, "wrap"); + JBLabel memoryTitleLabel = new JBLabel(MEMORY_STR); + dataSourceConfigPanel.add(memoryTitleLabel, "wrap"); + dataSourceConfigPanel.add(allCheckBox); + dataSourceConfigPanel.add(memoryJavaCheckBox, "wrap"); + dataSourceConfigPanel.add(memoryNativeCheckBox); + dataSourceConfigPanel.add(memoryGraphicsCheckBox, "wrap"); + dataSourceConfigPanel.add(memoryStackCheckBox); + dataSourceConfigPanel.add(memoryCodeCheckBox, "wrap"); + dataSourceConfigPanel.add(memoryOthersCheckBox); + } + + /** + * southPanelItems + */ + private void initSouthPanelItems() { + southPanel = new JBPanel(new MigLayout("insets 0", "push[]20[]20", + "[fill,fill]")); + southPanel.setPreferredSize(new Dimension(1200, 40)); + lastStepBtn = new JButton(LAST_STEP_BTN_STR); + lastStepBtn.setName(LAST_STEP_BTN_STR); + lastStepBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT)); + lastStepBtn.setFocusPainted(false); + lastStepBtn.setOpaque(false); + lastStepBtn.setPreferredSize(new Dimension(140, 40)); + startTaskBtn = new JButton(START_TASK_BTN_STR); + startTaskBtn.setName(UtConstant.UT_TASK_SCENE_PANE_START); + startTaskBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT)); + startTaskBtn.setOpaque(false); + startTaskBtn.setFocusPainted(false); + startTaskBtn.setPreferredSize(new Dimension(140, 40)); + } + + /** + * add panels + */ + private void addPanels() { + northPanel.setOpaque(false); + northPanel.add(sceneTitlePanel); + northPanel.add(sceneDesPanel, "gap 5"); + centerPanel.setOpaque(false); + centerPanel.add(deviceConnectPanel, "width max(100, 100%)"); + southPanel.setOpaque(false); + southPanel.add(lastStepBtn); + southPanel.add(startTaskBtn); + this.add(northPanel, "wrap"); + this.add(centerPanel, "wrap"); + this.add(southPanel, "wrap"); + this.setBackground(JBColor.background().darker()); + this.setOpaque(true); + } + + /** + * addEventListener + */ + private void addEventListener() { + allCheckBox.addItemListener(this); + lastStepBtn.addMouseListener(this); + startTaskBtn.addMouseListener(this); + addDeviceBtn.addMouseListener(this); + } + + /** + * obtainMap + * + * @param jTaskPanel jTaskPanel + * @return List + */ + public List obtainMap(TaskPanel jTaskPanel) { + SessionManager sessionManager = SessionManager.getInstance(); + Collection> selectMaps = Constant.map.values(); + if (selectMaps.isEmpty()) { + return new ArrayList<>(); + } + ArrayList hosJLabels = new ArrayList<>(); + for (Map seMap : selectMaps) { + for (Map.Entry entry : seMap.entrySet()) { + DeviceIPPortInfo mapKey = null; + DeviceIPPortInfo keyObj = entry.getKey(); + if (keyObj != null) { + mapKey = keyObj; + } + ProcessInfo mapValue = null; + ProcessInfo valueObj = entry.getValue(); + if (valueObj != null) { + mapValue = valueObj; + } + if (mapKey != null && mapValue != null) { + Long localSessionID = sessionManager.createSession(mapKey, mapValue); + if (localSessionID.equals(ohos.devtools.datasources.utils.common.Constant.ABNORMAL)) { + return new ArrayList<>(); + } + jTaskPanel.setLocalSessionId(localSessionID); + CustomJLabel hosJLabel = new CustomJLabel(); + hosJLabel.setSessionId(localSessionID); + hosJLabel.setDeviceName(mapKey.getDeviceName()); + hosJLabel.setProcessName(mapValue.getProcessName() + "(" + mapValue.getProcessId() + ")"); + hosJLabel.setConnectType(mapKey.getConnectType()); + // start session + sessionManager.startSession(localSessionID, false); + // get the data + sessionManager.fetchData(localSessionID); + hosJLabels.add(hosJLabel); + } + } + } + return hosJLabels; + } + + /** + * Get the value of the drop-down box + * + * @return JSONObject + */ + private JSONObject getCheckBoxJson() { + JSONObject memoryObject = new JSONObject(); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_ONE].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_ONE].isSelected()); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_TWO].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_TWO].isSelected()); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_THREE].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_THREE].isSelected()); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_FOUR].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_FOUR].isSelected()); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_FIVE].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_FIVE].isSelected()); + memoryObject.put(memoryCheckBoxItems[LayoutConstants.INDEX_SIX].getText(), + memoryCheckBoxItems[LayoutConstants.INDEX_SIX].isSelected()); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Memory", memoryObject); + return jsonObject; + } + + @Override + public void mouseClicked(MouseEvent event) { + } + + @Override + public void mousePressed(MouseEvent event) { + } + + @Override + public void mouseReleased(MouseEvent event) { + String name = event.getComponent().getName(); + if (name.equals(LAST_STEP_BTN_STR)) { + taskPanel.getTabContainer().remove(this); + taskPanel.getTabItem().setVisible(true); + taskPanel.getTabContainer().repaint(); + } + if (name.equals(START_TASK_BTN_STR)) { + startTaskBtn.dispatchEvent(new FocusEvent(startTaskBtn, FocusEvent.FOCUS_GAINED, true)); + startTaskBtn.requestFocusInWindow(); + int itemCount = deviceProcessPanel.getDeviceNameComboBox().getItemCount(); + if (itemCount == 0) { + new SampleDialog("prompt", "Device list is empty !").show(); + return; + } + if ("Please select the device process !" + .equals(deviceProcessPanel.getSelectedProcessName().getText())) { + new SampleDialog("prompt", "Please select the device process !").show(); + return; + } + boolean isSelected = memoryJavaCheckBox.isSelected() || memoryNativeCheckBox.isSelected() || + memoryGraphicsCheckBox.isSelected() || memoryStackCheckBox.isSelected() || + memoryCodeCheckBox.isSelected() || memoryOthersCheckBox.isSelected(); + if (!isSelected) { + new SampleDialog("prompt", "please choose Monitor Items !").show(); + return; + } + // get the process map + List hosJLabels = obtainMap(taskPanel); + if (!hosJLabels.isEmpty()) { + taskPanel.getTabContainer().removeAll(); + QuartzManager.getInstance().endExecutor(DEVICE_REFRESH); + taskPanel.getTabContainer().add(new TaskScenePanelChart(taskPanel, hosJLabels)); + taskPanel.getTabContainer().setOpaque(true); + taskPanel.getTabContainer().setBackground(JBColor.background()); + taskPanel.getTabContainer().repaint(); + } + } + if (name.equals(ADD_DEVICE_STR)) { + deviceNum++; + scrollContainerHeight += 450; + DeviceProcessPanel addDeviceProcessPanel = + new DeviceProcessPanel(scrollContainer, deviceNum, scrollContainerHeight); + scrollContainer.add(addDeviceProcessPanel.getGraphicsLine(), "wrap, gapy 15, gapx 12 12, height 30!, span"); + scrollContainer.add(addDeviceProcessPanel, "wrap, span"); + scrollContainer + .setPreferredSize(new Dimension(LayoutConstants.DEVICE_PRO_WIDTH, 450 + scrollContainerHeight)); + } + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseExited(MouseEvent event) { + } + + @Override + public void itemStateChanged(ItemEvent event) { + if (allCheckBox.isSelected()) { + memoryJavaCheckBox.setSelected(true); + memoryNativeCheckBox.setSelected(true); + memoryGraphicsCheckBox.setSelected(true); + memoryStackCheckBox.setSelected(true); + memoryCodeCheckBox.setSelected(true); + memoryOthersCheckBox.setSelected(true); + } else { + memoryJavaCheckBox.setSelected(false); + memoryNativeCheckBox.setSelected(false); + memoryGraphicsCheckBox.setSelected(false); + memoryStackCheckBox.setSelected(false); + memoryCodeCheckBox.setSelected(false); + memoryOthersCheckBox.setSelected(false); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/DeviceProcessPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/DeviceProcessPanel.java new file mode 100644 index 000000000..1cf918b83 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/DeviceProcessPanel.java @@ -0,0 +1,311 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.openapi.ui.ComboBox; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.process.service.ProcessManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.GraphicsLinePanel; +import ohos.devtools.views.layout.event.DeviceProcessPanelEvent; +import ohos.devtools.views.common.customcomp.CustomTextField; + +import javax.swing.*; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; + +/** + * DeviceProcessPanel + */ +public class DeviceProcessPanel extends JBPanel { + private JBLabel currentDeviceNum; + private JBLabel deviceLabel; + private ComboBox connectTypeComboBox; + private ComboBox deviceNameComboBox; + private JBLabel applicationDesLabel; + private CustomTextField selectedProcessName; + private CustomTextField searchField; + private JBPanel processPanel; + private JBTable processTable; + private JBScrollPane processScrollPane; + private GraphicsLinePanel graphicsLine; + private DeviceProcessPanelEvent deviceProcessPanelEvent; + private List deviceInfoList; + private List processInfoList; + private int deviceNum = 1; + private int scrollContainerHeight = 0; + + /** + * DeviceProcessPanel + * + * @param deviceConnectScrollPane deviceConnectScrollPane + */ + public DeviceProcessPanel(JBPanel deviceConnectScrollPane, int deviceNum, int scrollContainerHeight) { + this.deviceNum = deviceNum; + this.scrollContainerHeight = scrollContainerHeight; + initComponents(); + initDeviceList(); + initProcessList(deviceInfoList.get(0)); + addEvent(deviceConnectScrollPane); + } + + /** + * initComponents + */ + private void initComponents() { + this.setLayout(new MigLayout("insets 0", "[grow,fill]", "[fill,fill]")); + this.setOpaque(false); + this.setBounds(10, scrollContainerHeight, 800, 500); + this.setBackground(JBColor.background()); + currentDeviceNum = new JBLabel("Devices " + String.format(Locale.ENGLISH, "%02d", deviceNum)); + currentDeviceNum.setOpaque(false); + currentDeviceNum.setFont(new Font(Font.DIALOG, Font.PLAIN, 16)); + currentDeviceNum.setForeground(JBColor.foreground().brighter()); + // connect type and device name + deviceLabel = new JBLabel("Device"); + deviceLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + connectTypeComboBox = new ComboBox(); + connectTypeComboBox.addItem(LayoutConstants.USB); + connectTypeComboBox.setName(UtConstant.UT_DEVICE_PROCESS_PANEL_CONNECT_TYPE); + connectTypeComboBox.setBackground(JBColor.background()); + connectTypeComboBox.setOpaque(true); + deviceNameComboBox = new ComboBox(); + deviceNameComboBox.setName(UtConstant.UT_DEVICE_PROCESS_PANEL_DEVICE_NAME); + deviceNameComboBox.setBackground(JBColor.background()); + deviceNameComboBox.setOpaque(true); + // application name + applicationDesLabel = new JBLabel("Application"); + selectedProcessName = new CustomTextField("device"); + selectedProcessName.setBackground(JBColor.background()); + selectedProcessName.setOpaque(true); + selectedProcessName.setForeground(JBColor.foreground().brighter()); + selectedProcessName.setEditable(false); + selectedProcessName.setBorder(BorderFactory.createLineBorder(JBColor.background().darker(), 1)); + searchField = new CustomTextField("press"); + searchField.setBackground(JBColor.background()); + searchField.setOpaque(true); + searchField.setForeground(JBColor.foreground().brighter()); + searchField.setName(UtConstant.UT_DEVICE_PROCESS_PANEL_SEARCH_FIELD); + // process scroll + processPanel = new JBPanel(new MigLayout("insets 0", "[grow,fill]", + "[fill,fill]")); + processPanel.setBackground(JBColor.background()); + processPanel.setOpaque(true); + processTable = new JBTable(); + processPanel.setVisible(false); + processScrollPane = new JBScrollPane(); + processScrollPane.setBackground(JBColor.background()); + processScrollPane.setOpaque(true); + graphicsLine = new GraphicsLinePanel(); + this.add(currentDeviceNum, "wrap, gapx 16, gapy 16"); + this.add(deviceLabel, "wrap, gapx 16"); + this.add(connectTypeComboBox, "gapx 16, width 30%"); + this.add(deviceNameComboBox, "wrap, gapx 0 16, width 70%"); + this.add(applicationDesLabel, "wrap, gapx 16"); + this.add(selectedProcessName, "wrap, span, gapx 16 16"); + this.add(processPanel, "wrap, span, gapx 16 16, height 55%"); + } + + /** + * get the deviceData + */ + private void initDeviceList() { + deviceInfoList = MultiDeviceManager.getInstance().getOnlineDeviceInfoList(); + if (deviceInfoList.isEmpty()) { + deviceInfoList.add(new DeviceIPPortInfo()); + processInfoList = new ArrayList<>(); + } else { + processInfoList = ProcessManager.getInstance().getProcessList(deviceInfoList.get(0)); + Map mapObject = new HashMap<>(); + if (!processInfoList.isEmpty()) { + mapObject.put(deviceInfoList.get(0), processInfoList.get(0)); + } + Constant.map.put("Devices " + String.format(Locale.ENGLISH, "%02d", deviceNum), mapObject); + } + } + + /** + * Process drop-down list + * + * @param deviceInfo deviceInfo + */ + public void initProcessList(DeviceIPPortInfo deviceInfo) { + selectedProcessName.setName(UtConstant.UT_DEVICE_PROCESS_PANEL_PROCESS_NAME); + if (!processInfoList.isEmpty()) { + selectedProcessName.setText(processInfoList.get(0).getProcessName() + + "(" + processInfoList.get(0).getProcessId() + ")"); + } else { + selectedProcessName.setText("Please select the device process !"); + } + // create column + Vector columnNames = new Vector(); + columnNames.add(""); + // get process + Vector processNames = new Vector<>(); + for (int i = 0; i < processInfoList.size(); i++) { + ProcessInfo processInfo = processInfoList.get(i); + Vector vector = new Vector(); + vector.add(processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"); + processNames.add(vector); + } + if (!processInfoList.isEmpty()) { + // update map + Map mapObject = new HashMap<>(); + mapObject.put(deviceInfo, processInfoList.get(0)); + Constant.map.put(currentDeviceNum.getText(), mapObject); + } + // renderProcessTable + renderProcessTable(processNames, columnNames); + } + + private void renderProcessTable(Vector processNames, Vector columnNames) { + DefaultTableModel model = new DefaultTableModel(processNames, columnNames); + processTable.setName(UtConstant.UT_DEVICE_PROCESS_PANEL_TABLE); + processTable.setModel(model); + processTable.getTableHeader().setVisible(false); + processTable.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); + DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); + renderer.setPreferredSize(new Dimension(0, 0)); + renderer.setOpaque(false); + processTable.getTableHeader().setDefaultRenderer(renderer); + processScrollPane.setViewportView(processTable); + processPanel.add(searchField, "wrap, span"); + processPanel.add(processScrollPane, "span"); + } + + private void addEvent(JBPanel deviceConnectScrollPane) { + deviceProcessPanelEvent = new DeviceProcessPanelEvent(); + deviceProcessPanelEvent.devicesInfoJComboBoxUpdate(this); + // device and process state change + deviceProcessPanelEvent.itemStateChanged(this); + // addClickListener and open the process list + deviceProcessPanelEvent.addClickListener(this, deviceConnectScrollPane, + "Devices " + String.format(Locale.ENGLISH, "%02d", deviceNum)); + deviceProcessPanelEvent.connectTypeChanged(deviceInfoList.get(0), connectTypeComboBox); + deviceProcessPanelEvent.mouseEffectTable(processTable); + deviceProcessPanelEvent + .clickTable(this, currentDeviceNum.getText(), deviceConnectScrollPane); + deviceProcessPanelEvent.searchJButtonSelect(this, processInfoList); + } + + /** + * getProcessTable + * + * @return JTable + */ + public JBTable getProcessTable() { + return processTable; + } + + /** + * getSelectedProcessName + * + * @return JTextField + */ + public JTextField getSelectedProcessName() { + return selectedProcessName; + } + + /** + * setDeviceInfoList + * + * @param deviceInfoList deviceInfoList + */ + public void setDeviceInfoList(List deviceInfoList) { + this.deviceInfoList = deviceInfoList; + } + + /** + * getDeviceInfoList + * + * @return List + */ + public List getDeviceInfoList() { + return deviceInfoList; + } + + /** + * getProcessInfoList + * + * @return List + */ + public List getProcessInfoList() { + return processInfoList; + } + + /** + * setProcessInfoList + * + * @param processInfoList processInfoList + */ + public void setProcessInfoList(List processInfoList) { + this.processInfoList = processInfoList; + } + + /** + * getDeviceNameComboBox + * + * @return JComboBox + */ + public JComboBox getDeviceNameComboBox() { + return deviceNameComboBox; + } + + /** + * getSearchField + * + * @return JTextField + */ + public JTextField getSearchField() { + return searchField; + } + + /** + * getProcessPanel + * + * @return JPanel + */ + public JBPanel getProcessPanel() { + return processPanel; + } + + /** + * getGraphicsLine + * + * @return GraphicsLinePanel + */ + public GraphicsLinePanel getGraphicsLine() { + return graphicsLine; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomePanel.java new file mode 100644 index 000000000..fd8b84bf0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomePanel.java @@ -0,0 +1,219 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.ui.JBMenuItem; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.layout.dialog.HelpDialog; +import ohos.devtools.views.layout.utils.OpenFileDialogUtils; +import org.apache.logging.log4j.Level; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import static ohos.devtools.views.common.LayoutConstants.WINDOW_HEIGHT; +import static ohos.devtools.views.common.LayoutConstants.WINDOW_WIDTH; + +/** + * HomePanel + */ +public class HomePanel extends JBPanel implements ActionListener, MouseListener { + private static final String LOG_SWITCH_STR = "Path to Log"; + private static final String FILE_MENU_STR = " File "; + private static final String NEW_TASK_STR = "New Task"; + private static final String OPEN_FILE_STR = "Open File"; + private static final String SAVE_AS_STR = "Save as"; + private static final String QUIT_STR = "Quit"; + private static final String SETTING_STR = "Setting"; + private static final String HILOG = "HiLog"; + private static final String HELP = "Help"; + private static final String ABOUT = "About"; + private JBPanel menuPanel; + private WelcomePanel welcomePanel; + private JBPanel containerPanel; + private JMenu fileMenu; + private JMenu settingMenu; + private JMenu helpMenu; + private JBMenuItem newTaskItem; + private JBMenuItem openFileItem; + private JBMenuItem saveAsItem; + private JBMenuItem quitItem; + private JBMenuItem logSwitchItem; + private JBMenuItem helpItem; + + /** + * HomePanel + */ + public HomePanel() { + initComponents(); + } + + /** + * init Components + */ + private void initComponents() { + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT)); + menuPanel = new JBPanel(new BorderLayout()); + menuPanel.setName("menuPanel"); + menuPanel.setBackground(JBColor.background().brighter()); + containerPanel = new JBPanel(new GridLayout()); + welcomePanel = new WelcomePanel(); + // init fileMenu + fileMenu = new JMenu(FILE_MENU_STR); + newTaskItem = new JBMenuItem(NEW_TASK_STR); + openFileItem = new JBMenuItem(OPEN_FILE_STR); + saveAsItem = new JBMenuItem(SAVE_AS_STR); + quitItem = new JBMenuItem(QUIT_STR); + fileMenu.add(newTaskItem); + fileMenu.add(openFileItem); + fileMenu.add(saveAsItem); + fileMenu.add(quitItem); + // init settingMenu + settingMenu = new JMenu(SETTING_STR); + settingMenu.setIcon(AllIcons.Actions.InlayGear); + logSwitchItem = new JBMenuItem(LOG_SWITCH_STR); + helpItem = new JBMenuItem(ABOUT); + helpMenu = new JMenu(HELP); + helpMenu.setIcon(IconLoader.getIcon("/images/help.png", getClass())); + helpMenu.setName(UtConstant.UT_HOME_PANEL_HELP_MENU); + JMenuBar settingMenuBar = new JMenuBar(); + settingMenuBar.add(settingMenu); + settingMenuBar.add(helpMenu); + settingMenu.add(logSwitchItem); + helpMenu.add(helpItem); + // MenuPanel set + menuPanel.add(settingMenuBar); + menuPanel.setPreferredSize(new Dimension(LayoutConstants.WINDOW_WIDTH, LayoutConstants.THIRTY)); + containerPanel.add(welcomePanel); + add(menuPanel, BorderLayout.NORTH); + add(containerPanel, BorderLayout.CENTER); + logSwitchItem.addActionListener(this); + newTaskItem.addActionListener(this); + openFileItem.addActionListener(this); + helpItem.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + String actionCommand = actionEvent.getActionCommand(); + // switch log + if (actionCommand.equals(LOG_SWITCH_STR)) { + Level logLevel = ProfilerLogManager.getSingleton().getNowLogLevel(); + if (Level.ERROR.equals(logLevel)) { + ProfilerLogManager.getSingleton().updateLogLevel(Level.DEBUG); + logSwitchItem.setIcon(AllIcons.Actions.Commit); + } else { + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + logSwitchItem.setIcon(null); + } + } + // new task + if (actionCommand.equals(NEW_TASK_STR)) { + if (Constant.jtasksTab == null || Constant.jtasksTab.getTabCount() == 0) { + Constant.jtasksTab = new JBTabbedPane(); + } + new TaskPanel(containerPanel, welcomePanel); + welcomePanel.setVisible(false); + } + // open file + if (actionCommand.equals(OPEN_FILE_STR)) { + if (Constant.jtasksTab == null || Constant.jtasksTab.getTabCount() == 0) { + Constant.jtasksTab = new JBTabbedPane(); + } + TaskPanel taskPanel = new TaskPanel(containerPanel, welcomePanel); + OpenFileDialogUtils.getInstance().showFileOpenDialog(taskPanel.getTabItem(), taskPanel); + welcomePanel.setVisible(false); + } + if (actionCommand.equals(ABOUT)) { + new HelpDialog(); + } + } + + /** + * getContainerPanel + * + * @return JPanel + */ + public JBPanel getContainerPanel() { + return containerPanel; + } + + /** + * mouseClicked + * + * @param event MouseEvent + */ + @Override + public void mouseClicked(MouseEvent event) { + if (event.getComponent().getName().equals(UtConstant.UT_HOME_PANEL_HILOG_MENU)) { + if (Constant.jtasksTab == null || (Constant.jtasksTab != null && Constant.jtasksTab.getTabCount() == 0)) { + Constant.jtasksTab = new JBTabbedPane(); + } + } + } + + /** + * mousePressed + * + * @param event MouseEvent + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * mouseReleased + * + * @param event MouseEvent + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * mouseEntered + * + * @param event MouseEvent + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * mouseExited + * + * @param event MouseEvent + */ + @Override + public void mouseExited(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomeWindow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomeWindow.java deleted file mode 100644 index 8f0131461..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/HomeWindow.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout; - -/** - * @Description 主要负责IDE主框架的绘制。 - * @Date 2021/2/7 13:51 - **/ -public class HomeWindow { -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemConfigPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemConfigPanel.java new file mode 100644 index 000000000..b06d91d27 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemConfigPanel.java @@ -0,0 +1,804 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Vector; + +import com.intellij.openapi.ui.ComboBox; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.*; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.transport.grpc.SystemTraceHelper; +import ohos.devtools.datasources.utils.common.GrpcException; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.dialog.SampleDialog; +import ohos.devtools.views.layout.dialog.TraceRecordDialog; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import static ohos.devtools.views.common.Constant.DEVICE_REFRESH; + +/** + * SystemConfigPanel + */ +public class SystemConfigPanel extends JBPanel implements MouseListener, ItemListener { + private static final String HTRACE_AUDIO_STR = "Audio"; + private static final String HTRACE_CAMERA_STR = "Camera"; + private static final String HTRACE_DATABASE_STR = "Database"; + private static final String HTRACE_GRAPHICS_STR = "Graphics"; + private static final String HTRACE_INPUT_STR = "Input"; + private static final String HTRACE_NETWORK_STR = "NetWork"; + private static final String HTRACE_VIDEO_STR = "Video"; + private static final String LAST_STEP_BTN = "Last Step"; + private static final String START_TASK_BTN = "Start Task"; + private static final String SCENE_TITLE_STR = "Device"; + private static final String SCENE_TITLE_DES_STR = "Task scene: Connected devices"; + private static final String CONFIG_TITLE_STR = "Trace config & Probes"; + private static final String CONFIG_TITLE_DES_STR = "Task scene: System tuning"; + private static final String TRACE_CONFIG_TITLE_STR = "Trace config"; + private static final String PROBES_TITLE_STR = "Probes"; + private static final String RECORD_MODEL_STR = "Record Mode"; + private static final String SCHEDULING_STR = "Scheduling details"; + private static final String SCHEDULING_DES_STR = "Enables high-detailed tracking of scheduling events"; + private static final String CPU_FREQUENCY_STR = "CPU Frequency and idle states"; + private static final String CPU_FREQUENCY_DES_STR = "Records cpu frequency and idle state change viaftrace"; + private static final String BOARD_STR = "Board voltages & frequency"; + private static final String BOARD_DES_STR = "Tracks voltage and frequency changes from board sensors"; + private static final String TRACE_CONFIG_MODE_STR = "Record Mode"; + private static final String TRACE_CONFIG_MODE_BUTTON_STR = "Stop when full"; + private static final String BUFFER_SIZE_TITLE_STR = "In-memory buffer size:"; + private static final String DURATION_TITLE_STR = "Max duration:"; + private static final String HIGH_FREQUENCY_STR = "High frequency memory"; + private static final String HIGH_FREQUENCY_DES_STR = "Allows to track short memory splikes and transitories " + + "through ftrace's mm_event. rss_stat and ion events." + + " Available only on recent Kernel version >= 4.19" + + ""; + private static final String HTRACE_USERSPACE_STR = "Bytrace categories"; + private static final String HTRACE_USERSPACE_DES_STR = "" + "Enables C++ / Java codebase annotations " + + "(HTRACE_BEGIN() / os.Trace())" + ""; + private static final String SYSCALLS_STR = "Syscalls"; + private static final String SYSCALLS_DES_STR = "Tracks the enter and exit of all syscalls"; + private static final String LOW_MEMORY_STR = "Low memory killer"; + private static final String LOW_MEMORY_DES_STR = "" + + "Record LMK events. Works both with the old in kernel LMK and" + + "the newer userspace Imkd. It also tracks OOM score adjustments " + + ""; + private static final String RECORD_SETTING_STR = "" + + "

Record Setting

" + + "

" + + "Buffer mode.size and duration

" + + ""; + private static final String PROBES_CPU_STR = "" + + "

probes config

" + + "

CPU usage,scheduling" + + "
wakeups

" + + ""; + + JSeparator separator = new JSeparator(); + + ArrayList schedulingEvents = new ArrayList(Arrays.asList( + "sched/sched_switch", + "power/suspend_resume", + "sched/sched_wakeup", + "sched/sched_wakeup_new", + "sched/sched_waking", + "sched/sched_process_exit", + "sched/sched_process_free", + "task/task_newtask", + "task/task_rename")); + ArrayList powerEvents = new ArrayList(Arrays.asList( + "regulator/regulator_set_voltage", + "regulator/regulator_set_voltage_complete", + "power/clock_enable", + "power/clock_disable", + "power/clock_set_rate", + "power/suspend_resume")); + + ArrayList cpuFreqEvents = new ArrayList(Arrays.asList( + "power/cpu_frequency", + "power/cpu_idle", + "power/suspend_resume" + )); + ArrayList sysCallsEvents = new ArrayList(Arrays.asList( + "raw_syscalls/sys_enter", + "raw_syscalls/sys_exit" + )); + ArrayList highFrequencyEvents = new ArrayList(Arrays.asList( + "mm_event/mm_event_record", + "kmem/rss_stat", + "ion/ion_stat", + "dmabuf_heap/dma_heap_stat", + "kmem/ion_heap_grow", + "kmem/ion_heap_shrink" + )); + ArrayList hTraceAudioEvents = new ArrayList(Arrays.asList( + "audio" + )); + ArrayList hTraceCameraEvents = new ArrayList(Arrays.asList( + "camera" + )); + ArrayList hTraceDatabaseEvents = new ArrayList(Arrays.asList( + "database" + )); + ArrayList hTraceGraphicsEvents = new ArrayList(Arrays.asList( + "gfx" + )); + ArrayList hTraceInputEvents = new ArrayList(Arrays.asList( + "input" + )); + ArrayList hTraceNetWorkEvents = new ArrayList(Arrays.asList( + "network" + )); + ArrayList hTraceVideoEvents = new ArrayList(Arrays.asList( + "video" + )); + private JBCheckBox hTraceAudio; + private JBCheckBox hTraceCamera; + private JBCheckBox hTraceDatabase; + private JBCheckBox hTraceGraphics; + private JBCheckBox hTraceInput; + private JBCheckBox hTraceNetWork; + private JBCheckBox hTraceVideo; + private TaskPanel contentPanel; + private JBPanel sceneTitlePanel; + private JBLabel sceneTitle; + private JBLabel sceneTitleDes; + private ComboBox connectTypeComboBox; + private ComboBox deviceComboBox; + private JBPanel configTitlePanel; + private JBLabel configTitle; + private JBLabel configTitleDes; + private JBPanel traceConfigTab; + private JBLabel traceConfigTitle; + private JBPanel probesTab; + private JBLabel probesTitle; + private JBTabbedPane configTabbedPane; + private JBPanel traceConfigWestPanel; + private JBPanel traceConfigCenterPanel; + private JBLabel recordSettingLabel; + private JBPanel probesWestPanel; + private JBPanel probesCenterPanel; + private JBLabel probesCpu; + private JButton lastStepBtn; + private JButton startTaskBtn; + private JBLabel recordModelTitle; + private JBCheckBox schedulingCheckBox; + private JBLabel schedulingCheckBoxDes; + private JBCheckBox cpuFrequencyCheckBox; + private JBLabel cpuFrequencyCheckBoxDes; + private JBCheckBox boardCheckBox; + private JBLabel boardCheckBoxDes; + private JBCheckBox highFrequencyCheckBox; + private JBLabel highFrequencyCheckBoxDes; + private JBCheckBox hTraceUserspaceCheckBox; + private JBLabel hTraceUserspaceCheckBoxDes; + private JBCheckBox syscallsCheckBox; + private JBLabel syscallsCheckBoxDes; + private JBPanel buttonPanel; + private int inMemoryValue = 10; + private int maxDuration = 10; + private String eventStr = ""; + private boolean chooseMode = true; + private List deviceInfoList = null; + private DeviceIPPortInfo deviceIPPortInfo = null; + private Vector deviceInfo = new Vector<>(); + + /** + * SystemConfigPanel + * + * @param taskPanel + */ + public SystemConfigPanel(TaskPanel taskPanel) { + contentPanel = taskPanel; + setLayout(new MigLayout("inset 0", "15[grow,fill]", "15[fill,fill]")); + setOpaque(true); + setBackground(JBColor.background().darker()); + initComponents(); + addEventListener(); + } + + /** + * initComponents + */ + private void initComponents() { + // init the sceneTitlePanel + initSceneTitlePanel(); + // init the device ComboBox + initDeviceComboBox(); + // init the configTitlePanel + initConfigTitlePanel(); + // init the ConfigTabbedPane + initConfigTabbedPane(); + // init the buttonPanel + initButtonPanel(); + } + + private void initSceneTitlePanel() { + sceneTitlePanel = new JBPanel(new MigLayout("insets 0", + "[]15[]push", "[fill,fill]")); + sceneTitlePanel.setOpaque(false); + sceneTitle = new JBLabel(SCENE_TITLE_STR); + sceneTitle.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); + sceneTitle.setForeground(JBColor.foreground().brighter()); + sceneTitleDes = new JBLabel(SCENE_TITLE_DES_STR); + sceneTitleDes.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + sceneTitlePanel.add(sceneTitle); + sceneTitlePanel.add(sceneTitleDes); + this.add(sceneTitlePanel, "wrap, span"); + } + + private void initDeviceComboBox() { + connectTypeComboBox = new ComboBox(); + connectTypeComboBox.addItem(LayoutConstants.USB); + deviceComboBox = new ComboBox(); + this.add(connectTypeComboBox, "width 20%"); + this.add(deviceComboBox, "wrap, width 50%"); + } + + private void initConfigTitlePanel() { + configTitlePanel = new JBPanel(new MigLayout("insets 0", + "[]15[]push", "15[fill,fill]")); + configTitlePanel.setOpaque(false); + configTitle = new JBLabel(CONFIG_TITLE_STR); + configTitle.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); + configTitle.setForeground(JBColor.foreground().brighter()); + configTitleDes = new JBLabel(CONFIG_TITLE_DES_STR); + configTitleDes.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + configTitlePanel.add(configTitle); + configTitlePanel.add(configTitleDes); + this.add(configTitlePanel, "wrap, span"); + } + + private void initConfigTabbedPane() { + // initTabPanel + initTabPanel(); + // initTraceConfigTabItems + initTraceConfigTabItems(); + // initProbesTabItems + initProbesTabItems(); + // initProbesHtraceTabItem + initProbesHTraceTabItem(); + } + + private void initTabPanel() { + // init the traceConfigTab + traceConfigTab = new JBPanel(new BorderLayout()); + traceConfigTitle = new JBLabel(TRACE_CONFIG_TITLE_STR, JBLabel.CENTER); + traceConfigTitle.setFont(new Font(Font.DIALOG, Font.BOLD, 16)); + traceConfigTitle.setPreferredSize(new Dimension(100, 40)); + traceConfigTab.add(traceConfigTitle); + // init the probesTab + probesTab = new JBPanel(new BorderLayout()); + probesTitle = new JBLabel(PROBES_TITLE_STR, JBLabel.CENTER); + probesTitle.setFont(new Font(Font.DIALOG, Font.BOLD, 16)); + probesTitle.setPreferredSize(new Dimension(100, 40)); + // init the configTabbedPane + configTabbedPane = new JBTabbedPane(); + configTabbedPane.addTab("", traceConfigTab); + configTabbedPane.addTab("", probesTab); + configTabbedPane.setTabComponentAt(configTabbedPane.indexOfComponent(traceConfigTab), traceConfigTitle); + configTabbedPane.setTabComponentAt(configTabbedPane.indexOfComponent(probesTab), probesTitle); + this.add(configTabbedPane, "wrap, span"); + } + + private void initTraceConfigTabItems() { + traceConfigWestPanel = new JBPanel(null); + traceConfigCenterPanel = new JBPanel(null); + recordSettingLabel = new JBLabel(RECORD_SETTING_STR, JBLabel.CENTER); + recordSettingLabel.setOpaque(true); + recordSettingLabel.setBorder(BorderFactory.createLineBorder(new Color(0, 117, 255), 1)); + recordSettingLabel.setBounds(0, 50, 200, 70); + recordSettingLabel.setVisible(false); + // init trace config items + JBLabel traceConfigRecordMode = new JBLabel(TRACE_CONFIG_MODE_STR); + JBRadioButton traceConfigModeButton = new JBRadioButton(TRACE_CONFIG_MODE_BUTTON_STR, true); + traceConfigRecordMode.setBounds(50, 13, 200, 50); + traceConfigModeButton.setBounds(50, 50, 160, 50); + traceConfigCenterPanel.add(traceConfigRecordMode); + traceConfigCenterPanel.add(traceConfigModeButton); + // bufferSizeTitle + JBLabel bufferSizeTitle = new JBLabel(BUFFER_SIZE_TITLE_STR); + bufferSizeTitle.setBounds(50, 100, 200, 50); + traceConfigCenterPanel.add(bufferSizeTitle); + // bufferSizeValue + JBLabel bufferSizeValue = getBufferSizeValueLabel(); + traceConfigCenterPanel.add(bufferSizeValue); + // bufferSizeSlider + JSlider bufferSizeSlider = new JSlider(0, 110); + bufferSizeSlider.setValue(10); + bufferSizeSlider.setPreferredSize(new Dimension(200, 0)); + bufferSizeSlider.setBounds(45, 140, 600, 30); + traceConfigCenterPanel.add(bufferSizeSlider); + // durationTitle + JBLabel durationTitle = new JBLabel(DURATION_TITLE_STR); + durationTitle.setBounds(50, 190, 200, 50); + traceConfigCenterPanel.add(durationTitle); + // durationValue + JBLabel durationValue = getDurationValueLabel(); + traceConfigCenterPanel.add(durationValue); + // durationSlider + JSlider durationSlider = new JSlider(10, 600); + durationSlider.setValue(10); + durationSlider.setPreferredSize(new Dimension(200, 0)); + durationSlider.setBounds(45, 230, 600, 30); + traceConfigCenterPanel.add(durationSlider); + traceConfigWestPanel.add(recordSettingLabel); + traceConfigWestPanel.setPreferredSize(new Dimension(200, 500)); + traceConfigTab.add(traceConfigWestPanel, BorderLayout.WEST); + traceConfigTab.add(traceConfigCenterPanel, BorderLayout.CENTER); + // bufferSizeSlider addChangeListener + addBufferSizeListener(bufferSizeValue, bufferSizeSlider); + // durationSlider addChangeListener + addDurationSilderListener(durationValue, durationSlider); + } + + @NotNull + private JBLabel getBufferSizeValueLabel() { + JBLabel bufferSizeValue = new JBLabel("" + 10 + " MB", JBLabel.CENTER); + bufferSizeValue.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); + bufferSizeValue.setVerticalTextPosition(JBLabel.CENTER); + bufferSizeValue.setHorizontalTextPosition(JBLabel.CENTER); + bufferSizeValue.setOpaque(true); + bufferSizeValue.setBounds(700, 135, 110, 45); + return bufferSizeValue; + } + + @NotNull + private JBLabel getDurationValueLabel() { + JBLabel durationValue = new JBLabel("00:00:" + 10 + " h:m:s ", JBLabel.CENTER); + durationValue.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); + durationValue.setVerticalTextPosition(JBLabel.CENTER); + durationValue.setHorizontalTextPosition(JBLabel.CENTER); + durationValue.setOpaque(true); + durationValue.setBounds(700, 225, 110, 45); + return durationValue; + } + + private void addDurationSilderListener(JBLabel durationValue, JSlider durationSlider) { + durationSlider.addChangeListener(new ChangeListener() { + /** + * stateChanged + * + * @param changeEvent changeEvent + */ + @Override + public void stateChanged(ChangeEvent changeEvent) { + int seconds = durationSlider.getValue() % 60; + int minutes = (durationSlider.getValue() / 60) % 60; + int hours = durationSlider.getValue() / (60 * 60); + durationValue.setText(" " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + + String.format(Locale.ENGLISH, "%02d", minutes) + + ":" + String.format(Locale.ENGLISH, "%02d", seconds) + + " h:m:s "); + durationValue.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); + durationValue.setVerticalTextPosition(JBLabel.CENTER); + durationValue.setHorizontalTextPosition(JBLabel.CENTER); + maxDuration = durationSlider.getValue(); + } + }); + } + + private void addBufferSizeListener(JBLabel bufferSizeValue, JSlider bufferSizeSlider) { + bufferSizeSlider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent changeEvent) { + bufferSizeValue.setText("" + bufferSizeSlider.getValue() + " MB"); + bufferSizeValue.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); + bufferSizeValue.setVerticalTextPosition(JBLabel.CENTER); + bufferSizeValue.setHorizontalTextPosition(JBLabel.CENTER); + inMemoryValue = bufferSizeSlider.getValue(); + } + }); + } + + private void initProbesHTraceTabItem() { + hTraceUserspaceCheckBox = new JBCheckBox(HTRACE_USERSPACE_STR, false); + hTraceUserspaceCheckBoxDes = new JBLabel(HTRACE_USERSPACE_DES_STR, JBLabel.LEFT); + hTraceUserspaceCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceUserspaceCheckBox.setBounds(50, 330, 250, 50); + hTraceUserspaceCheckBoxDes.setBounds(70, 360, 350, 80); + hTraceAudio = new JBCheckBox(HTRACE_AUDIO_STR, false); + hTraceCamera = new JBCheckBox(HTRACE_CAMERA_STR, false); + hTraceDatabase = new JBCheckBox(HTRACE_DATABASE_STR, false); + hTraceGraphics = new JBCheckBox(HTRACE_GRAPHICS_STR, false); + hTraceInput = new JBCheckBox(HTRACE_INPUT_STR, false); + hTraceNetWork = new JBCheckBox(HTRACE_NETWORK_STR, false); + hTraceVideo = new JBCheckBox(HTRACE_VIDEO_STR, false); + hTraceAudio.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceAudio.setBounds(500, 330, 90, 50); + hTraceCamera.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceCamera.setBounds(590, 330, 90, 50); + hTraceDatabase.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceDatabase.setBounds(680, 330, 90, 50); + hTraceGraphics.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceGraphics.setBounds(770, 330, 90, 50); + hTraceInput.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceInput.setBounds(500, 380, 90, 50); + hTraceNetWork.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceNetWork.setBounds(590, 380, 90, 50); + hTraceVideo.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + hTraceVideo.setBounds(680, 380, 90, 50); + hTraceAddActionListener(hTraceUserspaceCheckBox); + addActionListener(hTraceAudio); + addActionListener(hTraceCamera); + addActionListener(hTraceDatabase); + addActionListener(hTraceGraphics); + addActionListener(hTraceInput); + addActionListener(hTraceNetWork); + addActionListener(hTraceVideo); + probesCenterPanel.add(hTraceUserspaceCheckBox); + probesCenterPanel.add(hTraceUserspaceCheckBoxDes); + probesCenterPanel.add(hTraceAudio); + probesCenterPanel.add(hTraceCamera); + probesCenterPanel.add(hTraceDatabase); + probesCenterPanel.add(hTraceGraphics); + probesCenterPanel.add(hTraceInput); + probesCenterPanel.add(hTraceNetWork); + probesCenterPanel.add(hTraceVideo); + } + + /** + * hTraceAddActionListener + * + * @param checkBoxObject checkBoxObject + */ + public void hTraceAddActionListener(JBCheckBox checkBoxObject) { + checkBoxObject.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (hTraceUserspaceCheckBox.isSelected()) { + hTraceAudio.setSelected(true); + hTraceCamera.setSelected(true); + hTraceDatabase.setSelected(true); + hTraceGraphics.setSelected(true); + hTraceInput.setSelected(true); + hTraceNetWork.setSelected(true); + hTraceVideo.setSelected(true); + } else { + hTraceAudio.setSelected(false); + hTraceCamera.setSelected(false); + hTraceDatabase.setSelected(false); + hTraceGraphics.setSelected(false); + hTraceInput.setSelected(false); + hTraceNetWork.setSelected(false); + hTraceVideo.setSelected(false); + } + } + }); + } + + /** + * addActionListener + * + * @param checkBoxObject checkBoxObject + */ + public void addActionListener(JBCheckBox checkBoxObject) { + checkBoxObject.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (hTraceUserspaceCheckBoxAllSelected()) { + hTraceUserspaceCheckBox.setSelected(true); + } else { + hTraceUserspaceCheckBox.setSelected(false); + } + } + }); + } + + private boolean hTraceUserspaceCheckBoxAllSelected() { + if (hTraceAudio.isSelected() && hTraceCamera.isSelected()) { + if (hTraceDatabase.isSelected() && hTraceGraphics.isSelected()) { + if (hTraceInput.isSelected() && hTraceNetWork.isSelected()) { + if (hTraceVideo.isSelected()) { + return true; + } + } + } + } + return false; + } + + private void initProbesTabItems() { + // init the probes items + probesWestPanel = new JBPanel(null); + probesCenterPanel = new JBPanel(null); + probesCpu = new JBLabel(PROBES_CPU_STR, JBLabel.CENTER); + probesCpu.setOpaque(true); + probesCpu.setBorder(BorderFactory.createLineBorder(new Color(0, 117, 255), 1)); + probesCpu.setBounds(0, 50, 200, 70); + probesWestPanel.add(probesCpu); + probesCpu.setVisible(false); + probesWestPanel.setPreferredSize(new Dimension(200, 500)); + // init the component + recordModelTitle = new JBLabel(RECORD_MODEL_STR); + schedulingCheckBox = new JBCheckBox(SCHEDULING_STR, true); + schedulingCheckBoxDes = new JBLabel(SCHEDULING_DES_STR, JBLabel.LEFT); + cpuFrequencyCheckBox = new JBCheckBox(CPU_FREQUENCY_STR, false); + cpuFrequencyCheckBoxDes = new JBLabel(CPU_FREQUENCY_DES_STR, JBLabel.LEFT); + boardCheckBox = new JBCheckBox(BOARD_STR, false); + boardCheckBoxDes = new JBLabel(BOARD_DES_STR, JBLabel.LEFT); + highFrequencyCheckBox = new JBCheckBox(HIGH_FREQUENCY_STR, false); + highFrequencyCheckBoxDes = new JBLabel(HIGH_FREQUENCY_DES_STR, JBLabel.LEFT); + + syscallsCheckBox = new JBCheckBox(SYSCALLS_STR, false); + syscallsCheckBoxDes = new JBLabel(SYSCALLS_DES_STR, JBLabel.LEFT); + // set the font + schedulingCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + cpuFrequencyCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + boardCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + highFrequencyCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + + syscallsCheckBox.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + // set the bounds + recordModelTitle.setBounds(50, 13, 200, 50); + schedulingCheckBox.setBounds(50, 50, 250, 50); + schedulingCheckBoxDes.setBounds(70, 80, 350, 50); + + cpuFrequencyCheckBox.setBounds(50, 140, 250, 50); + cpuFrequencyCheckBoxDes.setBounds(70, 170, 350, 50); + boardCheckBox.setBounds(500, 50, 250, 50); + boardCheckBoxDes.setBounds(520, 80, 350, 60); + highFrequencyCheckBox.setBounds(500, 140, 250, 50); + highFrequencyCheckBoxDes.setBounds(520, 170, 350, 80); + syscallsCheckBox.setBounds(50, 230, 250, 50); + syscallsCheckBoxDes.setBounds(70, 260, 350, 50); + separator.setBounds(50, 310, 850, 10); + separator.setBackground(new Color(255, 255, 255)); + addProbesCenterPanel(); + } + + /** + * addProbesCenterPanel + */ + private void addProbesCenterPanel() { + // add component + probesCenterPanel.add(recordModelTitle); + probesCenterPanel.add(schedulingCheckBox); + probesCenterPanel.add(schedulingCheckBoxDes); + probesCenterPanel.add(cpuFrequencyCheckBox); + probesCenterPanel.add(cpuFrequencyCheckBoxDes); + probesCenterPanel.add(boardCheckBox); + probesCenterPanel.add(boardCheckBoxDes); + probesCenterPanel.add(highFrequencyCheckBox); + probesCenterPanel.add(highFrequencyCheckBoxDes); + probesCenterPanel.add(syscallsCheckBox); + probesCenterPanel.add(syscallsCheckBoxDes); + probesCenterPanel.add(separator); + // checkBoxState + probesTab.add(probesWestPanel, BorderLayout.WEST); + probesTab.add(probesCenterPanel, BorderLayout.CENTER); + } + + private void initButtonPanel() { + buttonPanel = new JBPanel(new MigLayout("insets 0", "push[]20[]20", + "[fill,fill]")); + buttonPanel.setOpaque(false); + lastStepBtn = new JButton(LAST_STEP_BTN); + lastStepBtn.setName(LAST_STEP_BTN); + lastStepBtn.setFocusPainted(false); + lastStepBtn.setOpaque(false); + lastStepBtn.setPreferredSize(new Dimension(140, 40)); + startTaskBtn = new JButton(START_TASK_BTN); + startTaskBtn.setName(START_TASK_BTN); + startTaskBtn.setFocusPainted(false); + startTaskBtn.setOpaque(false); + startTaskBtn.setPreferredSize(new Dimension(140, 40)); + buttonPanel.add(lastStepBtn); + buttonPanel.add(startTaskBtn); + this.add(buttonPanel, "wrap, span, height 40!"); + } + + /** + * addEventListener + */ + private void addEventListener() { + addDeviceRefresh(); + lastStepBtn.addMouseListener(this); + startTaskBtn.addMouseListener(this); + deviceComboBox.addItemListener(this); + } + + /** + * addDeviceRefresh + */ + public void addDeviceRefresh() { + QuartzManager.getInstance().addExecutor(DEVICE_REFRESH, new Runnable() { + /** + * run + */ + @Override + public void run() { + deviceInfoList = MultiDeviceManager.getInstance().getOnlineDeviceInfoList(); + Vector items = new Vector<>(); + deviceInfoList.forEach(deviceInfo -> { + items.add(deviceInfo.getDeviceName()); + }); + if (!deviceInfo.equals(items)) { + deviceInfo = items; + deviceComboBox.setModel(new DefaultComboBoxModel(items)); + for (DeviceIPPortInfo deviceIPInfo : deviceInfoList) { + if (deviceIPInfo.getDeviceName().equals(deviceComboBox.getSelectedItem())) { + deviceIPPortInfo = deviceIPInfo; + } else { + deviceIPPortInfo = deviceInfoList.get(0); + } + } + } + } + }); + QuartzManager.getInstance().startExecutor(DEVICE_REFRESH, LayoutConstants.DEFAULT_NUMBER, + LayoutConstants.NUMBER_THREAD); + } + + @Override + public void mouseClicked(MouseEvent mouseEvent) { + } + + @Override + public void mousePressed(MouseEvent mouseEvent) { + } + + @Override + public void mouseReleased(MouseEvent mouseEvent) { + String name = mouseEvent.getComponent().getName(); + if (name.equals(LAST_STEP_BTN)) { + contentPanel.getTabContainer().remove(this); + contentPanel.getTabItem().setVisible(true); + contentPanel.getTabContainer().repaint(); + } + if (name.equals(START_TASK_BTN)) { + int itemCount = deviceComboBox.getItemCount(); + // create system tuning load dialog object + if (itemCount == 0) { + new SampleDialog("prompt", "Device list is empty !").show(); + return; + } + if (deviceIPPortInfo == null) { + new SampleDialog("prompt", "Please select the device !").show(); + return; + } + QuartzManager.getInstance().endExecutor(DEVICE_REFRESH); + loadTraceRecordDialog(); + contentPanel.getTabContainer().repaint(); + } + } + + /** + * loadTraceRecordDialog + */ + private void loadTraceRecordDialog() { + try { + if (!getClassificationSelect()) { + new SampleDialog("prompt", "Please select the classification !").show(); + } else { + String sessionId; + if (chooseMode) { + eventStr = eventStr + ";sched"; + sessionId = new SystemTraceHelper() + .createSessionByTraceRequest(deviceIPPortInfo, eventStr, maxDuration, inMemoryValue, + "/data/local/tmp/hiprofiler_data.bytrace", false); + } else { + ArrayList> eventsList = new ArrayList(); + ArrayList> hTraceEventsList = new ArrayList(); + getEvent(eventsList, hTraceEventsList); + sessionId = new SystemTraceHelper() + .createSessionHtraceRequest(deviceIPPortInfo, eventsList, hTraceEventsList, maxDuration, + inMemoryValue); + } + new TraceRecordDialog().load(contentPanel, maxDuration, sessionId, deviceIPPortInfo, chooseMode); + } + } catch (GrpcException grpcException) { + grpcException.printStackTrace(); + } + } + + /** + * getClassificationSelect + * + * @return boolean + */ + public boolean getClassificationSelect() { + if (!schedulingCheckBox.isSelected() && !cpuFrequencyCheckBox.isSelected() && !boardCheckBox.isSelected() + && !syscallsCheckBox.isSelected() && !highFrequencyCheckBox.isSelected() && !hTraceAudio.isSelected() + && !hTraceCamera.isSelected() && !hTraceDatabase.isSelected() && !hTraceGraphics.isSelected() + && !hTraceInput.isSelected() && !hTraceNetWork.isSelected() && !hTraceVideo.isSelected()) { + return false; + }else { + return true; + } + } + + /** + * getEvent + * + * @param eventsList eventsList + * @param hTraceEventsList hTraceEventsList + */ + public void getEvent(ArrayList> eventsList, ArrayList> hTraceEventsList) { + if (schedulingCheckBox.isSelected()) { + eventsList.add(schedulingEvents); + } + if (boardCheckBox.isSelected()) { + eventsList.add(powerEvents); + } + if (cpuFrequencyCheckBox.isSelected()) { + eventsList.add(cpuFreqEvents); + } + if (syscallsCheckBox.isSelected()) { + eventsList.add(sysCallsEvents); + } + if (highFrequencyCheckBox.isSelected()) { + eventsList.add(highFrequencyEvents); + } + if (hTraceAudio.isSelected()) { + hTraceEventsList.add(hTraceAudioEvents); + } + if (hTraceCamera.isSelected()) { + hTraceEventsList.add(hTraceCameraEvents); + } + if (hTraceDatabase.isSelected()) { + hTraceEventsList.add(hTraceDatabaseEvents); + } + if (hTraceGraphics.isSelected()) { + hTraceEventsList.add(hTraceGraphicsEvents); + } + if (hTraceInput.isSelected()) { + hTraceEventsList.add(hTraceInputEvents); + } + if (hTraceNetWork.isSelected()) { + hTraceEventsList.add(hTraceNetWorkEvents); + } + if (hTraceVideo.isSelected()) { + hTraceEventsList.add(hTraceVideoEvents); + } + } + + @Override + public void mouseEntered(MouseEvent mouseEvent) { + } + + @Override + public void mouseExited(MouseEvent mouseEvent) { + } + + @Override + public void itemStateChanged(ItemEvent itemEvent) { + if (deviceInfoList != null && deviceInfoList.size() > 0) { + for (DeviceIPPortInfo deviceIPInfo : deviceInfoList) { + if (deviceIPInfo.getDeviceName().equals(deviceComboBox.getSelectedItem())) { + deviceIPPortInfo = deviceIPInfo; + } + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemPanel.java new file mode 100644 index 000000000..d56692d7d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/SystemPanel.java @@ -0,0 +1,250 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; + +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.customcomp.CustomTextField; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.metrics.InfoStatsPanel; +import ohos.devtools.views.trace.metrics.MetricsPanel; +import ohos.devtools.views.trace.metrics.QuerySqlPanel; + +import javax.swing.JButton; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * SystemTuningPanel + */ +public class SystemPanel extends JBPanel { + /** + * QUERY BUTTON WIDTH + */ + private static final int QUERY_BUTTON_WIDTH = 110; + + /** + * INFO BUTTON WIDTH + */ + private static final int INFO_BUTTON_WIDTH = 126; + + /** + * BUTTON HEIGHT + */ + private static final int BUTTON_HEIGHT = 30; + + /** + * button margin top + */ + private static final int BUTTON_MARGIN_TOP = 11; + + /** + * save button margin right + */ + private static final int SAVE_MARGIN_LEFT = 375; + + /** + * gc margin left + */ + private static final int GC_MARGIN_LEFT = 400; + + /** + * btn width or height + */ + private static final int BTN_WIDTH_HEIGHT = 20; + + /** + * INFO X + */ + private static final int INFO_X = 236; + + /** + * search margin right + */ + private static final int SEARCH_MARGIN_RIGHT = 530; + + /** + * down margin right + */ + private static final int DOWN_MARGIN_RIGHT = 65; + + /** + * left margin right + */ + private static final int LEFT_MARGIN_RIGHT = 40; + + /** + * top panel height + */ + private static final int TOP_PANEL_HEIGHT = 34; + + /** + * margin x + */ + private static final int MARGIN_Y = 2; + + /** + * margin x + */ + private static final int SEARCH_MARGIN_Y = 4; + + /** + * METRICS X + */ + private static final int METRICS_X = 126; + + /** + * margin + */ + private static final int MARGIN = 20; + + private JButton queryButton; + private JButton metricsButton; + private JButton infoButton; + private JBLabel saveBtn; + private JBLabel gcBtn; + private JBLabel downBtn; + private JBLabel leftBtn; + private JBPanel optionJPanel; + private AnalystPanel analystPanel; + + + /** + * device name drop down box + */ + private CustomTextField searchTextField; + + /** + * System Tuning Panel + */ + public SystemPanel(JBPanel optionJPanel, AnalystPanel analystPanel) { + this.optionJPanel = optionJPanel; + this.analystPanel = analystPanel; + this.setPreferredSize(new Dimension(optionJPanel.getWidth() - MARGIN, TOP_PANEL_HEIGHT)); + initComponents(); + // 设置属性 + setAttributes(); + addComponent(); + componentAddListener(); + } + + /** + * initComponents + */ + private void initComponents() { + queryButton = new JButton(); + queryButton.setText("Query(SQL)"); + queryButton.setIcon(IconLoader.getIcon("/images/preview_normal.png", getClass())); + metricsButton = new JButton(); + metricsButton.setIcon(IconLoader.getIcon("/images/overhead_normal.png", getClass())); + metricsButton.setText("Metrics"); + infoButton = new JButton(); + infoButton.setIcon(IconLoader.getIcon("/images/notificationInfo_normal.png", getClass())); + infoButton.setText("Info and stats"); + saveBtn = new JBLabel(); + saveBtn.setIcon(IconLoader.getIcon("/images/menu-saveAll_grey.png", getClass())); + saveBtn.setToolTipText("Save"); + gcBtn = new JBLabel(); + gcBtn.setIcon(IconLoader.getIcon("/images/gc_grey.png", getClass())); + gcBtn.setToolTipText("Delete"); + downBtn = new JBLabel(); + downBtn.setIcon(IconLoader.getIcon("/images/previewDetailsVertically_grey.png", getClass())); + downBtn.setToolTipText("Expand page down"); + leftBtn = new JBLabel(); + leftBtn.setIcon(IconLoader.getIcon("/images/previewDetails_grey.png", getClass())); + leftBtn.setToolTipText("Expand page left"); + searchTextField = new CustomTextField("press"); + } + + private void setAttributes() { + this.setLayout(null); + this.setOpaque(true); + this.setBackground(JBColor.background().darker()); + queryButton.setBounds(LayoutConstants.EIGHT_NUM, MARGIN_Y, QUERY_BUTTON_WIDTH, BUTTON_HEIGHT); + metricsButton.setBounds(METRICS_X, MARGIN_Y, LayoutConstants.DEVICE_ADD_WIDTH, BUTTON_HEIGHT); + infoButton.setBounds(INFO_X, MARGIN_Y, INFO_BUTTON_WIDTH, BUTTON_HEIGHT); + saveBtn.setBounds(SAVE_MARGIN_LEFT, BUTTON_MARGIN_TOP, BTN_WIDTH_HEIGHT, BTN_WIDTH_HEIGHT); + gcBtn.setBounds(GC_MARGIN_LEFT, BUTTON_MARGIN_TOP, BTN_WIDTH_HEIGHT, BTN_WIDTH_HEIGHT); + int panelWidth = optionJPanel.getWidth(); + searchTextField.setBounds(panelWidth - SEARCH_MARGIN_RIGHT, SEARCH_MARGIN_Y, LayoutConstants.HEIGHT_PRESSE, + LayoutConstants.TASK_SCENE_Y); + downBtn.setBounds(panelWidth - DOWN_MARGIN_RIGHT, BUTTON_MARGIN_TOP, BTN_WIDTH_HEIGHT, BTN_WIDTH_HEIGHT); + leftBtn.setBounds(panelWidth - LEFT_MARGIN_RIGHT, BUTTON_MARGIN_TOP, BTN_WIDTH_HEIGHT, BTN_WIDTH_HEIGHT); + } + + private void addComponent() { + this.add(queryButton); + this.add(metricsButton); + this.add(infoButton); + } + + private void componentAddListener() { + queryButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + QuerySqlPanel querySqlPanel = new QuerySqlPanel(optionJPanel, analystPanel, queryButton); + metricsButton.setIcon(IconLoader.getIcon("/images/overhead_normal.png", getClass())); + infoButton.setIcon(IconLoader.getIcon("/images/notificationInfo_normal.png", getClass())); + removeCenterComponent(); + optionJPanel.add(querySqlPanel, BorderLayout.CENTER); + optionJPanel.revalidate(); + } + }); + + metricsButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + MetricsPanel metricsPanel = new MetricsPanel(optionJPanel, analystPanel, metricsButton); + queryButton.setIcon(IconLoader.getIcon("/images/preview_normal.png", getClass())); + infoButton.setIcon(IconLoader.getIcon("/images/notificationInfo_normal.png", getClass())); + removeCenterComponent(); + optionJPanel.add(metricsPanel, BorderLayout.CENTER); + optionJPanel.revalidate(); + } + }); + + infoButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + InfoStatsPanel metricsPanel = new InfoStatsPanel(optionJPanel, analystPanel, infoButton); + queryButton.setIcon(IconLoader.getIcon("/images/preview_normal.png", getClass())); + metricsButton.setIcon(IconLoader.getIcon("/images/overhead_normal.png", getClass())); + removeCenterComponent(); + optionJPanel.add(metricsPanel, BorderLayout.CENTER); + optionJPanel.revalidate(); + } + }); + } + + private void removeCenterComponent() { + Component[] components = optionJPanel.getComponents(); + for (Component item : components) { + if (!(item instanceof SystemPanel)) { + optionJPanel.remove(item); + break; + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/TaskPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/TaskPanel.java new file mode 100644 index 000000000..2a3e9fe71 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/TaskPanel.java @@ -0,0 +1,457 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBLayeredPane; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.GraphicsLinePanel; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.utils.OpenFileDialogUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.FocusEvent; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Objects; + +import static ohos.devtools.views.common.Constant.DEVICE_REFRESH; + +/** + * TaskPanel + */ +public class TaskPanel extends JBLayeredPane implements MouseListener { + private static final Logger LOGGER = LogManager.getLogger(TaskPanel.class); + private static final String TAB_STR = "NewTask-Configure"; + private static final String TAB_CLOSE_STR = "x"; + private static final String TAB_ADD_STR = "+"; + private static final String TASK_SCENE_STR = "Task scene"; + private static final String TASK_SCENE_TIP_STR = "Choose the most suitable scene."; + private static final String CHOOSE_BTN_STR = "Choose"; + private static final String OPEN_FILE_STR = "Open File"; + private static final String APPLICATION_TITLE_STR = "Application Tuning"; + private static final String SYSTEM_TITLE_STR = "System Tuning"; + private static final String DISTRIBUTED_TITLE_STR = "Distributed Scenario"; + private static final String GPU_TITLE_STR = "GPU Counter"; + private static final String APPLICATION_TIP_STR = "Application Tuning

" + + "Use the performance profiler to check the CPU,memory,network and energy status of the application"; + private static final String SYSTEM_TIP_STR = "System Tuning

" + + "Collect system-wide performance traces from Harmony devices from a variety of data sources"; + private static final String DISTRIBUTED_TIP_STR = "Distributed Scenario

" + + "Collect performance data for distributed scenarios"; + private static final String GPU_TIP_STR = "GPU Counter

" + + "Collect performance data for GPU Counter"; + + private JBPanel parentPanel; + private JBPanel welcomePanel; + private JBPanel tabPanel; + private JBPanel tabLeftPanel; + private JBPanel tabRightPanel; + private JBLabel tabText; + private JBLabel tabCloseBtn; + private JButton tabAddBtn; + private JBPanel tabContainer; + private JBPanel tabItem; + private JBLabel taskSceneLabel; + private JBLabel taskSceneLabelTip; + private JBLabel applicationBtn; + private JBLabel systemBtn; + private JBLabel tipIconLabel; + private JBLabel tipInfoLabel; + private JButton chooseBtn; + private JButton openFileBtn; + private JBPanel btnPanel; + private GraphicsLinePanel graphicsLineUp; + private GraphicsLinePanel graphicsLineDown; + private Long localSessionId; + + /** + * Task Panel + */ + public TaskPanel() { + } + + /** + * Task Panel + * + * @param containerPanel JBPanel + * @param welcomePanel WelcomePanel + */ + public TaskPanel(JBPanel containerPanel, WelcomePanel welcomePanel) { + parentPanel = containerPanel; + this.welcomePanel = welcomePanel; + initComponents(); + initTab(containerPanel); + initTaskSceneItems(); + addEventListener(); + } + + /** + * initComponents + */ + private void initComponents() { + // init tabPanel + tabPanel = new JBPanel(); + tabLeftPanel = new JBPanel(); + tabRightPanel = new JBPanel(); + tabRightPanel.setName(UtConstant.UT_TASK_PANEL_CLOSE); + tabText = new JBLabel(TAB_STR); + tabCloseBtn = new JBLabel(TAB_CLOSE_STR); + tabAddBtn = new JButton(TAB_ADD_STR); + // init tab + tabContainer = new JBPanel(new BorderLayout()); + tabContainer.setOpaque(true); + tabContainer.setBackground(JBColor.background().darker()); + tabItem = new JBPanel(); + // init items + taskSceneLabel = new JBLabel(TASK_SCENE_STR); + taskSceneLabelTip = new JBLabel(TASK_SCENE_TIP_STR); + applicationBtn = new JBLabel(IconLoader.getIcon("/images/application_tuning.png", getClass())); + systemBtn = new JBLabel(IconLoader.getIcon("/images/system_tuning.png", getClass())); + tipIconLabel = new JBLabel(IconLoader.getIcon("/images/application_tuning.png", getClass())); + tipInfoLabel = new JBLabel(APPLICATION_TIP_STR); + graphicsLineUp = new GraphicsLinePanel(); + graphicsLineDown = new GraphicsLinePanel(); + chooseBtn = new JButton(CHOOSE_BTN_STR); + openFileBtn = new JButton(OPEN_FILE_STR); + } + + /** + * setTabAttributes + * + * @param containerPanel containerPanel + */ + private void initTab(JBPanel containerPanel) { + setPanelData(); + containerPanel.setLayout(new BorderLayout()); + tabAddBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.DEVICES_HEIGHT)); + tabAddBtn.setBorderPainted(false); + tabAddBtn.setBounds(LayoutConstants.NUMBER_X_ADD * Constant.jtasksTab.getTabCount(), LayoutConstants + .NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); + Constant.jtasksTab.setBounds(0, 0, containerPanel.getWidth(), containerPanel.getHeight()); + this.add(Constant.jtasksTab); + containerPanel.add(this); + double result = Constant.jtasksTab.getTabCount() * LayoutConstants.NUMBER_X; + if (result > containerPanel.getWidth()) { + for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { + Object tabObj = Constant.jtasksTab.getTabComponentAt(index); + if (tabObj instanceof JBPanel) { + ((JBPanel) tabObj).getComponents()[0].setPreferredSize(new Dimension( + (((containerPanel.getWidth() - LayoutConstants.MEMORY_WIDTH) / Constant.jtasksTab.getTabCount()) + - LayoutConstants.TASK_DEC_NUM) - LayoutConstants.JAVA_HEIGHT, + LayoutConstants.JAVA_HEIGHT)); + } + Constant.jtasksTab.getTabComponentAt(index).setPreferredSize(new Dimension( + ((containerPanel.getWidth() - LayoutConstants.MEMORY_WIDTH) / Constant.jtasksTab.getTabCount()) + - LayoutConstants.TASK_DEC_NUM, LayoutConstants.JAVA_HEIGHT)); + tabAddBtn.setBounds(containerPanel.getWidth() - LayoutConstants.TASK_LABEL_X, LayoutConstants.NUMBER_Y, + LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); + } + } + } + + /** + * setPanelData + */ + private void setPanelData() { + tabItem.setLayout(new MigLayout("insets 0", "[grow,fill]", + "15[fill,fill]20[]push[][][]20[]")); + tabPanel.setOpaque(false); + tabPanel.setPreferredSize(new Dimension(LayoutConstants.JPA_LABEL_WIDTH, LayoutConstants.DEVICES_HEIGHT)); + tabLeftPanel.setOpaque(false); + tabLeftPanel.setLayout(null); + tabLeftPanel.setPreferredSize(new Dimension(LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.JP_LEFT_HEIGHT)); + tabRightPanel.setOpaque(false); + tabRightPanel.setLayout(new GridLayout()); + tabRightPanel.setPreferredSize(new Dimension(LayoutConstants.JP_RIGHT_WIDTH, LayoutConstants.JP_RIGHT_HEIGHT)); + tabPanel.setLayout(new BorderLayout()); + tabPanel.add(tabLeftPanel, BorderLayout.WEST); + tabPanel.add(tabRightPanel, BorderLayout.CENTER); + tabText.setBounds(0, 0, LayoutConstants.JP_SET_WIDTH, LayoutConstants.JP_SET_HEIGHT); + tabLeftPanel.add(tabText); + tabRightPanel.add(tabCloseBtn); + tabCloseBtn.setHorizontalAlignment(JBLabel.RIGHT); + tabCloseBtn.setName(TAB_CLOSE_STR); + tipIconLabel + .setBounds(LayoutConstants.DEVICES_X, LayoutConstants.DESCRIPTION_NUMBER, LayoutConstants.HIGTHSCEECS, + LayoutConstants.HIGTHSCEECS); + tipInfoLabel + .setBounds(LayoutConstants.JAVA_WIDTH, LayoutConstants.DESCRIPTION_NUMBER, LayoutConstants.APP_LABEL_WIDTH, + LayoutConstants.JLABEL_SIZE); + Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TUN_LABEL_FONT); + tipInfoLabel.setFont(fontTaskTun); + tabContainer.add(tabItem); + Constant.jtasksTab.addTab("", tabContainer); + Constant.jtasksTab.setTabComponentAt(Constant.jtasksTab.indexOfComponent(tabContainer), tabPanel); + } + + /** + * init TaskScene Items + */ + private void initTaskSceneItems() { + setButtonAttr(); + setApplicationBtnData(); + setSystemBtnData(); + JBPanel taskScenePanel = new JBPanel(new MigLayout("insets 0")); + taskScenePanel.setOpaque(false); + taskScenePanel.add(taskSceneLabel, "gap 15"); + taskScenePanel.add(taskSceneLabelTip); + JBPanel sceneButtonPanel = new JBPanel(new MigLayout("insets 0")); + sceneButtonPanel.add(applicationBtn, "gap 15"); + sceneButtonPanel.add(systemBtn, "gap 15"); + sceneButtonPanel.setOpaque(false); + JBPanel tipPanel = new JBPanel(new MigLayout("insets 0")); + tipPanel.add(tipIconLabel, "gap 30"); + tipPanel.add(tipInfoLabel); + tipPanel.setOpaque(false); + btnPanel = new JBPanel(new MigLayout("insets 0", "push[]15[]15", + "[fill, fill]")); + btnPanel.add(openFileBtn); + btnPanel.add(chooseBtn); + btnPanel.setOpaque(false); + tabItem.add(taskScenePanel, "wrap, height 30!"); + tabItem.add(sceneButtonPanel, "wrap, height 150!"); + tabItem.add(graphicsLineUp, "wrap, height 10!, gapx 15 15"); + tabItem.add(tipPanel, "wrap"); + tabItem.add(graphicsLineDown, "wrap, height 10!, gapy 10, gapx 15 15"); + tabItem.add(btnPanel, "wrap, span, height 40!"); + tabItem.setOpaque(true); + tabItem.setBackground(JBColor.background().darker()); + } + + /** + * setSystemBtnData + */ + private void setSystemBtnData() { + systemBtn.setText(SYSTEM_TITLE_STR); + systemBtn.setName(SYSTEM_TITLE_STR); + systemBtn.setPreferredSize(new Dimension(210, 155)); + systemBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + systemBtn.setVerticalTextPosition(JBLabel.BOTTOM); + systemBtn.setHorizontalTextPosition(JBLabel.CENTER); + systemBtn.setOpaque(true); + systemBtn.setBackground(JBColor.background()); + } + + /** + * setApplicationBtnData + */ + private void setApplicationBtnData() { + taskSceneLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); + taskSceneLabel.setForeground(JBColor.foreground().brighter()); + taskSceneLabelTip.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + applicationBtn.setText(APPLICATION_TITLE_STR); + applicationBtn.setName(UtConstant.UT_TASK_PANEL_APPLICATION); + applicationBtn.setPreferredSize(new Dimension(210, 155)); + applicationBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + applicationBtn.setVerticalTextPosition(JBLabel.BOTTOM); + applicationBtn.setHorizontalTextPosition(JBLabel.CENTER); + applicationBtn.setOpaque(true); + applicationBtn.setBackground(JBColor.background()); + applicationBtn.setForeground(JBColor.foreground().brighter()); + applicationBtn.setBorder(BorderFactory.createLineBorder(new Color(0, 117, 255), 2)); + } + + /** + * addEventListener + */ + private void addEventListener() { + tabCloseBtn.addMouseListener(this); + applicationBtn.addMouseListener(this); + systemBtn.addMouseListener(this); + openFileBtn.addMouseListener(this); + chooseBtn.addMouseListener(this); + } + + /** + * setButtonAttr + */ + private void setButtonAttr() { + chooseBtn.setName(UtConstant.UT_TASK_PANEL_CHOOSE); + chooseBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT)); + chooseBtn.setFocusPainted(false); + chooseBtn.setOpaque(false); + chooseBtn.setPreferredSize(new Dimension(140, 40)); + openFileBtn.setName(UtConstant.UT_TASK_PANEL_OPEN_FILE); + openFileBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT)); + openFileBtn.setOpaque(false); + openFileBtn.setFocusPainted(false); + openFileBtn.setPreferredSize(new Dimension(140, 40)); + } + + @Override + public void mouseClicked(MouseEvent mouseEvent) { + } + + @Override + public void mousePressed(MouseEvent mouseEvent) { + } + + @Override + public void mouseReleased(MouseEvent mouseEvent) { + String name = mouseEvent.getComponent().getName(); + if (name.equals(APPLICATION_TITLE_STR)) { + tipInfoLabel.setText(APPLICATION_TIP_STR); + tipIconLabel.setIcon(IconLoader.getIcon("/images/application_tuning.png", getClass())); + applicationBtn.setBorder(BorderFactory.createLineBorder(new Color(0, 117, 255), 2)); + systemBtn.setBorder(null); + applicationBtn.setForeground(JBColor.foreground().brighter()); + systemBtn.setForeground(JBColor.foreground()); + } + if (name.equals(SYSTEM_TITLE_STR)) { + tipInfoLabel.setText(SYSTEM_TIP_STR); + tipIconLabel.setIcon(IconLoader.getIcon("/images/system_tuning.png", getClass())); + applicationBtn.setBorder(null); + systemBtn.setBorder(BorderFactory.createLineBorder(new Color(0, 117, 255), 2)); + applicationBtn.setForeground(JBColor.foreground()); + systemBtn.setForeground(JBColor.foreground().brighter()); + } + mouseReleasedExtra(name); + } + + /** + * mouseReleasedExtra + * + * @param name name + */ + private void mouseReleasedExtra(String name) { + if (name.equals(CHOOSE_BTN_STR)) { + chooseBtn.dispatchEvent(new FocusEvent(chooseBtn, FocusEvent.FOCUS_GAINED, true)); + chooseBtn.requestFocusInWindow(); + tabItem.setVisible(false); + setTabContainer(); + tabContainer.repaint(); + } + if (name.equals(OPEN_FILE_STR)) { + OpenFileDialogUtils.getInstance().showFileOpenDialog(tabItem, this); + } + if (name.equals(TAB_CLOSE_STR)) { + removeAll(); + Constant.jtasksTab.remove(Constant.jtasksTab.indexOfTabComponent(tabPanel)); + add(Constant.jtasksTab); + parentPanel.add(this); + parentPanel.repaint(); + Constant.jtasksTab.updateUI(); + if (Constant.jtasksTab.getTabCount() == 0) { + if (localSessionId != null && localSessionId != 0L) { + SessionManager sessionManager = SessionManager.getInstance(); + sessionManager.deleteSession(localSessionId); + } + removeAll(); + Constant.jtasksTab = null; + welcomePanel.setVisible(true); + } + QuartzManager.getInstance().endExecutor(DEVICE_REFRESH); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + ProfilerChartsView profilerChartsView = ProfilerChartsView.sessionMap.get(localSessionId); + if (Objects.nonNull(profilerChartsView)) { + profilerChartsView.getPublisher().stopRefresh(false); + } + } + } + + /** + * setTabContainer + */ + private void setTabContainer() { + if (tipInfoLabel.getText().contains(APPLICATION_TITLE_STR)) { + ApplicationConfigPanel taskScenePanel = new ApplicationConfigPanel(this); + tabContainer.setLayout(new BorderLayout()); + tabContainer.setOpaque(true); + tabContainer.setBackground(JBColor.background().darker()); + tabContainer.add(taskScenePanel); + } else if (tipInfoLabel.getText().contains(SYSTEM_TITLE_STR)) { + SystemConfigPanel configPanel = new SystemConfigPanel(this); + tabContainer.setLayout(new BorderLayout()); + tabContainer.setOpaque(true); + tabContainer.setBackground(JBColor.background().darker()); + tabContainer.add(configPanel); + } else { + // Distributed Scenario + tabItem.setVisible(true); + } + } + + @Override + public void mouseEntered(MouseEvent mouseEvent) { + } + + @Override + public void mouseExited(MouseEvent mouseEvent) { + } + + public JBLabel getTabCloseBtn() { + return tabCloseBtn; + } + + /** + * getChooseButton + * + * @return JButton + */ + public JButton getChooseButton() { + return chooseBtn; + } + + public JBPanel getTabContainer() { + return tabContainer; + } + + public JBPanel getTabItem() { + return tabItem; + } + + public JBPanel getTabRightPanel() { + return tabRightPanel; + } + + public JBPanel getTabLeftPanel() { + return tabLeftPanel; + } + + public JButton getTabAddBtn() { + return tabAddBtn; + } + + public JBPanel getBtnPanel() { + return btnPanel; + } + + public void setLocalSessionId(Long localSessionId) { + this.localSessionId = localSessionId; + } + + public Long getLocalSessionId() { + return localSessionId; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/WelcomePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/WelcomePanel.java new file mode 100644 index 000000000..5eb4d8b09 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/WelcomePanel.java @@ -0,0 +1,166 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.UtConstant; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +/** + * WelcomePanel class + */ +public class WelcomePanel extends JBPanel implements MouseListener { + private static final String NEW_BUTTON_STR = " + New Task"; + private static final String WELCOME_TITLE_STR = "Welcome HosProfiler"; + private static final String WELCOME_TIP_STR = "Click New Task Button to process or load a capture"; + + private JBLabel newTaskBtn; + private JBPanel newTaskBgPanel; + private JBLabel picImg; + private JBLabel welcomeTitleLabel; + private JBLabel welcomeTipLabel; + + /** + * WelcomePanel + */ + public WelcomePanel() { + initComponents(); + } + + /** + * initComponents + */ + private void initComponents() { + // init + setLayout(new MigLayout("inset 0", "[grow,fill]", + "[fill,fill]push[]push")); + // init newTaskBtn + newTaskBtn = new JBLabel(NEW_BUTTON_STR, JBLabel.CENTER); + newTaskBtn.setOpaque(true); + newTaskBtn.setBackground(JBColor.background().darker()); + newTaskBtn.setBounds(20, 6, 117, 20); + newTaskBtn.setName(UtConstant.UT_WELCOME_PANEL_NEW_TASK_BTN); + // init newTaskBgPanel + newTaskBgPanel = new JBPanel(null); + newTaskBgPanel.setBackground(JBColor.background()); + newTaskBgPanel.add(newTaskBtn); + // init tip + picImg = new JBLabel(); + picImg.setIcon(IconLoader.getIcon("/images/pic.png", getClass())); + picImg.setHorizontalAlignment(SwingConstants.CENTER); + picImg.setVerticalAlignment(SwingConstants.CENTER); + welcomeTitleLabel = new JBLabel(); + welcomeTitleLabel.setText(WELCOME_TITLE_STR); + welcomeTitleLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); + welcomeTitleLabel.setOpaque(false); + welcomeTitleLabel.setForeground(JBColor.foreground().brighter()); + welcomeTitleLabel.setHorizontalAlignment(SwingConstants.CENTER); + welcomeTipLabel = new JBLabel(); + welcomeTipLabel.setText(WELCOME_TIP_STR); + welcomeTipLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); + welcomeTipLabel.setForeground(JBColor.foreground().darker()); + welcomeTipLabel.setOpaque(false); + welcomeTipLabel.setHorizontalAlignment(SwingConstants.CENTER); + JBPanel containPanel = new JBPanel(new MigLayout("inset 0", "[grow,fill]", + "[fill,fill]")); + containPanel.add(picImg, "wrap"); + containPanel.add(welcomeTitleLabel, "wrap, height 30!"); + containPanel.add(welcomeTipLabel, "wrap, height 30!"); + containPanel.setBackground(JBColor.background().darker()); + containPanel.setOpaque(true); + // add the Component + add(newTaskBgPanel, "wrap, height 30!"); + add(containPanel, "center"); + setBackground(JBColor.background().darker()); + setOpaque(true); + newTaskBtn.addMouseListener(this); + } + + /** + * mouseClicked + * + * @param event MouseEvent + */ + @Override + public void mouseClicked(MouseEvent event) { + Object parentComponent = getParent(); + if (parentComponent instanceof JBPanel) { + JBPanel containerPanel = (JBPanel) parentComponent; + if (Constant.jtasksTab == null || Constant.jtasksTab.getTabCount() == 0) { + Constant.jtasksTab = new JBTabbedPane(); + } + new TaskPanel(containerPanel, this); + setVisible(false); + containerPanel.updateUI(); + containerPanel.repaint(); + } + } + + /** + * mousePressed + * + * @param event MouseEvent + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * mouseReleased + * + * @param event MouseEvent + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * mouseEntered + * + * @param event MouseEvent + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * mouseExited + * + * @param event MouseEvent + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * getNewTaskBtn + * + * @return JBLabel + */ + public JBLabel getNewTaskBtn() { + return newTaskBtn; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemTitleView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemTitleView.java deleted file mode 100644 index c904ae36d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemTitleView.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.OperationUtils; - -import javax.swing.JPanel; -import java.awt.BasicStroke; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.math.BigDecimal; - -import static ohos.devtools.views.common.ColorConstants.ITEM_PANEL; -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_WIDTH; - -/** - * Chart标题栏的抽象父类 - * - * @since 2021/4/22 15:42 - */ -public abstract class AbsItemTitleView extends JPanel implements MouseListener, MouseMotionListener { - /** - * 最底层面板 - */ - protected final ProfilerChartsView bottomPanel; - - /** - * 标题名称 - */ - private final String name; - - /** - * 构造函数 - * - * @param bottomPanel 最底层面板 - * @param name 指标项名称 - */ - public AbsItemTitleView(ProfilerChartsView bottomPanel, String name) { - this.bottomPanel = bottomPanel; - this.name = name; - this.setLayout(new FlowLayout(FlowLayout.LEFT)); - // 标题颜色 - this.setBackground(ITEM_PANEL); - // 这里宽度随意给一个值,渲染时Swing会自动把宽度铺满容器 - this.setPreferredSize(new Dimension(LABEL_DEFAULT_WIDTH, LABEL_DEFAULT_HEIGHT)); - this.addMouseListener(this); - this.addMouseMotionListener(this); - } - - @Override - public void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - drawMouseRuler(graphics); - drawSelectedRuler(graphics); - } - - /** - * 绘制跟随鼠标的标尺 - * - * @param graphics Graphics - */ - private void drawMouseRuler(Graphics graphics) { - int mouseX; - Point mousePoint = getMousePosition(); - if (mousePoint == null) { - // 没有鼠标位置时,绘制标尺的X坐标为0,或鼠标当前进入的组件为空,则不需要绘制 - if (this.bottomPanel.getRulerXCoordinate() == 0 || this.bottomPanel.getCurrentEntered() == null) { - return; - } - - // 绘制标尺的X坐标,以Chart和Timeline起点为0点 - mouseX = this.bottomPanel.getRulerXCoordinate(); - } else { - mouseX = (int) mousePoint.getX(); - // 绘制标尺的X坐标,以Chart和Timeline起点为0点 - this.bottomPanel.setRulerXCoordinate(mouseX); - } - Graphics graphic = graphics.create(); - Graphics2D graphicD = null; - if (graphic instanceof Graphics2D) { - graphicD = (Graphics2D) graphic; - } - // 获取原始线条特征 - Stroke stroke = graphicD.getStroke(); - BasicStroke defaultStroke = null; - if (stroke instanceof BasicStroke) { - defaultStroke = (BasicStroke) stroke; - } - float[] dash = {LayoutConstants.FLOAT_VALUE, 0f, LayoutConstants.FLOAT_VALUE}; - // 定义虚线条特征 - BasicStroke bs = - new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash, LayoutConstants.FLOAT_VALUE); - graphicD.setColor(ColorConstants.RULER); - graphicD.setStroke(bs); - graphicD.drawLine(mouseX, this.getY(), mouseX, this.getHeight()); - graphicD.setStroke(defaultStroke); - // 把当前组件标记为已绘制,刷新其他组件的标尺 - this.bottomPanel.compRulerDrawn(this); - this.bottomPanel.refreshCompRuler(); - } - - /** - * 绘制框选时的标尺 - * - * @param graphics Graphics - */ - private void drawSelectedRuler(Graphics graphics) { - ChartDataRange selectedRange = this.bottomPanel.getObserver().getStandard().getSelectedRange(); - if (selectedRange != null) { - graphics.setColor(ColorConstants.RULER); - int maxDisplay = this.bottomPanel.getObserver().getStandard().getMaxDisplayMillis(); - BigDecimal pixelPerTime = OperationUtils.divide(this.getWidth(), maxDisplay); - int startCoordinate = calcStartCoordinate(pixelPerTime); - - int startTime = this.bottomPanel.getObserver().getStandard().getDisplayRange().getStartTime(); - int offsetStartTime = selectedRange.getStartTime() - startTime; - int selectStartX = startCoordinate + OperationUtils.multiply(pixelPerTime, offsetStartTime); - // 绘制框选起始点的竖线 - graphics.drawLine(selectStartX, this.getY(), selectStartX, this.getHeight()); - - int offsetEndTime = selectedRange.getEndTime() - startTime; - int selectEndX = startCoordinate + OperationUtils.multiply(pixelPerTime, offsetEndTime); - // 绘制框选结束点的竖线 - graphics.drawLine(selectEndX, this.getY(), selectEndX, this.getHeight()); - } - } - - /** - * 出起始坐标startCoordinate,这一块和Timeline的一样 - * - * @param pixelPerTime 比例 - * @return int - */ - private int calcStartCoordinate(BigDecimal pixelPerTime) { - int maxDisplay = this.bottomPanel.getObserver().getStandard().getMaxDisplayMillis(); - int displayEndTime = this.bottomPanel.getObserver().getStandard().getDisplayRange().getEndTime(); - int startCoordinate; - if (displayEndTime > maxDisplay) { - startCoordinate = 0; - } else { - startCoordinate = this.getWidth() - OperationUtils.multiply(pixelPerTime, displayEndTime); - } - return startCoordinate; - } - - @Override - public void mouseClicked(MouseEvent mouseEvent) { - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - } - - @Override - public void mouseReleased(MouseEvent mouseEvent) { - } - - @Override - public void mouseEntered(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标进入,则更新底层父级panel的currentEntered - this.bottomPanel.setCurrentEntered(this); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - // 当前组件需要绘制标尺,鼠标退出,则更新底层父级panel的currentEntered为null - this.bottomPanel.setCurrentEntered(null); - - // 这里需要重绘一下当前界面,否则会残留有之前的ruler - this.bottomPanel.resetRulerDrawStatus(); - this.bottomPanel.refreshCompRuler(); - } - - @Override - public void mouseDragged(MouseEvent mouseEvent) { - } - - @Override - public void mouseMoved(MouseEvent mouseEvent) { - // 鼠标移动,则所有组件的标尺需要重新绘制 - this.bottomPanel.resetRulerDrawStatus(); - this.repaint(); - this.revalidate(); - } - - public String getName() { - return name; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemView.java deleted file mode 100644 index ebaa048b4..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/AbsItemView.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import ohos.devtools.views.charts.ProfilerChart; - -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import static ohos.devtools.views.common.ViewConstants.NUM_3; - -/** - * The abstract parent class of the view panel of each indicator analysis item - * - * @version 1.0 - * @date 2021/2/25 17:22 - */ -public abstract class AbsItemView extends JPanel { - /** - * Index item name - */ - protected String itemName; - - /** - * Chart - */ - protected ProfilerChart chart; - - /** - * Bottom panel - */ - protected ProfilerChartsView bottomPanel; - - /** - * The parent container of the current view - * - * @see "For custom zoom" - */ - protected ItemViewsPanel parent; - - /** - * The Y-axis coordinate of the current panel in the parent panel, that is, the Y-axis offset - */ - private int coordinateY; - - /** - * Constructor - * - * @param bottomPanel Bottom panel - * @param parent The parent container of the current view - * @param coordinateY The Y-axis coordinate of the current panel in the parent panel, that is, the Y-axis offset - */ - public AbsItemView(ProfilerChartsView bottomPanel, ItemViewsPanel parent, int coordinateY) { - super(true); - this.bottomPanel = bottomPanel; - this.parent = parent; - this.coordinateY = coordinateY; - this.setLayout(new BorderLayout()); - this.addMouseMotionListener(new MouseAdapter() { - @Override - public void mouseDragged(MouseEvent mouseEvent) { - dragEvent(mouseEvent); - } - - @Override - public void mouseMoved(MouseEvent mouseEvent) { - moveEvent(mouseEvent); - } - }); - } - - /** - * Initialize the title panel - * - * @param itemName Panel name - */ - protected void initTitlePanel(String itemName) { - this.itemName = itemName; - ItemTitleView itemTitleView = new ItemTitleView(this.bottomPanel, itemName); - this.add(itemTitleView, BorderLayout.NORTH); - // 标题面板需要绘制标尺,把他加入集合 - this.bottomPanel.addRulerComp(itemTitleView); - } - - /** - * Custom mouse drag events to achieve vertical zoom - * - * @param mouseEvent MouseEvent - */ - private void dragEvent(MouseEvent mouseEvent) { - // 鼠标在当前组件中的Y轴坐标,即为缩放时当前组件的高度 - int newHeight = mouseEvent.getY(); - // 目前只允许在Chart下方进行拖拽缩放,也就是mouseMoved中,鼠标变为resize之后 - if (this.getCursor().getType() == Cursor.S_RESIZE_CURSOR) { - this.setBounds(0, coordinateY, mouseEvent.getComponent().getWidth(), newHeight); - // 刷新父Panel,重新调整各个指标项面板的大小 - parent.resizeItemsByDrag(); - } - } - - /** - * Custom mouse movement events, change the mouse style - * - * @param mouseEvent MouseEvent - */ - private void moveEvent(MouseEvent mouseEvent) { - int mouseY = mouseEvent.getY(); - // 只监听鼠标靠近Panel底部时将样式修改为resize,顶部不允许resize - if (Math.abs(this.getHeight() - mouseY) < NUM_3) { - this.setCursor(new Cursor(Cursor.S_RESIZE_CURSOR)); - } else { - this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - - this.repaint(); - this.revalidate(); - } - - public ProfilerChart getChart() { - return chart; - } - - /** - * Setter - * - * @param coordinateY int - */ - public void setCoordinateY(int coordinateY) { - this.coordinateY = coordinateY; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/CountingThread.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/CountingThread.java similarity index 63% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/CountingThread.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/CountingThread.java index 6e466fb2f..75cd57861 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/CountingThread.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/CountingThread.java @@ -13,30 +13,31 @@ * limitations under the License. */ -package ohos.devtools.views.layout.swing; +package ohos.devtools.views.layout.chartview; import ohos.devtools.views.common.LayoutConstants; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import javax.swing.JLabel; +import javax.swing.*; import java.util.Locale; /** - * 数字时钟计时器 - * - * @version 1.0 - * @date 2021/03/25 17:00 - **/ + * CountingThread + */ public class CountingThread extends Thread { private static final Logger LOGGER = LogManager.getLogger(CountingThread.class); - private int hours = 0; private int minutes = 0; private int seconds = 0; private JLabel jTextArea; private boolean stopFlag = false; + /** + * CountingThread + * + * @param jTextArea + */ public CountingThread(JLabel jTextArea) { this.jTextArea = jTextArea; } @@ -55,19 +56,26 @@ public class CountingThread extends Thread { if (seconds > LayoutConstants.NUMBER_SECONDS) { continue; } - jTextArea.setText("| " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + String - .format(Locale.ENGLISH, "%02d", minutes) + ":" + String.format(Locale.ENGLISH, "%02d", seconds)); - seconds++; - if (seconds > LayoutConstants.NUMBER_SECONDS) { - seconds = 0; - minutes++; - if (minutes > LayoutConstants.NUMBER_SECONDS) { - minutes = 0; - hours++; + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + jTextArea.setText("Run 1 of 1 | " + String.format(Locale.ENGLISH, "%02d", hours) + + ":" + String + .format(Locale.ENGLISH, "%02d", minutes) + ":" + String + .format(Locale.ENGLISH, "%02d", seconds)); + seconds++; + if (seconds > LayoutConstants.NUMBER_SECONDS) { + seconds = 0; + minutes++; + if (minutes > LayoutConstants.NUMBER_SECONDS) { + minutes = 0; + hours++; + } + } } - } + }); } - jTextArea.setText("| 0:0:0"); + jTextArea.setText("Run 1 of 1 | 00:00:00"); } /** diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemTitleView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemTitleView.java deleted file mode 100644 index 3ef714500..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemTitleView.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import javax.swing.JLabel; -import java.awt.Dimension; - -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_WIDTH; - -/** - * 指标项标题面板 - * - * @see "包含名称(Memory,CPU等)" - * @since 2021/2/8 9:39 - */ -public class ItemTitleView extends AbsItemTitleView { - /** - * 构造函数 - * - * @param bottomPanel 最底层面板 - * @param name 指标项名称 - */ - public ItemTitleView(ProfilerChartsView bottomPanel, String name) { - super(bottomPanel, name); - initTitle(); - } - - private void initTitle() { - JLabel title = new JLabel(this.getName()); - title.setPreferredSize(new Dimension(LABEL_DEFAULT_WIDTH, LABEL_DEFAULT_HEIGHT)); - this.add(title); - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemViewsPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemViewsPanel.java deleted file mode 100644 index 9c6aad839..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemViewsPanel.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import ohos.devtools.views.common.ProfilerMonitorItem; - -import javax.swing.JPanel; -import java.awt.GridLayout; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.util.ArrayList; -import java.util.List; - -import static ohos.devtools.views.common.ColorConstants.CHART_BG; -import static ohos.devtools.views.common.ViewConstants.CHART_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.CHART_INIT_WIDTH; - -/** - * Save the custom layout panel of each indicator item View - * - * @since 2021/2/25 17:26 - */ -public class ItemViewsPanel extends JPanel { - /** - * Bottom panel - */ - private final ProfilerChartsView bottomPanel; - - /** - * Save the collection of each indicator item View - */ - private final List items; - - /** - * Constructor - * - * @param bottomPanel Bottom panel - */ - public ItemViewsPanel(ProfilerChartsView bottomPanel) { - super(true); - this.bottomPanel = bottomPanel; - this.items = new ArrayList<>(); - // Do not use the Swing preset layout, use a custom absolute layout, one observation item is paved. - // See the addMonitorItemView() method for the layout - this.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent exception) { - resizeItemsByComponent(exception); - } - }); - this.setBackground(CHART_BG); - } - - /** - * Add a monitored metric item view - * - * @param item Index item enumeration class - */ - void addMonitorItemView(ProfilerMonitorItem item) { - // Create a Chart panel for each row - int offsetY = this.items.size() * CHART_DEFAULT_HEIGHT; - AbsItemView itemView; - if (item != ProfilerMonitorItem.MEMORY) { - return; - } - - itemView = new MemoryItemView(bottomPanel, this, offsetY); - // The current Panel is an absolute layout, you must specify the position, and then add to the current Panel - itemView.setBounds(0, offsetY, CHART_INIT_WIDTH, CHART_DEFAULT_HEIGHT); - // Add to layout - this.add(itemView); - // Add to collection for zoom - this.items.add(itemView); - // Set the layout. When there is an observation item, - // it should cover the middle area. Do not use the Swing preset layout, use a custom absolute layout - if (this.items.size() == 1) { - this.setLayout(new GridLayout()); - } - if (this.items.size() > 1) { - this.setLayout(null); - } - this.repaint(); - this.revalidate(); - } - - /** - * Triggered by a drag event: resize all indicator items - */ - void resizeItemsByDrag() { - int refreshOffsetY = 0; - for (AbsItemView item : items) { - // Save offset - item.setCoordinateY(refreshOffsetY); - item.setBounds(0, refreshOffsetY, item.getWidth(), item.getHeight()); - refreshOffsetY += item.getHeight(); - } - - this.repaint(); - this.revalidate(); - } - - /** - * Triggered by the current component size change: re-adjust the size of all indicator items - * - * @param componentEvent Component Event - */ - void resizeItemsByComponent(ComponentEvent componentEvent) { - for (AbsItemView item : items) { - item.setSize(componentEvent.getComponent().getWidth(), item.getHeight()); - } - this.repaint(); - this.revalidate(); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemsView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemsView.java new file mode 100644 index 000000000..ec62a5477 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ItemsView.java @@ -0,0 +1,227 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.layout.chartview.memory.MemoryItemView; + +import javax.swing.SpringLayout; +import javax.swing.SpringLayout.Constraints; +import java.awt.Dimension; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import static javax.swing.Spring.constant; +import static javax.swing.Spring.minus; +import static javax.swing.SpringLayout.EAST; +import static javax.swing.SpringLayout.SOUTH; + +/** + * Save the custom layout panel of each indicator item View + */ +public class ItemsView extends JBPanel { + private static final int ITEM_MIN_EXPAND_HEIGHT = 400; + private static final int ITEM_MIN_HEIGHT = 175; + private final SpringLayout spring = new SpringLayout(); + private final ProfilerChartsView bottomPanel; + private final List items; + private int showHeight; + private int itemFoldHeight; + + /** + * Constructor + * + * @param bottomPanel ProfilerChartsView + */ + public ItemsView(ProfilerChartsView bottomPanel) { + this.setLayout(spring); + this.bottomPanel = bottomPanel; + this.items = new ArrayList<>(); + this.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + adjustLayout(event.getComponent().getWidth()); + } + }); + } + + void updateShowHeight(int showHeight) { + this.showHeight = showHeight; + adjustLayout(this.getWidth()); + } + + /** + * update need ShowTable View + */ + void updateShowTableView() { + for (MonitorItemView item : items) { + if (item instanceof MemoryItemView) { + MemoryItemView memoryItemView = (MemoryItemView) item; + JBPanel heapViewPanel = memoryItemView.getHeapViewPanel(); + if (heapViewPanel != null) { + memoryItemView.remove(heapViewPanel); + } + } + } + } + + /** + * Add a monitor item view + * + * @param item Profiler monitor item enum + * @throws NoSuchMethodException + * @throws IllegalAccessException + * @throws InvocationTargetException + * @throws InstantiationException + */ + void addMonitorItemView(ProfilerMonitorItem item) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + MonitorItemView itemView = item.getClazz().getConstructor().newInstance(); + itemView.init(bottomPanel, this, item); + this.add(itemView); + items.add(itemView); + // Add item constraints + if (items.size() == 1) { + itemView.setPreferredSize(new Dimension(this.getWidth(), this.getHeight())); + spring.putConstraint(EAST, itemView, minus(constant(0)), EAST, this); + Constraints currentCons = spring.getConstraints(itemView); + currentCons.setX(constant(0)); + currentCons.setY(constant(0)); + } else { + Constraints previousCons = spring.getConstraints(items.get(items.size() - 1)); + Constraints currentCons = spring.getConstraints(itemView); + currentCons.setX(constant(0)); + // When there is more than one item, the current item is placed in the SOUTH of the previous one + currentCons.setY(previousCons.getConstraint(SOUTH)); + currentCons.setConstraint(EAST, previousCons.getConstraint(EAST)); + } + adjustLayout(this.getWidth()); + } + + /** + * Adjust the layout of the current view,including constraints and size + * + * @param width width of this view + */ + private void adjustLayout(int width) { + if (items.size() == 0) { + return; + } + + if (items.size() == 1) { + items.get(0).setPreferredSize(new Dimension(width, this.getHeight())); + return; + } + + // Calculate and save the single item height when all items are folded + int heightSize = items.size() * ITEM_MIN_HEIGHT; + boolean flag = heightSize > showHeight; + itemFoldHeight = flag ? ITEM_MIN_HEIGHT : showHeight / items.size(); + + if (isItemExpend()) { + // If an item is expanded, there is no need to change the height + items.forEach(item -> { + int oldHeight = Double.valueOf(item.getPreferredSize().getHeight()).intValue(); + item.setPreferredSize(new Dimension(width, oldHeight)); + }); + } else { + items.forEach(item -> item.setPreferredSize(new Dimension(width, itemFoldHeight))); + } + + // When there is only one item, there is no need to adjust the constraint + if (items.size() > 1) { + adjustConstraints(); + } + // Adjust the height of current view + adjustTotalSize(); + } + + private boolean isItemExpend() { + boolean expend = false; + for (MonitorItemView item : items) { + if (!item.isFold()) { + expend = true; + break; + } + } + return expend; + } + + private void adjustConstraints() { + int size = items.size(); + for (int index = 1; index < size; index++) { + Constraints previousCons = spring.getConstraints(items.get(index - 1)); + Constraints currentCons = spring.getConstraints(items.get(index)); + currentCons.setX(constant(0)); + // the current item is placed in the SOUTH of the previous one + currentCons.setY(previousCons.getConstraint(SOUTH)); + currentCons.setConstraint(EAST, previousCons.getConstraint(EAST)); + } + } + + private void adjustTotalSize() { + int totalHeight = calcTotalHeight(); + this.setPreferredSize(new Dimension(this.getWidth(), totalHeight)); + } + + private int calcTotalHeight() { + int total = 0; + for (MonitorItemView item : items) { + total += Double.valueOf(item.getPreferredSize().getHeight()).intValue(); + } + return total; + } + + /** + * Fold or expend the item + * + * @param fold ture: fold, false: expand + * @param item Monitor item view + */ + public void itemFoldOrExpend(boolean fold, MonitorItemView item) { + if (items.size() == 1) { + return; + } + + int newHeight; + if (fold) { + newHeight = itemFoldHeight; + } else { + newHeight = ITEM_MIN_EXPAND_HEIGHT; + } + item.setPreferredSize(new Dimension(this.getWidth(), newHeight)); + adjustLayout(this.getWidth()); + } + + /** + * Click on chart of chart, expand item + * + * @param item MonitorItemView + */ + public void itemChartClick(MonitorItemView item) { + if (items.size() > 1) { + item.setPreferredSize(new Dimension(this.getWidth(), showHeight)); + adjustLayout(this.getWidth()); + } + } + + public List getItems() { + return items; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/LoadingPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/LoadingPanel.java new file mode 100644 index 000000000..db56f9fec --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/LoadingPanel.java @@ -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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; + +import javax.swing.ImageIcon; +import java.awt.BorderLayout; +import java.net.URL; + +import static java.awt.Image.SCALE_DEFAULT; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.LOADING_SIZE; + +/** + * Loading Panel + */ +public class LoadingPanel extends JBPanel { + /** + * Constructor + */ + public LoadingPanel() { + this.setLayout(new BorderLayout()); + JBLabel loadingLabel; + URL url = getClass().getClassLoader().getResource("images/loading.gif"); + if (url == null) { + loadingLabel = new JBLabel("Loading..."); + } else { + ImageIcon icon = new ImageIcon(url); + icon.setImage(icon.getImage().getScaledInstance(LOADING_SIZE, LOADING_SIZE, SCALE_DEFAULT)); + loadingLabel = new JBLabel(icon, JBLabel.CENTER); + } + this.add(loadingLabel, BorderLayout.CENTER); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryItemView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryItemView.java deleted file mode 100644 index c396113a3..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryItemView.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import ohos.devtools.views.charts.FilledLineChart; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.tooltip.LegendTooltip; -import ohos.devtools.views.layout.chartview.observer.MemoryChartObserver; - -import javax.swing.ImageIcon; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import static ohos.devtools.views.common.ColorConstants.CHART_BG; -import static ohos.devtools.views.common.ViewConstants.CHART_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.CHART_INIT_WIDTH; -import static ohos.devtools.views.common.ViewConstants.NUM_2; - -/** - * 内存指标分析项的视图面板 - * - * @since 2021/1/23 11:40 - */ -public class MemoryItemView extends AbsItemView { - /** - * 视图名称 - */ - private static final String NAME = "Memory"; - - /** - * 构造函数 - * - * @param bottomPanel 最底层面板 - * @param parent 当前视图的父级容器 - * @param coordinateY 当前面板在父级面板中的Y轴坐标,即Y轴偏移量 - */ - public MemoryItemView(ProfilerChartsView bottomPanel, ItemViewsPanel parent, int coordinateY) { - super(bottomPanel, parent, coordinateY); - // 初始化标题面板 - initTitlePanel(NAME); - // 添加Chart - addChart(); - } - - /** - * 添加Chart面板 - */ - private void addChart() { - chart = new FilledLineChart(this.bottomPanel); - chart.setMaxDisplayX(this.bottomPanel.getObserver().getStandard().getMaxDisplayMillis()); - chart.setMinMarkIntervalX(this.bottomPanel.getObserver().getStandard().getMinMarkInterval()); - chart.setSectionNumY(NUM_2); - chart.setAxisLabelY("MB"); - // 这里宽度给一个预设值,后面要根据chartPanel的宽度改变 - chart.setBounds(0, 0, CHART_INIT_WIDTH, CHART_DEFAULT_HEIGHT); - // Chart添加点击事件,点击后进入二级界面 - chart.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - MemoryStageView memoryStageView = bottomPanel.addMemoryStageView(); - memoryStageView.addChart(); - // 隐藏Tooltip,否则进入二级界面后,Tooltip仍然显示一级界面的数组 - LegendTooltip.getInstance().hideTip(); - // 手动刷新一次界面,否则暂停后进入二级界面Chart不会绘制 - ChartDataRange range = bottomPanel.getObserver().getStandard().getDisplayRange(); - bottomPanel.getObserver().notifyRefresh(range.getStartTime(), range.getEndTime()); - // 根据AbleUnfoldTable属性判断是否是选中状态 - if (bottomPanel.isAbleUnfoldTable()) { - bottomPanel.getTaskScenePanelChart().getjButtonBottom().setIcon(new ImageIcon( - MemoryItemView.class.getClassLoader().getResource("images/button_bottom_bar.png"))); - } else { - bottomPanel.getTaskScenePanelChart().getjButtonBottom().setIcon(new ImageIcon( - MemoryItemView.class.getClassLoader().getResource("images/button_bottom_bar_grey.png"))); - } - } - }); - - // 创建只存放Chart的面板,保证Chart可以正常添加至其他面板 - JPanel onlyChartPanel = new JPanel(null); - onlyChartPanel.add(chart); - // 添加chart面板背景颜色 - onlyChartPanel.setBackground(CHART_BG); - // 添加监听事件,面板宽高改变的时候要修改Chart的宽高 - onlyChartPanel.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent componentEvent) { - chart.setBounds(0, 0, componentEvent.getComponent().getWidth(), - componentEvent.getComponent().getHeight()); - onlyChartPanel.repaint(); - onlyChartPanel.revalidate(); - } - }); - - // Chart需要绘制标尺,把他加入集合 - this.bottomPanel.addRulerComp(chart); - // 把Chart观察者注册到主界面,监听主界面的刷新时事件 - MemoryChartObserver chartObserver = new MemoryChartObserver(chart, bottomPanel.getSessionId()); - this.bottomPanel.getObserver().attach(chartObserver); - - this.add(onlyChartPanel, BorderLayout.CENTER); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageTitleView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageTitleView.java deleted file mode 100644 index ae456de46..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageTitleView.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import com.intellij.openapi.ui.ComboBox; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.chart.ProfilerTimeline; -import ohos.devtools.views.layout.swing.LevelTablePanel; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; -import java.awt.Dimension; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import static ohos.devtools.views.common.ColorConstants.ITEM_PANEL; -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.LABEL_DEFAULT_WIDTH; - -/** - * @Description 二级界面标题面板 - * @Date 2021/2/2 19:02 - **/ -public class MemoryStageTitleView extends AbsItemTitleView { - private final MemoryStageView memoryStageView; - - /** - * @param bottomPanel 最底层面板 - * @param name 二级页面的标题名称 - * @param memoryStageView 二级页面 - */ - public MemoryStageTitleView(ProfilerChartsView bottomPanel, String name, MemoryStageView memoryStageView) { - super(bottomPanel, name); - this.memoryStageView = memoryStageView; - initBackTitle(); - initCheckBox(name); - } - - /** - * 初始化标题 - */ - private void initBackTitle() { - JButton jButtonRun = new JButton( - new ImageIcon(MemoryStageTitleView.class.getClassLoader().getResource("images/backtrack.png"))); - jButtonRun.setPreferredSize(new Dimension(LABEL_DEFAULT_HEIGHT, LABEL_DEFAULT_HEIGHT)); - jButtonRun.setBorder(null); - jButtonRun.setBackground(ITEM_PANEL); - jButtonRun.setOpaque(false); - this.add(jButtonRun); - jButtonRun.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - bottomPanel.getObserver().detach(memoryStageView.getChartObserver()); - bottomPanel.removeStageView(memoryStageView); - bottomPanel.resumeMonitorItemView(); - bottomPanel.getTaskScenePanelChart().getjButtonBottom().setIcon(new ImageIcon( - MemoryStageTitleView.class.getClassLoader().getResource("images/button_bottom_bar_grey.png"))); - bottomPanel.setFlagDown(false); - bottomPanel.getTimeline().removeTablePanel(); - hideLeftTable(); - } - }); - } - - private void initCheckBox(String name) { - ComboBox jComboBox = new ComboBox<>(); - jComboBox.setBorder(null); - jComboBox.addItem(name); - jComboBox.setBackground(ITEM_PANEL); - jComboBox.setBounds(LayoutConstants.CHOOSE_HEIGHT, LayoutConstants.JLABEL_SIZE, LABEL_DEFAULT_WIDTH, - LABEL_DEFAULT_HEIGHT); - this.add(jComboBox); - } - - /** - * 隐藏右边列表 - */ - private void hideLeftTable() { - ProfilerTimeline timeline = bottomPanel.getTimeline(); - if (timeline != null) { - LevelTablePanel levelTablePanel = timeline.getLevelTablePanel(); - if (levelTablePanel != null) { - JPanel suspensionTable = levelTablePanel.getSuspensionTable(); - if (suspensionTable != null) { - suspensionTable.setVisible(false); - } - } - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageView.java deleted file mode 100644 index 5995a791d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MemoryStageView.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview; - -import ohos.devtools.views.charts.FilledLineChart; -import ohos.devtools.views.charts.ProfilerChart; -import ohos.devtools.views.layout.chartview.observer.MemoryStageObserver; - -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; - -import static ohos.devtools.views.common.ColorConstants.CHART_BG; -import static ohos.devtools.views.common.ViewConstants.CHART_DEFAULT_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.CHART_INIT_WIDTH; -import static ohos.devtools.views.common.ViewConstants.NUM_2; - -/** - * MemoryStageView类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class MemoryStageView extends JPanel { - /** - * 视图名称 - */ - private static final String NAME = "Memory"; - - /** - * 最底层面板 - */ - private final ProfilerChartsView bottomPanel; - - private MemoryStageTitleView memoryStageTitleView; - - private ProfilerChart chart; - - private MemoryStageObserver chartObserver; - - /** - * 构造函数 - * - * @param bottomPanel 最底层面板 - */ - public MemoryStageView(ProfilerChartsView bottomPanel) { - super(true); - this.setLayout(new BorderLayout()); - this.bottomPanel = bottomPanel; - initTitlePanel(); - } - - /** - * 初始化标题面板 - */ - private void initTitlePanel() { - memoryStageTitleView = new MemoryStageTitleView(this.bottomPanel, NAME, this); - this.add(memoryStageTitleView, BorderLayout.NORTH); - // 标题面板需要绘制标尺,把他加入集合 - this.bottomPanel.addRulerComp(memoryStageTitleView); - } - - /** - * 添加Chart面板 - */ - public void addChart() { - chart = new FilledLineChart(this.bottomPanel); - chart.setMaxDisplayX(this.bottomPanel.getObserver().getStandard().getMaxDisplayMillis()); - chart.setMinMarkIntervalX(this.bottomPanel.getObserver().getStandard().getMinMarkInterval()); - chart.setSectionNumY(NUM_2); - chart.setAxisLabelY("MB"); - // 这里宽度给一个预设值,后面要根据chartPanel的宽度改变 - chart.setBounds(0, 0, CHART_INIT_WIDTH, CHART_DEFAULT_HEIGHT); - - // 创建只存放Chart的面板,保证Chart可以正常添加至其他面板 - JPanel onlyChartPanel = new JPanel(null); - onlyChartPanel.add(chart); - // 添加chart面板背景颜色 - onlyChartPanel.setBackground(CHART_BG); - // 添加监听事件,面板宽高改变的时候要修改Chart的宽高 - onlyChartPanel.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent componentEvent) { - chart.setBounds(0, 0, componentEvent.getComponent().getWidth(), - componentEvent.getComponent().getHeight()); - onlyChartPanel.repaint(); - onlyChartPanel.revalidate(); - } - }); - - // Chart需要绘制标尺,把他加入集合 - this.bottomPanel.addRulerComp(chart); - // 把Chart观察者注册到主界面,监听主界面的刷新时事件 - chartObserver = new MemoryStageObserver(chart, bottomPanel.getSessionId()); - this.bottomPanel.getObserver().attach(chartObserver); - this.add(onlyChartPanel, BorderLayout.CENTER); - } - - ProfilerChart getChart() { - return chart; - } - - MemoryStageTitleView getItemTitleStagePanel() { - return memoryStageTitleView; - } - - /** - * getChartObserver - * - * @return MemoryStageObserver - */ - public MemoryStageObserver getChartObserver() { - return chartObserver; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/MonitorItemDetail.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemDetail.java similarity index 61% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/MonitorItemDetail.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemDetail.java index c28116c1f..caf8ee60c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/MonitorItemDetail.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemDetail.java @@ -13,16 +13,26 @@ * limitations under the License. */ -package ohos.devtools.views.common; +package ohos.devtools.views.layout.chartview; + +import ohos.devtools.views.common.ColorConstants; import java.awt.Color; /** * 监控项详情,各个二级界面监控项的监控项 - * - * @since 2021/3/1 16:50 */ public enum MonitorItemDetail { + /** + * 内存监控项:Java + */ + CPU_APP(1, "App", ColorConstants.MEM_JAVA), + + /** + * 内存监控项:Native + */ + CPU_SYSTEM(0, "System", ColorConstants.MEM_NATIVE), + /** * 内存监控项:Java */ @@ -56,17 +66,57 @@ public enum MonitorItemDetail { /** * Network监控项:received */ - NETWORK_RCV(1, "received", ColorConstants.NETWORK_RCV), + NETWORK_RCV(0, "Receiving", ColorConstants.NETWORK_RCV), /** * Network监控项:Sent */ - NETWORK_SENT(1, "Sent", ColorConstants.NETWORK_SENT), + NETWORK_SENT(1, "Sending", ColorConstants.NETWORK_SENT), /** * Network监控项:connections */ - NETWORK_CONN(1, "connections", ColorConstants.NETWORK_CONN), + NETWORK_CONN(2, "Connections", ColorConstants.NETWORK_CONN), + + /** + * Energy monitoring item: CPU + */ + ENERGY_CPU(1, "CPU", ColorConstants.ENERGY_CPU), + + /** + * Energy monitoring item: Network + */ + ENERGY_NETWORK(2, "Network", ColorConstants.ENERGY_NETWORK), + + /** + * Energy monitoring item: Location + */ + ENERGY_LOCATION(3, "Location", ColorConstants.ENERGY_LOCATION), + + /** + * Energy monitoring item: System event Location + */ + ENERGY_EVENT_LOCATION(1, "Event Location", ColorConstants.ENERGY_EVENT_LOCATION), + + /** + * Energy monitoring item: System event Wake Locks + */ + ENERGY_EVENT_LOCKS(2, "Wake Locks", ColorConstants.ENERGY_EVENT_LOCKS), + + /** + * Energy monitoring item: System event Alarms&Jobs + */ + ENERGY_EVENT_ALARMS_JOBS(3, "Alarms&Jobs", ColorConstants.ENERGY_EVENT_ALARMS_JOBS), + + /** + * diskIO:Read + */ + DISK_IO_READ(0, "DiskIO_read", ColorConstants.DISK_IO_READ), + + /** + * diskIO:write + */ + DISK_IO_WRITE(1, "DiskIO_write", ColorConstants.DISK_IO_WRITE), /** * 未知项 diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemInterface.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemInterface.java new file mode 100644 index 000000000..1789a1c03 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemInterface.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +/** + * MonitorItemInterface + */ +public interface MonitorItemInterface { + /** + * init + * + * @param bottomPanel bottomPanel + * @param parent parent + * @param item item + */ + void init(ProfilerChartsView bottomPanel, ItemsView parent, ProfilerMonitorItem item); + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemView.java new file mode 100644 index 000000000..c68c70330 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/MonitorItemView.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.charts.ProfilerChart; + +/** + * Abstract parent class profiler monitor item view + */ +public abstract class MonitorItemView extends JBPanel implements MonitorItemInterface { + /** + * bottomPanel + */ + protected ProfilerChartsView bottomPanel; + + /** + * parent + */ + protected ItemsView parent; + + /** + * chart + */ + protected ProfilerChart chart; + + /** + * chart + */ + protected ProfilerChart expandShowChart; + + /** + * fold + */ + protected boolean fold = true; + + /** + * showTable + */ + protected boolean showTable = false; + + public ProfilerChartsView getBottomPanel() { + return bottomPanel; + } + + public ProfilerChart getChart() { + return chart; + } + + public boolean isFold() { + return fold; + } + + public boolean isShowTable() { + return showTable; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/PerformanceIndexPopupMenu.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/PerformanceIndexPopupMenu.java new file mode 100644 index 000000000..3c08dcb08 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/PerformanceIndexPopupMenu.java @@ -0,0 +1,265 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.openapi.ui.JBPopupMenu; +import com.intellij.ui.components.JBCheckBox; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; + +import javax.swing.AbstractButton; +import javax.swing.JCheckBox; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * PerformanceIndexPopupMenu + */ +public class PerformanceIndexPopupMenu { + private static final int OTHER_ITEM = 2; + private static final int HORIZONTAL_GAP = 15; + private static final int VERTICAL_GAP = 13; + private static final int ITEM_WIDTH = 140; + private static final int ITEM_HEIGHT = 20; + private static final int MEMORY_ITEM_PANEL_WIDTH = 160; + private static final int MARGIN_RIGHT = 160; + private static final int MEMORY_ITEM_HEIGHT = 35; + private static final int POPUP_OFFSET = 15; + private static final String ITEM = "item"; + private JBLabel titleLabel = new JBLabel("DataSource"); + private JBCheckBox checkBoxSelectAll = new JBCheckBox("Select all"); + private final LinkedList ITEMS; + private final JBPopupMenu popupMenu; + private final ArrayList allCheckBoxes; + private final List cacheItemList; + private final Map> map; + private final ProfilerChartsView profilerView; + private final List profilerMonitorItemMap; + + /** + * PerformanceIndexPopupMenu constructor + * + * @param profilerView profilerView + */ + public PerformanceIndexPopupMenu(ProfilerChartsView profilerView, long sessionId) { + this.profilerView = profilerView; + ITEMS = new LinkedList<>(); + popupMenu = new JBPopupMenu(); + allCheckBoxes = new ArrayList<>(); + cacheItemList = new ArrayList<>(); + map = new HashMap<>(); + profilerMonitorItemMap = PlugManager.getInstance().getProfilerMonitorItemList(sessionId); + addCheckBoxes(); + addCheckItemsToPanel(); + initItemPreferredSize(); + initDefaultCheck(); + initListener(); + } + + private void initDefaultCheck() { + for (JBCheckBox box : allCheckBoxes) { + box.setSelected(true); + } + } + + private void addCheckBoxes() { + for (ProfilerMonitorItem item : profilerMonitorItemMap) { + ITEMS.add(item.getName()); + } + map.put(ITEM, ITEMS); + for (String str : ITEMS) { + JBCheckBox checkBox = new JBCheckBox(str); + allCheckBoxes.add(checkBox); + } + } + + private void addCheckItemsToPanel() { + JBPanel panel = new JBPanel(new FlowLayout(FlowLayout.LEADING, HORIZONTAL_GAP, VERTICAL_GAP)); + panel.add(titleLabel); + panel.add(checkBoxSelectAll); + for (JBCheckBox box : allCheckBoxes) { + panel.add(box); + } + panel.setPreferredSize( + new Dimension(MEMORY_ITEM_PANEL_WIDTH, (allCheckBoxes.size() + OTHER_ITEM) * MEMORY_ITEM_HEIGHT)); + popupMenu.add(panel); + } + + private void initItemPreferredSize() { + titleLabel.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + checkBoxSelectAll.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + for (JBCheckBox box : allCheckBoxes) { + box.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + } + } + + private void initListener() { + checkBoxSelectAll.addItemListener(event -> { + if (checkBoxSelectAll.isSelected()) { + for (JBCheckBox box : allCheckBoxes) { + box.setSelected(true); + } + } else { + for (JBCheckBox box : allCheckBoxes) { + box.setSelected(false); + } + } + }); + ItemListener itemListener = new ItemListener() { + JCheckBox checkBox; + + /** + * itemStateChanged + * + * @param event event + */ + public void itemStateChanged(ItemEvent event) { + Object sourceObject = event.getSource(); + if (sourceObject instanceof JCheckBox) { + checkBox = (JCheckBox) sourceObject; + String itemStr = checkBox.getText(); + filterItemList(); + if (checkBox.isSelected()) { + addItemView(itemStr); + } else { + reduceItemView(itemStr); + } + profilerView.getItemsView().revalidate(); + profilerView.getItemsView().repaint(); + } + } + }; + for (JBCheckBox box : allCheckBoxes) { + box.addItemListener(itemListener); + } + } + + private void filterItemList() { + List selectedList = + allCheckBoxes.stream().filter(AbstractButton::isSelected).collect(Collectors.toList()); + LinkedList selectedItem = new LinkedList<>(); + for (JBCheckBox jc : selectedList) { + selectedItem.add(jc.getText()); + } + map.put(ITEM, selectedItem); + List items = profilerView.getItemsView().getItems(); + if (cacheItemList.size() == 0) { + cacheItemList.addAll(items); + } + } + + private void addItemView(String selectedStr) { + ItemsView itemsView = profilerView.getItemsView(); + List items = profilerView.getItemsView().getItems(); + Class selectClass = null; + int selectIndex = 0; + // Get the class information according to the selected string + for (ProfilerMonitorItem item : profilerMonitorItemMap) { + if (selectedStr.equals(item.getName())) { + selectClass = item.getClazz(); + selectIndex = item.getIndex(); + } + } + // Add the selected chart item to the chart again + for (MonitorItemView item : cacheItemList) { + if (selectClass.isInstance(item)) { + if (items.size() == 0) { + items.add(item); + itemsView.itemFoldOrExpend(false, item); + } + // Get the index of the item displayed in the interface through enumeration + for (int index = 0; index < items.size(); index++) { + for (ProfilerMonitorItem monitorItem : profilerMonitorItemMap) { + if (monitorItem.getClazz().isInstance(items.get(index))) { + // The selected one is smaller than the first one and is added to the 0 position + if (selectIndex < monitorItem.getIndex() && index == 0) { + items.add(0, item); + itemsView.itemFoldOrExpend(false, item); + return; + } + // The selected one is larger than the last one, so add it directly + if (selectIndex > monitorItem.getIndex() && index == items.size() - 1) { + items.add(item); + itemsView.itemFoldOrExpend(false, item); + return; + } + // add Intermediate item + if (selectIndex < monitorItem.getIndex()) { + items.add(index, item); + itemsView.itemFoldOrExpend(false, item); + return; + } + } + } + } + } + } + if (items.size() == 1) { + items.get(0).setPreferredSize(new Dimension(items.get(0).getWidth(), itemsView.getHeight() - ITEM_HEIGHT)); + } + } + + private void reduceItemView(String notSelectStr) { + List items = profilerView.getItemsView().getItems(); + Class notSelectClass = null; + // Get the class information according to the unselected string + for (ProfilerMonitorItem item : profilerMonitorItemMap) { + if (notSelectStr.equals(item.getName())) { + notSelectClass = item.getClazz(); + } + } + // Delete the item view of chart according to the class information + for (MonitorItemView item : items) { + if (notSelectClass.isInstance(item)) { + hideItem(items, item); + break; + } + } + // resize + ItemsView itemsView = profilerView.getItemsView(); + for (MonitorItemView item : items) { + itemsView.itemFoldOrExpend(true, item); + break; + } + if (items.size() == 1) { + items.get(0).setPreferredSize(new Dimension(items.get(0).getWidth(), itemsView.getHeight() - ITEM_HEIGHT)); + } + } + + private void hideItem(List items, MonitorItemView item) { + item.setPreferredSize(new Dimension(item.getWidth(), 0)); + items.remove(item); + } + + /** + * show ItemMenu + * + * @param event event + */ + public void showItemMenu(MouseEvent event) { + popupMenu.show(event.getComponent(), event.getX() - MARGIN_RIGHT, event.getY() + POPUP_OFFSET); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerChartsView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerChartsView.java index 3c99fbc2e..871defd59 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerChartsView.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerChartsView.java @@ -1,489 +1,347 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.chartview; - -import com.intellij.ui.components.JBLabel; -import ohos.devtools.views.common.ProfilerMonitorItem; -import ohos.devtools.views.common.chart.ProfilerScrollbar; -import ohos.devtools.views.common.chart.ProfilerTimeline; -import ohos.devtools.views.layout.chartview.observer.CacheObserver; -import ohos.devtools.views.layout.chartview.observer.ProfilerChartsViewObserver; -import ohos.devtools.views.layout.chartview.observer.TimelineObserver; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; - -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.Spring; -import javax.swing.SpringLayout; -import javax.swing.SwingWorker; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import static java.awt.Image.SCALE_DEFAULT; -import static javax.swing.SpringLayout.Constraints; -import static ohos.devtools.views.common.ColorConstants.CHART_BG; -import static ohos.devtools.views.common.LayoutConstants.LOADING_SIZE; -import static ohos.devtools.views.common.ViewConstants.NUM_2; -import static ohos.devtools.views.common.ViewConstants.TIMELINE_HEIGHT; -import static ohos.devtools.views.common.ViewConstants.TIMELINE_WIDTH; - -/** - * 监控界面Chart面板,包括顶部Timeline和Chart - * - * @since 2021/1/25 9:30 - */ -public class ProfilerChartsView extends JPanel { - /** - * sessionMap - */ - public static Map sessionMap = new HashMap<>(); - - /** - * sessionId - */ - private final long sessionId; - - /** - * Chart显示界面的Monitor - */ - private final ProfilerChartsViewObserver observer; - - /** - * 保存时间线和监控项的Pane - * - * @see "加这个Panel是由于Java heap的table之前会add到south,和滚动条位置冲突,造成两个组件闪烁" - */ - private final JPanel mainPanel; - - /** - * 保存各个指标项的面板 - */ - private final ItemViewsPanel itemsPanel; - - /** - * 需要绘制标尺的组件集合 - * - * @see "Map<组件,是否已经绘制了标尺>" - */ - private final Map rulerCompMap = new HashMap<>(); - - /** - * 绘制标尺的X坐标,以Chart和Timeline起点为0点 - */ - private int rulerXCoordinate = 0; - - /** - * 鼠标当前进入的组件 - */ - private JComponent currentEntered; - - /** - * 自定义水平滚动条 - */ - private ProfilerScrollbar horizontalBar; - - /** - * 暂停标志 - */ - private boolean flagEnd = false; - - /** - * 停止标志 - */ - private boolean stopFlag = false; - - /** - * 向下扩展标志 - */ - private boolean flagDown = false; - - /** - * 新增配置项标志 - */ - private boolean addItemFlag = false; - - private final TaskScenePanelChart taskScenePanelChart; - - private ProfilerTimeline timeline; - - private JPanel loadingPanel; - - /** - * chart界面的层级判断 - * - * @see "true:二级界面,false:一级界面" - */ - private boolean chartLevel = false; - - /** - * chart界面的是否展开 - * - * @see "true:二级界面,false:一级界面" - */ - private boolean ableUnfoldTable = false; - - /** - * Chart是否在加载(初始化时等待数据库处理数据) - */ - private boolean isLoading = false; - - /** - * 构造函数 - * - * @param sessionId JPanel - * @param isTraceFile 是否为Trace文件静态导入模式 - * @param taskScenePanelChart 用于chart滚动条拖动,获取对象,设置暂停或者开始按钮图标 - */ - public ProfilerChartsView(long sessionId, boolean isTraceFile, TaskScenePanelChart taskScenePanelChart) { - super(true); - this.setOpaque(true); - this.setLayout(new BorderLayout()); - this.setBackground(CHART_BG); - - // 初始化mainPanel并add至当前View - this.mainPanel = new JPanel(new BorderLayout()); - this.mainPanel.setOpaque(true); - this.add(mainPanel, BorderLayout.CENTER); - - this.sessionId = sessionId; - this.taskScenePanelChart = taskScenePanelChart; - this.observer = new ProfilerChartsViewObserver(this, isTraceFile); - // 初始化Timeline - initTimeline(taskScenePanelChart); - // 添加 - CacheObserver chartObserver = new CacheObserver(sessionId); - this.getObserver().attach(chartObserver); - - // 初始化并添加保存各个指标项的布局 - this.itemsPanel = new ItemViewsPanel(this); - this.mainPanel.add(itemsPanel, BorderLayout.CENTER); - sessionMap.put(this.sessionId, this); - // 添加组件大小变化的监听器 - addResizedListener(); - } - - /** - * 添加组件大小变化的监听器 - */ - private void addResizedListener() { - this.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent exception) { - // 组件大小变化时,要调整滚动条的大小和位置 - if (horizontalBar != null) { - horizontalBar.resizeAndReposition(); - } - } - }); - } - - /** - * 初始化Timeline - * - * @param taskScenePanelChart taskScenePanelChart - */ - private void initTimeline(TaskScenePanelChart taskScenePanelChart) { - // 初始化时间线,这里宽高给一个预设值 - timeline = new ProfilerTimeline(this, TIMELINE_WIDTH, TIMELINE_HEIGHT, taskScenePanelChart); - // 保存时间线的绘图标准 - timeline.setMaxDisplayTime(observer.getStandard().getMaxDisplayMillis()); - timeline.setMinMarkInterval(observer.getStandard().getMinMarkInterval()); - - // 创建Timeline的观察者,并注册至主界面 - TimelineObserver timelineObserver = new TimelineObserver(timeline); - observer.attach(timelineObserver); - // Timeline需要绘制标尺,把他加入集合 - this.addRulerComp(timeline); - - // 组件添加至mainPanel - this.mainPanel.add(timeline, BorderLayout.NORTH); - } - - /** - * 初始化水平滚动条 - */ - public void initScrollbar() { - this.horizontalBar = new ProfilerScrollbar(this); - this.mainPanel.add(horizontalBar, BorderLayout.SOUTH); - this.observer.setScrollbarShow(true); - } - - /** - * 移除水平滚动条 - */ - public void removeScrollbar() { - this.observer.setScrollbarShow(false); - if (horizontalBar != null) { - this.mainPanel.remove(horizontalBar); - this.horizontalBar = null; - } - } - - /** - * 显示Loading标识,并且禁用停止和暂停按钮事件 - */ - public void showLoading() { - SpringLayout spring = new SpringLayout(); - loadingPanel = new JPanel(spring); - loadingPanel.setBackground(CHART_BG); - JBLabel loadingLabel = new JBLabel(); - - new SwingWorker<>() { - @Override - protected Object doInBackground() { - URL url = ProfilerChartsView.class.getClassLoader().getResource("images/loading.gif"); - if (url != null) { - ImageIcon icon = new ImageIcon(url); - icon.setImage(icon.getImage().getScaledInstance(LOADING_SIZE, LOADING_SIZE, SCALE_DEFAULT)); - loadingLabel.setIcon(icon); - } - loadingPanel.add(loadingLabel); - - return loadingPanel; - } - - @Override - protected void done() { - // 增加约束,保持Loading图在组件中间 - Constraints loadingCons = spring.getConstraints(loadingLabel); - loadingCons.setX(Spring.constant((loadingPanel.getWidth() - LOADING_SIZE) / NUM_2)); - loadingCons.setY(Spring.constant((loadingPanel.getHeight() - LOADING_SIZE) / NUM_2)); - // 手动触发组件布局事件 - loadingPanel.revalidate(); - - loadingPanel.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent componentEvent) { - super.componentResized(componentEvent); - Constraints loadingCons = spring.getConstraints(loadingLabel); - loadingCons.setX(Spring.constant((loadingPanel.getWidth() - LOADING_SIZE) / NUM_2)); - loadingCons.setY(Spring.constant((loadingPanel.getHeight() - LOADING_SIZE) / NUM_2)); - loadingPanel.revalidate(); - } - }); - - // Loading界面加载完成,现在开始检查Loading结果:Loading完成后启动刷新 - observer.checkLoadingResult(); - } - }.execute(); - - isLoading = true; - this.remove(mainPanel); - this.add(loadingPanel, BorderLayout.CENTER); - } - - /** - * 隐藏Loading标识,并且禁用停止和暂停按钮事件 - */ - public void hideLoading() { - if (loadingPanel != null) { - this.remove(loadingPanel); - } - isLoading = false; - this.add(mainPanel, BorderLayout.CENTER); - } - - /** - * 添加一项监控的指标项视图 - * - * @param item 指标项枚举类 - */ - public void addMonitorItemView(ProfilerMonitorItem item) { - itemsPanel.addMonitorItemView(item); - } - - /** - * 添加内存信息二级视图 - * - * @return MemoryStageView - */ - public MemoryStageView addMemoryStageView() { - chartLevel = true; - removeMonitorItemView(); - MemoryStageView memoryStageItem = new MemoryStageView(this); - this.mainPanel.add(memoryStageItem, BorderLayout.CENTER); - return memoryStageItem; - } - - /** - * 创建二级界面时,移除一级界面的监控项视图 - * - * @see "不能通过visible来实现,这样从二级界面返回一级时,itemsPanel宽高无法自适应" - */ - private void removeMonitorItemView() { - this.mainPanel.remove(itemsPanel); - } - - /** - * 移除二级界面视图 - * - * @param stageView MemoryStageView - */ - void removeStageView(MemoryStageView stageView) { - this.mainPanel.remove(stageView); - // Chart和Title也从标尺Map中移除 - rulerCompMap.remove(stageView.getChart()); - rulerCompMap.remove(stageView.getItemTitleStagePanel()); - } - - /** - * 返回一级界面时,重新添加监控项视图 - */ - void resumeMonitorItemView() { - // 返回一级界面时增加关闭展开 - flagDown = false; - chartLevel = false; - for (Component comp : itemsPanel.getComponents()) { - if (comp instanceof AbsItemView) { - AbsItemView absItemView = (AbsItemView) comp; - absItemView.getChart().initMaxUnitY(); - } - } - this.mainPanel.add(itemsPanel); - } - - /** - * 添加需要绘制标尺的组件 - * - * @param comp JComponent - */ - void addRulerComp(JComponent comp) { - rulerCompMap.put(comp, Boolean.FALSE); - } - - /** - * 组件的标尺已绘制 - * - * @param comp JComponent - */ - public void compRulerDrawn(JComponent comp) { - rulerCompMap.put(comp, Boolean.TRUE); - } - - /** - * 重置组件标尺状态为未绘制 - */ - public void resetRulerDrawStatus() { - rulerCompMap.keySet().forEach((comp -> rulerCompMap.put(comp, Boolean.FALSE))); - } - - /** - * 刷新组件列表的标尺 - */ - public void refreshCompRuler() { - rulerCompMap.forEach((comp, isDrawn) -> { - // 如果已经绘制过,不需要再重复绘制,防止无限循环 - if (!isDrawn) { - comp.repaint(); - comp.revalidate(); - } - }); - } - - public ProfilerChartsViewObserver getObserver() { - return observer; - } - - public JPanel getMainPanel() { - return mainPanel; - } - - public int getRulerXCoordinate() { - return rulerXCoordinate; - } - - public void setRulerXCoordinate(int rulerXCoordinate) { - this.rulerXCoordinate = rulerXCoordinate; - } - - public JComponent getCurrentEntered() { - return currentEntered; - } - - public void setCurrentEntered(JComponent currentEntered) { - this.currentEntered = currentEntered; - } - - public ProfilerScrollbar getHorizontalBar() { - return horizontalBar; - } - - public long getSessionId() { - return sessionId; - } - - public boolean isFlagEnd() { - return flagEnd; - } - - public void setFlagEnd(boolean flagEnd) { - this.flagEnd = flagEnd; - } - - public boolean isStopFlag() { - return stopFlag; - } - - public void setStopFlag(boolean stopFlag) { - this.stopFlag = stopFlag; - } - - public boolean isFlagDown() { - return flagDown; - } - - public void setFlagDown(boolean flagDown) { - this.flagDown = flagDown; - } - - public boolean isAddItemFlag() { - return addItemFlag; - } - - public void setAddItemFlag(boolean addItemFlag) { - this.addItemFlag = addItemFlag; - } - - public ProfilerTimeline getTimeline() { - return timeline; - } - - public TaskScenePanelChart getTaskScenePanelChart() { - return taskScenePanelChart; - } - - public boolean isChartLevel() { - return chartLevel; - } - - public boolean isAbleUnfoldTable() { - return ableUnfoldTable; - } - - public void setAbleUnfoldTable(boolean ableUnfoldTable) { - this.ableUnfoldTable = ableUnfoldTable; - } - - public boolean isLoading() { - return isLoading; - } -} +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.icons.AllIcons; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.observer.ProfilerChartsViewPublisher; +import ohos.devtools.views.layout.chartview.observer.TimelineObserver; + +import javax.swing.Icon; +import java.awt.BorderLayout; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER; +import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.TIMELINE_HEIGHT; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.TIMELINE_WIDTH; + +/** + * Profiler Chart view main panel + */ +public class ProfilerChartsView extends JBPanel { + /** + * Map of saving Session id and ProfilerChartsView + * + * @see "Key: Session id, value: ProfilerChartsView" + */ + public static Map sessionMap = new HashMap<>(); + + /** + * Session id + */ + private final long sessionId; + + /** + * Event publisher of charts display view + */ + private final ProfilerChartsViewPublisher publisher; + + /** + * Panel to save timeline and monitor items + */ + private final JBPanel mainPanel; + + /** + * Saves the parent panel of the current view + */ + private TaskScenePanelChart taskScenePanelChart; + + /** + * Panel to save all monitor items + */ + private ItemsView itemsView; + + /** + * User-defined horizontal scroll bar + */ + private ProfilerScrollbar horizontalBar; + + /** + * User-defined timeline + */ + private ProfilerTimeline timeline; + + /** + * User-defined loading panel + */ + private JBPanel loadingPanel; + + /** + * Sign of pause + */ + private boolean pause = false; + + /** + * Sign of stop + */ + private boolean stop = false; + + /** + * Sign of add item + */ + private boolean addItemFlag = false; + + /** + * Is chart loading (waiting for database to process data during initialization) + */ + private boolean loading = false; + + /** + * Constructor + * + * @param sessionId Session id + * @param traceFile Is track file static import mode + * @param taskScenePanelChart Saves the parent panel of the current view + */ + public ProfilerChartsView(long sessionId, boolean traceFile, TaskScenePanelChart taskScenePanelChart) { + super(true); + this.setOpaque(true); + this.setLayout(new BorderLayout()); + this.sessionId = sessionId; + this.taskScenePanelChart = taskScenePanelChart; + this.mainPanel = new JBPanel(new BorderLayout()); + this.add(mainPanel, BorderLayout.CENTER); + this.publisher = new ProfilerChartsViewPublisher(this, traceFile); + if (traceFile) { + initTimeline(); + this.mainPanel.add(timeline, BorderLayout.NORTH); + } + initScrollPane(); + sessionMap.put(this.sessionId, this); + addResizedListener(); + } + + /** + * Constructor + * + * @param sessionId Session id + * @param traceFile Is track file static import mode + */ + public ProfilerChartsView(long sessionId, boolean traceFile) { + super(true); + this.setOpaque(true); + this.setLayout(new BorderLayout()); + this.sessionId = sessionId; + this.mainPanel = new JBPanel(new BorderLayout()); + this.add(mainPanel, BorderLayout.CENTER); + this.publisher = new ProfilerChartsViewPublisher(this, traceFile); + SessionInfo sessionInfo = SessionManager.getInstance().getSessionInfo(sessionId); + if (traceFile || sessionInfo.getDeviceIPPortInfo().getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + initTimeline(); + this.mainPanel.add(timeline, BorderLayout.NORTH); + } else { + initTimeAndAbility(); + } + initScrollPane(); + sessionMap.put(this.sessionId, this); + addResizedListener(); + } + + /** + * init timeLine and Ability + */ + private void initTimeAndAbility() { + JBPanel timeAbilityPanel = new JBPanel(new BorderLayout()); + initTimeline(); + timeAbilityPanel.add(timeline, BorderLayout.NORTH); + this.mainPanel.add(timeAbilityPanel, BorderLayout.NORTH); + } + + /** + * Add listener for component size change + */ + private void addResizedListener() { + this.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + // Adjust the size and position of the scroll bar when the component size changes + if (horizontalBar != null) { + horizontalBar.resizeAndReposition(); + } + } + }); + } + + private void initTimeline() { + timeline = new ProfilerTimeline(TIMELINE_WIDTH, TIMELINE_HEIGHT); + // Save chart standard for timeline + timeline.setMaxDisplayTime(publisher.getStandard().getMaxDisplayMillis()); + timeline.setMinMarkInterval(publisher.getStandard().getMinMarkInterval()); + // Create the observer for timeline and register to the current view + TimelineObserver timelineObserver = new TimelineObserver(timeline); + publisher.attach(timelineObserver); + } + + private void initScrollPane() { + this.itemsView = new ItemsView(this); + JBScrollPane itemsScroll = + new JBScrollPane(itemsView, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER); + itemsScroll.getVerticalScrollBar().setUnitIncrement(LayoutConstants.SCROLL_UNIT_INCREMENT); + itemsScroll.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + itemsView.updateShowHeight(event.getComponent().getHeight()); + } + }); + this.mainPanel.add(itemsScroll, BorderLayout.CENTER); + } + + /** + * Initialize horizontal scroll bar + */ + public void initScrollbar() { + this.horizontalBar = new ProfilerScrollbar(this); + this.mainPanel.add(horizontalBar, BorderLayout.SOUTH); + this.publisher.setDisplayScrollbar(true); + } + + /** + * Remove horizontal scroll bar + */ + public void removeScrollbar() { + this.publisher.setDisplayScrollbar(false); + if (horizontalBar != null) { + this.mainPanel.remove(horizontalBar); + this.horizontalBar = null; + } + } + + /** + * Show Loading panel + */ + public void showLoading() { + loadingPanel = new LoadingPanel(); + loading = true; + this.remove(mainPanel); + this.add(loadingPanel, BorderLayout.CENTER); + // Check the loading result: start the refresh after loading + publisher.checkLoadingResult(); + } + + /** + * Hide Loading panel and show main panel + */ + public void hideLoading() { + if (loadingPanel != null) { + this.remove(loadingPanel); + } + loading = false; + this.add(mainPanel, BorderLayout.CENTER); + } + + /** + * Add a monitor item view + * + * @param item 指标项枚举类 + * @throws InvocationTargetException + * @throws NoSuchMethodException + * @throws InstantiationException + * @throws IllegalAccessException + */ + public void addMonitorItemView(ProfilerMonitorItem item) + throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + itemsView.addMonitorItemView(item); + } + + /** + * Set pause status + * + * @param pause pause/resume + */ + public void setPause(boolean pause) { + this.pause = pause; + Icon icon; + String text; + if (pause) { + icon = AllIcons.Process.ProgressResumeHover; + text = "Start"; + } else { + icon = AllIcons.Process.ProgressPauseHover; + text = "Suspend"; + if (itemsView != null) { + // Update the pop-up state of the table event after the left-click on all charts + itemsView.updateShowTableView(); + } + } + + if (taskScenePanelChart != null) { + taskScenePanelChart.getjButtonStop().setIcon(icon); + taskScenePanelChart.getjButtonStop().setToolTipText(text); + } + } + + public ProfilerChartsViewPublisher getPublisher() { + return publisher; + } + + public JBPanel getMainPanel() { + return mainPanel; + } + + public ProfilerScrollbar getHorizontalBar() { + return horizontalBar; + } + + public long getSessionId() { + return sessionId; + } + + public boolean isPause() { + return pause; + } + + public boolean isStop() { + return stop; + } + + public void setStop(boolean stop) { + this.stop = stop; + } + + public boolean isAddItemFlag() { + return addItemFlag; + } + + public void setAddItemFlag(boolean addItemFlag) { + this.addItemFlag = addItemFlag; + } + + public ProfilerTimeline getTimeline() { + return timeline; + } + + public TaskScenePanelChart getTaskScenePanelChart() { + return taskScenePanelChart; + } + + public boolean isLoading() { + return loading; + } + + public ItemsView getItemsView() { + return itemsView; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerMonitorItem.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerMonitorItem.java new file mode 100644 index 000000000..aa168fa39 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerMonitorItem.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +/** + * Profiler的监控项 + */ +public class ProfilerMonitorItem { + private int index; + private final String name; + private final Class clazz; + + /** + * ProfilerMonitorItem + * + * @param index + * @param name + * @param clazz + */ + public ProfilerMonitorItem(int index, String name, Class clazz) { + this.index = index; + this.name = name; + this.clazz = clazz; + } + + /** + * getName + * + * @return String + */ + public String getName() { + return name; + } + + /** + * getClazz + * + * @return Class + */ + public Class getClazz() { + return clazz; + } + + /** + * getIndex + * + * @return + */ + public int getIndex() { + return index; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/ProfilerScrollbar.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerScrollbar.java similarity index 76% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/ProfilerScrollbar.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerScrollbar.java index b3439e10f..7bbaa57a1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/chart/ProfilerScrollbar.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerScrollbar.java @@ -13,32 +13,26 @@ * limitations under the License. */ -package ohos.devtools.views.common.chart; +package ohos.devtools.views.layout.chartview; +import com.intellij.ui.components.JBPanel; import ohos.devtools.views.charts.model.ChartDataRange; import ohos.devtools.views.charts.model.ChartStandard; import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import javax.swing.ImageIcon; -import javax.swing.JPanel; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.math.BigDecimal; -import static ohos.devtools.views.common.ViewConstants.INITIAL_VALUE; -import static ohos.devtools.views.common.OperationUtils.divide; -import static ohos.devtools.views.common.OperationUtils.multiply; +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; +import static ohos.devtools.views.layout.chartview.utils.OperationUtils.divide; +import static ohos.devtools.views.layout.chartview.utils.OperationUtils.multiply; /** * 自定义滚动条 - * - * @see "Chart面板上的水平滚动条" - * @see "实现思路:控件是一个自定义布局的JPanel,滚动条是一个填充了背景色的子JPanel,拖动滚动条时,手动计算移动距离并setBound" - * @since 2021/2/20 14:18 */ -public class ProfilerScrollbar extends JPanel { +public class ProfilerScrollbar extends JBPanel { /** * 滚动条的高度 */ @@ -50,7 +44,7 @@ public class ProfilerScrollbar extends JPanel { private static final int MIN_WIDTH = 20; /** - * 窗口的父面板,即要悬浮在哪个面板上 + * 滚动条的父面板 */ private final ProfilerChartsView parent; @@ -62,7 +56,7 @@ public class ProfilerScrollbar extends JPanel { /** * 拖动时的滚动条控件 */ - private JPanel bar; + private JBPanel bar; /** * 拖动滚动条时,滚动条起点坐标和鼠标点之间的偏移量 @@ -90,15 +84,13 @@ public class ProfilerScrollbar extends JPanel { this.setVisible(true); this.setLayout(null); // 初始化用于拖动的bar - bar = new JPanel(); + bar = new JBPanel(); // 滚动条颜色 bar.setBackground(ColorConstants.SCROLLBAR); // 第一次出现时表明Chart刚刚铺满界面,此时滚动条应和整个Chart一样长,后面随着时间推移,滚动条慢慢缩小 moveScopeWidth = parent.getWidth(); bar.setPreferredSize(new Dimension(moveScopeWidth, BAR_HEIGHT)); bar.setBounds(0, 0, bar.getPreferredSize().width, bar.getPreferredSize().height); - // 滚动条底板颜色设置 - this.setBackground(ColorConstants.CHART_BG); this.add(bar); this.setPreferredSize(new Dimension(moveScopeWidth, BAR_HEIGHT)); } @@ -121,7 +113,7 @@ public class ProfilerScrollbar extends JPanel { @Override public void mouseReleased(MouseEvent mouseEvent) { - releaseEvent(mouseEvent); + releaseEvent(); } }); } @@ -138,10 +130,8 @@ public class ProfilerScrollbar extends JPanel { /** * 自定义鼠标释放事件 - * - * @param mouseEvent MouseEvent */ - private void releaseEvent(MouseEvent mouseEvent) { + private void releaseEvent() { // 恢复偏移量为初始值 offsetPixel = INITIAL_VALUE; } @@ -154,12 +144,12 @@ public class ProfilerScrollbar extends JPanel { private void dragEvent(MouseEvent mouseEvent) { int newLocationX = getNewLocationX(mouseEvent); int barWidth = bar.getWidth(); - if (moveScopeWidth == (barWidth + newLocationX) && !parent.isStopFlag()) { + if (moveScopeWidth == (barWidth + newLocationX) && !parent.isStop()) { setRestartRefresh(); return; } // 拖拽时停止刷新Chart - if (!parent.isStopFlag()) { + if (!parent.isStop()) { setPauseRefresh(); } // 计算拖动后的应显示的时间区域 @@ -172,24 +162,16 @@ public class ProfilerScrollbar extends JPanel { * 设置重启状态 */ private void setRestartRefresh() { - parent.getTaskScenePanelChart().getjButtonStop() - .setIcon(new ImageIcon(ProfilerScrollbar.class.getClassLoader().getResource("images/button_stop.png"))); - parent.getTaskScenePanelChart().getjButtonStop().setToolTipText("暂停"); - parent.getObserver().restartRefresh(); - parent.setFlagEnd(false); - // 拉到最右边重新开始刷新,这里也要清掉agent table等信息,调用时间线上的右击方法即可 - parent.getTimeline().mouseRightClick(); + parent.getPublisher().restartRefresh(); + parent.setPause(false); } /** * 设置暂停状态 */ private void setPauseRefresh() { - parent.getTaskScenePanelChart().getjButtonStop() - .setIcon(new ImageIcon(ProfilerScrollbar.class.getClassLoader().getResource("images/suspended.png"))); - parent.getTaskScenePanelChart().getjButtonStop().setToolTipText("开始"); - parent.getObserver().pauseRefresh(); - parent.setFlagEnd(true); + parent.getPublisher().pauseRefresh(); + parent.setPause(true); } /** @@ -204,7 +186,7 @@ public class ProfilerScrollbar extends JPanel { return; } // 隐藏掉的时间:lastTime - displayTime - ChartStandard standard = parent.getObserver().getStandard(); + ChartStandard standard = parent.getPublisher().getStandard(); int lastTime = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); int hideTime = lastTime - standard.getMaxDisplayMillis(); // 计算未占用的地方,1px代表多少隐藏时间,得到一个比例 @@ -227,7 +209,7 @@ public class ProfilerScrollbar extends JPanel { newStart = lastTime - standard.getMaxDisplayMillis(); } int newEnd = newStart + standard.getMaxDisplayMillis(); - parent.getObserver().notifyRefresh(newStart, newEnd); + parent.getPublisher().notifyRefresh(newStart, newEnd); } /** @@ -253,16 +235,17 @@ public class ProfilerScrollbar extends JPanel { * 计算并调整滚动条调整后的宽度和位置 */ public void resizeAndReposition() { - ChartStandard standard = parent.getObserver().getStandard(); + ChartStandard standard = parent.getPublisher().getStandard(); int lastTime = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); // 最后的时间小于最大展示时间,则不需要滚动条 - int maxDisplay = parent.getObserver().getStandard().getMaxDisplayMillis(); + int maxDisplay = parent.getPublisher().getStandard().getMaxDisplayMillis(); if (lastTime <= maxDisplay) { return; } // 每次调整位置和长度时,需要更新moveScopeWidth,因为界面可能缩放 moveScopeWidth = parent.getWidth(); - /* ------- 用户可能把滚动条拖动值中间,然后触发当前方法,所以要计算进度条前面的空白长度来确定滚动条位置 ------- */ + // 用户可能把滚动条拖动值中间,然后触发当前方法, + // 所以要计算进度条前面的空白长度来确定滚动条位置 // 计算进度条前面的空白长度 int startTime = standard.getDisplayRange().getStartTime(); BigDecimal leftEmptyRatio = divide(startTime, lastTime); @@ -273,13 +256,15 @@ public class ProfilerScrollbar extends JPanel { // 保证宽度不能超过最小值,否则会滚动条会缩小到看不清 if (barNewWidth < MIN_WIDTH) { barNewWidth = MIN_WIDTH; - // 保证宽度不能超过最小值后,滚动条的比例和空白的比例已经不一样了,需要重新计算,比例和宽度均减去maxDisplay(barNewWidth) + // 保证宽度不能超过最小值后,滚动条的比例和空白的比例已经不一样了,需要重新计算, + // 比例和宽度均减去maxDisplay(barNewWidth) leftEmptyRatio = divide(startTime, lastTime - maxDisplay); leftEmptyWidth = multiply(leftEmptyRatio, moveScopeWidth - barNewWidth); } bar.setPreferredSize(new Dimension(barNewWidth, BAR_HEIGHT)); - // Chart再刷新时,滚动条一定在最右边,由于上面的运算会丢失精度,会导致滚动条在闪烁,这里做个运算保证滚动条一直在右侧 - if (parent.getObserver().isRefreshing()) { + // Chart再刷新时,滚动条一定在最右边,由于上面的运算会丢失精度, + // 会导致滚动条在闪烁,这里做个运算保证滚动条一直在右侧 + if (parent.getPublisher().isRefreshing()) { leftEmptyWidth = moveScopeWidth - barNewWidth; } // 更新进度条位置 diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerTimeline.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerTimeline.java new file mode 100644 index 000000000..395f9e9b7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/ProfilerTimeline.java @@ -0,0 +1,321 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.charts.utils.ChartUtils; +import ohos.devtools.views.layout.chartview.utils.OperationUtils; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.math.BigDecimal; + +import static ohos.devtools.views.common.ColorConstants.TIMELINE_SCALE; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.TIMELINE_FONT_SIZE; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.TIMELINE_MARK_COUNTS; + +/** + * User-defined timeline component of Profiler + */ +public class ProfilerTimeline extends JBPanel { + private static final int NUM_5 = 5; + + private static final int NUM_6 = 6; + + private static final int NUM_10 = 10; + + private static final int NUM_1000 = 1000; + + /** + * The maximum time that can be displayed on the timeline + */ + private int maxDisplayTime; + + /** + * Minimum interval between timescales + */ + private int minMarkInterval; + + /** + * Right coordinates of timeline + */ + private int right; + + /** + * Top coordinates of timeline + */ + private int top; + + /** + * The start time of the timeline when drawing + */ + private int startTime; + + /** + * The end time of the timeline when drawing + */ + private int endTime; + + /** + * Coordinate axis X0 point when drawing timeline + * + * @see "It is the coordinate axis X0 point used in daily drawing, not the coordinate axis origin of Swing" + */ + private int x0; + + /** + * Coordinate axis Y0 point when drawing timeline + * + * @see "It is the coordinate axis Y0 point used in daily drawing, not the coordinate axis origin of Swing" + */ + private int y0; + + /** + * The start time offset when the scale is drawn when the timeline is full of panels + */ + private int offsetTime = 0; + + /** + * The x-axis is the coordinate of the starting plot + * + * @see "The dynamic timeline and chart appear from right to left" + */ + private int startCoordinate; + + /** + * Number of pixels per X-axis time unit + */ + private BigDecimal pixelPerTime; + + /** + * Constructor + * + * @param width Width of timeline + * @param height Height of timeline + */ + public ProfilerTimeline(int width, int height) { + this.setPreferredSize(new Dimension(width, height)); + } + + /** + * paintComponent + * + * @param graphics graphics + */ + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + initPoints(); + drawAxis(graphics); + } + + /** + * Initialization of points and scale information + */ + private void initPoints() { + // Determine the origin of the drawn axis + x0 = this.getX(); + right = x0 + this.getWidth(); + top = this.getY(); + y0 = top + this.getHeight() - 1; + if (right == 0 || maxDisplayTime == 0) { + return; + } + // Calculate how many pixels a time unit takes + pixelPerTime = OperationUtils.divide(right, maxDisplayTime); + // If the current time is greater than the maximum time, the offset is calculated + if (endTime > maxDisplayTime && minMarkInterval != 0) { + startCoordinate = x0; + // Determine if there is offset time + if (endTime % minMarkInterval == 0) { + offsetTime = 0; + } else { + // If the remainder of current time and minMarkInterval is not 0, + // the offset is calculated: minimum interval - current time% minimum interval + offsetTime = minMarkInterval - endTime % minMarkInterval; + } + } else { + // If the current time is less than the maximum time, + // the timeline needs to be drawn from the middle with an offset of 0 + offsetTime = 0; + startCoordinate = x0 + right - OperationUtils.multiply(pixelPerTime, endTime); + } + } + + /** + * Draw the coordinate axis of the timeline + * + * @param graphics Graphics + */ + private void drawAxis(Graphics graphics) { + graphics.setColor(TIMELINE_SCALE); + // Draw the vertical line to the left of the timeline + graphics.drawLine(x0, top, x0, y0); + // Draw a horizontal line at the bottom of the timeline + graphics.drawLine(x0, y0, right, y0); + // The time line is drawn from offset time (the scale is drawn in fact) + for (int drawTime = offsetTime; drawTime <= maxDisplayTime; drawTime += minMarkInterval) { + int pointX = startCoordinate + ChartUtils.multiply(pixelPerTime, drawTime); + // Calculate the actual time to show + int showTime = startTime + drawTime; + int result = (showTime / minMarkInterval) % TIMELINE_MARK_COUNTS; + // Draw coordinate axis numbers and large scale every minMarkInterval + graphics.setColor(TIMELINE_SCALE); + if (result == 0) { + // Draw a long scale + graphics.drawLine(pointX, y0, pointX, top); + graphics.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, TIMELINE_FONT_SIZE)); + // Time after conversion + String str = millisecondToTime(showTime); + graphics.setColor(JBColor.foreground()); + graphics.drawString(str, pointX + NUM_5, y0 - NUM_10); + } else { + graphics.drawLine(pointX, top, pointX, top + NUM_6); + } + } + } + + /** + * Draw the coordinate number of the timeline + * + * @param time time + * @return String + */ + private String millisecondToTime(int time) { + String timeStr; + int hour; + int minute; + int second; + int millisecond; + int num60 = NUM_6 * NUM_10; + if (time <= 0) { + return "0s"; + } else { + second = time / NUM_1000; + minute = second / num60; + millisecond = time % NUM_1000; + if (second < num60) { + timeStr = secondFormat(second) + "." + millisecondFormat(millisecond) + "s"; + } else if (minute < num60) { + second = second % num60; + timeStr = + secondFormat(minute) + ":" + secondFormat(second) + "." + millisecondFormat(millisecond) + "s"; + } else { + hour = minute / num60; + minute = minute % num60; + int num3600 = num60 * num60; + second = second - hour * num3600 - minute * num60; + timeStr = secondFormat(hour) + ":" + secondFormat(minute) + ":" + secondFormat(second) + "." + + millisecondFormat(millisecond) + "s"; + } + } + return timeStr; + } + + /** + * Format conversion of hour, minute and second + * + * @param secondTime secondTime + * @return String + */ + private String secondFormat(int secondTime) { + String retStr; + if (secondTime == 0) { + retStr = "00"; + } else if (secondTime > 0 && secondTime < NUM_10) { + retStr = Integer.toString(secondTime); + } else { + retStr = "" + secondTime; + } + return retStr; + } + + /** + * Millisecond format conversion + * + * @param millisecondTime millisecondTime + * @return String + */ + private String millisecondFormat(int millisecondTime) { + String retStr; + if (millisecondTime == 0) { + retStr = "000"; + } else if (millisecondTime > 0 && millisecondTime < NUM_10) { + retStr = Integer.toString(millisecondTime); + } else if (millisecondTime >= NUM_10 && millisecondTime < NUM_10 * NUM_10) { + retStr = Integer.toString(millisecondTime); + } else { + retStr = "" + millisecondTime; + } + return retStr; + } + + /** + * setMaxDisplayTime + * + * @param maxDisplayTime maxDisplayTime + */ + public void setMaxDisplayTime(int maxDisplayTime) { + this.maxDisplayTime = maxDisplayTime; + } + + /** + * setMinMarkInterval + * + * @param minMarkInterval minMarkInterval + */ + public void setMinMarkInterval(int minMarkInterval) { + this.minMarkInterval = minMarkInterval; + } + + /** + * getStartTime + * + * @return int + */ + public int getStartTime() { + return startTime; + } + + /** + * setStartTime + * + * @param startTime startTime + */ + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + /** + * getEndTime + * + * @return int + */ + public int getEndTime() { + return endTime; + } + + /** + * setEndTime + * + * @param endTime endTime + */ + public void setEndTime(int endTime) { + this.endTime = endTime; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/SubSessionListJBPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/SubSessionListJBPanel.java new file mode 100644 index 000000000..3e4203a67 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/SubSessionListJBPanel.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.common.customcomp.CustomJLabel; + +/** + * SubSessionListJBPanel + */ +public class SubSessionListJBPanel extends JBPanel { + private String startTime; + + private CustomJLabel hosJLabel; + + private String panelName; + + private String dbPath; + + public CustomJLabel getHosJLabel() { + return hosJLabel; + } + + public void setHosJLabel(CustomJLabel hosJLabel) { + this.hosJLabel = hosJLabel; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getPanelName() { + return panelName; + } + + public void setPanelName(String panelName) { + this.panelName = panelName; + } + + public String getDbPath() { + return dbPath; + } + + public void setDbPath(String dbPath) { + this.dbPath = dbPath; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/TaskScenePanelChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/TaskScenePanelChart.java new file mode 100644 index 000000000..7f78d96cd --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/TaskScenePanelChart.java @@ -0,0 +1,1074 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.utils.plugin.service.PlugManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.applicationtrace.AppTracePanel; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomComboBox; +import ohos.devtools.views.common.customcomp.CustomJButton; +import ohos.devtools.views.common.customcomp.CustomJLabel; +import ohos.devtools.views.layout.TaskPanel; +import ohos.devtools.views.layout.event.TaskScenePanelChartEvent; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JSplitPane; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.LayoutManager; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static ohos.devtools.datasources.utils.common.Constant.DEVICE_STAT_OFFLINE; + +/** + * TaskScenePanelChart + */ +public class TaskScenePanelChart extends JBPanel { + private static final Logger LOGGER = LogManager.getLogger(TaskScenePanelChart.class); + private static final int SELECTED_INDEX = 4; + private static final int DUMP_LABLE_WIDTH = 160; + private static final int SESSION_LIST_HEIGHT = 60; + private static final int SESSION_LIST_WIDTH = 220; + private static final int LABLE_FIRST_ITEM = 0; + private static final int LABLE_TWO_ITEM = 1; + private static final int LABLE_THREE_ITEM = 2; + private static final int SESSION_LABLE_LENGTH = 3; + private static final int SESSION_LEFT_LABLE_WIDTH = 8; + + /** + * Task Scene Panel Chart + */ + public TaskScenePanelChart() { + } + + /** + * 整体页面top容器 + */ + private JBPanel panelTop; + + /** + * 整体页面center容器 + */ + private JBPanel panelMiddle; + + /** + * 整体页面Bottom容器 + */ + private JBPanel panelBottom; + + /** + * panelTop中,west容器 + */ + private JBPanel jPanelWest; + + /** + * panelTop中,Center容器 + */ + private JBPanel jPanelCenter; + + /** + * panelTop中,East容器 + */ + private JBPanel jPanelEast; + + /** + * 选项卡标签命名 + */ + private JBLabel jLabelSetting; + + /** + * 停止按钮 + */ + private CustomJButton jButtonStop; + + /** + * 暂停按钮 + */ + private CustomJButton jButtonSuspend; + + /** + * 保存任务按钮 + */ + private CustomJButton jButtonSave; + + /** + * 删除任务按钮 + */ + private CustomJButton jButtonDelete; + + /** + * 新增配置项按钮 + */ + private CustomJButton configButton; + + /** + * 向下扩展页面按钮 + */ + private CustomJButton jButtonBottom; + + /** + * 向左扩展页面按钮 + */ + private CustomJButton jButtonLeft; + + /** + * 切换上一页按钮 + */ + private CustomJButton jButtonUp; + + /** + * 切换下一页按钮 + */ + private CustomJButton jButtonNext; + + /** + * Run xx of xx 信息文本 + */ + private JBLabel jLabelMidde; + + /** + * 00:24:27 chart计时容器 + */ + private JBPanel jPanelLabel; + + /** + * 计时器文字显示 + */ + private JBLabel jTextArea; + + /** + * panelMiddle容器中左边容器 + */ + private JBPanel jPanelMiddleLeft; + + /** + * panelMiddle容器中右边容器 + */ + private JBPanel jPanelMiddleRight; + + /** + * panelMiddle容器分割线 + */ + private JSplitPane splitPane; + + /** + * jPanelMiddleLeft容器子容器 + */ + private JBPanel jScrollCardsPanel; + + /** + * jScrollCardsPanel容器子容器 + */ + private JBPanel jScrollCardsPanelInner; + + /** + * jPanelMiddleLeft滚动条 + */ + private JBScrollPane jScrollPane; + + /** + * 卡片式布局的面板,用于多个chart页面 + */ + private JBPanel cards; + + /** + * 卡片模型对象 + */ + private CardLayout cardLayout; + + /** + * 用于jPanelMiddleLeft布局和内容显示 + */ + private int number; + private int numberJlabel; + private TaskScenePanelChartEvent taskScenePanelChartEvent; + private CountingThread counting; + private ProfilerChartsView profilerView; + private JBPanel jPanelSuspension; + private JBPanel jpanelSupen; + private CustomComboBox jComboBox; + private CustomComboBox timeJComboBox; + private int sumInt; + private boolean greyFlag; + private List sessionList; + private List dumpOrHookSessionList; + + /** + * getCardLayout + * + * @param cards cards + */ + private void getCardLayout(JBPanel cards) { + if (cards != null) { + LayoutManager layout = cards.getLayout(); + if (layout instanceof CardLayout) { + cardLayout = (CardLayout) layout; + } + } + } + + /** + * chart监测页面三级容器 + * + * @param jTaskPanel jTaskPanel + * @param hosJLabelList hosJLabelList + */ + public TaskScenePanelChart(TaskPanel jTaskPanel, List hosJLabelList) { + init(); + getCardLayout(cards); + // 整体页面布局设置 + setLayAttributes(jTaskPanel, hosJLabelList); + // 设置按钮属性 + setButtonAttributes(); + // 布局panelTop容器,添加按钮 + setPanelTopAttributes(); + // 设置标签页标题滚动显示 + new DynamicThread().start(); + // 布局panelBigTwo中间容器 + panelMiddle.setLayout(new BorderLayout()); + // 创建页面分割事件 + createSplitPanel(); + // 布局jPanelMiddleLeft容器 + setScrollPane(); + jPanelMiddleRight.add(cards); + // 获取有多少个设备开始了任务,并循环设置 + int numberSum = hosJLabelList.size(); + setTaskLoop(numberSum, hosJLabelList); + // 默认显示第一页 + cardLayout.show(cards, "card0"); + // 监听窗体大小使悬浮窗紧贴窗体 + taskScenePanelChartEvent.setSceneSize(jTaskPanel, this); + // 给删除按钮添加点击事件 + taskScenePanelChartEvent.clickDelete(this); + // 给上一个页面按钮,下一个页面按钮添加点击事件 + taskScenePanelChartEvent.clickUpAndNext(this); + // 给jsplitPane添加监听事件 + taskScenePanelChartEvent.splitPaneChange(this, numberSum); + // 给jButtonLeft按钮添加点击事件,向左放大页面 + taskScenePanelChartEvent.clickLeft(this, hosJLabelList); + jButtonLeft.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_LEFT); + // 给jButton按钮添加点击时间,保存trace文件 + taskScenePanelChartEvent.clickSave(jButtonSave, this); + // memory配置项新增点击事件 + taskScenePanelChartEvent.clickConfig(this, profilerView); + // Performance analysis index configuration + PerformanceIndexPopupMenu itemMenu = + new PerformanceIndexPopupMenu(profilerView, this.getJButtonDelete().getSessionId()); + taskScenePanelChartEvent.clickIndexConfig(configButton, itemMenu); + // trace导入,不需要这些按钮 + if (!hosJLabelList.get(0).isOnline()) { + jPanelWest.removeAll(); + } else { + // 开始计时 + counting = new CountingThread(jTextArea); + counting.start(); + } + // 刷新页面 + jTaskPanel.getTabContainer().repaint(); + } + + private void init() { + panelTop = new JBPanel(new BorderLayout()); + panelMiddle = new JBPanel(new BorderLayout()); + panelBottom = new JBPanel(new BorderLayout()); + jPanelWest = new JBPanel(); + jPanelCenter = new JBPanel(); + jPanelEast = new JBPanel(); + jLabelSetting = new JBLabel(); + jButtonStop = new CustomJButton(AllIcons.Debugger.Db_set_breakpoint, "Stop"); + jButtonSuspend = new CustomJButton(AllIcons.Process.ProgressPauseHover, "Suspend"); + jButtonSave = new CustomJButton(AllIcons.Actions.Menu_saveall, "Save current task"); + jButtonDelete = new CustomJButton(IconLoader.getIcon("/images/gc.png", getClass()), "Delete current task"); + configButton = new CustomJButton(AllIcons.General.Add, ""); + jButtonBottom = new CustomJButton(IconLoader.getIcon("/images/previewDetailsVertically_grey.png", getClass()), + "Expand page down"); + jButtonLeft = new CustomJButton(AllIcons.Actions.PreviewDetails, "Expand page left"); + jButtonUp = new CustomJButton(AllIcons.General.ArrowLeft, "Previous page"); + jButtonNext = new CustomJButton(AllIcons.General.ArrowRight, "Next page"); + jLabelMidde = new JBLabel(); + jPanelLabel = new JBPanel(new GridLayout()); + jTextArea = new JBLabel(); + jPanelMiddleLeft = new JBPanel(); + jPanelMiddleRight = new JBPanel(); + splitPane = new JSplitPane(); + jScrollCardsPanel = new JBPanel(new BorderLayout()); + jScrollCardsPanelInner = new JBPanel(); + jScrollPane = new JBScrollPane(jScrollCardsPanel, JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + cards = new JBPanel(new CardLayout()); + taskScenePanelChartEvent = new TaskScenePanelChartEvent(); + jPanelSuspension = new JBPanel(); + jpanelSupen = new JBPanel(); + jComboBox = new CustomComboBox(); + timeJComboBox = new CustomComboBox(); + sessionList = new ArrayList<>(); + dumpOrHookSessionList = new ArrayList<>(); + } + + /** + * 创建表格 + * + * @param panelBottom panelBottom + * @param jTaskPanel jTaskPanel + */ + public void createTable(JBPanel panelBottom, TaskPanel jTaskPanel) { + JButton jButtonSuspen = new JButton("Suspension frame"); + panelBottom.add(jButtonSuspen); + taskScenePanelChartEvent.showSuspension(this, jTaskPanel, jButtonSuspen); + } + + /** + * chart display + * + * @param num num + * @param jcardsPanel jcardsPanel + * @param hosJLabel hosJLabel + */ + private void chartDisplay(int num, JBPanel jcardsPanel, CustomJLabel hosJLabel) { + // sessionId绑定按钮 + if (num == 0) { + jButtonStop.setSessionId(hosJLabel.getSessionId()); + jButtonSuspend.setSessionId(hosJLabel.getSessionId()); + jButtonSave.setSessionId(hosJLabel.getSessionId()); + jButtonSave.setDeviceName(hosJLabel.getDeviceName()); + jButtonSave.setProcessName(hosJLabel.getProcessName()); + jButtonDelete.setSessionId(hosJLabel.getSessionId()); + jButtonDelete.setDeviceName(hosJLabel.getDeviceName()); + jButtonDelete.setProcessName(hosJLabel.getProcessName()); + configButton.setSessionId(hosJLabel.getSessionId()); + jButtonBottom.setSessionId(hosJLabel.getSessionId()); + jButtonLeft.setSessionId(hosJLabel.getSessionId()); + jComboBox.setSessionId(hosJLabel.getSessionId()); + timeJComboBox.setSessionId(hosJLabel.getSessionId()); + } + // 判断是导入还是实时 + if (!hosJLabel.isOnline()) { + // 添加chart + profilerView = new ProfilerChartsView(hosJLabel.getSessionId(), true, this); + jcardsPanel.add(profilerView); + addMonitorItem(hosJLabel.getSessionId()); + profilerView.getPublisher().showTraceResult(hosJLabel.getStartTime(), hosJLabel.getEndTime()); + taskScenePanelChartEvent.clickZoomEvery(timeJComboBox, profilerView); + } else { + // 添加chart + profilerView = new ProfilerChartsView(hosJLabel.getSessionId(), false, this); + jcardsPanel.add(profilerView); + addMonitorItem(hosJLabel.getSessionId()); + // 显示Loading标识,等数据库初始化完成时再显示chart + profilerView.showLoading(); + taskScenePanelChartEvent.clickZoomEvery(timeJComboBox, profilerView); + // 给开始暂停按钮添加点击事件 + taskScenePanelChartEvent.clickRunAndStop(this, profilerView); + } + } + + private void addMonitorItem(long sessionId) { + List profilerMonitorItems = + PlugManager.getInstance().getProfilerMonitorItemList(sessionId); + profilerMonitorItems.forEach(item -> { + try { + profilerView.addMonitorItemView(item); + } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException exception) { + LOGGER.error("addMonitorItemView failed {} ", item.getName()); + } + }); + } + + private void setTaskLoop(int numberSum, List hosJLabelList) { + for (int index = 0; index < numberSum; index++) { + sumInt += LayoutConstants.SIXTY; + JBPanel jcardsPanel = new JBPanel(new BorderLayout()); + jcardsPanel.setOpaque(true); + CustomJLabel hosJLabel = hosJLabelList.get(index); + // sessionId绑定按钮,判断是导入还是实时 + chartDisplay(index, jcardsPanel, hosJLabel); + String labelText = getLabelText(hosJLabel); + // 显示设备进程名称 + CustomJLabel jLabelRight = new CustomJLabel(labelText); + jLabelRight.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_SESSION_MANAGE); + // 绑定sessionid,进程设备信息 + jLabelRight.setSessionId(hosJLabel.getSessionId()); + jLabelRight.setDeviceName(hosJLabel.getDeviceName()); + jLabelRight.setProcessName(hosJLabel.getProcessName()); + jLabelRight.setOpaque(true); + // 判断显示具体颜色布局 + judge(index, jLabelRight, hosJLabel); + // 每个设备进程信息用jpanel包围 + JBPanel jMultiplePanel = new JBPanel(new FlowLayout(0, 0, 0)); + jMultiplePanel.setBounds(0, number, LayoutConstants.SESSION_LIST_DIVIDER_WIDTH, LayoutConstants.SIXTY); + number += LayoutConstants.SIXTY; + numberJlabel += LayoutConstants.INDEX_THREE; + sessionList.add(jLabelRight); + // margin left lable + if (hosJLabel.isOnline()) { + CustomJLabel left = new CustomJLabel(""); + left.setOpaque(true); + left.setPreferredSize(new Dimension(SESSION_LEFT_LABLE_WIDTH, LayoutConstants.SIXTY)); + left.setBackground(ColorConstants.SELECTED_COLOR); + sessionList.add(left); + jLabelRight.setLeft(left); + jMultiplePanel.add(left); + } + jMultiplePanel.add(jLabelRight); + jScrollCardsPanelInner.add(jMultiplePanel); + cards.add(jcardsPanel, "card" + index); + // 存放点击选择的进程信息用于标签动态展示 + String jLabelSelect = hosJLabel.getProcessName() + "(" + hosJLabel.getDeviceName() + ")"; + // 给每个jpanel添加点击事件 + taskScenePanelChartEvent.clickEvery(this, jLabelRight, numberSum, jLabelSelect, jMultiplePanel); + } + if (sumInt > LayoutConstants.SCROPNUM) { + jScrollCardsPanelInner.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, sumInt)); + } + } + + /** + * getLabelText + * + * @param hosJLabel hosJLabel + * @return String + */ + private String getLabelText(CustomJLabel hosJLabel) { + String labelText = ""; + if (DEVICE_STAT_OFFLINE.equals(hosJLabel.getConnectType())) { + String[] strs = hosJLabel.getProcessName().split(";"); + if (strs.length == SESSION_LABLE_LENGTH) { + labelText = "

" + + strs[LABLE_FIRST_ITEM] + "
" + strs[LABLE_TWO_ITEM] + "
" + + strs[LABLE_THREE_ITEM] + "

"; + } + } else { + labelText = "

" + "  " + hosJLabel.getProcessName() + "
" + "(" + hosJLabel + .getDeviceName() + ")" + "

"; + } + return labelText; + } + + /** + * Determine the specific color layout + * + * @param index index + * @param jLabelRight jLabelRight + * @param hosJLabel hosJLabel + */ + public void judge(int index, JBLabel jLabelRight, CustomJLabel hosJLabel) { + if (index == 0) { + jLabelRight.setBackground(ColorConstants.SELECTED_COLOR); + jLabelRight.setForeground(JBColor.WHITE); + jLabelRight.setPreferredSize(new Dimension(LayoutConstants.SESSION_LIST_WIDTH, LayoutConstants.SIXTY)); + if (!hosJLabel.isOnline()) { + jLabelRight.setPreferredSize(new Dimension(LayoutConstants.NUM_200, LayoutConstants.SIXTY)); + splitPane.setDividerLocation(LayoutConstants.NUM_200); + } + } else { + jLabelRight.setForeground(JBColor.gray); + jLabelRight.setPreferredSize(new Dimension(LayoutConstants.SESSION_LIST_WIDTH, LayoutConstants.SIXTY)); + } + Icon imageIcon = null; + if (LayoutConstants.USB.equals(hosJLabel.getConnectType())) { + imageIcon = IconLoader.getIcon("/images/icon_usb.png", getClass()); + } else if (DEVICE_STAT_OFFLINE.equals(hosJLabel.getConnectType())) { + jLabelRight.setIcon(null); + } else { + imageIcon = IconLoader.getIcon("/images/icon_wifi.png", getClass()); + } + jLabelRight.setIcon(imageIcon); + } + + /** + * 布局jPanelMiddleLeft容器 + */ + public void setScrollPane() { + jPanelMiddleLeft.setLayout(new BorderLayout()); + jScrollCardsPanelInner.setOpaque(true); + jScrollPane.setBorder(null); + jScrollPane.getVerticalScrollBar().setUnitIncrement(LayoutConstants.MEMORY_Y); + jScrollPane.setHorizontalScrollBarPolicy(JBScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + jScrollPane.setVerticalScrollBarPolicy(JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + jScrollCardsPanel.add(jScrollCardsPanelInner); + jScrollCardsPanelInner.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.SCROPNUM)); + jPanelMiddleLeft.add(jScrollPane); + jScrollCardsPanelInner.setLayout(null); + } + + /** + * 创建页面分割事件 + */ + public void createSplitPanel() { + jPanelMiddleLeft.setMinimumSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.JAVA_WIDTH)); + jPanelMiddleRight.setMinimumSize(new Dimension(0, LayoutConstants.JAVA_WIDTH)); + jpanelSupen.setPreferredSize(new Dimension(0, LayoutConstants.HUNDRED)); + jPanelMiddleLeft.setLayout(new GridLayout()); + jPanelMiddleRight.setLayout(new GridLayout()); + jPanelMiddleLeft.setOpaque(true); + jPanelMiddleRight.setOpaque(true); + jPanelMiddleLeft.setBackground(ColorConstants.BLACK_COLOR); + jPanelMiddleRight.setBackground(Color.white); + jPanelMiddleLeft.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.JAVA_WIDTH)); + // 让分割线显示出箭头 + splitPane.setOneTouchExpandable(false); + splitPane.setContinuousLayout(true); + // 设定分割线的距离左边的位置. + splitPane.setDividerLocation(LayoutConstants.SESSION_LIST_DIVIDER_WIDTH); + splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); + splitPane.setDividerSize(1); + splitPane.setLeftComponent(jPanelMiddleLeft); + splitPane.setRightComponent(jPanelMiddleRight); + splitPane.setEnabled(false); + panelMiddle.add(splitPane); + panelMiddle.add(jpanelSupen, BorderLayout.EAST); + } + + /** + * 使用内部类完成标签移动操作 + */ + private class DynamicThread extends Thread { + @Override + public void run() { + while (true) { + for (int index = 0; index < 200; index++) { + try { + TimeUnit.MILLISECONDS.sleep(200); + } catch (InterruptedException exception) { + LOGGER.error(exception.getMessage()); + } + jLabelSetting.setLocation(-index, 0); + } + } + } + } + + /** + * 布局panelTop容器,添加按钮 + */ + public void setPanelTopAttributes() { + jButtonSuspend.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_STOP_BUTTON); + jButtonStop.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_RUN_BUTTON); + jButtonSave.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_SAVE_BUTTON); + jButtonDelete.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_DELETE_BUTTON); + timeJComboBox.setBorder(BorderFactory.createLineBorder(JBColor.background().brighter())); + timeJComboBox.setPreferredSize(new Dimension(LayoutConstants.SE_PANEL_Y_TWO, LayoutConstants.APP_LABEL_X)); + timeJComboBox.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_TIME); + timeJComboBox.addItem("200ms"); + timeJComboBox.addItem("400ms"); + timeJComboBox.addItem("600ms"); + timeJComboBox.addItem("800ms"); + timeJComboBox.addItem("1000ms"); + configButton.setName(UtConstant.UT_TASK_SCENE_PANEL_CHART_CONFIG); + timeJComboBox.setSelectedIndex(SELECTED_INDEX); + jPanelWest.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 0)); + jPanelEast.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 0)); + jPanelWest.add(jButtonStop); + jPanelWest.add(jButtonSuspend); + jPanelWest.add(jButtonUp); + jPanelWest.add(jLabelMidde); + jPanelWest.add(jPanelLabel); + jPanelWest.add(jButtonNext); + jPanelWest.add(jButtonSave); + jPanelWest.add(jButtonDelete); + jPanelEast.add(timeJComboBox); + jPanelEast.add(configButton); + jPanelEast.add(jButtonBottom); + jPanelEast.add(jButtonLeft); + } + + /** + * 设置按钮属性 + */ + public void setButtonAttributes() { + this.setButtonStyle(jButtonUp, "Previous page"); + this.setButtonStyle(jButtonNext, "Next page"); + this.setButtonStyle(jButtonStop, "Stop"); + this.setButtonStyle(jButtonSuspend, "Suspend"); + this.setButtonStyle(jButtonSave, "Save current task"); + this.setButtonStyle(jButtonDelete, "Delete current task"); + this.setButtonStyle(configButton, "Data Source"); + this.setButtonStyle(jButtonBottom, "Expand page down"); + this.setButtonStyle(jButtonLeft, "Expand page left"); + } + + /** + * set HosJButton Style + * + * @param button button + * @param tipText tipText + */ + private void setButtonStyle(CustomJButton button, String tipText) { + button.setOpaque(false); + button.setFocusPainted(false); + button.setBorderPainted(false); + button.setToolTipText(tipText); + } + + /** + * Overall page layout settings + * + * @param jTaskPanel jTaskPanel + * @param hosJLabelList hosJLabelList + */ + public void setLayAttributes(TaskPanel jTaskPanel, List hosJLabelList) { + this.setLayout(new BorderLayout()); + panelTop.setBackground(JBColor.background()); + panelTop.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.TOP_PANEL_HEIGHT)); + // 页面中间部分 + panelMiddle.setBackground(JBColor.WHITE); + panelMiddle.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.JAVA_WIDTH)); + // 页面下面部分 + panelBottom.setBackground(ColorConstants.BLACK_COLOR); + panelBottom.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.LABEL_NAME_WIDTH)); + this.add(panelTop, BorderLayout.NORTH); + setPanelTop(panelTop); + this.add(panelMiddle, BorderLayout.CENTER); + jPanelWest.setOpaque(false); + jPanelCenter.setOpaque(false); + jPanelEast.setOpaque(false); + jPanelWest.setPreferredSize(new Dimension(LayoutConstants.EAST_LABEL_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); + jPanelCenter.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); + jPanelEast + .setPreferredSize(new Dimension(LayoutConstants.TOP_PANEL_EAST_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); + panelTop.add(jPanelWest, BorderLayout.WEST); + panelTop.add(jPanelCenter, BorderLayout.CENTER); + panelTop.add(jPanelEast, BorderLayout.EAST); + CustomJLabel hosJLabel = hosJLabelList.get(0); + jLabelSetting = new JBLabel(hosJLabel.getProcessName() + "(" + hosJLabel.getDeviceName() + ")"); + jLabelSetting.setBounds(0, 0, LayoutConstants.EAST_LABEL_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT); + jTaskPanel.getTabLeftPanel().removeAll(); + jTaskPanel.getTabRightPanel().removeAll(); + jTaskPanel.getTabLeftPanel().add(jLabelSetting); + jTaskPanel.getTabRightPanel().add(jTaskPanel.getTabCloseBtn()); + jTextArea.setOpaque(true); + jTextArea.setBackground(JBColor.background()); + jPanelLabel.add(jTextArea); + } + + /** + * createNativeHook + * + * @param name Native Hook Recoding name + * @param startTime Native Hook Recoding Time + * @param sessionId Native Hook Session Id + * @param dbPath dbPath + */ + public void createSessionList(String name, String startTime, long sessionId, String dbPath) { + JBPanel jScrollCardsPanelSession = this.getJScrollCardsPanelInner(); + Component[] innerPanel = jScrollCardsPanelSession.getComponents(); + SubSessionListJBPanel sessionListPanel = null; + CustomJLabel labelSave = null; + for (Component inner : innerPanel) { + Component[] innerLable; + if (inner instanceof JBPanel) { + innerLable = ((JBPanel) inner).getComponents(); + for (Component item : innerLable) { + if (item instanceof CustomJLabel && ((CustomJLabel) item).getSessionId() == sessionId) { + // 添加Dump + CustomJLabel nameLable = new CustomJLabel(name); + nameLable.setPreferredSize(new Dimension(DUMP_LABLE_WIDTH, LayoutConstants.THIRTY)); + String btnStr = "Save Heap Dump"; + if (name.contains("Native Hook")) { + btnStr = "Save Native Hook Recording"; + } + sessionListPanel = new SubSessionListJBPanel(); + MigLayout layout = new MigLayout(); + sessionListPanel.setLayout(layout); + if (name.contains(LayoutConstants.TRACE_SYSTEM_CALLS)) { + nameLable.setIcon(IconLoader.getIcon("/images/cpu.png", getClass())); + sessionListPanel.add(nameLable, "gapleft 15,wrap 5"); + } else { + nameLable.setIcon(IconLoader.getIcon("/images/icon_heap_dump_normal.png", getClass())); + labelSave = new CustomJLabel(); + labelSave.setIcon(IconLoader.getIcon("/images/menu-saveall.png", getClass())); + labelSave.setToolTipText(btnStr); + sessionListPanel.add(nameLable, "gapleft 15"); + sessionListPanel.add(labelSave, "wrap 5,width 15:15:15,height 15:15:15"); + taskScenePanelChartEvent.saveButtonAddClick(labelSave, name); + } + CustomJLabel timeLabel = new CustomJLabel(" " + startTime); + timeLabel.setBounds(LayoutConstants.TIMELABLE_XY, LayoutConstants.TIMELABLE_XY, + LayoutConstants.HUNDRED_EIGHTY, LayoutConstants.THIRTY); + Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT); + timeLabel.setFont(font); + sessionListPanel.add(timeLabel, "gapleft 28"); + sessionListPanel.setHosJLabel(nameLable); + sessionListPanel.setStartTime(startTime); + dumpOrHookSessionList.add(sessionListPanel); + sessionListPanel.setBounds(0, number, SESSION_LIST_WIDTH, SESSION_LIST_HEIGHT); + jScrollCardsPanelSession.add(sessionListPanel); + if (number > LayoutConstants.LEFT_TOP_WIDTH) { + jScrollCardsPanelSession + .setPreferredSize(new Dimension(SESSION_LIST_WIDTH, number + SESSION_LIST_HEIGHT)); + } + taskScenePanelChartEvent.sessionListPanelAddClick(sessionListPanel, this); + number += SESSION_LIST_HEIGHT; + } + } + } + } + if (sessionListPanel != null) { + sessionListPanel.setBackground(ColorConstants.SELECTED_COLOR); + } + String cardName = ""; + if (name.contains(LayoutConstants.TRACE_SYSTEM_CALLS)) { + cardName = "traceApp" + startTime; + Objects.requireNonNull(sessionListPanel).setPanelName(cardName); + sessionListPanel.setDbPath(dbPath); + showAppTrace(dbPath, sessionId); + } + // set Button disabled + greyFlag = true; + setButtonEnable(greyFlag, cardName); + } + + /** + * showAppTrace + * + * @param dbPathParam dbPathParam + * @param sessionId sessionId + */ + public void showAppTrace(String dbPathParam, long sessionId) { + this.remove(panelTop); + AppTracePanel component = new AppTracePanel(); + component.load(dbPathParam, SessionManager.getInstance().tempPath() + "cpuDb", + (int) SessionManager.getInstance().getPid(sessionId), true); + cards.add(component, dbPathParam); + cardLayout.show(cards, dbPathParam); + } + + /** + * handleFailed + * + * @param sessionListPanel + */ + public void handleFailed(SubSessionListJBPanel sessionListPanel) { + if (sessionListPanel != null && sessionList.size() >= 1) { + this.getJScrollCardsPanelInner().remove(sessionListPanel); + cardLayout.show(cards, "card0"); + sessionList.get(0).setBackground(ColorConstants.SELECTED_COLOR); + number -= SESSION_LIST_HEIGHT; + } + } + + /** + * showSubSessionList + * + * @param list list + */ + public void showSubSessionList(List list) { + SubSessionListJBPanel tempSub; + for (int index = 0; index < list.size(); index++) { + tempSub = list.get(index); + if (index == 0) { + number = 0; + tempSub.setBounds(0, 0, SESSION_LIST_WIDTH, SESSION_LIST_HEIGHT); + if (tempSub.getPanelName().contains("heapDump") || (tempSub.getPanelName().contains("nativeHook"))) { + cardLayout.show(cards, tempSub.getPanelName()); + setButtonEnable(true, ""); + } else { + cardLayout.show(cards, tempSub.getDbPath()); + this.remove(panelTop); + } + tempSub.setBackground(ColorConstants.SELECTED_COLOR); + } else { + number += SESSION_LIST_HEIGHT; + tempSub.setBounds(0, number, SESSION_LIST_WIDTH, SESSION_LIST_HEIGHT); + } + } + } + + /** + * Set button available or not and set sessionList not selected background + * + * @param flag flag + * @param panelName panelName + */ + public void setButtonEnable(boolean flag, String panelName) { + if (flag) { + jButtonStop.setIcon(IconLoader.getIcon("/images/db_set_breakpoint_grey.png", getClass())); + jButtonSuspend.setIcon(AllIcons.Process.ProgressPause); + jButtonDelete.setIcon(IconLoader.getIcon("/images/gc_grey.png", getClass())); + for (CustomJLabel customJLabel : sessionList) { + customJLabel.setBackground(JBColor.background().brighter()); + } + for (SubSessionListJBPanel tempsubSession : dumpOrHookSessionList) { + if (!tempsubSession.getPanelName().equals(panelName)) { + tempsubSession.setBackground(JBColor.background().brighter()); + } + if (tempsubSession.getDbPath() != null && !tempsubSession.getDbPath().equals(panelName) && panelName + .contains(".db")) { + tempsubSession.setBackground(JBColor.background().brighter()); + } + } + } else { + jButtonStop.setIcon(AllIcons.Debugger.Db_set_breakpoint); + jButtonSuspend.setIcon(AllIcons.Process.ProgressPauseHover); + jButtonDelete.setIcon(IconLoader.getIcon("/images/gc.png", getClass())); + // disable all dump or native hook + for (SubSessionListJBPanel subSessionListJBPanel : dumpOrHookSessionList) { + subSessionListJBPanel.setBackground(JBColor.background().brighter()); + } + } + } + + /** + * getJButtonDelete + * + * @return CustomJButton + */ + public CustomJButton getJButtonDelete() { + return jButtonDelete; + } + + /** + * getjButtonRun + * + * @return CustomJButton + */ + public CustomJButton getjButtonRun() { + return jButtonStop; + } + + /** + * getjButtonStop + * + * @return CustomJButton + */ + public CustomJButton getjButtonStop() { + return jButtonSuspend; + } + + /** + * getjButtonSave + * + * @return CustomJButton + */ + public CustomJButton getjButtonSave() { + return jButtonSave; + } + + /** + * getConfigButton + * + * @return CustomJButton + */ + public CustomJButton getConfigButton() { + return configButton; + } + + /** + * getjButtonBottom + * + * @return CustomJButton + */ + public CustomJButton getjButtonBottom() { + return jButtonBottom; + } + + /** + * getjButtonLeft + * + * @return CustomJButton + */ + public CustomJButton getjButtonLeft() { + return jButtonLeft; + } + + /** + * getjButtonUp + * + * @return JButton + */ + public JButton getjButtonUp() { + return jButtonUp; + } + + /** + * getjButtonNext + * + * @return JButton + */ + public JButton getjButtonNext() { + return jButtonNext; + } + + /** + * getSplitPane + * + * @return JSplitPane + */ + public JSplitPane getSplitPane() { + return splitPane; + } + + /** + * getJScrollCardsPanelInner + * + * @return JBPanel + */ + public JBPanel getJScrollCardsPanelInner() { + return jScrollCardsPanelInner; + } + + /** + * getCards + * + * @return JBPanel + */ + public JBPanel getCards() { + return cards; + } + + /** + * CardLayout + * + * @return CardLayout + */ + public CardLayout getCardLayout() { + return cardLayout; + } + + /** + * getjPanelSuspension + * + * @return JBPanel + */ + public JBPanel getjPanelSuspension() { + return jPanelSuspension; + } + + /** + * getjComboBox + * + * @return CustomComboBox + */ + public CustomComboBox getjComboBox() { + return jComboBox; + } + + /** + * getTimeJComboBox + * + * @return CustomComboBox + */ + public CustomComboBox getTimeJComboBox() { + return timeJComboBox; + } + + /** + * getCounting + * + * @return CountingThread + */ + public CountingThread getCounting() { + return counting; + } + + /** + * setCounting + * + * @param counting + */ + public void setCounting(CountingThread counting) { + this.counting = counting; + } + + /** + * getjTextArea + * + * @return JBLabel + */ + public JBLabel getjTextArea() { + return jTextArea; + } + + /** + * isGreyFlag + * + * @return boolean + */ + public boolean isGreyFlag() { + return greyFlag; + } + + /** + * setGreyFlag + * + * @param greyFlag + */ + public void setGreyFlag(boolean greyFlag) { + this.greyFlag = greyFlag; + } + + /** + * getjPanelMiddleRight + * + * @return JBPanel + */ + public JBPanel getjPanelMiddleRight() { + return jPanelMiddleRight; + } + + /** + * getPanelTop + * + * @return JBPanel + */ + public JBPanel getPanelTop() { + return panelTop; + } + + /** + * setPanelTop + * + * @param panelTop + */ + public void setPanelTop(JBPanel panelTop) { + this.panelTop = panelTop; + } + + /** + * getDumpOrHookSessionList + * + * @return + */ + public List getDumpOrHookSessionList() { + return dumpOrHookSessionList; + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/cpu/CpuItemView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/cpu/CpuItemView.java new file mode 100644 index 000000000..9c6f449a7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/cpu/CpuItemView.java @@ -0,0 +1,398 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.cpu; + +import com.intellij.icons.AllIcons; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.transport.grpc.SystemTraceHelper; +import ohos.devtools.datasources.utils.common.GrpcException; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.charts.FilledLineChart; +import ohos.devtools.views.charts.ProfilerChart; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.charts.model.ChartLegendColorRect; +import ohos.devtools.views.charts.tooltip.TooltipItem; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.DottedLine; +import ohos.devtools.views.layout.chartview.ItemsView; +import ohos.devtools.views.layout.chartview.MonitorItemView; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.observer.CpuChartObserver; +import ohos.devtools.views.layout.dialog.CpuItemViewLoadDialog; +import ohos.devtools.views.layout.dialog.SampleDialog; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.SwingWorker; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; + +/** + * Cpu monitor item view + */ +public class CpuItemView extends MonitorItemView { + private static final int CHART_INIT_WIDTH = 1000; + private static final int CHART_DEFAULT_HEIGHT = 150; + private static final int NUM_2 = 2; + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + private CpuChartObserver chartObserver; + private JBLabel foldBtn; + private final JBLabel totalLabel = new JBLabel(); + private final ChartLegendColorRect totalColor = new ChartLegendColorRect(); + private final JBLabel appLabel = new JBLabel(); + private final ChartLegendColorRect appColor = new ChartLegendColorRect(); + private final JBLabel systemLabel = new JBLabel(); + private final ChartLegendColorRect systemColor = new ChartLegendColorRect(); + private long sessionId; + private JComboBox jComboBoxType = new JComboBox(); + private JButton jButtonRecord = new JButton("Record"); + private JBPanel threadNorthPanel = new JBPanel(null); + private JBScrollPane threadScrollPane; + private JBPanel threadCenterPanel = new JBPanel(); + private JBLabel threadLabel = new JBLabel("Threads (10)"); + private JBPanel southCpuThreadPanel = new JBPanel(new BorderLayout()); + private JBPanel threadInfoPanel; + private ProfilerMonitorItem item; + + /** + * Constructors + */ + public CpuItemView() { + } + + @Override + public void init(ProfilerChartsView bottomPanel, ItemsView parent, ProfilerMonitorItem item) { + this.setName(UtConstant.UT_CPU_ITEM_VIEW); + this.item = item; + this.bottomPanel = bottomPanel; + this.parent = parent; + this.sessionId = bottomPanel.getSessionId(); + this.setLayout(new BorderLayout()); + this.add(new CpuTitleView(), BorderLayout.NORTH); + initLegendsComp(); + addChart(); + } + + /** + * initLegendsComp + */ + private void initLegendsComp() { + totalLabel.setPreferredSize(new Dimension(60, 13)); + totalLabel.setOpaque(false); + totalColor.setColor(ColorConstants.DISK_IO_READ); + totalColor.setOpaque(false); + appLabel.setPreferredSize(new Dimension(60, 13)); + appLabel.setOpaque(false); + appColor.setColor(ColorConstants.MEM_JAVA); + appColor.setOpaque(false); + systemLabel.setPreferredSize(new Dimension(70, 13)); + systemLabel.setOpaque(false); + systemColor.setColor(ColorConstants.MEM_NATIVE); + systemColor.setOpaque(false); + } + + /** + * Add chart panel + */ + private void addChart() { + chart = generateChart(); + chart.setBounds(0, 0, CHART_INIT_WIDTH, CHART_DEFAULT_HEIGHT); + southCpuThreadPanel.setPreferredSize(new Dimension(50, 0)); + threadNorthPanel.setPreferredSize(new Dimension(50, 30)); + southCpuThreadPanel.add(threadNorthPanel, BorderLayout.NORTH); + threadInfoPanel = new JBPanel(new MigLayout("inset 0, gapy 0", "[grow,fill]", + "[fill,fill]")); + threadScrollPane = new JBScrollPane(threadInfoPanel); + southCpuThreadPanel.add(threadScrollPane, BorderLayout.CENTER); + threadLabel.setBounds(15, 0, 100, 30); + threadLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); + threadNorthPanel.add(threadLabel); + threadNorthPanel.setOpaque(true); + threadNorthPanel.setBackground(JBColor.background()); + this.add(southCpuThreadPanel, BorderLayout.SOUTH); + // Register the chart observer to the ProfilerChartsView and listen to the refresh events of the main interface + chartObserver = new CpuChartObserver(chart, threadInfoPanel, bottomPanel, true, threadLabel); + this.bottomPanel.getPublisher().attach(chartObserver); + this.add(chart, BorderLayout.CENTER); + } + + private ProfilerChart generateChart() { + ProfilerChart cpuChart = new FilledLineChart(this.bottomPanel, item.getName(), true) { + @Override + protected void initLegends() { + CpuItemView.this.initChartLegends(legends); + } + + @Override + protected void buildLegends(List lastModels) { + CpuItemView.this.buildChartLegends(lastModels); + } + + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + String totalValue = calcTotal(actualKey, dataMap); + List tooltipItems = buildTooltipItems(actualKey, dataMap); + tooltip.showTip(this, showKey + "", totalValue, tooltipItems, newChart, "%"); + } + }; + cpuChart.setFold(true); + cpuChart.setMaxDisplayX(this.bottomPanel.getPublisher().getStandard().getMaxDisplayMillis()); + cpuChart.setMinMarkIntervalX(this.bottomPanel.getPublisher().getStandard().getMinMarkInterval()); + cpuChart.setSectionNumY(NUM_2); + cpuChart.setAxisLabelY("%"); + cpuChart.setMaxUnitY(100); + cpuChart.setEnableSelect(false); + return cpuChart; + } + + /** + * Calculate the total value at a time + * + * @param time time + * @param dataMap dataMap + * @return Totalֵ + */ + private String calcTotal(int time, LinkedHashMap> dataMap) { + List models = dataMap.get(time); + if (models == null || models.size() == 0) { + return ""; + } + int value = chart.getListSum(models, 0); + return String.valueOf(value); + } + + /** + * Init legend components of chart + * + * @param legends legends + */ + private void initChartLegends(JBPanel legends) { + checkAndAdd(legends, totalColor); + checkAndAdd(legends, totalLabel); + checkAndAdd(legends, systemColor); + checkAndAdd(legends, systemLabel); + checkAndAdd(legends, appColor); + checkAndAdd(legends, appLabel); + } + + /** + * checkAndAdd + * + * @param legends legends + * @param component component + */ + private void checkAndAdd(JBPanel legends, Component component) { + boolean contain = false; + for (Component legend : legends.getComponents()) { + if (legend.equals(component)) { + contain = true; + break; + } + } + if (!contain) { + legends.add(component); + } + } + + /** + * buildChartLegends + * + * @param lastModels lastModels + */ + private void buildChartLegends(List lastModels) { + new SwingWorker<>() { + @Override + protected Object doInBackground() { + // Total label + int total = chart.getListSum(lastModels, 0); + String totalText; + if (fold) { + totalText = String.format(Locale.ENGLISH, "Total:%s%s", total, chart.getAxisLabelY()); + systemLabel.setVisible(false); + systemColor.setVisible(false); + appLabel.setVisible(false); + appColor.setVisible(false); + } else { + totalText = String.format(Locale.ENGLISH, "Total:%s%s", total, chart.getAxisLabelY()); + if (lastModels != null) { + lastModels.forEach(chartDataModel -> CpuItemView.this.parseModelToLegend(chartDataModel)); + } + } + totalLabel.setText(totalText); + totalColor.setVisible(true); + totalLabel.setVisible(true); + return new Object(); + } + }.execute(); + } + + /** + * Processing data into legend and remove from allItemLegendMap + * + * @param model Data model + */ + private void parseModelToLegend(ChartDataModel model) { + String itemParam = model.getName(); + switch (itemParam) { + case "System": + systemLabel.setText("System:" + model.getValue() + chart.getAxisLabelY()); + systemLabel.setVisible(true); + systemColor.setVisible(true); + break; + case "App": + appLabel.setText("App:" + model.getValue() + chart.getAxisLabelY()); + appLabel.setVisible(true); + appColor.setVisible(true); + break; + default: + break; + } + } + + /** + * Build tooltip items + * + * @param time Current time + * @param dataMap dataMap + * @return List + */ + private List buildTooltipItems(int time, LinkedHashMap> dataMap) { + List tooltipItems = new ArrayList<>(); + if (dataMap == null || dataMap.size() == 0 || dataMap.get(time) == null) { + return tooltipItems; + } + for (ChartDataModel model : dataMap.get(time)) { + String text = + String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), model.getValue(), chart.getAxisLabelY()); + TooltipItem tooltipItem = new TooltipItem(model.getColor(), text); + tooltipItems.add(tooltipItem); + } + return tooltipItems; + } + + private class CpuTitleView extends JBPanel { + /** + * Save the components should be hidden when item fold + */ + private JBPanel hiddenComp; + + CpuTitleView() { + this.setLayout(new FlowLayout(FlowLayout.LEFT)); + initFixedComps(); + initHiddenComponents(); + this.setBackground(JBColor.background().brighter()); + } + + private void initFixedComps() { + foldBtn = new JBLabel(); + foldBtn.setName(UtConstant.UT_CPU_ITEM_VIEW_FOLD); + foldBtn.setIcon(AllIcons.General.ArrowRight); + this.add(foldBtn); + foldBtn.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + foldBtnClick(); + } + }); + JBLabel title = new JBLabel(item.getName()); + this.add(title); + } + + private void initHiddenComponents() { + hiddenComp = new JBPanel(new FlowLayout(FlowLayout.LEFT)); + hiddenComp.setBackground(JBColor.background().brighter()); + hiddenComp.add(new DottedLine()); + this.add(hiddenComp); + jComboBoxType.setName(UtConstant.UT_CPU_ITEM_VIEW_COMBO); + jComboBoxType.addItem(LayoutConstants.TRACE_SYSTEM_CALLS); + jComboBoxType.setBounds(880, 0, 200, 30); + jButtonRecord.setBounds(1100, 0, 60, 30); + jButtonRecord.setOpaque(false); + jButtonRecord.addActionListener(new ActionListener() { + CpuItemViewLoadDialog cpuItemViewLoadDialog = null; + String requestSessionId = null; + DeviceIPPortInfo deviceIPPortInfo = SessionManager.getInstance().getDeviceInfoBySessionId(sessionId); + + @Override + public void actionPerformed(ActionEvent e) { + Date date = new Date(); + if (jComboBoxType.getSelectedItem().toString().equals(LayoutConstants.TRACE_SYSTEM_CALLS)) { + if (deviceIPPortInfo.getDeviceType() != DeviceType.LEAN_HOS_DEVICE) { + new SampleDialog("Info", + "Trace App Calls does not support P40 at the moment").show(); + } else { + try { + requestSessionId = new SystemTraceHelper() + .createSessionByTraceRequestNoParam(deviceIPPortInfo, sdf.format(date), null); + } catch (GrpcException grpcException) { + grpcException.printStackTrace(); + } + cpuItemViewLoadDialog = + new CpuItemViewLoadDialog(bottomPanel, false, requestSessionId); + cpuItemViewLoadDialog.load(deviceIPPortInfo, requestSessionId, sdf.format(date)); + } + } else { + return; + } + } + }); + hiddenComp.add(jComboBoxType); + hiddenComp.add(jButtonRecord); + hiddenComp.setVisible(false); + } + + private void foldBtnClick() { + fold = !fold; + // Item fold, buttons hide + hiddenComp.setVisible(!fold); + if (fold) { + chart.setFold(true); + southCpuThreadPanel.setPreferredSize(new Dimension(50, 0)); + chart.getTooltip().hideTip(); + foldBtn.setIcon(AllIcons.General.ArrowRight); + } else { + chart.setFold(false); + southCpuThreadPanel.setPreferredSize(new Dimension(50, 200)); + foldBtn.setIcon(AllIcons.General.ArrowDown); + } + parent.itemFoldOrExpend(fold, CpuItemView.this); + chartObserver.setChartFold(fold); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventObserver.java index 4e8b4ab46..7f7433282 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventObserver.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventObserver.java @@ -19,27 +19,27 @@ import ohos.devtools.views.charts.model.ChartDataRange; import ohos.devtools.views.charts.model.ChartStandard; /** - * Chart刷新事件观察者 + * Observer of chart refreshes event * * @since 2021/1/26 19:28 */ public interface IChartEventObserver { /** - * 刷新绘图标准 + * Refresh chart drawing standard * - * @param standard 绘图标准 - * @param startTime 开始时间 - * @param endTime 结束时间 - * @param maxDisplayTime 最大显示时间 + * @param startTime Start time of chart + * @param endTime End time of chart + * @param maxDisplayMillis Maximum display time on view + * @param minMarkInterval The minimum scale interval */ - void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime); + void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval); /** - * 刷新视图 + * Refresh view * - * @param range 时间范围 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @param isUseCache 是否使用缓存机制 + * @param range Chart display time range + * @param firstTimestamp The first time stamp of this chart's data + * @param useCache whether or not use cache */ - void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache); + void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache); } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventPublisher.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventPublisher.java index 19155878a..807b41ad3 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventPublisher.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/event/IChartEventPublisher.java @@ -1,46 +1,43 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview.event; - -/** - * Chart事件发布者 - * - * @ClassName: IChartEventPublisher - * @since 2021/1/26 19:32 - */ -public interface IChartEventPublisher { - /** - * 添加监听者 - * - * @param listener IChartEventListener - */ - void attach(IChartEventObserver listener); - - /** - * 移除监听者 - * - * @param listener IChartEventListener - */ - void detach(IChartEventObserver listener); - - /** - * 通知刷新 - * - * @param start 开始时间 - * @param end 结束时间 - */ - void notifyRefresh(int start, int end); -} +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.event; + +/** + * Publisher of chart event + */ +public interface IChartEventPublisher { + /** + * Add observer + * + * @param observer Observer of chart refreshes event + */ + void attach(IChartEventObserver observer); + + /** + * Remove observer + * + * @param observer Observer of chart refreshes event + */ + void detach(IChartEventObserver observer); + + /** + * notify to refresh + * + * @param start Start time of chart + * @param end End time of chart + */ + void notifyRefresh(int start, int end); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/AgentTreeTableRowSorter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/AgentTreeTableRowSorter.java new file mode 100644 index 000000000..228bf9fda --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/AgentTreeTableRowSorter.java @@ -0,0 +1,212 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.views.applicationtrace.listener.ITreeTableSortChangeListener; + +import javax.swing.DefaultRowSorter; +import javax.swing.SortOrder; +import javax.swing.table.TableModel; +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import static ohos.devtools.views.common.Constant.MEMORY_AGENT_INIT_COUNT; + +/** + * AgentTreeTableRowSorter + */ +public class AgentTreeTableRowSorter extends DefaultRowSorter { + private int sorterColumn = -1; + private M treeTablemodel; + private TreeTableRowSorterModelWrapper modelWrapper; + private ITreeTableSortChangeListener listener; + + /** + * TreeTableRowSorter + * + * @param mode mode + */ + public AgentTreeTableRowSorter(M mode) { + treeTablemodel = mode; + modelWrapper = new TreeTableRowSorterModelWrapper(); + setModelWrapper(modelWrapper); + } + + public void setListener(ITreeTableSortChangeListener listener) { + this.listener = listener; + } + + @Override + public void toggleSortOrder(int column) { + if (column < 0 || column > treeTablemodel.getColumnCount()) { + return; + } + sorterColumn = column; + List newKeys = new ArrayList<>(); + List sortKeys = getSortKeys(); + SortOrder sortOrder; + if (sortKeys.size() > 0) { + if (sortKeys.stream() + .anyMatch(item -> item.getColumn() == column && item.getSortOrder() == SortOrder.ASCENDING)) { + sortOrder = SortOrder.DESCENDING; + } else { + sortOrder = SortOrder.ASCENDING; + } + } else { + sortOrder = SortOrder.DESCENDING; + } + newKeys.add(new SortKey(column, sortOrder)); + setSortKeys(newKeys); + fireSortOrderChanged(); + if (listener != null) { + listener.reSort(column, sortOrder); + } + } + + /** + * sort + */ + @Override + public void sort() { + } + + /** + * sortDescTree + * + * @param agentDataNodes agentDataNodes + * @param name name + * @param listTreeTableModelOnColumns listTreeTableModelOnColumns + */ + public static void sortDescTree(MemoryAgentHeapInfoPanel agentDataNodes, String name, + ListTreeTableModelOnColumns listTreeTableModelOnColumns) { + Comparator comparator = chooseCompare(name); + agentDataNodes.allAgentDatas = + agentDataNodes.allAgentDatas.stream().sorted(comparator).collect(Collectors.toList()); + DefaultMutableTreeNode root = null; + Object columnsRoot = listTreeTableModelOnColumns.getRoot(); + if (columnsRoot instanceof DefaultMutableTreeNode) { + root = (DefaultMutableTreeNode) columnsRoot; + root.removeAllChildren(); + for (int index = 0; index < MEMORY_AGENT_INIT_COUNT; index++) { + if (agentDataNodes.allAgentDatas.size() <= index) { + return; + } + AgentHeapBean node = agentDataNodes.allAgentDatas.get(index); + if (index == MEMORY_AGENT_INIT_COUNT - 1) { + agentDataNodes.lastDataNode = node; + } + root.add(new DefaultMutableTreeNode(node)); + } + } + } + + /** + * sortDescTree + * + * @param agentDataNodes agentDataNodes + * @param name name + * @param listTreeTableModelOnColumns listTreeTableModelOnColumns + */ + public static void sortTree(MemoryAgentHeapInfoPanel agentDataNodes, String name, + ListTreeTableModelOnColumns listTreeTableModelOnColumns) { + Comparator comparator = chooseCompare(name); + agentDataNodes.allAgentDatas = + agentDataNodes.allAgentDatas.stream().sorted(comparator.reversed()).collect(Collectors.toList()); + DefaultMutableTreeNode root = null; + Object columnsRoot = listTreeTableModelOnColumns.getRoot(); + if (columnsRoot instanceof DefaultMutableTreeNode) { + root = (DefaultMutableTreeNode) columnsRoot; + root.removeAllChildren(); + for (int index = 0; index < MEMORY_AGENT_INIT_COUNT; index++) { + if (agentDataNodes.allAgentDatas.size() <= index) { + return; + } + AgentHeapBean node = agentDataNodes.allAgentDatas.get(index); + if (index == MEMORY_AGENT_INIT_COUNT - 1) { + agentDataNodes.lastDataNode = node; + } + root.add(new DefaultMutableTreeNode(node)); + } + } + } + + private static Comparator chooseCompare(String name) { + Comparator agentDataNodeComparator = null; + switch (name) { + case "Allocations": + agentDataNodeComparator = (previousNode, lastNode) -> Integer + .compare(previousNode.getAgentAllocationsCount(), lastNode.getAgentAllocationsCount()); + break; + case "Deallocations": + agentDataNodeComparator = (previousNode, lastNode) -> Integer + .compare(previousNode.getAgentDeAllocationsCount(), lastNode.getAgentDeAllocationsCount()); + break; + case "Total Count": + agentDataNodeComparator = (previousNode, lastNode) -> Integer + .compare(previousNode.getAgentTotalInstanceCount(), lastNode.getAgentTotalInstanceCount()); + break; + case "Shallow Size": + agentDataNodeComparator = (previousNode, lastNode) -> Long + .compare(previousNode.getAgentTotalshallowSize(), lastNode.getAgentTotalshallowSize()); + break; + default: + agentDataNodeComparator = (previousNode, lastNode) -> previousNode.toString() + .compareTo(lastNode.toString()); + } + return agentDataNodeComparator; + } + + private class TreeTableRowSorterModelWrapper extends ModelWrapper { + @Override + public M getModel() { + return treeTablemodel; + } + + @Override + public int getColumnCount() { + if (treeTablemodel == null) { + return 0; + } + return treeTablemodel.getColumnCount(); + } + + @Override + public int getRowCount() { + if (treeTablemodel == null) { + return 0; + } + return treeTablemodel.getRowCount(); + } + + @Override + public Object getValueAt(int row, int column) { + if (treeTablemodel == null) { + return null; + } + return treeTablemodel.getValueAt(row, column); + } + + @Override + public Integer getIdentifier(int row) { + return row; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanel.java new file mode 100644 index 000000000..dc116958e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanel.java @@ -0,0 +1,357 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.ui.HighlightableCellRenderer; +import com.intellij.ui.JBSplitter; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; +import com.intellij.ui.treeStructure.treetable.TreeColumnInfo; +import com.intellij.util.ui.ColumnInfo; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentdao.ClassInfoManager; +import ohos.devtools.services.memory.agentdao.MemoryHeapManager; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.common.treetable.ExpandTreeTable; +import ohos.devtools.views.common.treetable.TreeTableColumn; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.BoundedRangeModel; +import javax.swing.JLabel; +import javax.swing.JScrollBar; +import javax.swing.SortOrder; +import javax.swing.SwingWorker; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.awt.BorderLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.util.ArrayList; +import java.util.List; + +import static ohos.devtools.views.common.Constant.MEMORY_AGENT_INIT_COUNT; + +/** + * MemoryAgentHeapInfoPanel + */ +public class MemoryAgentHeapInfoPanel extends JBPanel { + private static final Logger LOGGER = LogManager.getLogger(MemoryAgentHeapInfoPanel.class); + + /** + * allAgentDatas + */ + public List allAgentDatas; + + /** + * lastDataNode + */ + public AgentHeapBean lastDataNode; + + /** + * mouseMotionAdapter + */ + public MouseMotionAdapter mouseMotionAdapter; + + /** + * mouseListener + */ + public MouseAdapter mouseListener; + + /** + * columns + */ + public ColumnInfo[] columns = + new ColumnInfo[] {new TreeColumnInfo("Class Name"), new TreeTableColumn<>("Allocations", + AgentHeapBean.class) { + @Override + public String getColumnValue(AgentHeapBean nodeData) { + return String.valueOf(nodeData.getAgentAllocationsCount()); + } + }, new TreeTableColumn<>("Deallocations", AgentHeapBean.class) { + @Override + public String getColumnValue(AgentHeapBean nodeData) { + return String.valueOf(nodeData.getAgentDeAllocationsCount()); + } + }, new TreeTableColumn<>("Total Count", AgentHeapBean.class) { + @Override + public String getColumnValue(AgentHeapBean nodeData) { + return String.valueOf(nodeData.getAgentTotalInstanceCount()); + } + }, new TreeTableColumn<>("Shallow Size", AgentHeapBean.class) { + @Override + public String getColumnValue(AgentHeapBean nodeData) { + return String.valueOf(nodeData.getAgentTotalshallowSize()); + } + }}; + + private ExpandTreeTable treeTable; + + /** + * MemoryAgentHeapInfoPanel + * + * @param memoryItemView memoryItemView + * @param sessionId long + * @param chartName String + */ + public MemoryAgentHeapInfoPanel(MemoryItemView memoryItemView, long sessionId, String chartName) { + setLayout(new BorderLayout()); + SwingWorker task = new SwingWorker<>() { + /** + * doInBackground + * + * @return JTreeTable + * @throws Exception Exception + */ + @Override + protected ExpandTreeTable doInBackground() { + treeTable = createTable(memoryItemView, sessionId, chartName); + return treeTable; + } + + /** + * done + */ + @Override + protected void done() { + add(treeTable); + } + }; + task.execute(); + } + + /** + * Copy list according to subscript + * + * @param dataList dataList + * @param startIndex startIndex + * @param endIndex endIndex + * @return list + */ + public List listCopy(List dataList, int startIndex, int endIndex) { + List list = new ArrayList(); + for (int i = startIndex + 1; i < endIndex; i++) { + if (i < dataList.size()) { + AgentHeapBean agentHeapBean = dataList.get(i); + if (agentHeapBean != null) { + list.add(agentHeapBean); + } + } + } + return list; + } + + /** + * createTreeTable + * + * @param memoryItemView memoryItemView + * @param sessionId long + * @param chartName String + * @return ExpandTreeTable + */ + public ExpandTreeTable createTable(MemoryItemView memoryItemView, long sessionId, String chartName) { + DefaultMutableTreeNode root = initData(sessionId, chartName); + ListTreeTableModelOnColumns tableModelOnColumns = new ListTreeTableModelOnColumns(root, columns); + ExpandTreeTable treeTables = new ExpandTreeTable(tableModelOnColumns); + treeTables.getTable().setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {{ + setHorizontalAlignment(JLabel.RIGHT); + }}); + JScrollBar tableVerticalScrollBar1 = treeTables.getVerticalScrollBar(); + getMouseMotionAdapter(tableModelOnColumns, treeTables); + tableVerticalScrollBar1.addMouseMotionListener(mouseMotionAdapter); + AgentTreeTableRowSorter sorter = new AgentTreeTableRowSorter(treeTables.getTable().getModel()); + sorter.setListener((columnIndex, sortOrder) -> { + if (columnIndex <= 0 || columnIndex > columns.length) { + return; + } + if (sortOrder == SortOrder.ASCENDING) { + AgentTreeTableRowSorter.sortDescTree(MemoryAgentHeapInfoPanel.this, + columns[columnIndex].getName(), tableModelOnColumns); + } else { + AgentTreeTableRowSorter.sortTree(MemoryAgentHeapInfoPanel.this, + columns[columnIndex].getName(), tableModelOnColumns); + } + tableModelOnColumns.reload(); + }); + treeTables.getTree().setRootVisible(true); + treeTables.getTree().setExpandsSelectedPaths(true); + treeTables.getTable().setRowSorter(sorter); + treeTables.getTree().setCellRenderer(new HighlightableCellRenderer()); + treeTables.getTree().getExpandableItemsHandler().setEnabled(true); + mouseListener = getTreeTableMouseListener(memoryItemView, sessionId, chartName); + treeTables.getTable().addMouseListener(mouseListener); + treeTables.getTree().addMouseListener(mouseListener); + return treeTables; + } + + private MouseAdapter getTreeTableMouseListener(MemoryItemView memoryItemView, long sessionId, String chartName) { + return new MouseAdapter() { + /** + * mouseClicked + * + * @param mouseEvent mouseEvent + */ + @Override + public void mouseClicked(MouseEvent mouseEvent) { + if (mouseEvent.getClickCount() == 1) { + int selectedRow = treeTable.getTable().getSelectedRow(); + TreePath treePath = treeTable.getTree().getPathForRow(selectedRow); + if (treePath == null) { + return; + } + Object rowNode = treePath.getLastPathComponent(); + if (rowNode instanceof DefaultMutableTreeNode) { + DefaultMutableTreeNode rowData = (DefaultMutableTreeNode) rowNode; + Object dataNode = rowData.getUserObject(); + if (dataNode instanceof AgentHeapBean) { + String className = ((AgentHeapBean) dataNode).getAgentClazzName(); + int cid = new ClassInfoManager().getClassIdByClassName(className); + // Need to be obtained from the first-level interface + JBPanel instanceViewPanel = + memoryItemView.setSecondLevelTreeTable(sessionId, cid, className, chartName); + memoryItemView.instanceAndDetailSplitter.setFirstComponent(instanceViewPanel); + memoryItemView.instanceAndDetailSplitter.setSecondComponent(new JBSplitter(false, 1)); + if (memoryItemView.instanceViewTable != null) { + memoryItemView.instanceViewTable.addMouseListener(new MouseAdapter() { + /** + * mouseClicked + * + * @param mouseEvent mouseEvent + */ + @Override + public void mouseClicked(MouseEvent mouseEvent) { + int selectedRow = memoryItemView.instanceViewTable.getSelectedRow(); + if (selectedRow < 0) { + return; + } + Object id = memoryItemView.instanceViewTable.getValueAt(selectedRow, 3); + if (id instanceof Integer) { + Integer instanceId = (Integer) id; + JBPanel callStack = + memoryItemView.setThirdLevelTreeTable(sessionId, instanceId, className); + memoryItemView.instanceAndDetailSplitter.setSecondComponent(callStack); + } + } + }); + } + memoryItemView.agentHeapSplitter + .setSecondComponent(memoryItemView.instanceAndDetailSplitter); + } + } + } + } + }; + } + + /** + * getMouseMotionAdapter + * + * @param tableModelOnColumns tableModelOnColumns + * @param treeTables treeTables + */ + private void getMouseMotionAdapter(ListTreeTableModelOnColumns tableModelOnColumns, ExpandTreeTable treeTables) { + mouseMotionAdapter = new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent mouseEvent) { + JScrollBar jScrollBar = null; + Object sourceObject = mouseEvent.getSource(); + if (sourceObject instanceof JScrollBar) { + jScrollBar = (JScrollBar) sourceObject; + BoundedRangeModel model = jScrollBar.getModel(); + if (model.getExtent() + model.getValue() == model.getMaximum()) { + ListTreeTableModelOnColumns model1 = null; + Object modelObject = treeTables.getTree().getModel(); + if (modelObject instanceof ListTreeTableModelOnColumns) { + model1 = (ListTreeTableModelOnColumns) modelObject; + DefaultMutableTreeNode root1 = null; + Object rootObject = model1.getRoot(); + if (rootObject instanceof DefaultMutableTreeNode) { + root1 = (DefaultMutableTreeNode) rootObject; + int index = allAgentDatas.indexOf(lastDataNode); + List list = listCopy(allAgentDatas, index, index + 20); + for (AgentHeapBean agentDataNode : list) { + DefaultMutableTreeNode defaultMutableTreeNode = + new DefaultMutableTreeNode(agentDataNode); + tableModelOnColumns + .insertNodeInto(defaultMutableTreeNode, root1, root1.getChildCount()); + lastDataNode = agentDataNode; + } + } + } + } + } + } + }; + } + + /** + * init treeTable Data + * + * @param sessionId long + * @param chartName String + * @return DefaultMutableTreeNode + */ + public DefaultMutableTreeNode initData(long sessionId, String chartName) { + ChartStandard standard = ProfilerChartsView.sessionMap.get(sessionId).getPublisher().getStandard(); + MemoryHeapManager memoryHeapManager = new MemoryHeapManager(); + ChartDataRange selectedRang = standard.getSelectedRange(chartName); + String db = DataBaseApi.getInstance().checkTableRegister("ClassInfo"); + if (selectedRang == null || StringUtils.isBlank(db)) { + return new DefaultMutableTreeNode(); + } + long firstTime = standard.getFirstTimestamp(); + long endTimeNew = firstTime + selectedRang.getEndTime(); + allAgentDatas = memoryHeapManager.getMemoryHeapInfos(sessionId, 0L, endTimeNew); + AgentHeapBean agentHeapBean = new AgentHeapBean(); + DefaultMutableTreeNode appNode = new DefaultMutableTreeNode(); + int totalAllocations = 0; + int totalDeallocations = 0; + int totalTotalCount = 0; + long totalShallowSize = 0L; + if (!allAgentDatas.isEmpty()) { + for (int i = 0; i < MEMORY_AGENT_INIT_COUNT; i++) { + AgentHeapBean node = allAgentDatas.get(i); + if (i == MEMORY_AGENT_INIT_COUNT - 1) { + lastDataNode = node; + } + appNode.add(new DefaultMutableTreeNode(node)); + } + } + for (AgentHeapBean meInfo : allAgentDatas) { + totalAllocations = totalAllocations + meInfo.getAgentAllocationsCount(); + totalDeallocations = totalDeallocations + meInfo.getAgentDeAllocationsCount(); + totalTotalCount = totalTotalCount + meInfo.getAgentTotalInstanceCount(); + totalShallowSize = totalShallowSize + meInfo.getAgentTotalshallowSize(); + } + agentHeapBean.setAgentClazzName("app heap"); + agentHeapBean.setAgentAllocationsCount(totalAllocations); + agentHeapBean.setAgentDeAllocationsCount(totalDeallocations); + agentHeapBean.setAgentTotalInstanceCount(totalTotalCount); + agentHeapBean.setAgentTotalshallowSize(totalShallowSize); + appNode.setUserObject(agentHeapBean); + return appNode; + } + + public ExpandTreeTable getTreeTable() { + return treeTable; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemPopupMenu.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemPopupMenu.java new file mode 100644 index 000000000..6b30e5aa6 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemPopupMenu.java @@ -0,0 +1,198 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.openapi.ui.JBPopupMenu; +import com.intellij.ui.components.JBCheckBox; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.layout.chartview.MonitorItemDetail; +import ohos.devtools.views.layout.chartview.observer.MemoryChartObserver; + +import javax.swing.AbstractButton; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * MemoryPopupMenu + */ +class MemoryItemPopupMenu { + /** + * Number of memory monitoring items + */ + private static final int CHECK_BOX_AMOUNT = 6; + private static final int H_GAP = 15; + private static final int V_GAP = 13; + private static final int ITEM_WIDTH = 140; + private static final int ITEM_HEIGHT = 20; + private static final int MEMORY_ITEM_PANEL_WIDTH = 160; + private static final int MEMORY_ITEM_PANEL_HEIGHT = 275; + private static final int POPUP_OFFSET = 15; + private static final String MEMORY_NAME = "Memory"; + private final long sessionId; + private final MemoryChartObserver chartObserver; + private final JBPopupMenu popupMenu = new JBPopupMenu(); + private final JBLabel memoryLabel = new JBLabel(MEMORY_NAME); + private final JBCheckBox checkBoxSelectAll = new JBCheckBox("Select all"); + private final JBCheckBox checkBoxMemoryJava = new JBCheckBox(MonitorItemDetail.MEM_JAVA.getName()); + private final JBCheckBox checkBoxGpuMemoryNative = new JBCheckBox(MonitorItemDetail.MEM_NATIVE.getName()); + private final JBCheckBox checkBoxGraphics = new JBCheckBox(MonitorItemDetail.MEM_GRAPHICS.getName()); + private final JBCheckBox checkBoxStack = new JBCheckBox(MonitorItemDetail.MEM_STACK.getName()); + private final JBCheckBox checkBoxCode = new JBCheckBox(MonitorItemDetail.MEM_CODE.getName()); + private final JBCheckBox checkBoxOthers = new JBCheckBox(MonitorItemDetail.MEM_OTHERS.getName()); + private final ArrayList checkBoxes = new ArrayList<>(); + private Map> configMap; + + /** + * MemoryPopupMenu constructor + * + * @param sessionId sessionId + * @param chartObserver MemoryChartObserver + */ + MemoryItemPopupMenu(long sessionId, MemoryChartObserver chartObserver) { + this.sessionId = sessionId; + this.chartObserver = chartObserver; + initCheckBoxes(); + initCheckItems(); + initSelectedItems(); + initListener(); + } + + private void initCheckBoxes() { + checkBoxSelectAll.setSelected(true); + checkBoxSelectAll.setEnabled(false); + checkBoxes.add(checkBoxMemoryJava); + checkBoxes.add(checkBoxGpuMemoryNative); + checkBoxGpuMemoryNative.setName(UtConstant.UT_MEMORY_ITEM_POPUP_NATIVE); + checkBoxes.add(checkBoxGraphics); + checkBoxStack.setName(UtConstant.UT_MEMORY_ITEM_POPUP_STACK); + checkBoxes.add(checkBoxStack); + checkBoxes.add(checkBoxCode); + checkBoxes.add(checkBoxOthers); + } + + private void initCheckItems() { + JBPanel checkItemPanel = new JBPanel(new FlowLayout(FlowLayout.LEADING, H_GAP, V_GAP)); + checkItemPanel.add(memoryLabel); + memoryLabel.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + checkBoxSelectAll.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + checkItemPanel.add(checkBoxSelectAll); + for (JBCheckBox checkBox : checkBoxes) { + checkBox.setPreferredSize(new Dimension(ITEM_WIDTH, ITEM_HEIGHT)); + checkItemPanel.add(checkBox); + } + checkItemPanel.setPreferredSize(new Dimension(MEMORY_ITEM_PANEL_WIDTH, MEMORY_ITEM_PANEL_HEIGHT)); + popupMenu.add(checkItemPanel); + } + + private void initSelectedItems() { + configMap = MonitorConfigManager.dataMap.get(sessionId); + if (configMap == null || configMap.get(MEMORY_NAME) == null) { + configMap = initFullItems(); + MonitorConfigManager.dataMap.put(sessionId, configMap); + } + + for (String str : configMap.get(MEMORY_NAME)) { + for (JBCheckBox jCheckBox : checkBoxes) { + if (jCheckBox.getText().equals(str)) { + jCheckBox.setSelected(true); + } + } + } + } + + private Map> initFullItems() { + LinkedList items = new LinkedList<>(); + items.add(MonitorItemDetail.MEM_JAVA.getName()); + items.add(MonitorItemDetail.MEM_NATIVE.getName()); + items.add(MonitorItemDetail.MEM_GRAPHICS.getName()); + items.add(MonitorItemDetail.MEM_STACK.getName()); + items.add(MonitorItemDetail.MEM_CODE.getName()); + items.add(MonitorItemDetail.MEM_OTHERS.getName()); + Map> memoryMap = new HashMap<>(); + memoryMap.put(MEMORY_NAME, items); + return memoryMap; + } + + private void initListener() { + checkBoxSelectAll.addItemListener(event -> { + if (checkBoxSelectAll.isSelected()) { + for (JBCheckBox checkBox : checkBoxes) { + checkBox.setSelected(true); + } + } + }); + memoryAddItemListener(checkBoxMemoryJava); + memoryAddItemListener(checkBoxGpuMemoryNative); + memoryAddItemListener(checkBoxGraphics); + memoryAddItemListener(checkBoxStack); + memoryAddItemListener(checkBoxCode); + memoryAddItemListener(checkBoxOthers); + } + + private void memoryAddItemListener(JBCheckBox checkBox) { + checkBox.addItemListener(event -> filterItemList()); + } + + private void filterItemList() { + List selectedList = + checkBoxes.stream().filter(AbstractButton::isSelected).collect(Collectors.toList()); + // Increase the judgment of the selected number of Check Boxes + if (selectedList.size() < CHECK_BOX_AMOUNT) { + // Select All uncheck the state and set it to non-clickable state + checkBoxSelectAll.setSelected(false); + checkBoxSelectAll.setEnabled(true); + } else { + // Select All Check and set to clickable state + checkBoxSelectAll.setSelected(true); + checkBoxSelectAll.setEnabled(false); + } + LinkedList memoryFlushed = new LinkedList<>(); + for (JBCheckBox checkBox : selectedList) { + // When the checked quantity is 1, the last indicator item cannot be clicked + if (selectedList.size() == 1) { + checkBox.setEnabled(false); + } else { + checkBox.setEnabled(true); + } + memoryFlushed.add(checkBox.getText()); + } + configMap.remove(MEMORY_NAME); + configMap.put(MEMORY_NAME, memoryFlushed); + MonitorConfigManager.dataMap.put(sessionId, configMap); + // Refresh chart manually + chartObserver.refreshManually(); + } + + /** + * show memory items + * + * @param detailCfgBtn detailCfgBtn + * @param event event + */ + void showMemoryItems(JBLabel detailCfgBtn, MouseEvent event) { + popupMenu.show(detailCfgBtn, event.getX(), event.getY() + POPUP_OFFSET); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemView.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemView.java new file mode 100644 index 000000000..43554adb9 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryItemView.java @@ -0,0 +1,946 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.ui.ComboBox; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.JBSplitter; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceInfo; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsManager; +import ohos.devtools.services.memory.agentdao.MemoryInstanceManager; +import ohos.devtools.views.charts.FilledLineChart; +import ohos.devtools.views.charts.ProfilerChart; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartLegendColorRect; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.charts.tooltip.TooltipItem; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.MonitorItemDetail; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.DottedLine; +import ohos.devtools.views.common.treetable.ExpandTreeTable; +import ohos.devtools.views.layout.chartview.ItemsView; +import ohos.devtools.views.layout.chartview.MonitorItemView; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.observer.MemoryChartObserver; + +import javax.swing.BoundedRangeModel; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JScrollBar; +import javax.swing.JTable; +import javax.swing.RowSorter; +import javax.swing.SortOrder; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; +import javax.swing.tree.DefaultMutableTreeNode; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; +import java.util.concurrent.TimeUnit; + +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.NUM_1024; +import static ohos.devtools.views.charts.utils.ChartUtils.divide; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_CODE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_GRAPHICS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_JAVA; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_NATIVE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_OTHERS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_STACK; + +/** + * Memory monitor item view + */ +public class MemoryItemView extends MonitorItemView { + /** + * Splitter PROPORTION + */ + private static final float PROPORTION_SEGMENT_HEAP = 0.5f; + + /** + * instance title width + */ + private static final int INSTANCE_TITLE_WIDTH = 630; + + /** + * instance title height + */ + private static final int INSTANCE_TITLE_HEIGHT = 34; + + /** + * instance pane height + */ + private static final int INSTANCE_PANE_HEIGHT = 450; + + /** + * instance jScrollPane height + */ + private static final int INSTANCE_SCROLL_HEIGHT = 425; + + /** + * instance view width + */ + private static final float PROPORTION_SEGMENT_VIEW = 0.4f; + + /** + * instance view width + */ + private static final int HEAP_VIEW_PANEL_WIDTH = 410; + + private static final int NUM_418 = 418; + + private static final int NUM_384 = 384; + + private static final int NUM_2 = 2; + + /** + * KB,MB转换时的单位 + */ + private static final int UNIT = 1024; + + /** + * instanceViewTable + */ + public JBTable instanceViewTable; + + /** + * agentHeapSplitter + */ + public JBSplitter agentHeapSplitter = new JBSplitter(false, PROPORTION_SEGMENT_HEAP); + + /** + * instanceAndDetailSplitter + */ + public JBSplitter instanceAndDetailSplitter = new JBSplitter(false, PROPORTION_SEGMENT_HEAP); + private final JBLabel totalLabel = new JBLabel(); + private final JBLabel javaLabel = new JBLabel(); + private final ChartLegendColorRect javaColor = new ChartLegendColorRect(); + private final JBLabel nativeLabel = new JBLabel(); + private final ChartLegendColorRect nativeColor = new ChartLegendColorRect(); + private final JBLabel graphicsLabel = new JBLabel(); + private final ChartLegendColorRect graphicsColor = new ChartLegendColorRect(); + private final JBLabel stackLabel = new JBLabel(); + private final ChartLegendColorRect stackColor = new ChartLegendColorRect(); + private final JBLabel codeLabel = new JBLabel(); + private final ChartLegendColorRect codeColor = new ChartLegendColorRect(); + private final JBLabel othersLabel = new JBLabel(); + private final ChartLegendColorRect othersColor = new ChartLegendColorRect(); + private MemoryChartObserver chartObserver; + private JBPanel heapViewPanel; + private MemoryTreeTablePanel memoryTreeTablePanel; + private JBLabel foldBtn; + private JBLabel heapDumpBtn; + private JBLabel detailCfgBtn; + private JButton nativeBtn; + private ProfilerMonitorItem item; + + /** + * Constructor + */ + public MemoryItemView() { + } + + @Override + public void init(ProfilerChartsView bottomPanel, ItemsView parent, ProfilerMonitorItem item) { + this.setName(UtConstant.UT_MEMORY_ITEM_VIEW); + this.bottomPanel = bottomPanel; + this.parent = parent; + this.item = item; + this.setLayout(new BorderLayout()); + initLegendsComp(); + addChart(); + MemoryTitleView titleView = new MemoryTitleView(); + this.add(titleView, BorderLayout.NORTH); + this.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + int height = bottomPanel.getHeight() / 5 * 3; + if (heapViewPanel != null) { + chart.setPreferredSize(new Dimension(bottomPanel.getWidth(), height)); + repaint(); + } + } + }); + } + + private void initLegendsComp() { + totalLabel.setOpaque(false); + totalLabel.setOpaque(false); + javaLabel.setOpaque(false); + nativeLabel.setOpaque(false); + graphicsLabel.setOpaque(false); + stackLabel.setOpaque(false); + codeLabel.setOpaque(false); + othersLabel.setOpaque(false); + addDivideMouseListener(agentHeapSplitter); + addDivideMouseListener(instanceAndDetailSplitter); + } + + /** + * Splitter Divide add MouseListener + * + * @param splitter jbSplitter + */ + private void addDivideMouseListener(JBSplitter splitter) { + splitter.getDivider().addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent event) { + bottomPanel.getTaskScenePanelChart().getSplitPane().setEnabled(true); + } + + @Override + public void mouseExited(MouseEvent event) { + bottomPanel.getTaskScenePanelChart().getSplitPane().setEnabled(false); + } + }); + } + + /** + * Add chart panel + */ + private void addChart() { + chart = generateChart(); + // Register the chart observer to the ProfilerChartsView and listen to the refresh events of the main interface + chartObserver = new MemoryChartObserver(chart, bottomPanel.getSessionId(), true); + this.bottomPanel.getPublisher().attach(chartObserver); + this.add(chart, BorderLayout.CENTER); + } + + private ProfilerChart generateChart() { + ProfilerChart memoryChart = new FilledLineChart(this.bottomPanel, item.getName(), true) { + @Override + protected void initLegends() { + MemoryItemView.this.initChartLegends(legends); + } + + @Override + protected String getYaxisLabelStr(int value) { + // Here we get KB, we need to convert it to MB + return value == maxUnitY ? divide(value, UNIT) + " " + axisLabelY : divide(value, UNIT) + ""; + } + + @Override + protected void buildLegends(List lastModels) { + MemoryItemView.this.buildChartLegends(lastModels); + } + + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + String totalValue = calcTotal(actualKey, dataMap); + List tooltipItems = buildTooltipItems(actualKey, dataMap); + tooltip.showTip(this, showKey + "", totalValue, tooltipItems, newChart, axisLabelY); + } + + @Override + protected void leftMouseClickEvent(MouseEvent event) { + MemoryItemView.this.chartLeftMouseClick(); + } + + @Override + protected void rightMouseClickEvent(MouseEvent event) { + MemoryItemView.this.chartRightMouseClick(); + } + + @Override + protected void mouseDraggedEvent(MouseEvent event) { + MemoryItemView.this.chartMouseDragged(); + } + + @Override + protected void mouseReleaseEvent(MouseEvent event) { + MemoryItemView.this.chartMouseRelease(); + } + }; + memoryChart.setMaxDisplayX(this.bottomPanel.getPublisher().getStandard().getMaxDisplayMillis()); + memoryChart.setMinMarkIntervalX(this.bottomPanel.getPublisher().getStandard().getMinMarkInterval()); + memoryChart.setSectionNumY(NUM_2); + memoryChart.setAxisLabelY("MB"); + memoryChart.setFold(true); + memoryChart.setEnableSelect(false); + return memoryChart; + } + + /** + * Init legend components of chart + * + * @param legends legends + */ + private void initChartLegends(JBPanel legends) { + checkAndAdd(legends, totalLabel); + checkAndAdd(legends, javaColor); + checkAndAdd(legends, javaLabel); + checkAndAdd(legends, nativeColor); + checkAndAdd(legends, nativeLabel); + checkAndAdd(legends, graphicsColor); + checkAndAdd(legends, graphicsLabel); + checkAndAdd(legends, stackColor); + checkAndAdd(legends, stackLabel); + checkAndAdd(legends, codeColor); + checkAndAdd(legends, codeLabel); + checkAndAdd(legends, othersColor); + checkAndAdd(legends, othersLabel); + } + + private void checkAndAdd(JBPanel legends, Component component) { + boolean contain = false; + for (Component legend : legends.getComponents()) { + if (legend.equals(component)) { + contain = true; + break; + } + } + if (!contain) { + legends.add(component); + } + component.setVisible(false); + } + + private void buildChartLegends(List lastModels) { + new SwingWorker<>() { + @Override + protected Object doInBackground() { + // Total label + BigDecimal totalMB = divide(new BigDecimal(chart.getListSum(lastModels, 0)), new BigDecimal(NUM_1024)); + String totalText; + if (fold) { + totalText = totalMB + chart.getAxisLabelY(); + } else { + totalText = String.format(Locale.ENGLISH, "Total:%s%s", totalMB, chart.getAxisLabelY()); + } + totalLabel.setText(totalText); + totalLabel.setVisible(true); + // Initialize a map of full memory legends + Map> allItemLegendMap = initItemLegends(); + // Processing data into legend and remove from allItemLegendMap + lastModels.forEach(model -> parseModelToLegend(model, allItemLegendMap)); + // There are only unselected monitoring items in the map, which need to be hidden + allItemLegendMap + .forEach((item, components) -> components.forEach(component -> component.setVisible(false))); + return new Object(); + } + }.execute(); + } + + /** + * Initialize a map of full memory legends + * + * @return Map + */ + private Map> initItemLegends() { + Map> map = new HashMap<>(); + map.put(MEM_JAVA, Arrays.asList(javaColor, javaLabel)); + map.put(MEM_NATIVE, Arrays.asList(nativeColor, nativeLabel)); + map.put(MEM_GRAPHICS, Arrays.asList(graphicsColor, graphicsLabel)); + map.put(MEM_STACK, Arrays.asList(stackColor, stackLabel)); + map.put(MEM_CODE, Arrays.asList(codeColor, codeLabel)); + map.put(MEM_OTHERS, Arrays.asList(othersColor, othersLabel)); + return map; + } + + /** + * Processing data into legend and remove from allItemLegendMap + * + * @param model Data model + * @param allItemLegendMap Map of memory legends + */ + private void parseModelToLegend(ChartDataModel model, Map> allItemLegendMap) { + MonitorItemDetail itemParam = MonitorItemDetail.getItemByName(model.getName()); + switch (itemParam) { + case MEM_JAVA: + refreshColorText(javaColor, javaLabel, model); + // If the model is saved as the current monitoring item, its components will be displayed + allItemLegendMap.get(MEM_JAVA).forEach(component -> component.setVisible(true)); + // After the component is set to display, it is removed from the map. After the loop is completed, + // only unselected monitoring items are left in the map and need to be hidden + allItemLegendMap.remove(MEM_JAVA); + break; + case MEM_NATIVE: + refreshColorText(nativeColor, nativeLabel, model); + allItemLegendMap.get(MEM_NATIVE).forEach(component -> component.setVisible(true)); + allItemLegendMap.remove(MEM_NATIVE); + break; + case MEM_GRAPHICS: + refreshColorText(graphicsColor, graphicsLabel, model); + allItemLegendMap.get(MEM_GRAPHICS).forEach(component -> component.setVisible(true)); + allItemLegendMap.remove(MEM_GRAPHICS); + break; + case MEM_STACK: + refreshColorText(stackColor, stackLabel, model); + allItemLegendMap.get(MEM_STACK).forEach(component -> component.setVisible(true)); + allItemLegendMap.remove(MEM_STACK); + break; + case MEM_CODE: + refreshColorText(codeColor, codeLabel, model); + allItemLegendMap.get(MEM_CODE).forEach(component -> component.setVisible(true)); + allItemLegendMap.remove(MEM_CODE); + break; + case MEM_OTHERS: + refreshColorText(othersColor, othersLabel, model); + allItemLegendMap.get(MEM_OTHERS).forEach(component -> component.setVisible(true)); + allItemLegendMap.remove(MEM_OTHERS); + break; + default: + break; + } + } + + /** + * Update the color and text of the legend + * + * @param colorRect Color component + * @param label text label + * @param model data + */ + private void refreshColorText(ChartLegendColorRect colorRect, JBLabel label, ChartDataModel model) { + String showValue = divide(model.getValue(), NUM_1024).toString(); + String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, chart.getAxisLabelY()); + colorRect.setColor(model.getColor()); + if (!label.getText().equals(text)) { + label.setText(text); + } + } + + /** + * Calculate the total value at a time + * + * @param time 时间 + * @param dataMap dataMap + * @return Total值 + */ + private String calcTotal(int time, LinkedHashMap> dataMap) { + List models = dataMap.get(time); + if (models == null || models.size() == 0) { + return ""; + } + // Here we get KB, we need to convert it to MB + int value = chart.getListSum(models, 0); + return divide(value, NUM_1024).toString(); + } + + /** + * Build tooltip items + * + * @param time Current time + * @param dataMap dataMap + * @return List + */ + private List buildTooltipItems(int time, LinkedHashMap> dataMap) { + List tooltipItems = new ArrayList<>(); + if (dataMap == null || dataMap.size() == 0 || dataMap.get(time) == null) { + return tooltipItems; + } + for (ChartDataModel model : dataMap.get(time)) { + BigDecimal showValue = divide(model.getValue(), NUM_1024); + String text = String.format(Locale.ENGLISH, "%s:%s%s", model.getName(), showValue, chart.getAxisLabelY()); + TooltipItem tooltipItem = new TooltipItem(model.getColor(), text); + tooltipItems.add(tooltipItem); + } + return tooltipItems; + } + + /** + * chartLeftMouseClick + */ + private void chartLeftMouseClick() { + long sessionId = this.bottomPanel.getSessionId(); + SessionInfo sessionInfo = SessionManager.getInstance().getSessionInfo(sessionId); + if (!sessionInfo.isOfflineMode() + && sessionInfo.getDeviceIPPortInfo().getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + return; + } + if (memoryTreeTablePanel != null) { + refreshAgentHeapInfo(sessionId); + } else { + memoryTreeTablePanel = new MemoryTreeTablePanel(this, sessionId, item.getName()); + parent.itemChartClick(this); + instanceAndDetailSplitter.setOpaque(true); + memoryTreeTablePanel.setOpaque(true); + agentHeapSplitter.setFirstComponent(memoryTreeTablePanel); + // heapView external total panel + heapViewPanel = new JBPanel(); + int height = bottomPanel.getHeight() / 5 * 2; + heapViewPanel.setPreferredSize(new Dimension(bottomPanel.getWidth(), height)); + heapViewPanel.setLayout(new MigLayout("insets 0", "[grow,fill]", "[grow,fill]")); + heapViewPanel.add(agentHeapSplitter, "span"); + } + this.add(heapViewPanel, BorderLayout.SOUTH); + } + + /** + * refresh agent heap info + * + * @param sessionId sessionId + */ + private void refreshAgentHeapInfo(long sessionId) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if (memoryTreeTablePanel != null) { + MemoryAgentHeapInfoPanel memoryAgentHeapInfoPanel = + memoryTreeTablePanel.getMemoryAgentHeapInfoPanel(); + if (memoryAgentHeapInfoPanel != null && memoryAgentHeapInfoPanel.getTreeTable() != null) { + DefaultMutableTreeNode root = memoryAgentHeapInfoPanel.initData(sessionId, item.getName()); + ListTreeTableModelOnColumns tableModelOnColumns = + new ListTreeTableModelOnColumns(root, memoryAgentHeapInfoPanel.columns); + ExpandTreeTable agentTreeTable = memoryAgentHeapInfoPanel.getTreeTable(); + agentTreeTable.setModel(tableModelOnColumns); + JScrollBar scrollBar = agentTreeTable.getVerticalScrollBar(); + scrollBar.setValue(0); + scrollBar.removeMouseMotionListener(memoryAgentHeapInfoPanel.mouseMotionAdapter); + createMouseMotionAdapter(memoryAgentHeapInfoPanel, tableModelOnColumns, agentTreeTable); + scrollBar.addMouseMotionListener(memoryAgentHeapInfoPanel.mouseMotionAdapter); + AgentTreeTableRowSorter sorter = + new AgentTreeTableRowSorter(agentTreeTable.getTable().getModel()); + sorter.setListener((columnIndex, sortOrder) -> { + if (columnIndex <= 0 || columnIndex > memoryAgentHeapInfoPanel.columns.length) { + return; + } + if (sortOrder == SortOrder.ASCENDING) { + AgentTreeTableRowSorter.sortDescTree(memoryAgentHeapInfoPanel, + memoryAgentHeapInfoPanel.columns[columnIndex].getName(), tableModelOnColumns); + } else { + AgentTreeTableRowSorter.sortTree(memoryAgentHeapInfoPanel, + memoryAgentHeapInfoPanel.columns[columnIndex].getName(), tableModelOnColumns); + } + tableModelOnColumns.reload(); + }); + agentTreeTable.getTable().setRowSorter(sorter); + agentHeapSplitter.setSecondComponent(new JBSplitter(false, 1)); + } + } + } + }); + } + + private void createMouseMotionAdapter(MemoryAgentHeapInfoPanel memoryAgentHeapInfoPanel, + ListTreeTableModelOnColumns tableModelOnColumns, ExpandTreeTable agentTreeTable) { + memoryAgentHeapInfoPanel.mouseMotionAdapter = new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent mouseEvent) { + JScrollBar jScrollBar = null; + Object sourceObject = mouseEvent.getSource(); + if (sourceObject instanceof JScrollBar) { + jScrollBar = (JScrollBar) sourceObject; + BoundedRangeModel model = jScrollBar.getModel(); + if (model.getExtent() + model.getValue() == model.getMaximum()) { + ListTreeTableModelOnColumns nodeModel = null; + Object modelObject = agentTreeTable.getTree().getModel(); + if (modelObject instanceof ListTreeTableModelOnColumns) { + nodeModel = (ListTreeTableModelOnColumns) modelObject; + DefaultMutableTreeNode rootNode = null; + Object rootObject = nodeModel.getRoot(); + if (rootObject instanceof DefaultMutableTreeNode) { + rootNode = (DefaultMutableTreeNode) rootObject; + int index = memoryAgentHeapInfoPanel.allAgentDatas + .indexOf(memoryAgentHeapInfoPanel.lastDataNode); + List list = memoryAgentHeapInfoPanel + .listCopy(memoryAgentHeapInfoPanel.allAgentDatas, index, index + 20); + for (AgentHeapBean agentDataNode : list) { + DefaultMutableTreeNode defaultMutableTreeNode = + new DefaultMutableTreeNode(agentDataNode); + tableModelOnColumns + .insertNodeInto(defaultMutableTreeNode, rootNode, rootNode.getChildCount()); + memoryAgentHeapInfoPanel.lastDataNode = agentDataNode; + } + } + } + } + } + } + }; + } + + /** + * Secondary treeTable interface + * + * @param sessionId sessionId + * @param clazzId clazzId + * @param className className + * @param chartName chartName + * @return JBPanel + */ + public JBPanel setSecondLevelTreeTable(long sessionId, int clazzId, String className, String chartName) { + agentHeapSplitter.setProportion(LayoutConstants.PROPORTION_SEGMENT); + // instance Table panel + JBPanel instanceView = new JBPanel(); + instanceView.setLayout(new BorderLayout()); + instanceView.setOpaque(true); + instanceView.setBackground(JBColor.background().darker()); + + setTitleStyle(className, instanceView, 1); + + instanceView.setPreferredSize(new Dimension(INSTANCE_TITLE_WIDTH, NUM_418)); + // Table header + Vector columnNames = new Vector<>(); + columnNames.add("instance"); + columnNames.add("allocTime"); + columnNames.add("DealloTime"); + columnNames.add("InstanceId"); + // Display JBTable + DefaultTableModel defaultTableModel = new DefaultTableModel() { + /** + * isCellEditable + * + * @param row row + * @param column column + * @return boolean + */ + public boolean isCellEditable(int row, int column) { + return false; + } + }; + defaultTableModel.setColumnIdentifiers(columnNames); + instanceViewTable = new JBTable(defaultTableModel); + setExtracted(defaultTableModel, instanceViewTable); + // Initialize table data + initData(defaultTableModel, clazzId, className, sessionId, chartName); + JBScrollPane jScrollPane = new JBScrollPane(instanceViewTable); + jScrollPane.setPreferredSize(new Dimension(INSTANCE_TITLE_WIDTH, INSTANCE_PANE_HEIGHT)); + instanceView.add(jScrollPane, BorderLayout.CENTER); + return instanceView; + } + + /** + * 初始化table 表格 + * + * @param model model + * @param cId cId + * @param className className + * @param sessionId long + * @param chartName chartName + */ + public void initData(DefaultTableModel model, Integer cId, String className, long sessionId, String chartName) { + MemoryInstanceManager memoryInstanceManager = new MemoryInstanceManager(); + ChartStandard standard = ProfilerChartsView.sessionMap.get(sessionId).getPublisher().getStandard(); + long firstTime = standard.getFirstTimestamp(); + ChartDataRange selectedRange = standard.getSelectedRange(chartName); + long endTime = selectedRange.getEndTime() + firstTime; + List memoryInstanceInfos = memoryInstanceManager.getMemoryInstanceInfos(cId, 0L, endTime); + memoryInstanceInfos.forEach(memoryInstanceInfo -> { + long deallocTime = memoryInstanceInfo.getDeallocTime(); + long alloc = TimeUnit.MILLISECONDS.toMicros(memoryInstanceInfo.getAllocTime() - firstTime); + String allocTime = getSemiSimplifiedClockString(alloc); + String deAllocTime = " - "; + if (deallocTime != 0) { + long deAllocations = TimeUnit.MILLISECONDS.toMicros(memoryInstanceInfo.getDeallocTime() - firstTime); + deAllocTime = getSemiSimplifiedClockString(deAllocations); + } + Integer instanceId = memoryInstanceInfo.getInstanceId(); + Vector rowData = new Vector<>(); + rowData.add(className); + rowData.add(allocTime); + rowData.add(deAllocTime); + rowData.add(instanceId); + model.addRow(rowData); + }); + } + + /** + * Return a formatted time String in the form of "hh:mm:ss.sss"". + * Hide hours value if both hours and minutes value are zero. + * Default format for Tooltips. + * + * @param micro micro + * @return String + */ + public String getSemiSimplifiedClockString(long micro) { + long micros = Math.max(0, micro); + String result = getFullClockString(micros); + return result; + } + + /** + * Return a formatted time String in the form of "hh:mm:ss.sss". + * Default format for Range description. + * + * @param micro micro + * @return String + */ + public String getFullClockString(long micro) { + long micros = Math.max(0, micro); + long milli = TimeUnit.MICROSECONDS.toMillis(micros) % TimeUnit.SECONDS.toMillis(1); + long sec = TimeUnit.MICROSECONDS.toSeconds(micros) % TimeUnit.MINUTES.toSeconds(1); + long min = TimeUnit.MICROSECONDS.toMinutes(micros) % TimeUnit.HOURS.toMinutes(1); + long hour = TimeUnit.MICROSECONDS.toHours(micros); + return String.format(Locale.ENGLISH, "%02d:%02d:%02d.%03d", hour, min, sec, milli); + } + + private void setExtracted(DefaultTableModel model, JBTable table) { + table.getTableHeader().setFont(new Font("PingFang SC", Font.PLAIN, LayoutConstants.FONT_SIZE)); + table.setFont(new Font("PingFang SC", Font.PLAIN, LayoutConstants.TWELVE)); + table.setOpaque(true); + table.setShowHorizontalLines(false); + table.getTableHeader().getColumnModel().getColumn(3).setMaxWidth(0); + table.getTableHeader().getColumnModel().getColumn(3).setMinWidth(0); + table.getTableHeader().getColumnModel().getColumn(3).setPreferredWidth(0); + RowSorter sorter = new TableRowSorter<>(model); + table.setRowSorter(sorter); + } + + /** + * Three-level treeTable interface + * + * @param sessionId sessionId + * @param instanceId instanceId + * @param name name + * @return JBPanel + */ + public JBPanel setThirdLevelTreeTable(long sessionId, int instanceId, String name) { + agentHeapSplitter.setProportion(PROPORTION_SEGMENT_VIEW); + instanceAndDetailSplitter.setProportion(PROPORTION_SEGMENT_HEAP); + // Reserved Tree Table panel + JBPanel fieldsView = new JBPanel(new BorderLayout()); + fieldsView.setOpaque(true); + setTitleStyle(name, fieldsView, 0); + fieldsView.setPreferredSize(new Dimension(NUM_384, NUM_418)); + Vector columnNames = new Vector<>(); + columnNames.add("Allocation Call Stack"); + DefaultTableModel model = new DefaultTableModel() { + /** + * Returns true regardless of parameter values. + * + * @param row the row whose value is to be queried + * @param column the column whose value is to be queried + * @return true + */ + @Override + public boolean isCellEditable(int row, int column) { + return false; + } + }; + model.setColumnIdentifiers(columnNames); + JBTable callStackTable = new JBTable(model); + DefaultTableCellRenderer defaultCellRender = new DefaultTableCellRenderer() { + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, + boolean hasFocus, int row, int column) { + JLabel jLabel = null; + Object jLabelObject = + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + if (jLabelObject instanceof JLabel) { + jLabel = (JLabel) jLabelObject; + jLabel.setIcon(AllIcons.Nodes.Method); + } + return jLabel; + } + }; + defaultCellRender.getTableCellRendererComponent(callStackTable, null, false, false, 1, 0); + callStackTable.getColumnModel().getColumn(0).setCellRenderer(defaultCellRender); + MemoryInstanceDetailsManager detailsManager = new MemoryInstanceDetailsManager(); + ArrayList detailsInfos = detailsManager.getMemoryInstanceDetailsInfos(instanceId); + detailsInfos.forEach(detailsInfo -> { + Vector rowData = new Vector<>(); + rowData.add( + detailsInfo.getMethodName() + ":" + detailsInfo.getLineNumber() + "," + detailsInfo.getClassName() + + "; (" + detailsInfo.getFieldName() + ")"); + model.addRow(rowData); + }); + callStackTable.setShowHorizontalLines(false); + JBScrollPane jScrollPane = new JBScrollPane(callStackTable); + jScrollPane.setPreferredSize(new Dimension(INSTANCE_TITLE_WIDTH, INSTANCE_SCROLL_HEIGHT)); + fieldsView.add(jScrollPane, BorderLayout.CENTER); + return fieldsView; + } + + private void setTitleStyle(String name, JBPanel viewStyle, int status) { + JBLabel jbLabel = new JBLabel(); + if (status == 0) { + jbLabel.setText(" Instance Details-" + name); + } else { + jbLabel.setText(" Instance view"); + } + Font font = new Font("PingFang SC", Font.PLAIN, LayoutConstants.FONT_SIZE); + jbLabel.setFont(font); + JBLabel closeLabel = new JBLabel(AllIcons.Actions.Close); + closeLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + super.mouseClicked(mouseEvent); + if (status == 0) { + instanceAndDetailSplitter.setSecondComponent(new JBSplitter(false, 1)); + } else { + agentHeapSplitter.setSecondComponent(new JBSplitter(false, 1)); + } + } + }); + + JBPanel titlePanel = new JBPanel(new BorderLayout()); + titlePanel.setOpaque(true); + titlePanel.setBackground(JBColor.background().darker()); + titlePanel.setPreferredSize(new Dimension(NUM_384, INSTANCE_TITLE_HEIGHT)); + titlePanel.add(jbLabel, BorderLayout.WEST); + titlePanel.add(closeLabel, BorderLayout.EAST); + viewStyle.add(titlePanel, BorderLayout.NORTH); + } + + private void chartRightMouseClick() { + if (heapViewPanel != null) { + this.remove(heapViewPanel); + heapViewPanel = null; + memoryTreeTablePanel = null; + } + } + + private void chartMouseDragged() { + } + + private void chartMouseRelease() { + long sessionId = this.bottomPanel.getSessionId(); + SessionInfo sessionInfo = SessionManager.getInstance().getSessionInfo(sessionId); + if (!sessionInfo.isOfflineMode() + && sessionInfo.getDeviceIPPortInfo().getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + return; + } + refreshAgentHeapInfo(sessionId); + } + + private class MemoryTitleView extends JBPanel { + /** + * Save the components should be hidden when item fold + */ + private JBPanel hiddenComp; + + MemoryTitleView() { + this.setLayout(new FlowLayout(FlowLayout.LEFT)); + initFixedComps(); + initHiddenComponents(); + this.setBackground(JBColor.background().brighter()); + } + + private void initFixedComps() { + foldBtn = new JBLabel(); + foldBtn.setName(UtConstant.UT_MEMORY_ITEM_VIEW_FOLD); + foldBtn.setIcon(AllIcons.General.ArrowRight); + this.add(foldBtn); + foldBtn.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + foldBtnClick(); + } + }); + JBLabel title = new JBLabel(item.getName()); + this.add(title); + } + + private void foldBtnClick() { + fold = !fold; + // Item fold, buttons hide + hiddenComp.setVisible(!fold); + if (fold) { + chart.setFold(true); + chart.setEnableSelect(false); + chart.getTooltip().hideTip(); + foldBtn.setIcon(AllIcons.General.ArrowRight); + if (heapViewPanel != null) { + MemoryItemView.this.remove(heapViewPanel); + heapViewPanel = null; + } + if (memoryTreeTablePanel != null) { + MemoryItemView.this.remove(memoryTreeTablePanel); + memoryTreeTablePanel = null; + } + } else { + // Uncheck the box after re-expanding + bottomPanel.getPublisher().getStandard().clearSelectedRange(item.getName()); + chart.setFold(false); + chart.setEnableSelect(true); + foldBtn.setIcon(AllIcons.General.ArrowDown); + } + parent.itemFoldOrExpend(fold, MemoryItemView.this); + // Initialize the maximum value of Y axis here, because it may change after fold/expand + chart.initMaxUnitY(); + chartObserver.setChartFold(fold); + } + + private void initHiddenComponents() { + hiddenComp = new JBPanel(new FlowLayout(FlowLayout.LEFT)); + hiddenComp.setBackground(JBColor.background().brighter()); + this.add(hiddenComp); + // Add components + hiddenComp.add(new DottedLine()); + initDetailCfgBtn(); + initTrackingLabel(); + initCollectBox(); + hiddenComp.add(new DottedLine()); + // The initial state is folded and hiddenComp needs to be hidden + hiddenComp.setVisible(false); + } + + private void initDetailCfgBtn() { + detailCfgBtn = new JBLabel(IconLoader.getIcon("/images/icon_dataselection_normal.png", getClass())); + detailCfgBtn.setName(UtConstant.UT_MEMORY_ITEM_VIEW_DETAIL); + hiddenComp.add(detailCfgBtn); + MemoryItemPopupMenu memoryPopupMenu = new MemoryItemPopupMenu(bottomPanel.getSessionId(), chartObserver); + detailCfgBtn.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + memoryPopupMenu.showMemoryItems(detailCfgBtn, mouseEvent); + } + }); + } + + private void initTrackingLabel() { + hiddenComp.add(new JBLabel("Allocation tracking")); + } + + private void initCollectBox() { + ComboBox collectBox = new ComboBox<>(); + collectBox.setName(UtConstant.UT_MEMORY_ITEM_VIEW_COLLECT_BOX); + collectBox.addItem("Full"); + hiddenComp.add(collectBox); + } + } + + public JBPanel getHeapViewPanel() { + return heapViewPanel; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanel.java new file mode 100644 index 000000000..35f959245 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanel.java @@ -0,0 +1,336 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; +import com.intellij.ui.treeStructure.treetable.TreeTableModel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomComboBox; +import ohos.devtools.views.common.customcomp.CustomJBComboBoxUI; +import ohos.devtools.views.common.customcomp.CustomJBTextField; +import ohos.devtools.views.common.treetable.ExpandTreeTable; + +import javax.swing.BorderFactory; +import javax.swing.SwingUtilities; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.tree.DefaultMutableTreeNode; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * MemoryTreeTablePanel + */ +public class MemoryTreeTablePanel extends JBPanel { + /** + * The record tabbed height + */ + private static final int FEATURES_WIDTH = 1520; + + private static final int NUM_5 = 5; + private static final int NUM_8 = 8; + private MemoryAgentHeapInfoPanel memoryAgentHeapInfoPanel; + + /** + * MemoryTreeTablePanel + * + * @param memoryItemView memoryItemView + * @param sessionId sessionId + * @param chartName chartName + */ + public MemoryTreeTablePanel(MemoryItemView memoryItemView, long sessionId, String chartName) { + this.setOpaque(true); + this.setLayout(new BorderLayout()); + // leftTab + JBLabel leftTab = new JBLabel("Table"); + leftTab.setBorder(BorderFactory + .createEmptyBorder(LayoutConstants.NUM_2, LayoutConstants.RECORD_BORDER_SPACE, LayoutConstants.NUM_2, 0)); + leftTab.setOpaque(false); + leftTab.setPreferredSize(new Dimension(LayoutConstants.JPA_LABEL_WIDTH, LayoutConstants.DEVICES_HEIGHT)); + Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.FONT_SIZE); + leftTab.setFont(font); + leftTab.setBounds(LayoutConstants.RECORD_BORDER_SPACE, LayoutConstants.NUM_2, + LayoutConstants.RECORD_TABBED_BOUNDS_WIDTH, LayoutConstants.NUM_20); + // TAB + JBTabbedPane jbTabbedPane = new JBTabbedPane(); + jbTabbedPane.setBorder( + BorderFactory.createEmptyBorder(LayoutConstants.NUM_2, LayoutConstants.NUM_20, LayoutConstants.NUM_2, 0)); + // tableTab + JBPanel tableTab = createTableTab(memoryItemView, sessionId, chartName); + tableTab.setBorder(BorderFactory.createEmptyBorder(NUM_8, 0, NUM_8, 0)); + // Custom jbTabbedPane + jbTabbedPane.addTab("", tableTab); + jbTabbedPane.setTabComponentAt(jbTabbedPane.indexOfComponent(tableTab), leftTab); + this.add(jbTabbedPane, BorderLayout.CENTER); + // Set the label panel changeListener + jbTabbedPane.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent event) { + } + }); + } + + private JBPanel createTableTab(MemoryItemView memoryItemView, long sessionId, String chartName) { + JBPanel tablePanel = new JBPanel(new MigLayout("insets 0")); + tablePanel.setBorder(BorderFactory.createEmptyBorder(NUM_5, 0, NUM_5, 0)); + tablePanel.setOpaque(true); + + // itemViewBox + List itemViewBox = new ArrayList<>(); + itemViewBox.add("View app heaps"); + + // itemViewBox + List itemArraysBox = new ArrayList<>(); + itemArraysBox.add("Arrange by class"); + + // Reserved Tree Table panel + memoryAgentHeapInfoPanel = new MemoryAgentHeapInfoPanel(memoryItemView, sessionId, chartName); + memoryAgentHeapInfoPanel.setOpaque(true); + memoryAgentHeapInfoPanel.setBackground(JBColor.background().brighter()); + + // add to table Tab Options panel + tablePanel.add(createHeapFeatures(itemViewBox, itemArraysBox), "wrap"); + tablePanel.add(memoryAgentHeapInfoPanel, "dock south"); + + return tablePanel; + } + + private JBPanel createViewTab() { + JBPanel viewPanel = new JBPanel(new BorderLayout()); + viewPanel.setBorder(BorderFactory.createEmptyBorder(NUM_5, 0, NUM_5, 0)); + viewPanel.setOpaque(true); + + List itemBox = new ArrayList<>(); + itemBox.add("View all heaps"); + itemBox.add("View app heaps"); + itemBox.add("View zygote heaps"); + itemBox.add("View image heaps"); + itemBox.add("View JNI heaps"); + + // Reserved Tree Table panel + JBPanel recordTable = new JBPanel(); + recordTable.setOpaque(true); + recordTable.setBorder(BorderFactory.createEmptyBorder(NUM_5, 0, 0, 0)); + + // add to table Tab Options panel + viewPanel.add(createHeapFeatures(itemBox, itemBox), BorderLayout.NORTH); + viewPanel.add(recordTable, BorderLayout.CENTER); + + return viewPanel; + } + + private JBPanel createHeapFeatures(List itemViewBox, List itemArrangeBox) { + // tableFeatures + JBPanel tableFeatures = new JBPanel(); + tableFeatures.setOpaque(false); + tableFeatures.setPreferredSize(new Dimension(FEATURES_WIDTH, LayoutConstants.RECORD_FEATURES_HEIGHT)); + tableFeatures.setBackground(JBColor.background().darker()); + tableFeatures.setBorder(BorderFactory.createEmptyBorder(NUM_8, 0, NUM_8, 0)); + tableFeatures.setLayout(new MigLayout("insets 0")); + tableFeatures.setBorder(BorderFactory.createEmptyBorder(NUM_8, 0, NUM_8, 0)); + + // tableFeatures add itemViewBox + CustomComboBox viewBox = new CustomComboBox(); + viewBox.setName(UtConstant.UT_MEMORY_TREE_TABLE_VIEW); + viewBox.setUI(new CustomJBComboBoxUI()); + viewBox.setBorder(BorderFactory.createLineBorder(ColorConstants.NATIVE_RECORD_BORDER, 1)); + viewBox.setPreferredSize( + new Dimension(LayoutConstants.RECORD_COMBO_BOX_WIDTH, LayoutConstants.RECORD_SEARCH_HEIGHT)); + for (String item : itemViewBox) { + viewBox.addItem(item); + } + viewBox.setSelectedIndex(0); + tableFeatures.add(viewBox); + + // tableFeatures add itemArrangeBox + CustomComboBox arrangeBox = new CustomComboBox(); + arrangeBox.setName(UtConstant.UT_MEMORY_TREE_TABLE_ARRANGE); + arrangeBox.setUI(new CustomJBComboBoxUI()); + arrangeBox.setBorder(BorderFactory.createLineBorder(ColorConstants.NATIVE_RECORD_BORDER, 1)); + arrangeBox.setPreferredSize( + new Dimension(LayoutConstants.RECORD_COMBO_BOX_WIDTH, LayoutConstants.RECORD_SEARCH_HEIGHT)); + for (String item : itemArrangeBox) { + arrangeBox.addItem(item); + } + arrangeBox.setSelectedIndex(0); + tableFeatures.add(arrangeBox); + + JBPanel searchPanel = new JBPanel(); + searchPanel.setOpaque(true); + searchPanel.setLayout(new BorderLayout()); + + // tableFeatures Search + CustomJBTextField search = new CustomJBTextField(); + search.setBorder(BorderFactory.createLineBorder(ColorConstants.NATIVE_RECORD_BORDER, 1)); + search.setText("Search"); + search + .setPreferredSize(new Dimension(LayoutConstants.RECORD_SEARCH_WIDTH, LayoutConstants.RECORD_SEARCH_HEIGHT)); + addSearchListener(search); + searchPanel.add(search, BorderLayout.WEST); + + tableFeatures.add(searchPanel, "wrap"); + return tableFeatures; + } + + private void addSearchListener(CustomJBTextField search) { + search.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent focusEvent) { + if ("Search".equals(search.getText())) { + search.setText(""); + memoryAgentHeapInfoPanel.getTreeTable().getVerticalScrollBar() + .removeMouseMotionListener(memoryAgentHeapInfoPanel.mouseMotionAdapter); + } + } + + @Override + public void focusLost(FocusEvent focusEvent) { + if (search.getText().length() < 1) { + search.setText("Search"); + memoryAgentHeapInfoPanel.getTreeTable().getVerticalScrollBar() + .addMouseMotionListener(memoryAgentHeapInfoPanel.mouseMotionAdapter); + } + } + }); + search.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent event) { + String text = search.getText(); + ExpandTreeTable treeTable = memoryAgentHeapInfoPanel.getTreeTable(); + TreeTableModel model = treeTable.getModel(); + if (model instanceof ListTreeTableModelOnColumns) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + ListTreeTableModelOnColumns tableModel = (ListTreeTableModelOnColumns) model; + DefaultMutableTreeNode root = null; + Object tableModelRoot = tableModel.getRoot(); + if (tableModelRoot instanceof DefaultMutableTreeNode) { + root = (DefaultMutableTreeNode) tableModelRoot; + List datas = memoryAgentHeapInfoPanel.allAgentDatas.stream() + .filter(agentDataNode -> agentDataNode.getAgentClazzName().contains(text)) + .collect(Collectors.toList()); + root.removeAllChildren(); + int totalAllocations = 0; + int totalDeallocations = 0; + int totalTotalCount = 0; + long totalShallowSize = 0; + for (AgentHeapBean agentHeapBean : datas) { + totalAllocations = totalAllocations + agentHeapBean.getAgentAllocationsCount(); + totalDeallocations = + totalDeallocations + agentHeapBean.getAgentDeAllocationsCount(); + totalTotalCount = totalTotalCount + agentHeapBean.getAgentTotalInstanceCount(); + totalShallowSize = totalShallowSize + agentHeapBean.getAgentTotalshallowSize(); + root.add(new DefaultMutableTreeNode(agentHeapBean)); + } + AgentHeapBean userObject = null; + Object rootUserObject = root.getUserObject(); + if (rootUserObject instanceof AgentHeapBean) { + userObject = (AgentHeapBean) rootUserObject; + userObject.setAgentAllocationsCount(totalAllocations); + userObject.setAgentDeAllocationsCount(totalDeallocations); + userObject.setAgentTotalInstanceCount(totalTotalCount); + userObject.setAgentTotalshallowSize(totalShallowSize); + root.setUserObject(userObject); + } + } + tableModel.reload(); + memoryAgentHeapInfoPanel.getTreeTable().getVerticalScrollBar().setValue(0); + } + }); + } + } + + @Override + public void removeUpdate(DocumentEvent event) { + // search + String text = search.getText(); + ExpandTreeTable treeTable = memoryAgentHeapInfoPanel.getTreeTable(); + TreeTableModel model = treeTable.getModel(); + if (model instanceof ListTreeTableModelOnColumns) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + ListTreeTableModelOnColumns tableModel = (ListTreeTableModelOnColumns) model; + DefaultMutableTreeNode root = null; + Object tableModelRoot = tableModel.getRoot(); + if (tableModelRoot instanceof DefaultMutableTreeNode) { + root = (DefaultMutableTreeNode) tableModelRoot; + List datas = memoryAgentHeapInfoPanel.allAgentDatas.stream() + .filter(agentDataNode -> agentDataNode.getAgentClazzName().contains(text)) + .collect(Collectors.toList()); + root.removeAllChildren(); + int totalAllocations = 0; + int totalDeallocations = 0; + int totalTotalCount = 0; + long totalShallowSize = 0; + for (AgentHeapBean agentHeapBean : datas) { + totalAllocations = totalAllocations + agentHeapBean.getAgentAllocationsCount(); + totalDeallocations = + totalDeallocations + agentHeapBean.getAgentDeAllocationsCount(); + totalTotalCount = totalTotalCount + agentHeapBean.getAgentTotalInstanceCount(); + totalShallowSize = totalShallowSize + agentHeapBean.getAgentTotalshallowSize(); + root.add(new DefaultMutableTreeNode(agentHeapBean)); + } + AgentHeapBean userObject = null; + Object rootUserObject = root.getUserObject(); + if (rootUserObject instanceof AgentHeapBean) { + userObject = (AgentHeapBean) rootUserObject; + userObject.setAgentAllocationsCount(totalAllocations); + userObject.setAgentDeAllocationsCount(totalDeallocations); + userObject.setAgentTotalInstanceCount(totalTotalCount); + userObject.setAgentTotalshallowSize(totalShallowSize); + root.setUserObject(userObject); + } + } + tableModel.reload(); + memoryAgentHeapInfoPanel.getTreeTable().getVerticalScrollBar().setValue(0); + } + }); + } + } + + /** + * Gives notification that an attribute or set of attributes changed. + * + * @param documentEvent the document event + */ + @Override + public void changedUpdate(DocumentEvent documentEvent) { + } + }); + } + + public MemoryAgentHeapInfoPanel getMemoryAgentHeapInfoPanel() { + return memoryAgentHeapInfoPanel; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CacheObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CacheObserver.java deleted file mode 100644 index 785cae699..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CacheObserver.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.services.memory.MemoryService; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.layout.chartview.event.IChartEventObserver; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import static ohos.devtools.views.common.LayoutConstants.INDEX_FOUR; -import static ohos.devtools.views.common.LayoutConstants.TEN; -import static ohos.devtools.views.common.ViewConstants.INITIAL_VALUE; - -/** - * 缓存观察类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class CacheObserver implements IChartEventObserver { - /** - * 缓存去数据库获取新数据的间隔 - */ - private static final int CACHE_FREQ = 500; - - /** - * 线程池 - */ - private final ThreadPoolExecutor executor; - - /** - * Session Id - */ - private final long sessionId; - - /** - * 标识时间,缓存每隔CACHE_FREQ去数据库拿一次数据 - */ - private int flagTime = INITIAL_VALUE; - - /** - * 构造函数 - * - * @param sessionId Session Id - */ - public CacheObserver(long sessionId) { - this.sessionId = sessionId; - executor = new ThreadPoolExecutor(INDEX_FOUR, TEN, TEN, TimeUnit.SECONDS, new ArrayBlockingQueue<>(INDEX_FOUR), - new ThreadPoolExecutor.DiscardOldestPolicy()); - } - - /** - * refreshStandard - * - * @param standard 绘图标准 - * @param startTime 开始时间 - * @param endTime 结束时间 - * @param maxDisplayTime 最大显示时间 - */ - @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - } - - /** - * refreshView - * - * @param range 时间范围 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @param isUseCache 是否使用缓存机制 - */ - @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { - if (flagTime == INITIAL_VALUE) { - addCacheData(range.getEndTime(), firstTimestamp); - } - int endTime = range.getEndTime(); - if (endTime < CACHE_FREQ) { - return; - } - // endTime < flagTime,说明停止后重新启动了新任务,这里要初始化flagTime - if (endTime < flagTime) { - addCacheData(range.getEndTime(), firstTimestamp); - flagTime = INITIAL_VALUE; - return; - } - if (endTime - flagTime > CACHE_FREQ) { - // 调用数据库,获取数据 - addCacheData(endTime, firstTimestamp); - // 刷新标识时间 - flagTime = endTime; - } - } - - private void addCacheData(int lastTime, long firstTimestamp) { - executor.execute(new MemoryCacheThread(lastTime, firstTimestamp)); - } - - private final class MemoryCacheThread implements Runnable { - private final int endTime; - private final long firstTimestamp; - - private MemoryCacheThread(int endTime, long firstTimestamp) { - this.endTime = endTime; - this.firstTimestamp = firstTimestamp; - } - - /** - * run - */ - @Override - public void run() { - // 每CACHE_FREQ去数据库拿一次数据,但是要拿超过CACHE_FREQ的数据 - // 否则会因为Chart已经刷新到x秒,缓存中最后的数据也在x秒,导致Chart右侧抖动 - MemoryService.getInstance().addData(sessionId, endTime, endTime + CACHE_FREQ + CACHE_FREQ, firstTimestamp); - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CpuChartObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CpuChartObserver.java new file mode 100644 index 000000000..e07826acd --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/CpuChartObserver.java @@ -0,0 +1,237 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.observer; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.services.cpu.CpuDao; +import ohos.devtools.services.cpu.CpuDataCache; +import ohos.devtools.views.charts.ProfilerChart; +import ohos.devtools.views.charts.RectChart; +import ohos.devtools.views.charts.model.ChartDataModel; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.event.IChartEventObserver; +import org.apache.commons.lang3.StringUtils; + +import java.util.*; +import java.util.List; + +/** + * Observer of cpu chart + */ +public class CpuChartObserver implements IChartEventObserver { + private final ProfilerChart chart; + private final long sessionId; + private boolean chartFold; + private JBPanel threadInfoPanel; + private JBLabel threadLabel; + private ProfilerChartsView bottomPanel; + private HashMap threadMap = new HashMap(); + private ArrayList rectChartList = new ArrayList(); + + /** + * Constructor + * + * @param chart Profiler Chart + * @param chartFold true: Chart fold/expand + */ + public CpuChartObserver(ProfilerChart chart, JBPanel threadInfoPanel, ProfilerChartsView bottomPanel, + boolean chartFold, JBLabel threadLabel) { + this.bottomPanel = bottomPanel; + this.sessionId = bottomPanel.getSessionId(); + this.chart = chart; + this.chartFold = chartFold; + this.threadInfoPanel = threadInfoPanel; + this.threadLabel = threadLabel; + } + + /** + * Refresh chart drawing standard + * + * @param startTime Start time of chart + * @param endTime End time of chart + * @param maxDisplayMillis Maximum display time on view + * @param minMarkInterval The minimum scale interval + */ + @Override + public void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval) { + chart.setMaxDisplayX(maxDisplayMillis); + chart.setMinMarkIntervalX(minMarkInterval); + chart.setStartTime(startTime); + chart.setEndTime(endTime); + chart.repaint(); + chart.revalidate(); + rectChartList.forEach(chart -> { + chart.setMaxDisplayX(maxDisplayMillis); + chart.setMinMarkIntervalX(minMarkInterval); + chart.setStartTime(startTime); + chart.setEndTime(endTime); + chart.repaint(); + chart.revalidate(); + }); + } + + /** + * Refresh view + * + * @param range Chart display time range + * @param firstTimestamp The first time stamp of this chart's data + * @param useCache whether or not use cache + */ + @Override + public void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache) { + LinkedHashMap> cpuResult; + LinkedHashMap> threadResult; + int start = range.getStartTime(); + int end = range.getEndTime(); + boolean chartStop = chart.getBottomPanel().isPause() || chart.getBottomPanel().isStop(); + if (chartStop || !useCache) { + cpuResult = CpuDao.getInstance().getCpuData(sessionId, start, end, firstTimestamp, true); + threadResult = CpuDao.getInstance().getThreadData(sessionId, start, end, firstTimestamp, true); + } else { + cpuResult = CpuDataCache.getInstance().getCpuData(sessionId, start, end); + threadResult = CpuDataCache.getInstance().getThreadData(sessionId, start, end); + } + LinkedHashMap> showDataMap = new LinkedHashMap<>(); + for (int time : cpuResult.keySet()) { + List dataModels = cpuResult.get(time); + if (chartFold) { + ChartDataModel total = new ChartDataModel(); + total.setName("System"); + total.setColor(ColorConstants.CPU); + total.setValue((int)sumChosenItems(dataModels)); + total.setCpuPercent(sumChosenItems(dataModels)); + showDataMap.put(time, Collections.singletonList(total)); + } else { + showDataMap.put(time, dataModels); + } + } + chart.refreshChart(range.getStartTime(), end, showDataMap); + refreshThreadPanel(range.getStartTime(), end, threadResult); + } + + /** + * Sum according to the selected cpu monitor items + * + * @param dataModels Data list + * @return int + */ + private double sumChosenItems(List dataModels) { + double total = 0; + if (dataModels.size() > 0) { + ChartDataModel systemChartDataModel = + dataModels.stream().filter(each -> StringUtils.equals(each.getName(), "System")).findFirst().get(); + if (systemChartDataModel != null) { + return systemChartDataModel.getCpuPercent(); + } + } + return total; + } + + /** + * Setter + * + * @param chartFold true: Chart fold/expand + */ + public void setChartFold(boolean chartFold) { + this.chartFold = chartFold; + ChartStandard standard = chart.getBottomPanel().getPublisher().getStandard(); + ChartDataRange range = standard.getDisplayRange(); + long firstTs = standard.getFirstTimestamp(); + refreshView(range, firstTs, !chart.getBottomPanel().getPublisher().isTraceFile()); + } + + /** + * refreshThreadPanel + * + * @param startTime startTime + * @param endTime endTime + * @param dataMap dataMap + */ + private void refreshThreadPanel(int startTime, int endTime, LinkedHashMap> dataMap) { + dataMap.forEach((integer, chartDataModels) -> { + chartDataModels.forEach(chartDataModel -> { + // add view + if (!threadMap.containsKey(chartDataModel.getIndex())) { + threadMap.put(chartDataModel.getIndex(), chartDataModel.getName()); + JBPanel itemPanel = new JBPanel(null); + itemPanel.setOpaque(false); + JBLabel label = + new JBLabel(" " + chartDataModel.getName() + "(" + chartDataModel.getIndex() + ")"); + label.setBounds(0, 0, 200, 35); + label.setOpaque(true); + label.setBackground(JBColor.background()); + itemPanel.add(label); + RectChart rectChart = new RectChart(this.bottomPanel, "Cpu") { + @Override + protected void buildTooltip(int showKey, int actualKey, boolean newChart) { + ChartDataModel dataModel = buildTooltipItem(actualKey, dataMap, chartDataModel.getIndex()); + tooltip.showThreadStatusTip(this, showKey + "", dataModel, newChart); + } + }; + rectChart.setFold(false); + rectChart.setMaxDisplayX(this.bottomPanel.getPublisher().getStandard().getMaxDisplayMillis()); + rectChart.setMinMarkIntervalX(this.bottomPanel.getPublisher().getStandard().getMinMarkInterval()); + rectChart.setSectionNumY(1); + rectChart.setAxisLabelY(""); + rectChart.setEnableSelect(false); + rectChart.setThreadId(chartDataModel.getIndex()); + rectChart.setBounds(0, 0, bottomPanel.getWidth(), 35); + rectChart.setOpaque(true); + itemPanel.add(rectChart); + rectChartList.add(rectChart); + rectChart.setOpaque(false); + threadInfoPanel.setOpaque(false); + threadInfoPanel.setBackground(JBColor.background().darker()); + threadInfoPanel.add(itemPanel, "wrap, height 30!, gapy 0"); + } + }); + }); + if (!rectChartList.isEmpty()) { + threadLabel.setText("Thread(" + rectChartList.size() + ")"); + for (RectChart rectChart : rectChartList) { + rectChart.refreshChart(startTime, endTime, dataMap); + } + } else { + threadLabel.setText("Thread(0)"); + } + } + + /** + * buildTooltipItem + * + * @param time time + * @param dataMap dataMap + * @param index index + * @return ChartDataModel + */ + private ChartDataModel buildTooltipItem(int time, LinkedHashMap> dataMap, int index) { + ChartDataModel chartDataModel = new ChartDataModel(); + if (dataMap == null || dataMap.size() == 0 || dataMap.get(time) == null) { + return chartDataModel; + } + for (ChartDataModel model : dataMap.get(time)) { + if (index == model.getIndex()) { + chartDataModel = model; + } + } + return chartDataModel; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserver.java index 40a1a5e00..41c1e069f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserver.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserver.java @@ -15,68 +15,69 @@ package ohos.devtools.views.layout.chartview.observer; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; -import ohos.devtools.services.memory.ChartDataCache; -import ohos.devtools.services.memory.MemoryDao; +import ohos.devtools.services.memory.memorydao.MemoryDao; +import ohos.devtools.services.memory.memoryservice.MemoryDataCache; import ohos.devtools.views.charts.ProfilerChart; import ohos.devtools.views.charts.model.ChartDataRange; import ohos.devtools.views.charts.model.ChartStandard; import ohos.devtools.views.charts.model.ChartDataModel; import ohos.devtools.views.layout.chartview.event.IChartEventObserver; import org.apache.commons.collections.CollectionUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static ohos.devtools.views.common.ColorConstants.MEMORY; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_CODE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_GRAPHICS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_JAVA; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_NATIVE; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_OTHERS; +import static ohos.devtools.views.layout.chartview.MonitorItemDetail.MEM_STACK; /** - * 一级界面Memory Chart的观察者 + * Observer of memory chart * * @since 2021/3/1 14:58 */ public class MemoryChartObserver implements IChartEventObserver { - private static final Logger LOGGER = LogManager.getLogger(MemoryChartObserver.class); - - /** - * Profiler Chart - */ private final ProfilerChart chart; - private final Long sessionId; + private final long sessionId; + + private boolean chartFold; /** - * 构造函数 + * Constructor * * @param chart Profiler Chart + * @param sessionId Session id + * @param chartFold true: Chart fold/expand */ - public MemoryChartObserver(ProfilerChart chart, Long sessionId) { + public MemoryChartObserver(ProfilerChart chart, long sessionId, boolean chartFold) { this.sessionId = sessionId; this.chart = chart; + this.chartFold = chartFold; } /** - * 刷新绘图标准 + * Refresh chart drawing standard * - * @param standard 绘图标准 - * @param startTime startTime - * @param endTime endTime - * @param maxDisplayTime maxDisplayTime + * @param startTime Start time of chart + * @param endTime End time of chart + * @param maxDisplayMillis Maximum display time on view + * @param minMarkInterval The minimum scale interval */ @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - // char绘制的跟随时间轴的放大缩小 - chart.setMaxDisplayX(standard.getMaxDisplayMillis()); - chart.setMinMarkIntervalX(standard.getMinMarkInterval()); + public void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval) { + chart.setMaxDisplayX(maxDisplayMillis); + chart.setMinMarkIntervalX(minMarkInterval); - // 跟随时间线同步 chart.setStartTime(startTime); chart.setEndTime(endTime); @@ -85,91 +86,142 @@ public class MemoryChartObserver implements IChartEventObserver { } /** - * 刷新视图 + * Refresh view * - * @param range 时间范围 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @param isUseCache 是否使用缓存 + * @param range Chart display time range + * @param firstTimestamp The first time stamp of this chart's data + * @param useCache whether or not use cache */ @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { - LinkedHashMap> dataMaps = new LinkedHashMap<>(); - LinkedHashMap dataMap; - - boolean isChartStop = chart.getBottomPanel().isFlagEnd() || chart.getBottomPanel().isStopFlag(); - if (isChartStop || !isUseCache) { - // 点击暂停后,读取数据库的时间 - dataMap = MemoryDao.getInstance() - .getData(sessionId, range.getStartTime(), range.getEndTime(), firstTimestamp, true); + public void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache) { + LinkedHashMap> queryResult; + int start = range.getStartTime(); + int end = range.getEndTime(); + boolean chartStop = chart.getBottomPanel().isPause() || chart.getBottomPanel().isStop(); + if (chartStop || !useCache) { + queryResult = MemoryDao.getInstance().getData(sessionId, start, end, firstTimestamp, true); } else { - dataMap = ChartDataCache.getInstance() - .getDataCache(String.valueOf(sessionId), range.getStartTime(), range.getEndTime(), firstTimestamp); + queryResult = MemoryDataCache.getInstance().getData(sessionId, start, end); } Map> configMap = MonitorConfigManager.dataMap.get(sessionId); - if (configMap == null) { // 存放离线采集项数据 - LinkedList offLineIterm = new LinkedList<>(); - offLineIterm.add("Java"); - offLineIterm.add("Native"); - offLineIterm.add("Graphics"); - offLineIterm.add("Stack"); - offLineIterm.add("Code"); - offLineIterm.add("Others"); - // 存放memory离线采集项数据 - Map> offLineMap = new HashMap<>(); - offLineMap.put("Memory", offLineIterm); - // 构建离线memory采集项的dataMap对象 - MonitorConfigManager.dataMap.put(sessionId, offLineMap); - configMap = MonitorConfigManager.dataMap.get(sessionId); + List monitorItemList = new ArrayList<>(); + if (configMap != null) { + monitorItemList = configMap.get("Memory"); } - List configList = configMap.get("Memory"); - for (Long time : dataMap.keySet()) { - ChartDataModel total = new ChartDataModel(); - total.setName("Total"); - total.setColor(MEMORY); - MemoryPluginResult.AppSummary app = dataMap.get(time); - total.setValue(calcTotalValue(app, configList)); - long showTime = time - firstTimestamp; - dataMaps.put((int) showTime, Collections.singletonList(total)); + LinkedHashMap> showDataMap = new LinkedHashMap<>(); + for (int time : queryResult.keySet()) { + List dataModels = queryResult.get(time); + if (chartFold) { + ChartDataModel total = new ChartDataModel(); + total.setName("Total"); + total.setColor(MEMORY); + total.setValue(sumChosenItems(dataModels, monitorItemList)); + showDataMap.put(time, Collections.singletonList(total)); + } else { + List chosenModels = getChosenItems(dataModels, monitorItemList); + showDataMap.put(time, chosenModels); + } } - chart.refreshChart(range.getStartTime(), range.getEndTime(), dataMaps); + chart.refreshChart(range.getStartTime(), end, showDataMap); } /** - * 计算一节界面的Total值,要根据界面选择的指标项,而非所有指标项的Total值 + * Sum according to the selected memory monitor items * - * @param app MemoryPluginResult.AppSummary - * @param configList List + * @param dataModels Data list + * @param monitorItemList List * @return int */ - private int calcTotalValue(MemoryPluginResult.AppSummary app, List configList) { + private int sumChosenItems(List dataModels, List monitorItemList) { int total = 0; - if (CollectionUtils.isEmpty(configList)) { - total = (int) (app.getJavaHeap() + app.getNativeHeap() + app.getGraphics() + app.getStack() + app.getCode() - + app.getPrivateOther()); - return total; - } + boolean configEmpty = CollectionUtils.isEmpty(monitorItemList); + for (ChartDataModel model : dataModels) { + if (configEmpty) { + total += model.getValue(); + continue; + } - if (configList.contains("Java")) { - total += (int) (app.getJavaHeap()); - } - if (configList.contains("Native")) { - total += (int) (app.getNativeHeap()); - } - if (configList.contains("Graphics")) { - total += (int) (app.getGraphics()); - } - if (configList.contains("Stack")) { - total += (int) (app.getStack()); - } - if (configList.contains("Code")) { - total += (int) (app.getCode()); - } - if (configList.contains("Others")) { - total += (int) (app.getPrivateOther()); + if (monitorItemList.contains(MEM_JAVA.getName()) && model.getName().equals(MEM_JAVA.getName())) { + total += model.getValue(); + continue; + } + if (monitorItemList.contains(MEM_NATIVE.getName()) && model.getName().equals(MEM_NATIVE.getName())) { + total += model.getValue(); + continue; + } + if (monitorItemList.contains(MEM_GRAPHICS.getName()) && model.getName().equals(MEM_GRAPHICS.getName())) { + total += model.getValue(); + continue; + } + if (monitorItemList.contains(MEM_STACK.getName()) && model.getName().equals(MEM_STACK.getName())) { + total += model.getValue(); + continue; + } + if (monitorItemList.contains(MEM_CODE.getName()) && model.getName().equals(MEM_CODE.getName())) { + total += model.getValue(); + continue; + } + if (monitorItemList.contains(MEM_OTHERS.getName()) && model.getName().equals(MEM_OTHERS.getName())) { + total += model.getValue(); + } } return total; } + private List getChosenItems(List dataModels, List monitorItemList) { + if (CollectionUtils.isEmpty(monitorItemList)) { + return dataModels; + } + + List result = new ArrayList<>(); + for (ChartDataModel model : dataModels) { + if (monitorItemList.contains(MEM_JAVA.getName()) && model.getName().equals(MEM_JAVA.getName())) { + result.add(model); + continue; + } + if (monitorItemList.contains(MEM_NATIVE.getName()) && model.getName().equals(MEM_NATIVE.getName())) { + result.add(model); + continue; + } + if (monitorItemList.contains(MEM_GRAPHICS.getName()) && model.getName().equals(MEM_GRAPHICS.getName())) { + result.add(model); + continue; + } + if (monitorItemList.contains(MEM_STACK.getName()) && model.getName().equals(MEM_STACK.getName())) { + result.add(model); + continue; + } + if (monitorItemList.contains(MEM_CODE.getName()) && model.getName().equals(MEM_CODE.getName())) { + result.add(model); + continue; + } + if (monitorItemList.contains(MEM_OTHERS.getName()) && model.getName().equals(MEM_OTHERS.getName())) { + result.add(model); + } + } + return result; + } + + /** + * Update fold status and refresh current chart + * + * @param chartFold true: Chart fold/expand + */ + public void setChartFold(boolean chartFold) { + this.chartFold = chartFold; + refreshManually(); + } + + /** + * Refresh current chart manually + */ + public void refreshManually() { + ChartStandard standard = chart.getBottomPanel().getPublisher().getStandard(); + ChartDataRange range = standard.getDisplayRange(); + long firstTs = standard.getFirstTimestamp(); + refreshView(range, firstTs, !chart.getBottomPanel().getPublisher().isTraceFile()); + } + } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserver.java deleted file mode 100644 index e14769339..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserver.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; -import ohos.devtools.services.memory.ChartDataCache; -import ohos.devtools.services.memory.MemoryDao; -import ohos.devtools.views.charts.ProfilerChart; -import ohos.devtools.views.charts.model.ChartDataModel; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.MonitorItemDetail; -import ohos.devtools.views.layout.chartview.event.IChartEventObserver; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import static ohos.devtools.views.common.MonitorItemDetail.MEM_CODE; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_GRAPHICS; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_JAVA; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_NATIVE; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_OTHERS; -import static ohos.devtools.views.common.MonitorItemDetail.MEM_STACK; - -/** - * MemoryStageObserver类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class MemoryStageObserver implements IChartEventObserver { - /** - * Profiler Chart - */ - private final ProfilerChart chart; - - private final Long sessionId; - - /** - * 构造函数 - * - * @param chart Profiler Chart - * @param sessionId Long sessionId - */ - public MemoryStageObserver(ProfilerChart chart, Long sessionId) { - this.chart = chart; - this.sessionId = sessionId; - } - - /** - * 刷新绘图标准 - * - * @param standard 绘图标准 - * @param startTime startTime - * @param endTime endTime - * @param maxDisplayTime maxDisplayTime - */ - @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - // char绘制的跟随时间轴的放大缩小 - chart.setMaxDisplayX(standard.getMaxDisplayMillis()); - chart.setMinMarkIntervalX(standard.getMinMarkInterval()); - - // 跟随时间线同步 - chart.setStartTime(startTime); - chart.setEndTime(endTime); - - chart.repaint(); - chart.revalidate(); - } - - /** - * 刷新视图 - * - * @param range 时间范围 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @param isUseCache 是否使用缓存 - */ - @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { - LinkedHashMap> dataMaps = new LinkedHashMap<>(); - LinkedHashMap dataMap; - - boolean isChartStop = chart.getBottomPanel().isFlagEnd() || chart.getBottomPanel().isStopFlag(); - if (isChartStop || !isUseCache) { - // 点击暂停后,读取数据库的时间 - dataMap = MemoryDao.getInstance() - .getData(sessionId, range.getStartTime(), range.getEndTime(), firstTimestamp, true); - } else { - dataMap = ChartDataCache.getInstance() - .getDataCache(String.valueOf(sessionId), range.getStartTime(), range.getEndTime(), firstTimestamp); - } - - Map> configMap = MonitorConfigManager.dataMap.get(sessionId); - if (configMap == null) { // 存放离线采集项数据 - LinkedList offLineIterm = new LinkedList<>(); - offLineIterm.add("Java"); - offLineIterm.add("Native"); - offLineIterm.add("Graphics"); - offLineIterm.add("Stack"); - offLineIterm.add("Code"); - offLineIterm.add("Others"); - // 存放memory离线采集项数据 - Map> offLineMap = new HashMap<>(); - offLineMap.put("Memory", offLineIterm); - // 构建离线memory采集项的dataMap对象 - MonitorConfigManager.dataMap.put(sessionId, offLineMap); - configMap = MonitorConfigManager.dataMap.get(sessionId); - } - - List configList = configMap.get("Memory"); - for (Long time : dataMap.keySet()) { - MemoryPluginResult.AppSummary app = dataMap.get(time); - List list = buildModelsByConfig(app, configList); - long showTime = time - firstTimestamp; - dataMaps.put((int) showTime, list); - } - chart.refreshChart(range.getStartTime(), range.getEndTime(), dataMaps); - } - - private List buildModelsByConfig(MemoryPluginResult.AppSummary app, List configList) { - List list = new ArrayList<>(); - if (configList.contains("Java")) { - ChartDataModel memJava = setConfigIndex(MEM_JAVA); - memJava.setValue((int) (app.getJavaHeap())); - list.add(memJava); - } - if (configList.contains("Native")) { - ChartDataModel memNative = setConfigIndex(MEM_NATIVE); - memNative.setValue((int) (app.getNativeHeap())); - list.add(memNative); - } - if (configList.contains("Graphics")) { - ChartDataModel memGraphics = setConfigIndex(MEM_GRAPHICS); - memGraphics.setValue((int) (app.getGraphics())); - list.add(memGraphics); - } - if (configList.contains("Stack")) { - ChartDataModel memStack = setConfigIndex(MEM_STACK); - memStack.setValue((int) (app.getStack())); - list.add(memStack); - } - if (configList.contains("Code")) { - ChartDataModel memCode = setConfigIndex(MEM_CODE); - memCode.setValue((int) (app.getCode())); - list.add(memCode); - } - if (configList.contains("Others")) { - ChartDataModel memOthers = setConfigIndex(MEM_OTHERS); - memOthers.setValue((int) (app.getPrivateOther())); - list.add(memOthers); - } - return list; - } - - private ChartDataModel setConfigIndex(MonitorItemDetail monitorItemDetail) { - ChartDataModel memIndex = new ChartDataModel(); - memIndex.setIndex(monitorItemDetail.getIndex()); - memIndex.setColor(monitorItemDetail.getColor()); - memIndex.setName(monitorItemDetail.getName()); - return memIndex; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisher.java similarity index 61% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserver.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisher.java index fc1445021..f888e2eac 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserver.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisher.java @@ -1,464 +1,433 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.datasources.utils.session.entity.SessionInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.services.memory.ChartDataCache; -import ohos.devtools.services.memory.MemoryService; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJButton; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.chartview.event.IChartEventObserver; -import ohos.devtools.views.layout.chartview.event.IChartEventPublisher; -import ohos.devtools.views.layout.swing.CountingThread; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.ImageIcon; -import javax.swing.SwingWorker; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import static ohos.devtools.views.common.LayoutConstants.CHART_START_DELAY; -import static ohos.devtools.views.common.ViewConstants.INITIAL_VALUE; -import static ohos.devtools.views.common.ViewConstants.NUM_10; -import static ohos.devtools.views.common.ViewConstants.REFRESH_FREQ; - -/** - * 监控界面保存Chart的面板的事件发布者 - * - * @since 2021/1/26 20:34 - */ -public class ProfilerChartsViewObserver implements IChartEventPublisher { - /** - * 日志 - */ - private static final Logger LOGGER = LogManager.getLogger(ProfilerChartsViewObserver.class); - - /** - * Chart监控界面的定时刷新线程的名称 - */ - private static final String RUN_NAME = "ProfilerChartsViewMonitorTimer"; - - /** - * Chart监控界面的定时刷新线程的进度条名称 - */ - private static final String RUN_NAME_SCROLLBAR = "ScrollbarTimer"; - - /** - * 监听的视图 - */ - private final ProfilerChartsView view; - - /** - * 是否为Trace文件静态导入模式 - * - * @see "true表示静态导入,false表示动态实时跟踪" - */ - private final boolean isTraceFile; - - /** - * 监听者的集合 - */ - private final List listeners = new ArrayList<>(); - - /** - * 异步初始化滚动条线程池 - */ - private final ThreadPoolExecutor scrollBarThreadPool = - new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); - - /** - * 绘图标准 - */ - private final ChartStandard standard; - - /** - * Chart刷新线程是否在运行 - */ - private boolean isRefreshing = false; - - /** - * 滚动条是否显示 - */ - private boolean isScrollbarShow = false; - - /** - * 启动任务时,本机时间和数据流中的时间偏移量 - */ - private long startOffset = INITIAL_VALUE; - - /** - * 刷新缓存所需要的时间范围 - */ - private ChartDataRange range = new ChartDataRange(); - - /** - * 构造函数 - * - * @param view 监听的视图 - * @param isTraceFile 是否为Trace文件静态导入模式 - */ - public ProfilerChartsViewObserver(ProfilerChartsView view, boolean isTraceFile) { - this.view = view; - this.isTraceFile = isTraceFile; - standard = new ChartStandard(view.getSessionId()); - } - - /** - * 展示Trace文件分析结果 - * - * @param firstTimestamp Trace文件中数据的开始时间 - * @param lastTimestamp Trace文件中数据的结束时间 - */ - public void showTraceResult(long firstTimestamp, long lastTimestamp) { - if (!isTraceFile) { - return; - } - - standard.setFirstTimestamp(firstTimestamp); - // 保存trace文件导入模式下最后一个数据的时间戳 - standard.setLastTimestamp(lastTimestamp); - int end = (int) (lastTimestamp - firstTimestamp); - int start; - if (end > standard.getMaxDisplayMillis()) { - start = end - standard.getMaxDisplayMillis(); - // 这里需要异步初始化滚动条,否则会因为view没有渲染导致滚动条无法显示 - scrollBarThreadPool.execute(() -> { - try { - TimeUnit.MILLISECONDS.sleep(LayoutConstants.FIVE_HUNDRED); - view.initScrollbar(); - view.getHorizontalBar().resizeAndReposition(); - isScrollbarShow = true; - } catch (InterruptedException exception) { - LOGGER.error("Asynchronous initialization scrollbar failed!", exception); - } - }); - } else { - start = 0; - } - notifyRefresh(start, end); - } - - /** - * 检查Loading结果:Loading完成后启动刷新 - */ - public void checkLoadingResult() { - new SwingWorker() { - @Override - protected SessionInfo doInBackground() { - SessionInfo info = SessionManager.getInstance().isRefsh(standard.getSessionId()); - while (info == null || !info.isStartRefsh()) { - try { - TimeUnit.MILLISECONDS.sleep(NUM_10); - } catch (InterruptedException exception) { - LOGGER.info("InterruptedException"); - } - info = SessionManager.getInstance().isRefsh(standard.getSessionId()); - } - return info; - } - - @Override - protected void done() { - try { - SessionInfo info = get(); - long first = info.getStartTimestamp(); - // 等待一段时间再启动刷新Chart,否则会导致查询的数据还未入库完成 - TimeUnit.MILLISECONDS.sleep(CHART_START_DELAY); - view.hideLoading(); - // 启动缓存和Chart - ChartDataCache.getInstance() - .initCache(String.valueOf(standard.getSessionId()), LayoutConstants.TWENTY_FIVE); - MemoryService.getInstance().addData(standard.getSessionId(), 0, CHART_START_DELAY, first); - startRefresh(first); - } catch (InterruptedException | ExecutionException e) { - LOGGER.error(String.format(Locale.ENGLISH, "Error occur when loading done: %s", e.toString())); - } - } - }.execute(); - } - - /** - * 开始刷新Chart - * - * @param firstTimestamp 本次Chart最后一个数据的时间戳 - */ - public void startRefresh(long firstTimestamp) { - if (isTraceFile) { - return; - } - view.setStopFlag(false); - view.setFlagEnd(false); - standard.setFirstTimestamp(firstTimestamp); - startOffset = DateTimeUtil.getNowTimeLong() - standard.getFirstTimestamp(); - // 启动Chart绘制定时器 - startChartTimer(); - isRefreshing = true; - } - - /** - * 启动Chart绘制定时器 - */ - private void startChartTimer() { - // 启动绘制Chart线程 - QuartzManager.getInstance().addExecutor(RUN_NAME, () -> { - try { - // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 - standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - startOffset - CHART_START_DELAY); - int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; - notifyRefresh(start, end); - } catch (Exception exception) { - LOGGER.error(exception.getMessage()); - } - }); - // 刷新间隔暂定30ms - QuartzManager.getInstance().startExecutor(RUN_NAME, 0, REFRESH_FREQ); - - // 如果有线程在刷新,则不需要再另起一个轮询线程。 - if (!isRefreshing) { - QuartzManager.getInstance().addExecutor(RUN_NAME_SCROLLBAR, () -> { - // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 - standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - startOffset - CHART_START_DELAY); - int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; - // 当end大于最大展示时间时,且滚动条未显示时,初始化显示滚动条,并把isScrollbarShow置为true - if (end > standard.getMaxDisplayMillis() && !isScrollbarShow) { - // isScrollbarShow判断必须保留,否则会导致Scrollbar重复初始化,频繁闪烁 - view.initScrollbar(); - isScrollbarShow = true; - } - notifyRefreshScrollbar(start, end); - }); - - // 刷新间隔暂定30ms - QuartzManager.getInstance().startExecutor(RUN_NAME_SCROLLBAR, 0, REFRESH_FREQ); - } - } - - /** - * 暂停刷新Chart - */ - public void pauseRefresh() { - if (isRefreshing) { - QuartzManager.getInstance().endExecutor(RUN_NAME); - isRefreshing = false; - view.setFlagEnd(true); - } - } - - /** - * 停止刷新Chart - * - * @param isOffline 设备是否断连 - */ - public void stopRefresh(boolean isOffline) { - QuartzManager.getInstance().endExecutor(RUN_NAME); - QuartzManager.getInstance().endExecutor(RUN_NAME_SCROLLBAR); - isRefreshing = false; - view.setStopFlag(true); - view.setFlagEnd(true); - if (isOffline) { - HosJButton buttonRun = view.getTaskScenePanelChart().getjButtonRun(); - HosJButton buttonStop = view.getTaskScenePanelChart().getjButtonStop(); - buttonRun.setIcon( - new ImageIcon(ProfilerChartsViewObserver.class.getClassLoader().getResource("images/over.png"))); - buttonRun.setEnabled(true); - ActionListener[] actionListenersRun = buttonRun.getActionListeners(); - for (ActionListener listener : actionListenersRun) { - buttonRun.removeActionListener(listener); - } - buttonStop.setIcon( - new ImageIcon(ProfilerChartsViewObserver.class.getClassLoader().getResource("images/suspended.png"))); - buttonStop.setEnabled(true); - ActionListener[] actionListenersStop = buttonStop.getActionListeners(); - for (ActionListener listener : actionListenersStop) { - buttonStop.removeActionListener(listener); - } - CountingThread countingThread = view.getTaskScenePanelChart().getCounting(); - countingThread.setStopFlag(true); - } - } - - /** - * 暂停后重新开始刷新Chart - */ - public void restartRefresh() { - if (isTraceFile) { - return; - } - - if (view.isStopFlag()) { - // 如果是已停止状态,则返回 - return; - } - - if (!isRefreshing) { - isRefreshing = true; - view.setFlagEnd(false); - startChartTimer(); - // 重新开始时,也要移除框选状态(暂定) - standard.clearSelectedRange(); - } - } - - /** - * 添加监听者 - * - * @param listener IChartEventListener - */ - @Override - public void attach(IChartEventObserver listener) { - listeners.add(listener); - } - - /** - * 移除监听者 - * - * @param listener IChartEventListener - */ - @Override - public void detach(IChartEventObserver listener) { - listeners.remove(listener); - } - - /** - * 通知刷新 - * - * @param start 开始时间 - * @param end 结束时间 - */ - @Override - public void notifyRefresh(int start, int end) { - standard.updateDisplayTimeRange(start, end); - listeners.forEach((lis) -> { - if (!(lis instanceof CacheObserver)) { - lis.refreshView(standard.getDisplayRange(), standard.getFirstTimestamp(), !isTraceFile); - } - }); - } - - /** - * 通知刷新滚动条 - * - * @param start 开始时间 - * @param end 结束时间 - */ - private void notifyRefreshScrollbar(int start, int end) { - // 当前时间超过最大展示时间,则调整滚动条长度和位置 - if (end > standard.getMaxDisplayMillis()) { - if (view.getHorizontalBar() != null) { - view.getHorizontalBar().resizeAndReposition(); - } - } - // 不暂停缓存的观察者 - listeners.forEach((lis) -> { - if (lis instanceof CacheObserver) { - range.setStartTime(start); - range.setEndTime(end); - lis.refreshView(range, standard.getFirstTimestamp(), !isTraceFile); - } - }); - } - - /** - * 时间线和char缩放 - * - * @param startTime 缩放后的界面开始时间 - * @param endTime 结束时间的界面开始时间 - * @param maxDisplayTime 窗体上可以显示的最大毫秒数 - */ - public void charZoom(int startTime, int endTime, int maxDisplayTime) { - // 修改char展示的时间范围 - standard.setMaxDisplayMillis(maxDisplayTime); - standard.updateDisplayTimeRange(startTime, endTime); - // standard绘图标准(这个参数传输需要创建新的对象,而缩放功能只是修改部分时间线和char的标准,所以这个参数建议移出) - listeners.forEach((lis) -> { - if (!(lis instanceof CacheObserver)) { - standard.setMaxDisplayMillis(maxDisplayTime); - lis.refreshStandard(standard, startTime, endTime, maxDisplayTime); - lis.refreshView(standard.getDisplayRange(), standard.getFirstTimestamp(), !isTraceFile); - } - }); - } - - /** - * 界面毫秒数的时间刻度缩放 - * - * @param maxDisplayTime 窗体上可以显示的最大毫秒数 - * @param minMarkInterval 窗体上可以显示的时间刻度的单位 - * @param newStartTime 新的开始时间 - * @param newEndTime 新的结束时间 - */ - public void msTimeZoom(int maxDisplayTime, int minMarkInterval, int newStartTime, int newEndTime) { - standard.setMaxDisplayMillis(maxDisplayTime); - standard.setMinMarkInterval(minMarkInterval); - standard.updateDisplayTimeRange(newStartTime, newEndTime); - // standard绘图标准(这个参数传输需要创建新的对象,而缩放功能只是修改部分时间线和chart的标准,所以这个参数建议移出) - listeners.forEach((lis) -> { - if (!(lis instanceof CacheObserver)) { - lis.refreshStandard(standard, newStartTime, newEndTime, maxDisplayTime); - lis.refreshView(standard.getDisplayRange(), standard.getFirstTimestamp(), !isTraceFile); - } - }); - } - - /** - * Getter - * - * @return ChartStandard - */ - public ChartStandard getStandard() { - return standard; - } - - /** - * Getter - * - * @return isTraceFile - */ - public boolean isTraceFile() { - return isTraceFile; - } - - public List getListeners() { - return listeners; - } - - public boolean isRefreshing() { - return isRefreshing; - } - - public boolean isScrollbarShow() { - return isScrollbarShow; - } - - public void setScrollbarShow(boolean scrollbarShow) { - isScrollbarShow = scrollbarShow; - } -} +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.observer; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.datasources.utils.session.entity.SessionInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.customcomp.CustomJButton; +import ohos.devtools.views.layout.chartview.CountingThread; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.event.IChartEventObserver; +import ohos.devtools.views.layout.chartview.event.IChartEventPublisher; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.SwingWorker; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import static ohos.devtools.views.common.LayoutConstants.INITIAL_VALUE; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.CHART_START_DELAY; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.REFRESH_FREQ; + +/** + * 监控界面保存Chart的面板的事件发布者 + */ +public class ProfilerChartsViewPublisher implements IChartEventPublisher { + /** + * 日志 + */ + private static final Logger LOGGER = LogManager.getLogger(ProfilerChartsViewPublisher.class); + + /** + * Chart监控界面的定时刷新线程的名称 + */ + private static final String RUN_NAME = "ProfilerChartsViewMonitorTimer"; + + /** + * Chart监控界面的定时刷新线程的进度条名称 + */ + private static final String RUN_NAME_SCROLLBAR = "ScrollbarTimer"; + + private static final int NUM_10 = 10; + + /** + * 监听的视图 + */ + private final ProfilerChartsView view; + + /** + * 是否为Trace文件静态导入模式 + * + * @see "true表示静态导入,false表示动态实时跟踪" + */ + private final boolean traceFile; + + /** + * 监听者的集合 + */ + private final List observers = new ArrayList<>(); + + /** + * 绘图标准 + */ + private final ChartStandard standard; + + /** + * Chart刷新线程是否在运行 + */ + private boolean refreshing = false; + + /** + * 滚动条是否显示 + */ + private boolean displayScrollbar = false; + + /** + * 启动任务时,本机时间和数据流中的时间偏移量 + */ + private long startOffset = INITIAL_VALUE; + + /** + * 构造函数 + * + * @param view 监听的视图 + * @param traceFile 是否为Trace文件静态导入模式 + */ + public ProfilerChartsViewPublisher(ProfilerChartsView view, boolean traceFile) { + this.view = view; + this.traceFile = traceFile; + standard = new ChartStandard(view.getSessionId()); + } + + /** + * 展示Trace文件分析结果 + * + * @param firstTimestamp Trace文件中数据的开始时间 + * @param lastTimestamp Trace文件中数据的结束时间 + */ + public void showTraceResult(long firstTimestamp, long lastTimestamp) { + if (!traceFile) { + return; + } + + standard.setFirstTimestamp(firstTimestamp); + // 保存trace文件导入模式下最后一个数据的时间戳 + standard.setLastTimestamp(lastTimestamp); + int end = (int) (lastTimestamp - firstTimestamp); + int start = 0; + if (end > standard.getMaxDisplayMillis()) { + start = end - standard.getMaxDisplayMillis(); + // 这里需要异步初始化滚动条,否则会因为view没有渲染导致滚动条无法显示 + new SwingWorker<>() { + @Override + protected Object doInBackground() { + try { + TimeUnit.MILLISECONDS.sleep(LayoutConstants.FIVE_HUNDRED); + } catch (InterruptedException exception) { + LOGGER.error("Asynchronous initialization scrollbar failed!", exception); + } + return new Object(); + } + + @Override + protected void done() { + view.initScrollbar(); + view.getHorizontalBar().resizeAndReposition(); + displayScrollbar = true; + } + }.execute(); + } + notifyRefresh(start, end); + } + + /** + * 检查Loading结果:Loading完成后启动刷新 + */ + public void checkLoadingResult() { + new SwingWorker() { + @Override + protected SessionInfo doInBackground() throws InterruptedException { + SessionInfo info = SessionManager.getInstance().getSessionInfo(standard.getSessionId()); + while (info == null || !info.isStartRefsh()) { + try { + TimeUnit.MILLISECONDS.sleep(NUM_10); + } catch (InterruptedException exception) { + LOGGER.info("InterruptedException"); + } + info = SessionManager.getInstance().getSessionInfo(standard.getSessionId()); + } + // 等待一段时间再启动刷新Chart,否则会导致查询的数据还未入库完成 + TimeUnit.MILLISECONDS.sleep(CHART_START_DELAY); + return info; + } + + @Override + protected void done() { + try { + SessionInfo info = get(); + long first = info.getStartTimestamp(); + view.hideLoading(); + startRefresh(first); + } catch (InterruptedException | ExecutionException e) { + LOGGER.error(String.format(Locale.ENGLISH, "Error occur when loading done: %s", e.toString())); + } + } + }.execute(); + } + + /** + * 开始刷新Chart + * + * @param firstTimestamp 本次Chart第一个数据的时间戳 + */ + public void startRefresh(long firstTimestamp) { + if (traceFile) { + return; + } + view.setStop(false); + view.setPause(false); + standard.setFirstTimestamp(firstTimestamp); + startOffset = DateTimeUtil.getNowTimeLong() - standard.getFirstTimestamp(); + // 启动Chart绘制定时器 + startChartTimer(); + refreshing = true; + } + + /** + * 启动Chart绘制定时器 + */ + private void startChartTimer() { + // 启动绘制Chart线程 + QuartzManager.getInstance().addExecutor(RUN_NAME, () -> { + try { + // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 + standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - startOffset - CHART_START_DELAY); + int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); + int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; + notifyRefresh(start, end); + } catch (Exception exception) { + LOGGER.error("Exception", exception); + } + }); + // 刷新间隔暂定30ms + QuartzManager.getInstance().startExecutor(RUN_NAME, 0, REFRESH_FREQ); + + // 如果有线程在刷新,则不需要再另起一个轮询线程。 + if (!refreshing) { + QuartzManager.getInstance().addExecutor(RUN_NAME_SCROLLBAR, () -> { + // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 + standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - startOffset - CHART_START_DELAY); + int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); + int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; + // 当end大于最大展示时间时,且滚动条未显示时,初始化显示滚动条,并把isScrollbarShow置为true + if (end > standard.getMaxDisplayMillis() && !displayScrollbar) { + // isScrollbarShow判断必须保留,否则会导致Scrollbar重复初始化,频繁闪烁 + view.initScrollbar(); + displayScrollbar = true; + } + notifyRefreshScrollbar(start, end); + }); + + // 刷新间隔暂定30ms + QuartzManager.getInstance().startExecutor(RUN_NAME_SCROLLBAR, 0, REFRESH_FREQ); + } + } + + /** + * 暂停刷新Chart + */ + public void pauseRefresh() { + if (refreshing) { + QuartzManager.getInstance().endExecutor(RUN_NAME); + refreshing = false; + view.setPause(true); + } + } + + /** + * 停止刷新Chart + * + * @param isOffline 设备是否断连 + */ + public void stopRefresh(boolean isOffline) { + QuartzManager.getInstance().endExecutor(RUN_NAME); + QuartzManager.getInstance().endExecutor(RUN_NAME_SCROLLBAR); + refreshing = false; + view.setStop(true); + view.setPause(true); + if (isOffline) { + CustomJButton buttonRun = view.getTaskScenePanelChart().getjButtonRun(); + CustomJButton buttonStop = view.getTaskScenePanelChart().getjButtonStop(); + buttonRun.setIcon(IconLoader.getIcon("/images/breakpoint.png", getClass())); + buttonRun.setEnabled(true); + ActionListener[] actionListenersRun = buttonRun.getActionListeners(); + for (ActionListener listener : actionListenersRun) { + buttonRun.removeActionListener(listener); + } + + buttonStop.setIcon(AllIcons.Process.ProgressResumeHover); + buttonStop.setEnabled(true); + ActionListener[] actionListenersStop = buttonStop.getActionListeners(); + for (ActionListener listener : actionListenersStop) { + buttonStop.removeActionListener(listener); + } + CountingThread countingThread = view.getTaskScenePanelChart().getCounting(); + countingThread.setStopFlag(true); + } + } + + /** + * 暂停后重新开始刷新Chart + */ + public void restartRefresh() { + if (traceFile) { + return; + } + + if (view.isStop()) { + // 如果是已停止状态,则返回 + return; + } + + if (!refreshing) { + refreshing = true; + view.setPause(false); + startChartTimer(); + // 重新开始时,也要移除框选状态(暂定) + standard.clearAllSelectedRanges(); + } + } + + /** + * Add observer + * + * @param observer Observer of chart refreshes event + */ + @Override + public void attach(IChartEventObserver observer) { + observers.add(observer); + } + + /** + * Remove observer + * + * @param observer Observer of chart refreshes event + */ + @Override + public void detach(IChartEventObserver observer) { + observers.remove(observer); + } + + /** + * notify to refresh + * + * @param start Start time of chart + * @param end End time of chart + */ + @Override + public void notifyRefresh(int start, int end) { + standard.updateDisplayTimeRange(start, end); + ChartDataRange range = standard.getDisplayRange(); + observers.forEach(lis -> lis.refreshView(range, standard.getFirstTimestamp(), !traceFile)); + } + + /** + * 通知刷新滚动条 + * + * @param start 开始时间 + * @param end 结束时间 + */ + private void notifyRefreshScrollbar(int start, int end) { + // 当前时间超过最大展示时间,则调整滚动条长度和位置 + if (end > standard.getMaxDisplayMillis()) { + if (view.getHorizontalBar() != null) { + view.getHorizontalBar().resizeAndReposition(); + } + } + } + + /** + * 时间线和char缩放 + * + * @param startTime 缩放后的界面开始时间 + * @param endTime 结束时间的界面开始时间 + * @param maxDisplayTime 窗体上可以显示的最大毫秒数 + */ + public void charZoom(int startTime, int endTime, int maxDisplayTime) { + // 修改char展示的时间范围 + standard.setMaxDisplayMillis(maxDisplayTime); + standard.updateDisplayTimeRange(startTime, endTime); + observers.forEach(lis -> { + standard.setMaxDisplayMillis(maxDisplayTime); + lis.refreshStandard(startTime, endTime, maxDisplayTime, standard.getMinMarkInterval()); + lis.refreshView(standard.getDisplayRange(), standard.getFirstTimestamp(), !traceFile); + }); + } + + /** + * 界面毫秒数的时间刻度缩放 + * + * @param maxDisplayTime 窗体上可以显示的最大毫秒数 + * @param minMarkInterval 窗体上可以显示的时间刻度的单位 + * @param newStartTime 新的开始时间 + * @param newEndTime 新的结束时间 + */ + public void msTimeZoom(int maxDisplayTime, int minMarkInterval, int newStartTime, int newEndTime) { + standard.setMaxDisplayMillis(maxDisplayTime); + standard.setMinMarkInterval(minMarkInterval); + standard.updateDisplayTimeRange(newStartTime, newEndTime); + observers.forEach(lis -> { + lis.refreshStandard(newStartTime, newEndTime, maxDisplayTime, minMarkInterval); + lis.refreshView(standard.getDisplayRange(), standard.getFirstTimestamp(), !traceFile); + }); + } + + /** + * Getter + * + * @return ChartStandard + */ + public ChartStandard getStandard() { + return standard; + } + + /** + * Getter + * + * @return traceFile + */ + public boolean isTraceFile() { + return traceFile; + } + + public List getObservers() { + return observers; + } + + public boolean isRefreshing() { + return refreshing; + } + + public boolean isDisplayScrollbar() { + return displayScrollbar; + } + + public void setDisplayScrollbar(boolean displayScrollbar) { + this.displayScrollbar = displayScrollbar; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/TimelineObserver.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/TimelineObserver.java index 01a23dd61..5f28ae93f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/TimelineObserver.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/observer/TimelineObserver.java @@ -16,45 +16,42 @@ package ohos.devtools.views.layout.chartview.observer; import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.chart.ProfilerTimeline; +import ohos.devtools.views.layout.chartview.ProfilerTimeline; import ohos.devtools.views.layout.chartview.event.IChartEventObserver; /** - * Profiler时间线的观察者 + * Observer of profiler timeline * * @since 2021/2/1 10:36 */ public class TimelineObserver implements IChartEventObserver { /** - * Profiler时间线 + * Profiler timeline */ private final ProfilerTimeline timeline; /** - * 构造函数 + * Constructor * - * @param timeline Profiler时间线 + * @param timeline Profiler timeline */ public TimelineObserver(ProfilerTimeline timeline) { this.timeline = timeline; } /** - * 刷新绘图标准 + * Refresh chart drawing standard * - * @param standard 绘图标准 - * @param startTime startTime - * @param endTime endTime - * @param maxDisplayTime maxDisplayTime + * @param startTime Start time of chart + * @param endTime End time of chart + * @param maxDisplayMillis Maximum display time on view + * @param minMarkInterval The minimum scale interval */ @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - // timeline绘制的缩放尺寸设置 - timeline.setMaxDisplayTime(standard.getMaxDisplayMillis()); - timeline.setMinMarkInterval(standard.getMinMarkInterval()); + public void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval) { + timeline.setMaxDisplayTime(maxDisplayMillis); + timeline.setMinMarkInterval(minMarkInterval); - // 重新更新开始和结束时间 timeline.setStartTime(startTime); timeline.setEndTime(endTime); timeline.repaint(); @@ -62,17 +59,16 @@ public class TimelineObserver implements IChartEventObserver { } /** - * 刷新视图 + * Refresh view * - * @param range 时间范围 - * @param firstTimestamp 本次Chart首次创建并启动刷新时的时间戳 - * @param isUseCache 是否使用缓存机制 + * @param range Chart display time range + * @param firstTimestamp The first time stamp of this chart's data + * @param useCache whether or not use cache */ @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { + public void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache) { timeline.setStartTime(range.getStartTime()); timeline.setEndTime(range.getEndTime()); - timeline.repaint(); timeline.revalidate(); } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/ChartViewConstants.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/ChartViewConstants.java new file mode 100644 index 000000000..d9b7b9e56 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/ChartViewConstants.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.utils; + +/** + * ChartViewConstants + */ +public final class ChartViewConstants { + /** + * 时间线默认宽度 + */ + public static final int TIMELINE_WIDTH = 1000; + + /** + * 时间线默认高度 + */ + public static final int TIMELINE_HEIGHT = 30; + + /** + * Chart界面刷新频率,单位为毫秒 + */ + public static final int REFRESH_FREQ = 20; + + /** + * 时间线字体大小 + */ + public static final int TIMELINE_FONT_SIZE = 11; + + /** + * 每隔N个minMarkInterval绘制坐标轴数字和大刻度 + */ + public static final int TIMELINE_MARK_COUNTS = 5; + + /** + * 数字 + */ + public static final int NUM_1024 = 1024; + + /** + * Chart延迟启动的时长,单位为毫秒 + */ + public static final int CHART_START_DELAY = 500; + + /** + * Chart loading图的大小 + */ + public static final int LOADING_SIZE = 100; + + /** + * 构造函数 + */ + private ChartViewConstants() { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/OperationUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/OperationUtils.java similarity index 93% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/common/OperationUtils.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/OperationUtils.java index dc31b1179..a177b9d47 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/common/OperationUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/chartview/utils/OperationUtils.java @@ -13,19 +13,18 @@ * limitations under the License. */ -package ohos.devtools.views.common; +package ohos.devtools.views.layout.chartview.utils; import java.math.BigDecimal; import static java.math.BigDecimal.ROUND_HALF_UP; -import static ohos.devtools.views.common.ViewConstants.DECIMAL_COUNTS; /** * View related tool classes - * - * @since 2021/2/2 10:25 */ public final class OperationUtils { + private static final int DECIMAL_COUNTS = 5; + /** * 构造函数 */ diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningDialogEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/AnalysisDialog.java similarity index 53% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningDialogEvent.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/AnalysisDialog.java index 8ae93df21..773dd0b5c 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningDialogEvent.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/AnalysisDialog.java @@ -13,39 +13,48 @@ * limitations under the License. */ -package ohos.devtools.views.layout.event; +package ohos.devtools.views.layout.dialog; -import java.awt.BorderLayout; -import java.awt.Frame; -import java.awt.Window; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.ui.components.JBLabel; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.views.layout.TaskPanel; import javax.annotation.Nullable; import javax.swing.JComponent; import javax.swing.JPanel; - -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.DialogWrapperDialog; +import javax.swing.Timer; +import java.awt.BorderLayout; /** - * SystemTunningDialog 加载框 - * - * @version 1.0 - * @date 2021/04/14 20:13 - **/ -public class SystemTunningDialogEvent extends DialogWrapper { - private JPanel fileJpanel = null; + * AnalysisDialog + */ +public class AnalysisDialog extends DialogWrapper { + private JPanel filePanel; + private JBLabel timeJLabel ; + private TaskPanel jTaskPanel; + private Timer timer; + private DeviceIPPortInfo deviceIPPortInfo; /** - * SystemTunningDialogEvent + * get timer * - * @param title title - * @param fileJpanel fileJpanel + * @return Timer */ - public SystemTunningDialogEvent(String title, JPanel fileJpanel) { + public Timer getTimer() { + return this.timer; + } + + /** + * AnalysisDialog + */ + public AnalysisDialog(DeviceIPPortInfo deviceIPPortInfo, JPanel filePanel) { super(true); - this.fileJpanel = fileJpanel; + this.deviceIPPortInfo = deviceIPPortInfo; + this.filePanel = filePanel; init(); - setTitle(title); + setTitle("Prompt"); + setResizable(false); } /** @@ -57,8 +66,8 @@ public class SystemTunningDialogEvent extends DialogWrapper { @Override protected JComponent createCenterPanel() { JPanel dialogPanel = new JPanel(new BorderLayout()); - if (fileJpanel != null) { - dialogPanel.add(fileJpanel, BorderLayout.CENTER); + if (filePanel != null) { + dialogPanel.add(filePanel, BorderLayout.CENTER); } return dialogPanel; } @@ -69,22 +78,4 @@ public class SystemTunningDialogEvent extends DialogWrapper { JPanel dialogSouthPanel = new JPanel(new BorderLayout()); return dialogSouthPanel; } - - /** - * closeWindow - * - * @param window window - * @param modalOnly modalOnly - */ - public static void closeWindow(Window window, boolean modalOnly) { - if (modalOnly && window instanceof Frame) { - return; - } - if (window instanceof DialogWrapperDialog) { - ((DialogWrapperDialog) window).getDialogWrapper().doCancelAction(); - return; - } - window.setVisible(false); - window.dispose(); - } } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemDialog.java new file mode 100644 index 000000000..a12bc60f4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemDialog.java @@ -0,0 +1,144 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.ui.components.JBLabel; +import ohos.devtools.views.common.LayoutConstants; + +import javax.annotation.Nullable; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.Timer; +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.util.Locale; + +/** + * CpuItemDialog + */ +public class CpuItemDialog extends DialogWrapper { + private JPanel filePanel; + private JBLabel timeLabel; + private int hours = 0; + private int minutes = 0; + private int seconds = 0; + private Timer timer = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); + private FileEnum fileType; + + /** + * CpuItemDialog + */ + public CpuItemDialog(String title, JPanel filePanel, FileEnum fileType, JBLabel timeJLabel) { + super(true); + this.filePanel = filePanel; + this.fileType = fileType; + this.timeLabel = timeJLabel; + init(); + setTitle(title); + setResizable(false); + } + + /** + * createCenterPanel + * + * @return JComponent + */ + @Nullable + @Override + protected JComponent createCenterPanel() { + if (fileType.equals(FileEnum.REAL_TIME_TRACE)) { + this.loadRealTimeTrace(); + } + JPanel dialogPanel = new JPanel(new BorderLayout()); + if (filePanel != null) { + dialogPanel.add(filePanel, BorderLayout.CENTER); + } + return dialogPanel; + } + + /** + * loadRealTimeTrace + */ + public void loadRealTimeTrace() { + timeLabel.setText(" 00:00:00"); + filePanel.add(timeLabel); + timer = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); + timer.start(); + } + + /** + * actionPerformed + * + * @param actionEvent actionEvent + */ + public void actionPerformed(ActionEvent actionEvent) { + if (seconds <= LayoutConstants.NUMBER_SECONDS) { + timeLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + + String.format(Locale.ENGLISH, "%02d", minutes) + ":" + + String.format(Locale.ENGLISH, "%02d", seconds)); + seconds++; + if (seconds > LayoutConstants.NUMBER_SECONDS) { + seconds = 0; + minutes++; + if (minutes > LayoutConstants.NUMBER_SECONDS) { + minutes = 0; + hours++; + } + } + } + } + + /** + * set Label Attribute + * + * @param statusJLabelParam statusJLabelParam + * @param durationJLabelParam durationJLabelParam + * @param recordingJLabelParam recordingJLabelParam + * @param timeJLabelParam timeJLabelParam + * @param typeJLabelParam typeJLabelParam + * @param typeValueJLabelParam typeValueJLabelParam + */ + public void setLabelAttribute(JLabel statusJLabelParam, JLabel durationJLabelParam, JLabel recordingJLabelParam, + JLabel timeJLabelParam, JLabel typeJLabelParam) { + statusJLabelParam.setBounds(70, 30, 70, 20); + recordingJLabelParam.setBounds(140, 30, 70, 20); + durationJLabelParam.setBounds(70, 60, 70, 20); + timeJLabelParam.setBounds(140, 60, 70, 20); + typeJLabelParam.setBounds(70, LayoutConstants.CPU_GRAP_TYPE_Y, 70, 20); + } + + /** + * FileEnum + */ + public enum FileEnum { + OFF_LINE_TRACE("offLineTrace"), REAL_TIME_TRACE("realTimeTrace"); + private String fileType; + + FileEnum(String fileType) { + this.fileType = fileType; + } + + public String getFileType() { + return fileType; + } + } + + public Timer getTimer() { + return this.timer; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemViewLoadDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemViewLoadDialog.java new file mode 100644 index 000000000..be91a5c2f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CpuItemViewLoadDialog.java @@ -0,0 +1,344 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.transport.grpc.SystemTraceHelper; +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import ohos.devtools.views.layout.utils.TraceStreamerUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.JButton; +import javax.swing.Timer; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.Locale; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_TRACE_FILE; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_TRACE_FILE_INFO; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.TRACE_STREAMER_LOAD; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_GET_TRACE_FILE; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_GET_TRACE_FILE_INFO; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * CpuItemViewLoadDialog + */ +public class CpuItemViewLoadDialog implements ActionListener { + private static final Logger LOGGER = LogManager.getLogger(CpuItemViewLoadDialog.class); + + ExecutorService executorAnalysis = Executors.newSingleThreadExecutor(); + + private int bytraceFileSize; + private int hoursLoading = 0; + private int minutesLoading = 0; + private int secondsLoading = 0; + private int numberOfParsingFile = 1; + private String sessionId; + private String fileSuffixTimestamp; + private boolean typeParam; + private boolean pullBytraceFileState = false; + private boolean analysisState = false; + + private Timer timerLoading = null; + private ProfilerChartsView bottomPanel; + private DeviceIPPortInfo deviceIPPortInfo; + private CpuItemDialog cpuItemDialogEvent; + private AnalysisDialog analysisDialogEvent; + + private JBPanel jPanel = new JBPanel(null); + + private JBLabel statusJLabel = new JBLabel("Status"); + + private JBLabel durationJLabel = new JBLabel("Duration"); + + private JBLabel recordingJLabel = new JBLabel("Recording"); + + private JBLabel timeJLabel = new JBLabel(" 00:00:00"); + + private JBLabel typeJLabel = new JBLabel("Type"); + + private JBLabel typeValueJLabel = new JBLabel(); + + private JButton cancelJButton = new JButton("Cancel"); + + private JButton stopJButton = new JButton("Stop"); + + private JBLabel statusAnalysisJLabel = new JBLabel("Status"); + + private JBLabel durationAnalysisJLabel = new JBLabel("Duration"); + + private JBLabel loadingJLabel = new JBLabel("Analysis"); + + private JBLabel loadingInitTimeJLabel = new JBLabel(" 00:00:00"); + + /** + * CpuItemViewLoadDialog + * + * @param bottomPanelParam + * @param typeParam + * @param sessionIdParam + */ + public CpuItemViewLoadDialog(ProfilerChartsView bottomPanelParam, boolean typeParam, String sessionIdParam) { + this.bottomPanel = bottomPanelParam; + this.sessionId = sessionIdParam; + this.typeParam = typeParam; + typeValueJLabel.setText(LayoutConstants.TRACE_SYSTEM_CALLS_TIPS); + cpuItemDialogEvent = new CpuItemDialog("Prompt", jPanel, CpuItemDialog.FileEnum.REAL_TIME_TRACE, timeJLabel); + } + + /** + * load + * + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param sessionIdParam sessionIdParam + * @param fileSuffixTimestampParam fileSuffixTimestampParam + */ + public void load(DeviceIPPortInfo deviceIPPortInfoParam, String sessionIdParam, String fileSuffixTimestampParam) { + deviceIPPortInfo = deviceIPPortInfoParam; + fileSuffixTimestamp = fileSuffixTimestampParam; + jPanel.removeAll(); + jPanel.add(statusJLabel); + jPanel.add(durationJLabel); + jPanel.add(recordingJLabel); + jPanel.add(timeJLabel); + jPanel.add(typeJLabel); + jPanel.add(typeValueJLabel); + jPanel.setPreferredSize(new Dimension(300, 150)); + cpuItemDialogEvent.setLabelAttribute(statusJLabel, durationJLabel, recordingJLabel, timeJLabel, typeJLabel); + typeValueJLabel.setBounds(140, LayoutConstants.CPU_GRAP_TYPE_Y, LayoutConstants.CPU_GRAP_TYPE_WIDTH, 20); + boolean showAndGet = cpuItemDialogEvent.showAndGet(); + // close timer + cpuItemDialogEvent.getTimer().stop(); + LOGGER.info(showAndGet); + if (showAndGet) { + stopAndDestroySession(deviceIPPortInfoParam, sessionIdParam); + loading(); + } else { + cancelActionDestroySession(deviceIPPortInfoParam, sessionIdParam); + } + } + + /** + * stop and destroy session + * + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param sessionIdParam sessionIdParam + */ + public void stopAndDestroySession(DeviceIPPortInfo deviceIPPortInfoParam, String sessionIdParam) { + ExecutorService executorCancel = Executors.newSingleThreadExecutor(); + executorCancel.execute(new Runnable() { + @Override + public void run() { + new SystemTraceHelper().stopSession(deviceIPPortInfoParam, sessionIdParam); + } + }); + } + + /** + * stop and destroy session + * + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param sessionIdParam sessionIdParam + */ + public void cancelActionDestroySession(DeviceIPPortInfo deviceIPPortInfoParam, String sessionIdParam) { + ExecutorService executorCancel = Executors.newSingleThreadExecutor(); + executorCancel.execute(new Runnable() { + @Override + public void run() { + new SystemTraceHelper().cancelActionDestroySession(deviceIPPortInfoParam, sessionIdParam); + } + }); + } + + /** + * loading + */ + public void loading() { + pullBytraceFileState = true; + analysisDialogEvent = new AnalysisDialog(deviceIPPortInfo, jPanel); + timerLoading = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); + jPanel.setPreferredSize(new Dimension(300, 150)); + cpuItemDialogEvent + .setLabelAttribute(statusAnalysisJLabel, durationAnalysisJLabel, loadingJLabel, loadingInitTimeJLabel, + typeJLabel); + typeValueJLabel.setBounds(140, LayoutConstants.CPU_GRAP_TYPE_Y, LayoutConstants.CPU_GRAP_TYPE_WIDTH, 20); + jPanel.removeAll(); + jPanel.add(statusAnalysisJLabel); + jPanel.add(durationAnalysisJLabel); + jPanel.add(loadingJLabel); + jPanel.add(loadingInitTimeJLabel); + jPanel.add(typeJLabel); + jPanel.add(typeValueJLabel); + timerLoading.start(); + analysisDialogEvent.show(); + } + + /** + * actionLoadingPerformed + * + * @param actionEvent actionEvent + */ + public void actionPerformed(ActionEvent actionEvent) { + if (secondsLoading <= LayoutConstants.NUMBER_SECONDS) { + loadingInitTimeJLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hoursLoading) + ":" + String + .format(Locale.ENGLISH, "%02d", minutesLoading) + ":" + String + .format(Locale.ENGLISH, "%02d", secondsLoading)); + secondsLoading++; + if (secondsLoading > LayoutConstants.NUMBER_SECONDS) { + secondsLoading = 0; + minutesLoading++; + if (minutesLoading > LayoutConstants.NUMBER_SECONDS) { + minutesLoading = 0; + hoursLoading++; + } + } + } + int num = secondsLoading % 2; + if (pullBytraceFileState && num == 0 && !analysisState) { + executorAnalysis.execute(new Runnable() { + @Override + public void run() { + ArrayList getSimperfOrTraceFileInfoByCmd = null; + String filePath = "/data/local/tmp/hiprofiler_data" + fileSuffixTimestamp + ".bytrace"; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + getSimperfOrTraceFileInfoByCmd = + conversionCommand(HDC_STD_GET_TRACE_FILE_INFO, deviceIPPortInfo.getDeviceID(), filePath); + } else { + getSimperfOrTraceFileInfoByCmd = + conversionCommand(HDC_GET_TRACE_FILE_INFO, deviceIPPortInfo.getDeviceID(), filePath); + } + String fileInfo = HdcWrapper.getInstance().getHdcStringResult(getSimperfOrTraceFileInfoByCmd); + if (fileInfo != null && fileInfo.length() > 0 && !analysisState && fileInfo.contains("\t")) { + String[] fileInfoArray = fileInfo.split("\t"); + if (bytraceFileSize != 0 && bytraceFileSize == Integer.valueOf(fileInfoArray[0]) + && !analysisState) { + pullBytraceFileState = false; + pullAndAnalysisByTraceFile(); + executorAnalysis.shutdown(); + } else { + bytraceFileSize = Integer.valueOf(fileInfoArray[0]); + } + } + } + }); + } + if (analysisState) { + timerLoading.stop(); + analysisDialogEvent.close(1); + } + } + + /** + * pull and analysis bytrace file + */ + public void pullAndAnalysisByTraceFile() { + getByTraceFile(); + new SystemTraceHelper().cancelActionDestroySession(deviceIPPortInfo, sessionId); + removeOldTraceStreamerLog(); + String dbPath = null; + try { + dbPath = analysisTraceFileToDbFile(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + analysisState = true; + // load AppTracePanel + String recordTime = timeJLabel.getText(); + long sessionIdTrace = bottomPanel.getSessionId(); + TaskScenePanelChart taskScenePanelChart = bottomPanel.getTaskScenePanelChart(); + taskScenePanelChart.createSessionList(LayoutConstants.TRACE_SYSTEM_CALLS, recordTime, sessionIdTrace, dbPath); + } + + /** + * get bytrace file + */ + public void getByTraceFile() { + String baseDir = TraceStreamerUtils.getInstance().getBaseDir(); + String filePath = "/data/local/tmp/hiprofiler_data" + fileSuffixTimestamp + ".bytrace"; + ArrayList cmd; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) { + cmd = conversionCommand(HDC_STD_GET_TRACE_FILE, deviceIPPortInfo.getDeviceID(), filePath, baseDir); + } else { + cmd = conversionCommand(HDC_GET_TRACE_FILE, deviceIPPortInfo.getDeviceID(), filePath, baseDir); + } + HdcWrapper.getInstance().execCmdBy(cmd); + LOGGER.info(cmd); + } + + /** + * remove old log + */ + public void removeOldTraceStreamerLog() { + String logPath = TraceStreamerUtils.getInstance().getLogPath(); + File logFile = new File(logPath); + if (logFile.exists()) { + logFile.delete(); + } + } + + /** + * analysis trace file to db file + * + * @return String + * @throws IOException + */ + public String analysisTraceFileToDbFile() throws IOException { + String dbPath = TraceStreamerUtils.getInstance().getBaseDir() + "realTimeTrace" + fileSuffixTimestamp + ".db"; + String cmd = + TraceStreamerUtils.getInstance().getBaseDir() + TraceStreamerUtils.getInstance().getTraceStreamerApp(); + String dir = + TraceStreamerUtils.getInstance().getBaseDir() + "hiprofiler_data" + fileSuffixTimestamp + ".bytrace"; + ArrayList arrayList = conversionCommand(TRACE_STREAMER_LOAD, cmd, dir, dbPath); + HdcWrapper.getInstance().getHdcStringResult(arrayList); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String logPath = TraceStreamerUtils.getInstance().getLogPath(); + File logFile = new File(logPath); + if (logFile.exists() && numberOfParsingFile > 0) { + RandomAccessFile randomFile = null; + randomFile = new RandomAccessFile(logFile, "r"); + String tmp = null; + while ((tmp = randomFile.readLine()) != null) { + if (Integer.valueOf(tmp.split(":")[1]) != 0) { + numberOfParsingFile--; + LOGGER.info("File parsing failed last time, try again. value is {}", + Integer.valueOf(tmp.split(":")[1])); + analysisTraceFileToDbFile(); + } + } + } + return dbPath; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CustomDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CustomDialog.java new file mode 100644 index 000000000..dd5cef318 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/CustomDialog.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.ui.DialogWrapper; + +import javax.annotation.Nullable; +import javax.swing.JComponent; +import javax.swing.JPanel; +import java.awt.BorderLayout; + +/** + * Custom dialog + */ +public class CustomDialog extends DialogWrapper { + private final JPanel fileJPanel; + + /** + * CustomDialog + * + * @param title title + * @param fileJPanel fileJPanel + */ + public CustomDialog(String title, JPanel fileJPanel) { + super(true); + this.fileJPanel = fileJPanel; + init(); + setTitle(title); + } + + /** + * createCenterPanel + * + * @return JComponent + */ + @Override + protected JComponent createCenterPanel() { + JPanel dialogPanel = new JPanel(new BorderLayout()); + if (fileJPanel != null) { + dialogPanel.add(fileJPanel, BorderLayout.CENTER); + } + return dialogPanel; + } + + /** + * createSouthPanel + * + * @return JComponent + */ + @Nullable + @Override + protected JComponent createSouthPanel() { + return new JPanel(new BorderLayout()); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ExportFileChooserDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ExportFileChooserDialog.java new file mode 100644 index 000000000..6f4753da0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ExportFileChooserDialog.java @@ -0,0 +1,169 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.ui.TextBrowseFolderListener; +import com.intellij.openapi.ui.TextFieldWithBrowseButton; +import com.intellij.openapi.ui.ValidationInfo; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomJButton; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; + +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JTextField; +import java.awt.Dimension; +import java.io.File; + +/** + * ExportFileChooserDialog + */ +public class ExportFileChooserDialog extends DialogWrapper { + private TextFieldWithBrowseButton textFieldWithBrowseButton; + + private JTextField jNameTextField; + + private String exportFileName; + + private String exportFilePath; + + private String fileType; + + private JComboBox fileTypeBox = new JComboBox(); + + /** + * constructor + * + * @param title title + * @param fileType fileType + */ + public ExportFileChooserDialog(String title, String fileType) { + super(true); + init(); + setTitle(title); + this.fileType = fileType; + fileTypeBox.addItem(fileType); + } + + @Nullable + @Override + protected JComponent createCenterPanel() { + JBPanel panel = new JBPanel(null); + JLabel taskNameLabel = new JLabel("File Name"); + taskNameLabel.setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.TWENTY, LayoutConstants.HUNDRED_FIFTY, + LayoutConstants.THIRTY); + panel.add(taskNameLabel); + jNameTextField = new JTextField(LayoutConstants.THIRTY); + jNameTextField.setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.FIFTY, LayoutConstants.SCROPNUM, + LayoutConstants.THIRTY); + jNameTextField.setName(UtConstant.UT_EXPORT_FILE_FILE_NAME); + panel.add(jNameTextField); + JLabel filePathLocation = new JLabel("File Location"); + filePathLocation.setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.NINETY, LayoutConstants.HUNDRED_FIFTY, + LayoutConstants.THIRTY); + panel.add(filePathLocation); + textFieldWithBrowseButton = new TextFieldWithBrowseButton(); + FileChooserDescriptor chooserDescriptor = new FileChooserDescriptor(true, true, true, true, true, true); + TextBrowseFolderListener listener = new TextBrowseFolderListener(chooserDescriptor); + textFieldWithBrowseButton.addBrowseFolderListener(listener); + textFieldWithBrowseButton.setText(System.getProperty("user.dir")); + textFieldWithBrowseButton + .setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.FILE_SELECT_Y, LayoutConstants.SCROPNUM, + LayoutConstants.THIRTY); + panel.add(textFieldWithBrowseButton); + JLabel fileTypeLabel = new JLabel("File Type"); + fileTypeLabel.setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.FILE_TYPE_Y, LayoutConstants.HUNDRED_FIFTY, + LayoutConstants.THIRTY); + panel.add(fileTypeLabel); + fileTypeBox.setBounds(LayoutConstants.MARGIN_LEFT, LayoutConstants.FILE_TYPE_BOX_Y, LayoutConstants.SCROPNUM, + LayoutConstants.THIRTY); + panel.add(fileTypeBox); + panel.setPreferredSize(new Dimension(LayoutConstants.DIALOG_WIDTH, LayoutConstants.DIALOG_HEIGHT)); + return panel; + } + + @Nullable + @Override + protected ValidationInfo doValidate() { + exportFilePath = textFieldWithBrowseButton.getText(); + exportFileName = jNameTextField.getText().trim(); + if (StringUtils.isBlank(exportFileName)) { + return new ValidationInfo("Please input the file name !", jNameTextField); + } + if (!exportFileName.matches("^[A-Za-z0-9]+$")) { + return new ValidationInfo("The file name can only contain numbers and letters !", jNameTextField); + } + VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(exportFilePath); + if (virtualFile == null || exportFilePath.isEmpty()) { + return new ValidationInfo("Illegal path", textFieldWithBrowseButton); + } + return null; + } + + /** + * save as trace file + * + * @param jButton jButton + */ + public void saveDataToFile(CustomJButton jButton) { + // 查询数据保存到file + String pathName = exportFilePath + File.separator + exportFileName + Constant.TRACE_SUFFIX; + DeviceProcessInfo deviceProcessInfo = new DeviceProcessInfo(); + deviceProcessInfo.setDeviceName(jButton.getDeviceName()); + deviceProcessInfo.setProcessName(jButton.getProcessName()); + deviceProcessInfo.setLocalSessionId(jButton.getSessionId()); + boolean saveResult = + SessionManager.getInstance().saveSessionDataToFile(jButton.getSessionId(), deviceProcessInfo, pathName); + if (saveResult) { + new SampleDialog("prompt", "Save Successfully !").show(); + } else { + new SampleDialog("prompt", "Save failure !").show(); + } + } + + /** + * get ExportFileName + * + * @return String FileName + */ + public String getExportFileName() { + return exportFileName; + } + + /** + * get exportFilePath + * + * @return String FilePath + */ + public String getExportFilePath() { + return exportFilePath; + } + + public String getFileType() { + return fileType; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/HelpDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/HelpDialog.java new file mode 100644 index 000000000..2aa7de8a6 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/HelpDialog.java @@ -0,0 +1,128 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.common.LayoutConstants; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.IOException; +import java.util.Properties; + +/** + * Help Dialog + */ +public class HelpDialog { + private static final Logger LOGGER = LogManager.getLogger(HelpDialog.class); + private static final int DIALOG_WIDTH = 650; + private static final int DIALOG_HEIGHT = 120; + private static final int FONT_SIZE = 16; + private static final int ICON_X = 15; + private static final int TEXT_X = 70; + private static final int THIRTY = 30; + private static final int LICENSE_X = 500; + private static final int LICENSE_Y = 90; + private static final int LICENSE_WIDTH = 150; + private static final int COPY_RIGHT_Y = 56; + private static final int COPY_RIGHT_WIDTH = 330; + private static final int VERSION_WIDTH = 590; + private CustomDialog sampleDialog; + private JBPanel jPanel; + private JBLabel toolVersionNumber; + private JBLabel copyRightIcon; + private JBLabel copyRightLabel; + private JBLabel license; + + /** + * HelpDialog + */ + public HelpDialog() { + initComponent(); + setFontAndBounds(); + // Add components + copyRightIcon.setIcon(IconLoader.getIcon("/images/copyright.png", getClass())); + jPanel.add(toolVersionNumber); + jPanel.add(copyRightIcon); + jPanel.add(copyRightLabel); + String labelText = "

" + + "Open Source Licenses

"; + license.setText(labelText); + addListener(); + jPanel.add(license); + sampleDialog.setResizable(true); + sampleDialog.show(); + } + + private void initComponent() { + jPanel = new JBPanel(null); + jPanel.setPreferredSize(new Dimension(DIALOG_WIDTH, DIALOG_HEIGHT)); + sampleDialog = new CustomDialog("About HosProfiler", jPanel); + toolVersionNumber = new JBLabel(""); + toolVersionNumber.setText("HosProfiler " + getVersion()); + copyRightIcon = new JBLabel(); + copyRightLabel = new JBLabel("Copyright (c) 2021 Huawei Device Co., Ltd."); + license = new JBLabel(); + } + + private String getVersion() { + Properties properties = new Properties(); + String version = ""; + try { + properties.load(HelpDialog.class.getClassLoader().getResourceAsStream("hosprofiler.properties")); + version = properties.getProperty("version"); + } catch (IOException exception) { + LOGGER.error("get version Exception {}", exception.getMessage()); + } + return version; + } + + private void addListener() { + license.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + sampleDialog.close(1); + new LicenseDialog(); + } + + @Override + public void mouseEntered(MouseEvent event) { + license.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + + @Override + public void mouseExited(MouseEvent event) { + license.setCursor(Cursor.getDefaultCursor()); + } + }); + } + + private void setFontAndBounds() { + copyRightIcon.setBounds(ICON_X, THIRTY, THIRTY, THIRTY); + toolVersionNumber.setFont(new Font("PingFang SC", Font.PLAIN, FONT_SIZE)); + toolVersionNumber.setBounds(TEXT_X, LayoutConstants.NUM_20, VERSION_WIDTH, LayoutConstants.NUM_20); + copyRightLabel.setBounds(TEXT_X, COPY_RIGHT_Y, COPY_RIGHT_WIDTH, LayoutConstants.NUM_20); + license.setBounds(LICENSE_X, LICENSE_Y, LICENSE_WIDTH, LayoutConstants.NUM_20); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ImportFileChooserDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ImportFileChooserDialog.java new file mode 100644 index 000000000..e2724c7ed --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/ImportFileChooserDialog.java @@ -0,0 +1,86 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.ui.TextBrowseFolderListener; +import com.intellij.openapi.ui.TextFieldWithBrowseButton; +import com.intellij.openapi.ui.ValidationInfo; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.ui.components.JBPanel; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; + +/** + * ImportFileChooserDialog + */ +public class ImportFileChooserDialog extends DialogWrapper { + private TextFieldWithBrowseButton textFieldWithBrowseButton; + private String importFilePath; + + public String getImportFilePath() { + return importFilePath; + } + + /** + * constructor + * + * @param title title + */ + public ImportFileChooserDialog(String title) { + super(true); + init(); + setTitle(title); + setResizable(false); + } + + @Nullable + @Override + protected JComponent createCenterPanel() { + JBPanel dialogPanel = new JBPanel(null); + JLabel filePathLocation = new JLabel("File Location:"); + filePathLocation.setBounds(15, 15, 350, 30); + dialogPanel.add(filePathLocation); + textFieldWithBrowseButton = new TextFieldWithBrowseButton(); + FileChooserDescriptor chooserDescriptor = new FileChooserDescriptor(true, true, true, true, true, true); + chooserDescriptor.setHideIgnored(false); + TextBrowseFolderListener listener = new TextBrowseFolderListener(chooserDescriptor); + textFieldWithBrowseButton.addBrowseFolderListener(listener); + textFieldWithBrowseButton.setText(""); + textFieldWithBrowseButton.setBounds(15, 60, 350, 30); + dialogPanel.add(textFieldWithBrowseButton); + dialogPanel.setPreferredSize(new Dimension(380, 120)); + return dialogPanel; + } + + @Nullable + @Override + protected ValidationInfo doValidate() { + importFilePath = textFieldWithBrowseButton.getText(); + VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(importFilePath); + if (virtualFile == null || importFilePath.isEmpty()) { + return new ValidationInfo("The path is empty!", textFieldWithBrowseButton); + } + if (virtualFile.isDirectory()) { + return new ValidationInfo("Please choose the file!", textFieldWithBrowseButton); + } + return null; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/LicenseDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/LicenseDialog.java new file mode 100644 index 000000000..259fea7a4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/LicenseDialog.java @@ -0,0 +1,119 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; + +import ohos.devtools.views.common.LayoutConstants; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import java.awt.Dimension; +import java.awt.Font; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +/** + * License Dialog + */ +public class LicenseDialog { + private static final Logger LOGGER = LogManager.getLogger(LicenseDialog.class); + private static final int DIALOG_WIDTH = 655; + private static final int TITLE_FONT_SIZE = 16; + private static final int FONT_SIZE = 12; + private static final int DIALOG_HEIGHT = 450; + private static final int TITLE_X = 210; + private static final int SCROLL_Y = 50; + private static final int SCROLL_HEIGHT = 400; + private static final int TITLE_Y = 10; + private static final int TITLE_WIDTH = 240; + private static final int TEXT_AREA_ROWS = 20; + private static final int TEXT_AREA_COLUMNS = 40; + private final CustomDialog sampleDialog; + private final JBPanel jPanel; + private final JBLabel titleLabel; + private final JTextArea licenseTextArea; + private final JScrollPane licenseScroll; + + /** + * LicenseDialog + */ + public LicenseDialog() { + jPanel = new JBPanel(null); + sampleDialog = new CustomDialog("Open Source Software Notice", jPanel); + titleLabel = new JBLabel("Open Source Software Notice"); + jPanel.setPreferredSize(new Dimension(DIALOG_WIDTH, DIALOG_HEIGHT)); + licenseTextArea = new JTextArea("", TEXT_AREA_ROWS, TEXT_AREA_COLUMNS); + licenseTextArea.setFont(new Font("PingFang SC", Font.PLAIN, FONT_SIZE)); + getLicenseText(); + licenseTextArea.setEditable(false); + licenseScroll = new JScrollPane(licenseTextArea); + licenseScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + licenseScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + setFontAndBounds(); + // Add components + jPanel.add(titleLabel); + jPanel.add(licenseScroll); + sampleDialog.setResizable(true); + sampleDialog.show(); + } + + private void getLicenseText() { + String str; + BufferedReader bufferedReader = null; + InputStream resourceAsStream = null; + try { + resourceAsStream = LicenseDialog.class.getClassLoader().getResourceAsStream("LICENSE"); + assert resourceAsStream != null; + bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream)); + while ((str = bufferedReader.readLine()) != null) { + licenseTextArea.append(str + System.lineSeparator()); + } + } catch (IOException exception) { + LOGGER.error(exception.getMessage()); + } finally { + if (resourceAsStream != null) { + try { + resourceAsStream.close(); + } catch (IOException exception) { + LOGGER.error(exception.getMessage()); + } + } + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException exception) { + LOGGER.error(exception.getMessage()); + } + } + } + } + + /** + * Set the style of J Panel and Button + */ + private void setFontAndBounds() { + titleLabel.setFont(new Font("PingFang SC", Font.BOLD, TITLE_FONT_SIZE)); + titleLabel.setBounds(TITLE_X, TITLE_Y, TITLE_WIDTH, LayoutConstants.NUM_20); + licenseScroll.setBounds(0, SCROLL_Y, DIALOG_WIDTH, SCROLL_HEIGHT); + licenseScroll.setBorder(null); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SampleDialogWrapper.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SampleDialog.java similarity index 76% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SampleDialogWrapper.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SampleDialog.java index 78ff43d64..8819d50b9 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SampleDialogWrapper.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SampleDialog.java @@ -13,7 +13,7 @@ * limitations under the License. */ -package ohos.devtools.views.layout.swing; +package ohos.devtools.views.layout.dialog; import javax.annotation.Nullable; import javax.swing.JComponent; @@ -29,23 +29,20 @@ import com.intellij.openapi.ui.DialogWrapper; import ohos.devtools.views.common.LayoutConstants; /** - * SampleDialogWrapper - * - * @version 1.0 - * @date 2021/4/1 15:01 - **/ -public class SampleDialogWrapper extends DialogWrapper { + * SampleDialog + */ +public class SampleDialog extends DialogWrapper { private String message = ""; private JFileChooser fileChooser = null; - private JPanel fileJpanel = null; + private JPanel filePanel = null; /** * SampleDialogWrapper * - * @param title title + * @param title title * @param message message */ - public SampleDialogWrapper(String title, String message) { + public SampleDialog(String title, String message) { super(true); this.message = message; init(); @@ -55,10 +52,10 @@ public class SampleDialogWrapper extends DialogWrapper { /** * SampleDialogWrapper * - * @param title title + * @param title title * @param fileChooser fileChooser */ - public SampleDialogWrapper(String title, JFileChooser fileChooser) { + public SampleDialog(String title, JFileChooser fileChooser) { super(true); this.fileChooser = fileChooser; init(); @@ -68,12 +65,12 @@ public class SampleDialogWrapper extends DialogWrapper { /** * SampleDialogWrapper * - * @param title title - * @param fileJpanel fileJpanel + * @param title title + * @param filePanel filePanel */ - public SampleDialogWrapper(String title, JPanel fileJpanel) { + public SampleDialog(String title, JPanel filePanel) { super(true); - this.fileJpanel = fileJpanel; + this.filePanel = filePanel; init(); setTitle(title); } @@ -95,8 +92,8 @@ public class SampleDialogWrapper extends DialogWrapper { if (fileChooser != null) { dialogPanel.add(fileChooser, BorderLayout.CENTER); } - if (fileJpanel != null) { - dialogPanel.add(fileJpanel, BorderLayout.CENTER); + if (filePanel != null) { + dialogPanel.add(filePanel, BorderLayout.CENTER); } return dialogPanel; } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SaveTraceDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SaveTraceDialog.java similarity index 76% rename from host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SaveTraceDialog.java rename to host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SaveTraceDialog.java index a197c71d4..697c65db3 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SaveTraceDialog.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/SaveTraceDialog.java @@ -1,180 +1,185 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJButton; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.UIManager; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.IOException; - -/** - * @ClassName: SaveTraceDialog - * @Description: SaveTraceDialog类 - * @Date: 2021/3/22 19:02 - */ -public class SaveTraceDialog { - /** - * 全局日志 - */ - private static final Logger LOGGER = LogManager.getLogger(SaveTraceDialog.class); - - /** - * 显示一个自定义的对话框 - * - * @param btn 对话框的父级组件 - */ - public void showCustomDialog(HosJButton btn) { - // 创建一个模态对话框 - JPanel fileJpanel = new JPanel(null); - fileJpanel.setPreferredSize(new Dimension(LayoutConstants.FOUR_HUNDRED, LayoutConstants.TWO_HUNDRED_SIXTY)); - fileJpanel.setBackground(ColorConstants.HOME_PANE); - JLabel taskNameLabel = new JLabel("Save as"); - taskNameLabel.setBounds(LayoutConstants.TWENTY, LayoutConstants.TWENTY, LayoutConstants.HUNDRED_FIFTY, - LayoutConstants.THIRTY); - JTextField jTextField = new JTextField(LayoutConstants.THIRTY); - jTextField.setBackground(ColorConstants.SELECT_PANEL); - jTextField - .setBounds(LayoutConstants.TWENTY, LayoutConstants.FIFTY, LayoutConstants.SCROPNUM, LayoutConstants.THIRTY); - JLabel filePathLocation = new JLabel("Save Location"); - filePathLocation.setBounds(LayoutConstants.TWENTY, LayoutConstants.NINETY, LayoutConstants.HUNDRED_FIFTY, - LayoutConstants.THIRTY); - JTextArea msgTextArea = new JTextArea(LayoutConstants.TWENTY, LayoutConstants.THIRTY); - msgTextArea.setEditable(false); - msgTextArea.setLineWrap(true); - msgTextArea.setBounds(LayoutConstants.TWENTY, LayoutConstants.HUNDRED_TWENTY_TWO, LayoutConstants.THREE_HUNDRED, - LayoutConstants.THIRTY); - msgTextArea.setBackground(ColorConstants.SELECT_PANEL); - if (StringUtils.isNotBlank(Constant.tracePath)) { - msgTextArea.setText(Constant.tracePath); - } - JPanel selectPanel = new JPanel(new BorderLayout()); - selectPanel.setBounds(LayoutConstants.TWENTY, LayoutConstants.HUNDRED_TWENTY_TWO, LayoutConstants.SCROPNUM, - LayoutConstants.THIRTY); - // 获取文件下拉箭头 - JLabel labelSvg = new JLabel(); - labelSvg.setIcon(new ImageIcon(SaveTraceDialog.class.getClassLoader().getResource("images/down.png"))); - labelSvg.setBounds(LayoutConstants.THREE_HUNDRED, LayoutConstants.OTHERS_Y, LayoutConstants.JLABEL_SIZE, - LayoutConstants.THIRTY); - selectPanel.add(msgTextArea, BorderLayout.WEST); - selectPanel.add(labelSvg, BorderLayout.CENTER); - labelSvg.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - try { - showFileSaveDialog(fileJpanel, msgTextArea); - } catch (IOException exception) { - LOGGER.error("SaveTraceDialog:{}", exception.getMessage()); - } - } - }); - fileJpanel.add(taskNameLabel); - fileJpanel.add(jTextField); - fileJpanel.add(filePathLocation); - fileJpanel.add(selectPanel); - customDialogWrapper(btn, new SampleDialogWrapper("Save The Task", fileJpanel), jTextField, msgTextArea); - } - - /** - * 创建一个对话框Wrapper - * - * @param btn btn - * @param sampleDialog sampleDialog - * @param jTextField jTextField - * @param msgTextArea msgTextArea - */ - private void customDialogWrapper(HosJButton btn, SampleDialogWrapper sampleDialog, JTextField jTextField, - JTextArea msgTextArea) { - boolean flag = sampleDialog.showAndGet(); - if (flag) { - String fileName = jTextField.getText().trim(); - String filePath = msgTextArea.getText(); - if (StringUtils.isBlank(fileName)) { - new SampleDialogWrapper("Warring", "Please input the file name !").show(); - return; - } - if (!fileName.matches("^[A-Za-z0-9]+$")) { - new SampleDialogWrapper("Warring", "The file name can only contain numbers and letters !").show(); - return; - } - if (StringUtils.isBlank(filePath)) { - new SampleDialogWrapper("Warring", "Please select the file path !").show(); - return; - } - // 查询数据保存到file - String pathName = filePath + File.separator + fileName + Constant.TRACE_SUFFIX; - DeviceProcessInfo deviceProcessInfo = new DeviceProcessInfo(); - deviceProcessInfo.setDeviceName(btn.getDeviceName()); - deviceProcessInfo.setProcessName(btn.getProcessName()); - deviceProcessInfo.setLocalSessionId(btn.getSessionId()); - boolean saveResult = - SessionManager.getInstance().saveSessionDataToFile(btn.getSessionId(), deviceProcessInfo, pathName); - if (saveResult) { - sampleDialog.close(0); - new SampleDialogWrapper("prompt", "Save Successfully !").show(); - } else { - sampleDialog.close(0); - new SampleDialogWrapper("prompt", "Save failure !").show(); - } - } - } - - /** - * 选择文件保存路径 - * - * @param parent parent - * @param msgTextArea msgTextArea - * @throws IOException IOException - */ - private void showFileSaveDialog(Component parent, JTextArea msgTextArea) throws IOException { - UIManager.put("FileChooser.cancelButtonText", "Cancel"); - // 创建一个默认的文件选取器 - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setDialogTitle("Select File Path"); - fileChooser.setCurrentDirectory(new File(".")); - fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileChooser.setMultiSelectionEnabled(false); - fileChooser.setApproveButtonText("choose"); - fileChooser.setControlButtonsAreShown(false); - SampleDialogWrapper sampleDialog = new SampleDialogWrapper("Select File Path", fileChooser); - boolean flag = sampleDialog.showAndGet(); - if (flag) { - File file = fileChooser.getCurrentDirectory(); - msgTextArea.setText(file.getAbsolutePath()); - Constant.tracePath = file.getAbsolutePath(); - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.util.IconLoader; +import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.customcomp.CustomJButton; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.UIManager; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.io.IOException; + +/** + * SaveTraceDialog + */ +public class SaveTraceDialog { + /** + * Global log + */ + private static final Logger LOGGER = LogManager.getLogger(SaveTraceDialog.class); + + /** + * trace file save path + */ + private String tracePath = ""; + + /** + * Displays a custom dialog box + * + * @param btn Parent component of dialog box + * @param title Dialog of title + */ + public void showCustomDialog(CustomJButton btn, String title) { + // 创建一个模态对话框 + JPanel fileJpanel = new JPanel(null); + fileJpanel.setPreferredSize(new Dimension(LayoutConstants.FOUR_HUNDRED, LayoutConstants.TWO_HUNDRED_SIXTY)); + fileJpanel.setBackground(ColorConstants.HOME_PANE); + JLabel taskNameLabel = new JLabel("Save as"); + taskNameLabel.setBounds(LayoutConstants.TWENTY, LayoutConstants.TWENTY, LayoutConstants.HUNDRED_FIFTY, + LayoutConstants.THIRTY); + JTextField jTextField = new JTextField(LayoutConstants.THIRTY); + jTextField.setBackground(ColorConstants.SELECT_PANEL); + jTextField + .setBounds(LayoutConstants.TWENTY, LayoutConstants.FIFTY, LayoutConstants.SCROPNUM, LayoutConstants.THIRTY); + JLabel filePathLocation = new JLabel("Save Location"); + filePathLocation.setBounds(LayoutConstants.TWENTY, LayoutConstants.NINETY, LayoutConstants.HUNDRED_FIFTY, + LayoutConstants.THIRTY); + JTextArea msgTextArea = new JTextArea(LayoutConstants.TWENTY, LayoutConstants.THIRTY); + msgTextArea.setEditable(false); + msgTextArea.setLineWrap(true); + msgTextArea + .setBounds(LayoutConstants.TWENTY, LayoutConstants.HUNDRED_TWENTY_TWO, LayoutConstants.SAVE_LOCATION_WIDTH, + LayoutConstants.THIRTY); + msgTextArea.setBackground(ColorConstants.SELECT_PANEL); + if (StringUtils.isNotBlank(tracePath)) { + msgTextArea.setText(tracePath); + } + JPanel selectPanel = new JPanel(new BorderLayout()); + selectPanel.setBounds(LayoutConstants.TWENTY, LayoutConstants.HUNDRED_TWENTY_TWO, LayoutConstants.SCROPNUM, + LayoutConstants.THIRTY); + // 获取文件下拉箭头 + JLabel labelSvg = new JLabel(); + labelSvg.setIcon(IconLoader.getIcon(("/images/down.png"), getClass())); + labelSvg.setBounds(LayoutConstants.THREE_HUNDRED, LayoutConstants.OTHERS_Y, LayoutConstants.JLABEL_SIZE, + LayoutConstants.THIRTY); + selectPanel.add(msgTextArea, BorderLayout.WEST); + selectPanel.add(labelSvg, BorderLayout.CENTER); + labelSvg.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + super.mouseClicked(mouseEvent); + try { + showFileSaveDialog(fileJpanel, msgTextArea); + } catch (IOException exception) { + LOGGER.error("SaveTraceDialog:{}", exception.getMessage()); + } + } + }); + fileJpanel.add(taskNameLabel); + fileJpanel.add(jTextField); + fileJpanel.add(filePathLocation); + fileJpanel.add(selectPanel); + customDialogWrapper(btn, new SampleDialog(title, fileJpanel), jTextField, msgTextArea); + } + + /** + * 创建一个对话框Wrapper + * + * @param btn btn + * @param sampleDialog sampleDialog + * @param jTextField jTextField + * @param msgTextArea msgTextArea + */ + private void customDialogWrapper(CustomJButton btn, SampleDialog sampleDialog, JTextField jTextField, + JTextArea msgTextArea) { + boolean flag = sampleDialog.showAndGet(); + if (flag) { + String fileName = jTextField.getText().trim(); + String filePath = msgTextArea.getText(); + if (StringUtils.isBlank(fileName)) { + new SampleDialog("Warring", "Please input the file name !").show(); + return; + } + if (!fileName.matches("^[A-Za-z0-9]+$")) { + new SampleDialog("Warring", "The file name can only contain numbers and letters !").show(); + return; + } + if (StringUtils.isBlank(filePath)) { + new SampleDialog("Warring", "Please select the file path !").show(); + return; + } + // 查询数据保存到file + String pathName = filePath + File.separator + fileName + Constant.TRACE_SUFFIX; + DeviceProcessInfo deviceProcessInfo = new DeviceProcessInfo(); + deviceProcessInfo.setDeviceName(btn.getDeviceName()); + deviceProcessInfo.setProcessName(btn.getProcessName()); + deviceProcessInfo.setLocalSessionId(btn.getSessionId()); + boolean saveResult = + SessionManager.getInstance().saveSessionDataToFile(btn.getSessionId(), deviceProcessInfo, pathName); + if (saveResult) { + sampleDialog.close(0); + new SampleDialog("prompt", "Save Successfully !").show(); + } else { + sampleDialog.close(0); + new SampleDialog("prompt", "Save failure !").show(); + } + } + } + + /** + * 选择文件保存路径 + * + * @param parent parent + * @param msgTextArea msgTextArea + * @throws IOException IOException + */ + private void showFileSaveDialog(Component parent, JTextArea msgTextArea) throws IOException { + UIManager.put("FileChooser.cancelButtonText", "Cancel"); + // 创建一个默认的文件选取器 + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Select File Path"); + fileChooser.setCurrentDirectory(new File(".")); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileChooser.setMultiSelectionEnabled(false); + fileChooser.setApproveButtonText("choose"); + fileChooser.setControlButtonsAreShown(false); + SampleDialog sampleDialog = new SampleDialog("Select File Path", fileChooser); + boolean flag = sampleDialog.showAndGet(); + if (flag) { + File file = fileChooser.getCurrentDirectory(); + msgTextArea.setText(file.getCanonicalPath()); + tracePath = file.getCanonicalPath(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceLoadDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceLoadDialog.java new file mode 100644 index 000000000..81189d8e0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceLoadDialog.java @@ -0,0 +1,152 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.ui.components.JBLabel; +import ohos.devtools.views.common.LayoutConstants; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.annotation.Nullable; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.Timer; +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.util.Locale; + +/** + * SystemTuningDialog + */ +public class TraceLoadDialog extends DialogWrapper { + private static final Logger LOGGER = LogManager.getLogger(TraceLoadDialog.class); + private static final int MINUTE_TO_S = 60; + private JPanel filePanel; + private JBLabel timeJLabel ; + private Timer timer; + + private int maxDurationParam = 0; + private int hours = 0; + private int minutes = 0; + private int seconds = 0; + + /** + * get timer + * + * @return Timer + */ + public Timer getTimer() { + return this.timer; + } + + /** + * SystemTunningDialogEvent + * + * @param filePanel filePanel + * @param timeJLabel timeJLabel + * @param maxDurationParam maxDurationParam + */ + public TraceLoadDialog(JPanel filePanel, + JBLabel timeJLabel, int maxDurationParam) { + super(true); + this.filePanel = filePanel; + this.timeJLabel = timeJLabel; + this.maxDurationParam = maxDurationParam; + init(); + setTitle("Prompt"); + setResizable(false); + } + + /** + * createCenterPanel + * + * @return JComponent + */ + @Nullable + @Override + protected JComponent createCenterPanel() { + this.offLineTrace(); + JPanel dialogPanel = new JPanel(new BorderLayout()); + if (filePanel != null) { + dialogPanel.add(filePanel, BorderLayout.CENTER); + } + return dialogPanel; + } + + @Nullable + @Override + protected JComponent createSouthPanel() { + JPanel dialogSouthPanel = new JPanel(new BorderLayout()); + return dialogSouthPanel; + } + + /** + * offLineTrace + */ + public void offLineTrace() { + timer = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); + timer.start(); + } + + /** + * actionPerformed + * + * @param actionEvent actionEvent + */ + public void actionPerformed(ActionEvent actionEvent) { + if ((hours * MINUTE_TO_S * MINUTE_TO_S + + minutes * MINUTE_TO_S + seconds) > maxDurationParam) { + timer.stop(); + this.doOKAction(); + } + if (seconds <= LayoutConstants.NUMBER_SECONDS) { + timeJLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + String + .format(Locale.ENGLISH, "%02d", minutes) + ":" + String.format(Locale.ENGLISH, "%02d", seconds)); + seconds++; + if (seconds > LayoutConstants.NUMBER_SECONDS) { + seconds = 0; + minutes++; + if (minutes > LayoutConstants.NUMBER_SECONDS) { + minutes = 0; + hours++; + } + } + } + } + + /** + * set Label Attribute + * + * @param statusJLabelParam statusJLabelParam + * @param durationJLabelParam durationJLabelParam + * @param recordingJLabelParam recordingJLabelParam + * @param timeJLabelParam timeJLabelParam + * @param stopJButton stopJButton + */ + public void setLableAttribute(JLabel statusJLabelParam, JLabel durationJLabelParam, JLabel recordingJLabelParam, + JLabel timeJLabelParam, JButton stopJButton) { + statusJLabelParam.setBounds(120, 30, 70, 20); + recordingJLabelParam.setBounds(190, 30, 70, 20); + durationJLabelParam.setBounds(120, 60, 70, 20); + timeJLabelParam.setBounds(190, 60, 70, 20); + if (stopJButton != null) { + stopJButton.setBounds(150, 110, 70, 20); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceRecordDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceRecordDialog.java new file mode 100644 index 000000000..6eac2de1e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/dialog/TraceRecordDialog.java @@ -0,0 +1,286 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.dialog; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.transport.grpc.SystemTraceHelper; +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.SystemPanel; +import ohos.devtools.views.layout.TaskPanel; +import ohos.devtools.views.layout.utils.TraceStreamerUtils; +import ohos.devtools.views.trace.component.AnalystPanel; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; +import javax.swing.Timer; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_TRACE_FILE; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_GET_TRACE_FILE_INFO; +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.TRACE_STREAMER_LOAD; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_GET_TRACE_FILE; +import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_GET_TRACE_FILE_INFO; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; +import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC; + +/** + * TraceRecordDialog + */ +public class TraceRecordDialog { + private static final Logger LOGGER = LogManager.getLogger(TraceRecordDialog.class); + private int bytraceFileSize; + private Timer timerLoading; + private DeviceIPPortInfo deviceIPPortInfo; + private String sessionId; + private String fileExtension; + private Boolean analysisState = false; + private Boolean pullBytraceFileState = false; + private Boolean chooseMode; + private JBLabel statusAnalysisJLabel = new JBLabel("Status"); + private JBLabel durationAnalysisJLabel = new JBLabel("Duration"); + private JBLabel loadingJLabel = new JBLabel("Loading"); + private JBLabel loadingInitTimeJLabel = new JBLabel(" 00:00:00"); + private int hoursLoading = 0; + private int minutesLoading = 0; + private int secondsLoading = 0; + private TaskPanel taskPanel = null; + private JPanel countPanel = new JPanel(null); + private JBLabel statusJLabel = new JBLabel("Status"); + private JBLabel durationJLabel = new JBLabel("Duration"); + private JBLabel recordingJLabel = new JBLabel("Recording"); + private JBLabel timeJLabel = new JBLabel(); + private JButton stopJButton = new JButton("Stop"); + private TraceLoadDialog traceLoadDialog; + private AnalysisDialog analysisDialogEvent; + + /** + * load + * + * @param taskPanel taskPanel + * @param maxDurationParam maxDurationParam + * @param sessionIdParam sessionIdParam + * @param deviceIPPortInfoParam deviceIPPortInfoParam + * @param chooseMode chooseMode + */ + public void load(TaskPanel taskPanel, int maxDurationParam, String sessionIdParam, + DeviceIPPortInfo deviceIPPortInfoParam, boolean chooseMode) { + this.taskPanel = taskPanel; + this.sessionId = sessionIdParam; + this.deviceIPPortInfo = deviceIPPortInfoParam; + this.chooseMode = chooseMode; + timeJLabel.setText(" 00:00:00"); + this.fileExtension = chooseMode ? ".bytrace" : ".htrace"; + traceLoadDialog = new TraceLoadDialog(countPanel, timeJLabel, maxDurationParam); + stopJButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + traceLoadDialog.getTimer().stop(); + traceLoadDialog.doCancelAction(); + new SystemTraceHelper().cancelActionDestroySession(deviceIPPortInfo, sessionId); + } + }); + countPanel.setPreferredSize(new Dimension(300, 150)); + statusJLabel.setForeground(Color.white); + durationJLabel.setForeground(Color.white); + recordingJLabel.setForeground(Color.white); + timeJLabel.setForeground(Color.white); + traceLoadDialog.setLableAttribute(statusJLabel, durationJLabel, recordingJLabel, timeJLabel, stopJButton); + countPanel.add(statusJLabel); + countPanel.add(durationJLabel); + countPanel.add(recordingJLabel); + countPanel.add(timeJLabel); + countPanel.add(stopJButton); + traceLoadDialog.show(); + int exitCode = traceLoadDialog.getExitCode(); + traceLoadDialog.getTimer().stop(); + if (exitCode == 0) { + this.loading(); + if (chooseMode) { + ExecutorService executorCancel = Executors.newSingleThreadExecutor(); + executorCancel.execute(new Runnable() { + @Override + public void run() { + new SystemTraceHelper().stopSession(deviceIPPortInfo, sessionId); + } + }); + } + } else { + if (chooseMode) { + new SystemTraceHelper().cancelActionDestroySession(deviceIPPortInfo, sessionId); + } + } + } + + /** + * loading + */ + public void loading() { + pullBytraceFileState = true; + analysisDialogEvent = new AnalysisDialog(deviceIPPortInfo, countPanel); + timerLoading = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformedLoading); + countPanel.setPreferredSize(new Dimension(300, 150)); + statusAnalysisJLabel.setForeground(Color.white); + durationAnalysisJLabel.setForeground(Color.white); + loadingJLabel.setForeground(Color.white); + loadingInitTimeJLabel.setForeground(Color.white); + traceLoadDialog + .setLableAttribute(statusAnalysisJLabel, durationAnalysisJLabel, loadingJLabel, loadingInitTimeJLabel, + null); + countPanel.removeAll(); + countPanel.add(statusAnalysisJLabel); + countPanel.add(durationAnalysisJLabel); + countPanel.add(loadingJLabel); + countPanel.add(loadingInitTimeJLabel); + countPanel.repaint(); + timerLoading.start(); + analysisDialogEvent.show(); + } + + /** + * actionLoadingPerformed + * + * @param actionEvent actionEvent + */ + public void actionPerformedLoading(ActionEvent actionEvent) { + if (secondsLoading <= LayoutConstants.NUMBER_SECONDS) { + loadingInitTimeJLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hoursLoading) + ":" + String + .format(Locale.ENGLISH, "%02d", minutesLoading) + ":" + String + .format(Locale.ENGLISH, "%02d", secondsLoading)); + secondsLoading++; + if (secondsLoading > LayoutConstants.NUMBER_SECONDS) { + secondsLoading = 0; + minutesLoading++; + if (minutesLoading > LayoutConstants.NUMBER_SECONDS) { + minutesLoading = 0; + hoursLoading++; + } + } + int num = secondsLoading % 2; + if (pullBytraceFileState && num == 0) { + String filePath = "/data/local/tmp/hiprofiler_data" + fileExtension; + ArrayList getBytraceFileInfoCmd; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + getBytraceFileInfoCmd = conversionCommand(HDC_STD_GET_TRACE_FILE_INFO, deviceIPPortInfo.getDeviceID(), filePath); + } else { + getBytraceFileInfoCmd = conversionCommand(HDC_GET_TRACE_FILE_INFO, deviceIPPortInfo.getDeviceID(), filePath); + } + String bytraceFileInfo = HdcWrapper.getInstance().getHdcStringResult(getBytraceFileInfoCmd); + if (bytraceFileInfo != null && bytraceFileInfo.length() > 0) { + String[] bytraceFileInfoArray = bytraceFileInfo.split("\t"); + LOGGER.info("trace file size: {}", bytraceFileInfoArray[0]); + if (bytraceFileSize != 0 && bytraceFileSize == Integer.valueOf(bytraceFileInfoArray[0])) { + pullBytraceFileState = false; + pullAndAnalysisBytraceFile(); + } else { + bytraceFileSize = Integer.valueOf(bytraceFileInfoArray[0]); + } + } + } + } + if (analysisState) { + timerLoading.stop(); + analysisDialogEvent.close(1); + } + } + + /** + * pull and analysis bytrace file + */ + public void pullAndAnalysisBytraceFile() { + ExecutorService executor = Executors.newSingleThreadExecutor(); + executor.execute(new Runnable() { + @Override + public void run() { + new SwingWorker() { + @Override + protected String doInBackground() { + getBytraceFile(); + String baseDir = TraceStreamerUtils.getInstance().getBaseDir(); + String dir = baseDir + "hiprofiler_data" + fileExtension; + String dbPath = TraceStreamerUtils.getInstance().getDbPath(); + ArrayList arrayList = conversionCommand(TRACE_STREAMER_LOAD, + baseDir + TraceStreamerUtils.getInstance().getTraceStreamerApp(), dir, dbPath); + HdcWrapper.getInstance().getHdcStringResult(arrayList); + return TraceStreamerUtils.getInstance().getDbPath(); + } + + @Override + protected void done() { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + analysisState = true; + if (chooseMode) { + new SystemTraceHelper().cancelActionDestroySession(deviceIPPortInfo, sessionId); + } + JBPanel tabContainer = taskPanel.getTabContainer(); + tabContainer.removeAll(); + AnalystPanel component = new AnalystPanel(); + String dbPath = get(); + component.load(dbPath, true); + tabContainer.setBackground(JBColor.background()); + SystemPanel systemTuningPanel = new SystemPanel(tabContainer, component); + tabContainer.add(systemTuningPanel, BorderLayout.NORTH); + tabContainer.add(component, BorderLayout.CENTER); + taskPanel.getTabContainer().add(component, BorderLayout.CENTER); + taskPanel.repaint(); + } catch (InterruptedException | ExecutionException exception) { + LOGGER.error(" ExecutionException ", exception); + } + } + }); + } + }.execute(); + } + }); + } + + /** + * get bytrace file + */ + public void getBytraceFile() { + String filePath = "/data/local/tmp/hiprofiler_data" + fileExtension; + ArrayList cmd; + if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) { + cmd = conversionCommand(HDC_STD_GET_TRACE_FILE, deviceIPPortInfo.getDeviceID(), filePath, + TraceStreamerUtils.getInstance().getBaseDir()); + } else { + cmd = conversionCommand(HDC_GET_TRACE_FILE, deviceIPPortInfo.getDeviceID(), filePath, + TraceStreamerUtils.getInstance().getBaseDir()); + } + HdcWrapper.getInstance().execCmdBy(cmd); + LOGGER.info(cmd); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEvent.java deleted file mode 100644 index 15761e26b..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEvent.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.process.service.ProcessManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.swing.DeviceProcessJpanel; -import ohos.devtools.views.layout.swing.TaskScenePanel; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.DefaultComboBoxModel; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.SwingWorker; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.DefaultTableModel; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; -import java.util.concurrent.ExecutionException; - -import static ohos.devtools.views.common.Constant.DEVICEREFRESH; - -/** - * DeviceProcessJpanelEvent - * - * @version 1.0 - * @date 2021/3/4 19:02 - **/ -public class DeviceProcessJpanelEvent extends TaskScenePanelEvent { - private static final Logger LOGGER = LogManager.getLogger(DeviceProcessJpanelEvent.class); - - private boolean flag = false; - - private Vector oldDevice = new Vector<>(); - - // 原始jTable,包含当前表格所有的进程列表 - private List processInfoList; - - private int rowCount = -1; - - /** - * searchJButtonSelect - * - * @param deviceProcessJpanel deviceProcessJpanel - * @param processInfoList processInfoList - */ - public void searchJButtonSelect(DeviceProcessJpanel deviceProcessJpanel, List processInfoList) { - // 搜索框输入值直接开始搜索 - deviceProcessJpanel.getTextField().getDocument().addDocumentListener(new DocumentListener() { - /** - * insertUpdate - * - * @param exception exception - */ - @Override - public void insertUpdate(DocumentEvent exception) { - DeviceProcessJpanelEvent.this.processInfoList = deviceProcessJpanel.getProinfos(); - if (!StringUtils.isEmpty(deviceProcessJpanel.getTextField().getText())) { - autoComplete(deviceProcessJpanel.getTextField().getText(), deviceProcessJpanel.getTable()); - } else { - autoComplete("", deviceProcessJpanel.getTable()); - } - } - - /** - * removeUpdate - * - * @param exception exception - */ - @Override - public void removeUpdate(DocumentEvent exception) { - DeviceProcessJpanelEvent.this.processInfoList = deviceProcessJpanel.getProinfos(); - if (!StringUtils.isEmpty(deviceProcessJpanel.getTextField().getText())) { - autoComplete(deviceProcessJpanel.getTextField().getText(), deviceProcessJpanel.getTable()); - } else { - autoComplete("", deviceProcessJpanel.getTable()); - } - } - - /** - * changedUpdate - * - * @param exception exception - */ - @Override - public void changedUpdate(DocumentEvent exception) { - } - }); - } - - /** - * itemStateChanged - * - * @param deviceProcessJpanel deviceProcessJpanel - * @param taskScenePanel taskScenePanel - * @param deviceNum deviceNum - * @param scrollPane scrollPane - */ - public void itemStateChanged(DeviceProcessJpanel deviceProcessJpanel, TaskScenePanel taskScenePanel, - String deviceNum, JPanel scrollPane) { - deviceProcessJpanel.getJComboBoxPhone().addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent exception) { - // 获取选中项,设置对象信息用于查询对应的进程信息 - for (DeviceIPPortInfo deviceInfo : deviceProcessJpanel.getDeviceInfos()) { - if (deviceInfo.getDeviceName().equals(deviceProcessJpanel.getJComboBoxPhone().getSelectedItem())) { - deviceProcessJpanel.createProcessList(deviceInfo, deviceNum, scrollPane, taskScenePanel); - } - } - } - }); - } - - /** - * clickTable - * - * @param deviceProcessJpanel deviceProcessJpanel - * @param deviceNum deviceNum - * @param deviceInfo deviceInfo - * @param scrollPane scrollPane - * @param taskScenePanel taskScenePanel - */ - public void clickTable(DeviceProcessJpanel deviceProcessJpanel, String deviceNum, DeviceIPPortInfo deviceInfo, - JPanel scrollPane, TaskScenePanel taskScenePanel) { - deviceProcessJpanel.getTable().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - int selectedRow = deviceProcessJpanel.getTable().getSelectedRow(); - deviceProcessJpanel.getLabelName() - .setText(deviceProcessJpanel.getTable().getValueAt(selectedRow, 0) + ""); - // 获取当前设备下的选中的进程信息 - for (int index = 0; index < deviceProcessJpanel.getProinfos().size(); index++) { - ProcessInfo mapValue = deviceProcessJpanel.getProinfos().get(index); - if (deviceProcessJpanel.getLabelName().getText() - .equals(mapValue.getProcessName() + "(" + mapValue.getProcessId() + ")")) { - // 更新map - DeviceIPPortInfo deviceIPPortInfo = deviceProcessJpanel.getDeviceInfos().get(0); - Map mapObject = new HashMap<>(); - mapObject.put(deviceIPPortInfo, deviceProcessJpanel.getProinfos().get(index)); - Constant.map.put(deviceNum, mapObject); - } - } - // 当选中值后,关闭进程下拉列表 - closeProcessList(deviceProcessJpanel, scrollPane, deviceProcessJpanel.getTaskScenePanelEvent(), - taskScenePanel); - } - }); - } - - /** - * 设备信息修改 - * - * @param deviceProcessJpanel deviceProcessJpanel - */ - public void devicesInfoJComboBoxUpdate(DeviceProcessJpanel deviceProcessJpanel) { - QuartzManager.getInstance().addExecutor(DEVICEREFRESH, new Runnable() { - @Override - public void run() { - List deviceInfos = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - - if (!deviceInfos.isEmpty()) { - deviceProcessJpanel.setDeviceInfos(deviceInfos); - Vector items = new Vector<>(); - deviceInfos.forEach(deviceInfo -> { - items.add(deviceInfo.getDeviceName()); - }); - if (!oldDevice.equals(items)) { - oldDevice = items; - deviceProcessJpanel.getJComboBoxPhone().setModel(new DefaultComboBoxModel(items)); - } - } else { - // 清空设备列表 - Vector items = new Vector<>(); - deviceProcessJpanel.getJComboBoxPhone().setModel(new DefaultComboBoxModel(items)); - Constant.map.clear(); - deviceProcessJpanel.getDeviceInfos().clear(); - // 清空进程列表 - List processInfos = new ArrayList<>(); - deviceProcessJpanel.setDeviceInfos(deviceInfos); - deviceProcessJpanel.setProinfos(processInfos); - deviceProcessJpanel.getLabelName().setText(""); - Vector columnNames = new Vector(); - columnNames.add(""); - Vector processNames = new Vector<>(); - DefaultTableModel model = new DefaultTableModel(processNames, columnNames); - JTable table = deviceProcessJpanel.getTable(); - table.setModel(model); - table.getTableHeader().setVisible(false); - table.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); - } - } - }); - QuartzManager.getInstance().startExecutor(DEVICEREFRESH, 0, LayoutConstants.THOUSAND); - } - - /** - * 自动完成 - * - * @param name name - * @param jTable jTable - */ - public void autoComplete(String name, JTable jTable) { - int rowCountNew = processInfoList.size(); - String[] columnNames = {""}; - if (!name.isEmpty()) { - int numTableValues = 0; - int count = 0; - for (int index = 0; index < rowCountNew; index++) { - ProcessInfo processInfo = processInfoList.get(index); - String processName = processInfo.getProcessName(); - if (processName.contains(name)) { - count++; - } - } - String[][] tableValues = new String[count][1]; - for (int index = 0; index < rowCountNew; index++) { - ProcessInfo processInfo = processInfoList.get(index); - String processName = processInfo.getProcessName(); - if (processName.contains(name)) { - tableValues[numTableValues][0] = - processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"; - numTableValues++; - } - } - DefaultTableModel model = new DefaultTableModel(tableValues, columnNames); - jTable.setModel(model); - } else { - int numTableValues = 0; - String[][] tableValues = new String[rowCountNew][1]; - for (int index = 0; index < rowCountNew; index++) { - ProcessInfo processInfo = processInfoList.get(index); - tableValues[numTableValues][0] = processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"; - numTableValues++; - } - DefaultTableModel model = new DefaultTableModel(tableValues, columnNames); - jTable.setModel(model); - } - } - - private void judgmentJbutton(DeviceProcessJpanel deviceProcessJpanel, TaskScenePanel taskScenePanel, String type) { - if ("open".equals(type) && deviceProcessJpanel.getComponentCount() == LayoutConstants.EIGHT_NUM) { - taskScenePanel.getJButtonAddDevice().setBounds(LayoutConstants.APP_LABEL_Y1, - taskScenePanel.getJButtonAddDevice().getY() + LayoutConstants.DEVICE_NAME_WIDTH, - LayoutConstants.DEVICE_ADD_WIDTH, LayoutConstants.DEVICE_ADD_HEIGHT); - } - if ("close".equals(type) && deviceProcessJpanel.getComponentCount() == LayoutConstants.INDEX_SEVEN) { - taskScenePanel.getJButtonAddDevice().setBounds(LayoutConstants.APP_LABEL_Y1, - taskScenePanel.getJButtonAddDevice().getY() - LayoutConstants.DEVICE_NAME_WIDTH, - LayoutConstants.DEVICE_ADD_WIDTH, LayoutConstants.DEVICE_ADD_HEIGHT); - } - } - - private void closeOrOpenProcessList(DeviceProcessJpanel deviceProcessJpanel, JPanel scrollPane, - TaskScenePanelEvent taskScenePanelEvent, String deviceNum, TaskScenePanel taskScenePanel) { - if (!flag) { - int numHeight = 0; - deviceProcessJpanel.add(deviceProcessJpanel.getJPanelProcess()); - deviceProcessJpanel - .setBounds(LayoutConstants.DEVICE_PRO_X, deviceProcessJpanel.getY(), LayoutConstants.DEVICE_PRO_WIDTH, - deviceProcessJpanel.getHeight() + LayoutConstants.DEVICE_NAME_WIDTH); - numHeight = forCycle(deviceProcessJpanel, scrollPane); - scrollPane.setPreferredSize(new Dimension(LayoutConstants.DEVICE_PRO_WIDTH, numHeight)); - taskScenePanelEvent.setNum(taskScenePanelEvent.getNum() + LayoutConstants.DEVICE_NAME_WIDTH); - // 判断当前panel是否含有adddevice按钮 - judgmentJbutton(deviceProcessJpanel, taskScenePanel, "open"); - SwingWorker>, Integer> task = - new SwingWorker>, Integer>() { - /** - * doInBackground - * - * @return HashMap> - * @throws Exception Exception - */ - @Override - protected HashMap> doInBackground() throws Exception { - List processInfos = new ArrayList<>(); - HashMap> map = new HashMap<>(); - for (DeviceIPPortInfo deviceInfo : deviceProcessJpanel.getDeviceInfos()) { - if (deviceInfo.getDeviceName() - .equals(deviceProcessJpanel.getJComboBoxPhone().getSelectedItem())) { - processInfos = ProcessManager.getInstance().getProcessList(deviceInfo); - map.put(deviceInfo, processInfos); - break; - } - } - return map; - } - - /** - * done - */ - @Override - protected void done() { - try { - doneProcessList(get(), deviceProcessJpanel, deviceNum, scrollPane); - } catch (InterruptedException exception) { - LOGGER.error(exception.getMessage()); - } catch (ExecutionException exception) { - LOGGER.error(exception.getMessage()); - } - } - }; - task.execute(); - flag = true; - } else { - // 关闭进程下拉列表 - closeProcessList(deviceProcessJpanel, scrollPane, taskScenePanelEvent, taskScenePanel); - } - } - - private void doneProcessList(HashMap> deviceProcess, - DeviceProcessJpanel deviceProcessJpanel, String deviceNum, JPanel scrollPane) { - List processInfos = new ArrayList<>(); - DeviceIPPortInfo deviceInfo = new DeviceIPPortInfo(); - Set>> entries = deviceProcess.entrySet(); - Iterator>> iterator = entries.iterator(); - while (iterator.hasNext()) { - Map.Entry> entry = iterator.next(); - deviceInfo = entry.getKey(); - processInfos = entry.getValue(); - } - - deviceProcessJpanel.setProinfos(processInfos); - // 创建列表 - Vector columnNames = new Vector(); - columnNames.add(""); - // 根据设备信息获取进程信息 - Vector processNames = new Vector<>(); - for (int index = 0; index < processInfos.size(); index++) { - ProcessInfo processInfo = processInfos.get(index); - Vector vector = new Vector(); - vector.add(processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"); - processNames.add(vector); - } - if (!processInfos.isEmpty()) { - // 更新map - Map mapObject = new HashMap<>(); - mapObject.put(deviceInfo, processInfos.get(0)); - Constant.map.put(deviceNum, mapObject); - } - - DefaultTableModel model = new DefaultTableModel(processNames, columnNames); - JTable table = deviceProcessJpanel.getTable(); - table.setModel(model); - table.getTableHeader().setVisible(false); - table.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); - scrollPane.updateUI(); - scrollPane.repaint(); - } - - /** - * forCycle - * - * @param deviceProcessJpanel deviceProcessJpanel - * @param numHeight numHeight - * @param scrollPane scrollPane - * @return int - */ - public int forCycle(DeviceProcessJpanel deviceProcessJpanel, JPanel scrollPane) { - Component[] component = scrollPane.getComponents(); - int newHeight = 0; - for (Component componentJpanel : component) { - JPanel jCom = (JPanel) componentJpanel; - newHeight += jCom.getHeight(); - if (jCom.getY() > deviceProcessJpanel.getY()) { - jCom.setBounds(LayoutConstants.DEVICE_PRO_X, jCom.getY() + LayoutConstants.DEVICE_NAME_WIDTH, - LayoutConstants.DEVICE_PRO_WIDTH, jCom.getHeight()); - } - } - return newHeight; - } - - private void closeProcessList(DeviceProcessJpanel deviceProcessJpanel, JPanel scrollPane, - TaskScenePanelEvent taskScenePanelEvent, TaskScenePanel taskScenePanel) { - deviceProcessJpanel.remove(deviceProcessJpanel.getJPanelProcess()); - deviceProcessJpanel - .setBounds(LayoutConstants.DEVICE_PRO_X, deviceProcessJpanel.getY(), LayoutConstants.DEVICE_PRO_WIDTH, - deviceProcessJpanel.getHeight() - LayoutConstants.DEVICE_NAME_WIDTH); - Component[] component = scrollPane.getComponents(); - for (Component componentJpanel : component) { - JPanel jCom = null; - if (componentJpanel instanceof JPanel) { - jCom = (JPanel) componentJpanel; - if (jCom.getY() > deviceProcessJpanel.getY()) { - jCom.setBounds(LayoutConstants.DEVICE_PRO_X, jCom.getY() - LayoutConstants.DEVICE_NAME_WIDTH, - LayoutConstants.DEVICE_PRO_WIDTH, jCom.getHeight()); - } - } - } - scrollPane.setPreferredSize(new Dimension(LayoutConstants.DEVICE_PRO_WIDTH, - scrollPane.getHeight() - LayoutConstants.DEVICE_NAME_WIDTH)); - taskScenePanelEvent.setNum(taskScenePanelEvent.getNum() - LayoutConstants.DEVICE_NAME_WIDTH); - // 判断当前panel是否含有adddevice按钮 - judgmentJbutton(deviceProcessJpanel, taskScenePanel, "close"); - scrollPane.updateUI(); - scrollPane.repaint(); - flag = false; - } - - /** - * addClickListener - * - * @param deviceProcessJpanel deviceProcessJpanel - * @param scrollPane scrollPane - * @param taskScenePanelEvent taskScenePanelEvent - * @param taskScenePanel taskScenePanel - * @param deviceNum deviceNum - */ - public void addClickListener(DeviceProcessJpanel deviceProcessJpanel, JPanel scrollPane, - TaskScenePanelEvent taskScenePanelEvent, TaskScenePanel taskScenePanel, String deviceNum) { - deviceProcessJpanel.getLabelName().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - closeOrOpenProcessList(deviceProcessJpanel, scrollPane, taskScenePanelEvent, deviceNum, taskScenePanel); - } - }); - } - - /** - * table鼠标悬停效果 - * - * @param table table - */ - public void mouseEffectTable(JTable table) { - table.setDefaultRenderer(Object.class, new TableCellRenderer()); - table.addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseMoved(final MouseEvent mMoved) { - rowCount = table.rowAtPoint(mMoved.getPoint()); - int row = table.rowAtPoint(mMoved.getPoint()); - int col = table.columnAtPoint(mMoved.getPoint()); - table.setRowSelectionInterval(row, row); - table.setColumnSelectionInterval(col, col); - } - }); - table.addMouseListener(new java.awt.event.MouseAdapter() { - @Override - public void mouseReleased(java.awt.event.MouseEvent mre) { - if (mre.getClickCount() == LayoutConstants.INDEX_ONE && SwingUtilities.isRightMouseButton(mre)) { - int row = table.rowAtPoint(mre.getPoint()); - int col = table.columnAtPoint(mre.getPoint()); - table.setRowSelectionInterval(row, row); - table.setColumnSelectionInterval(col, col); - } - } - }); - } - - class TableCellRenderer extends DefaultTableCellRenderer { - private static final long serialVersionUID = LayoutConstants.SERIALVERSIONUID; - - @Override - public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, - boolean hasFocus, int row, int column) { - JLabel label = null; - Component tableCellRendererComponent = - super.getTableCellRendererComponent(jtable, value, isSelected, hasFocus, row, column); - - if (tableCellRendererComponent instanceof JLabel) { - label = (JLabel) tableCellRendererComponent; - if (row == rowCount) { - label.setBackground(ColorConstants.SELECTED_TABLE_COLOR); - } else { - label.setBackground(ColorConstants.SYSTEM_TUNNING_SETTING_CENTER); - } - } - return label; - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessPanelEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessPanelEvent.java new file mode 100644 index 000000000..dbbd778c0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/DeviceProcessPanelEvent.java @@ -0,0 +1,437 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.event; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.process.service.ProcessManager; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.DeviceProcessPanel; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.DefaultComboBoxModel; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import java.awt.Component; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.ExecutionException; + +import static ohos.devtools.views.common.Constant.DEVICE_REFRESH; + +/** + * DeviceProcessPanelEvent + */ +public class DeviceProcessPanelEvent { + private static final Logger LOGGER = LogManager.getLogger(DeviceProcessPanelEvent.class); + private Vector oldDevice = new Vector<>(); + private List processInfoList; + private int rowCount = -1; + + /** + * searchJButtonSelect + * + * @param deviceProcessPanel deviceProcessPanel + * @param processInfoList processInfoList + */ + public void searchJButtonSelect(DeviceProcessPanel deviceProcessPanel, List processInfoList) { + deviceProcessPanel.getSearchField().getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent exception) { + DeviceProcessPanelEvent.this.processInfoList = deviceProcessPanel.getProcessInfoList(); + if (!StringUtils.isEmpty(deviceProcessPanel.getSearchField().getText())) { + autoComplete(deviceProcessPanel.getSearchField().getText(), deviceProcessPanel.getProcessTable()); + } else { + autoComplete("", deviceProcessPanel.getProcessTable()); + } + } + + @Override + public void removeUpdate(DocumentEvent exception) { + DeviceProcessPanelEvent.this.processInfoList = deviceProcessPanel.getProcessInfoList(); + if (!StringUtils.isEmpty(deviceProcessPanel.getSearchField().getText())) { + autoComplete(deviceProcessPanel.getSearchField().getText(), deviceProcessPanel.getProcessTable()); + } else { + autoComplete("", deviceProcessPanel.getProcessTable()); + } + } + + @Override + public void changedUpdate(DocumentEvent exception) { + } + }); + } + + /** + * itemStateChanged + * + * @param deviceProcessPanel deviceProcessPanel + */ + public void itemStateChanged(DeviceProcessPanel deviceProcessPanel) { + deviceProcessPanel.getDeviceNameComboBox().addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent exception) { + for (DeviceIPPortInfo deviceInfo : deviceProcessPanel.getDeviceInfoList()) { + if (deviceInfo.getDeviceName() + .equals(deviceProcessPanel.getDeviceNameComboBox().getSelectedItem())) { + deviceProcessPanel.initProcessList(deviceInfo); + } + } + } + }); + } + + /** + * clickTable + * + * @param deviceProcessPanel deviceProcessPanel + * @param deviceNum deviceNum + * @param scrollPane scrollPane + */ + public void clickTable(DeviceProcessPanel deviceProcessPanel, String deviceNum, JPanel scrollPane) { + deviceProcessPanel.getProcessTable().addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + super.mouseClicked(mouseEvent); + int selectedRow = deviceProcessPanel.getProcessTable().getSelectedRow(); + deviceProcessPanel.getSelectedProcessName() + .setText(deviceProcessPanel.getProcessTable().getValueAt(selectedRow, 0) + ""); + // 获取当前设备下的选中的进程信息 + for (int index = 0; index < deviceProcessPanel.getProcessInfoList().size(); index++) { + ProcessInfo mapValue = deviceProcessPanel.getProcessInfoList().get(index); + if (deviceProcessPanel.getSelectedProcessName().getText() + .equals(mapValue.getProcessName() + "(" + mapValue.getProcessId() + ")")) { + // 更新map + DeviceIPPortInfo deviceIPPortInfo = deviceProcessPanel.getDeviceInfoList().get(0); + Map mapObject = new HashMap<>(); + mapObject.put(deviceIPPortInfo, deviceProcessPanel.getProcessInfoList().get(index)); + Constant.map.put(deviceNum, mapObject); + } + } + closeProcessList(deviceProcessPanel, scrollPane); + } + }); + } + + /** + * devicesInfoJComboBoxUpdate + * + * @param deviceProcessPanel deviceProcessPanel + */ + public void devicesInfoJComboBoxUpdate(DeviceProcessPanel deviceProcessPanel) { + QuartzManager.getInstance().addExecutor(DEVICE_REFRESH, new Runnable() { + @Override + public void run() { + List deviceInfos = MultiDeviceManager.getInstance().getOnlineDeviceInfoList(); + + if (!deviceInfos.isEmpty()) { + deviceProcessPanel.setDeviceInfoList(deviceInfos); + Vector items = new Vector<>(); + deviceInfos.forEach(deviceInfo -> { + items.add(deviceInfo.getDeviceName()); + }); + if (!oldDevice.equals(items)) { + oldDevice = items; + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + deviceProcessPanel.getDeviceNameComboBox().setModel(new DefaultComboBoxModel(items)); + } + }); + } + } else { + // clear the device info + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + Vector items = new Vector<>(); + deviceProcessPanel.getDeviceNameComboBox().setModel(new DefaultComboBoxModel(items)); + Constant.map.clear(); + deviceProcessPanel.getDeviceInfoList().clear(); + // clear the process info + List processInfos = new ArrayList<>(); + deviceProcessPanel.setDeviceInfoList(deviceInfos); + deviceProcessPanel.setProcessInfoList(processInfos); + deviceProcessPanel.getSelectedProcessName().setText(""); + Vector columnNames = new Vector(); + columnNames.add(""); + Vector processNames = new Vector<>(); + DefaultTableModel model = new DefaultTableModel(processNames, columnNames); + JTable table = deviceProcessPanel.getProcessTable(); + table.setModel(model); + table.getTableHeader().setVisible(false); + table.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); + } + }); + } + } + }); + QuartzManager.getInstance().startExecutor(DEVICE_REFRESH, 0, LayoutConstants.THOUSAND); + } + + /** + * autoComplete + * + * @param name name + * @param jTable jTable + */ + public void autoComplete(String name, JTable jTable) { + int rowCountNew = processInfoList.size(); + String[] columnNames = {""}; + if (!name.isEmpty()) { + int numTableValues = 0; + int count = 0; + for (int index = 0; index < rowCountNew; index++) { + ProcessInfo processInfo = processInfoList.get(index); + String processName = processInfo.getProcessName(); + if (processName.contains(name)) { + count++; + } + } + String[][] tableValues = new String[count][1]; + for (int index = 0; index < rowCountNew; index++) { + ProcessInfo processInfo = processInfoList.get(index); + String processName = processInfo.getProcessName(); + if (processName.contains(name)) { + tableValues[numTableValues][0] = + processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"; + numTableValues++; + } + } + DefaultTableModel model = new DefaultTableModel(tableValues, columnNames); + jTable.setModel(model); + } else { + int numTableValues = 0; + String[][] tableValues = new String[rowCountNew][1]; + for (int index = 0; index < rowCountNew; index++) { + ProcessInfo processInfo = processInfoList.get(index); + tableValues[numTableValues][0] = processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"; + numTableValues++; + } + DefaultTableModel model = new DefaultTableModel(tableValues, columnNames); + jTable.setModel(model); + } + } + + private void switchProcessList(DeviceProcessPanel deviceProcessPanel, JBPanel scrollPane, String deviceNum) { + if (!deviceProcessPanel.getProcessPanel().isVisible()) { + openProcessList(deviceProcessPanel, scrollPane, deviceNum); + } else { + closeProcessList(deviceProcessPanel, scrollPane); + } + } + + private void openProcessList(DeviceProcessPanel deviceProcessPanel, JPanel scrollPane, String deviceNum) { + deviceProcessPanel.getProcessPanel().setVisible(true); + SwingWorker>, Integer> task = + new SwingWorker>, Integer>() { + @Override + protected HashMap> doInBackground() { + List processInfos = new ArrayList<>(); + HashMap> map = new HashMap<>(); + for (DeviceIPPortInfo deviceInfo : deviceProcessPanel.getDeviceInfoList()) { + if (deviceInfo.getDeviceName() + .equals(deviceProcessPanel.getDeviceNameComboBox().getSelectedItem())) { + ProcessManager instance = ProcessManager.getInstance(); + if (!instance.isRequestProcess()) { + processInfos = ProcessManager.getInstance().getProcessList(deviceInfo); + map.put(deviceInfo, processInfos); + } + break; + } + } + return map; + } + + @Override + protected void done() { + try { + doneProcessList(get(), deviceProcessPanel, deviceNum, scrollPane); + } catch (InterruptedException interruptedException) { + LOGGER.error(interruptedException.getMessage()); + } catch (ExecutionException executionException) { + LOGGER.error(executionException.getMessage()); + } + } + }; + task.execute(); + } + + private void closeProcessList(DeviceProcessPanel deviceProcessPanel, JPanel scrollPane) { + deviceProcessPanel.getProcessPanel().setVisible(false); + } + + private void doneProcessList(HashMap> deviceProcess, + DeviceProcessPanel deviceProcessPanel, String deviceNum, JPanel scrollPane) { + List processInfos = new ArrayList<>(); + DeviceIPPortInfo deviceInfo = new DeviceIPPortInfo(); + if (deviceProcess.isEmpty()) { + return; + } + Set>> entries = deviceProcess.entrySet(); + Iterator>> iterator = entries.iterator(); + while (iterator.hasNext()) { + Map.Entry> entry = iterator.next(); + deviceInfo = entry.getKey(); + processInfos = entry.getValue(); + } + + deviceProcessPanel.setProcessInfoList(processInfos); + // 创建列表 + Vector columnNames = new Vector(); + columnNames.add(""); + // 根据设备信息获取进程信息 + Vector processNames = new Vector<>(); + for (int index = 0; index < processInfos.size(); index++) { + ProcessInfo processInfo = processInfos.get(index); + Vector vector = new Vector(); + vector.add(processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"); + processNames.add(vector); + } + if (!processInfos.isEmpty()) { + // 更新map + Map mapObject = new HashMap<>(); + mapObject.put(deviceInfo, processInfos.get(0)); + Constant.map.put(deviceNum, mapObject); + } + + DefaultTableModel model = new DefaultTableModel(processNames, columnNames); + JTable table = deviceProcessPanel.getProcessTable(); + table.setModel(model); + table.getTableHeader().setVisible(false); + table.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); + scrollPane.updateUI(); + scrollPane.repaint(); + } + + /** + * addClickListener + * + * @param deviceProcessPanel deviceProcessPanel + * @param scrollPane scrollPane + * @param deviceNum deviceNum + */ + public void addClickListener(DeviceProcessPanel deviceProcessPanel, JBPanel scrollPane, String deviceNum) { + deviceProcessPanel.getSelectedProcessName().addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + super.mouseClicked(mouseEvent); + switchProcessList(deviceProcessPanel, scrollPane, deviceNum); + } + }); + } + + /** + * mouseEffectTable + * + * @param table table + */ + public void mouseEffectTable(JTable table) { + table.setDefaultRenderer(Object.class, new TableCellRenderer()); + table.addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseMoved(final MouseEvent mMoved) { + try { + rowCount = table.rowAtPoint(mMoved.getPoint()); + int row = table.rowAtPoint(mMoved.getPoint()); + int col = table.columnAtPoint(mMoved.getPoint()); + table.setRowSelectionInterval(row, row); + table.setColumnSelectionInterval(col, col); + } catch (IllegalArgumentException illegalArgumentException) { + LOGGER.error("DeviceProcessJpanelEvent happen llegalArgumentException"); + } + } + }); + table.addMouseListener(new java.awt.event.MouseAdapter() { + @Override + public void mouseReleased(java.awt.event.MouseEvent mre) { + try { + if (mre.getClickCount() == LayoutConstants.INDEX_ONE && SwingUtilities.isRightMouseButton(mre)) { + int row = table.rowAtPoint(mre.getPoint()); + int col = table.columnAtPoint(mre.getPoint()); + table.setRowSelectionInterval(row, row); + table.setColumnSelectionInterval(col, col); + } + } catch (IllegalArgumentException illegalArgumentException) { + LOGGER.error("DeviceProcessPanelEvent happen illegalArgumentException"); + } + } + }); + } + + /** + * Device connection mode changed, set to the latest value + * + * @param deviceInfo deviceInfo + * @param jComboBoxConnect jComboBoxConnect + */ + public void connectTypeChanged(DeviceIPPortInfo deviceInfo, JComboBox jComboBoxConnect) { + jComboBoxConnect.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent exception) { + deviceInfo.setConnectType(jComboBoxConnect.getSelectedItem().toString()); + } + }); + } + + class TableCellRenderer extends DefaultTableCellRenderer { + private static final long serialVersionUID = LayoutConstants.SERIALVERSIONUID; + + @Override + public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, + boolean hasFocus, int row, int column) { + JLabel label = null; + Component tableCellRendererComponent = + super.getTableCellRendererComponent(jtable, value, isSelected, hasFocus, row, column); + + if (tableCellRendererComponent instanceof JLabel) { + label = (JLabel) tableCellRendererComponent; + label.setForeground(JBColor.foreground().brighter()); + if (row == rowCount) { + label.setBackground(JBColor.background().darker()); + } else { + label.setBackground(JBColor.background()); + } + } + return label; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/HomeWindowEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/HomeWindowEvent.java deleted file mode 100644 index cf0b26055..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/HomeWindowEvent.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.views.common.Common; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.layout.swing.HomeWindow; -import ohos.devtools.views.layout.swing.TaskPanel; -import org.apache.logging.log4j.Level; - -import javax.swing.ImageIcon; -import javax.swing.JMenuItem; -import javax.swing.JTabbedPane; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * 一级界面事件处理对象 - * - * @version 1.0 - * @date 2021/03/01 15:20 - **/ -public class HomeWindowEvent { - // 初始化公共方法类 - private Common common = new Common(); - - /** - * clickAddTask - * - * @param homeWindow homeWindow - */ - public void clickAddTask(HomeWindow homeWindow) { - homeWindow.getJNewRealTimeTaskJMenuItem().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - homeWindow.getTaskPanel().removeAll(); - if (Constant.jtasksTab == null || (Constant.jtasksTab != null - && Constant.jtasksTab.getTabCount() == 0)) { - Constant.jtasksTab = new JTabbedPane(); - } - new TaskPanel(homeWindow.getTaskPanel(), homeWindow.getTaskPanelWelcome()); - // 更新所有的run -- of -- - common.updateNum(Constant.jtasksTab); - homeWindow.setVisible(true); - } - }); - } - - /** - * clickUpdateLogLevel - * - * @param homeWindow homeWindow - */ - public void clickUpdateLogLevel(HomeWindow homeWindow) { - JMenuItem switchLog = HomeWindow.getJLogSwitch(); - switchLog.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - Level logLevel = ProfilerLogManager.getSingleton().getNowLogLevel(); - if (Level.ERROR.equals(logLevel)) { - ProfilerLogManager.getSingleton().updateLogLevel(Level.DEBUG); - switchLog.setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader() - .getResource("images/selected.png"))); - } else { - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - switchLog.setIcon(null); - } - } - }); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningByTraceConfigEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningByTraceConfigEvent.java deleted file mode 100644 index 1c9b0e3db..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningByTraceConfigEvent.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.views.layout.swing.SystemTunningConfigPanel; -import ohos.devtools.views.layout.swing.TaskSystemTunningByTracePanel; - -import javax.swing.DefaultComboBoxModel; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.ClipboardOwner; -import java.awt.datatransfer.Transferable; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.List; -import java.util.Vector; - -import static ohos.devtools.views.common.Constant.DEVICEREFRESH; - -/** - * SystemTunningByTraceConfigEvent - * - * @version 1.0 - * @date 2021/04/10 15:16 - **/ -public class SystemTunningByTraceConfigEvent implements ClipboardOwner { - private Vector oldDevice = new Vector<>(); - - DeviceIPPortInfo deviceIPPortInfo = null; - - /** - * requestByTrace - */ - public void requestByTrace() { - } - - /** - * devicesInfoJComboBoxUpdate - * - * @param taskSystemTunningByTracePanel taskSystemTunningByTracePanel - */ - public void devicesInfoJComboBoxUpdate(TaskSystemTunningByTracePanel taskSystemTunningByTracePanel) { - QuartzManager.getInstance().addExecutor(DEVICEREFRESH, new Runnable() { - @Override - public void run() { - List deviceInfos = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - taskSystemTunningByTracePanel.setDeviceInfos(deviceInfos); - Vector items = new Vector<>(); - deviceInfos.forEach(deviceInfo -> { - items.add(deviceInfo.getDeviceName()); - }); - if (!oldDevice.equals(items)) { - oldDevice = items; - taskSystemTunningByTracePanel.getJComboBoxPhone().setModel(new DefaultComboBoxModel(items)); - } - } - }); - QuartzManager.getInstance().startExecutor(DEVICEREFRESH, 0, 1000); - } - - /** - * itemStateChanged - * - * @param taskSystemTunningPanel taskSystemTunningPanel - */ - public void itemStateChanged(SystemTunningConfigPanel taskSystemTunningPanel) { - taskSystemTunningPanel.getJComboBoxPhone().addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent exception) { - // 获取选中项,设置对象信息用于查询对应的进程信息 - for (DeviceIPPortInfo deviceInfo : taskSystemTunningPanel.getDeviceInfos()) { - if (deviceInfo.getDeviceName() - .equals(taskSystemTunningPanel.getJComboBoxPhone().getSelectedItem())) { - deviceIPPortInfo = deviceInfo; - } - } - } - }); - if (taskSystemTunningPanel.getDeviceInfos() != null && deviceIPPortInfo == null) { - deviceIPPortInfo = taskSystemTunningPanel.getDeviceInfos().get(0); - } - } - - /** - * lostOwnership - * - * @param clipboard clipboard - * @param contents contents - */ - @Override - public void lostOwnership(Clipboard clipboard, Transferable contents) { - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningConfigEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningConfigEvent.java deleted file mode 100644 index 77d01d139..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/SystemTunningConfigEvent.java +++ /dev/null @@ -1,1006 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import static ohos.devtools.views.common.Constant.DEVICEREFRESH; - -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Toolkit; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.ClipboardOwner; -import java.awt.datatransfer.StringSelection; -import java.awt.datatransfer.Transferable; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Vector; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultComboBoxModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSlider; -import javax.swing.JTextArea; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohos.devtools.datasources.utils.common.GrpcException; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.datasources.utils.trace.service.TraceManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.SystemTunningProbesCheckbox; -import ohos.devtools.views.layout.swing.SystemTunningLoadDialog; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.SystemTunningConfigPanel; - -/** - * SystemTunningConfigEvent - * - * @version 1.0 - * @date 2021/04/14 20:13 - **/ -public class SystemTunningConfigEvent implements ClipboardOwner { - /** - * 显示maxDuration label的值 - */ - private int hours = 0; - private int minutes = 0; - private int seconds = 10; - - /** - * oldDevice - */ - private Vector oldDevice = new Vector<>(); - - /** - * getUserCheckBoxForPerfettoStr - */ - private String getUserCheckBoxForPerfettoStr = ""; - - /** - * 用于判断从bytrace还是ptrace 0:bytrace 1:ptrace 2:perfetto - */ - private int differentRequests = 0; - - /** - * 用于获取startsession后返回的sessionId - */ - private String sessionId = null; - - /** - * probes 复选框 - */ - private Boolean rbSchedulingIsSelect = true; - - /** - * rb2IsSelect - */ - private Boolean rbCpuIsSelect = true; - - /** - * rb3IsSelect - */ - private Boolean rbSyscallsIsSelect = false; - - /** - * rb4IsSelect - */ - private Boolean rbBoardIsSelect = false; - - /** - * rb5IsSelect - */ - private Boolean rbFrequencyIsSelect = false; - - /** - * rb6IsSelect - */ - private Boolean rbLowMemoryIsSelect = false; - - /** - * rb7IsSelect - */ - private Boolean rbAtraceIsSelect = false; - - /** - * RecordSetting 的参数值 - */ - private int inMemoryValue = LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER; - - /** - * maxDuration - */ - private int maxDuration = LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MIN_DURATION_NUMBER; - - /** - * maxFileSize - */ - private int maxFileSize = LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER; - - /** - * flushOnDisk - */ - private int flushOnDisk = LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER; - - /** - * param - */ - private HashMap> param = new HashMap<>(); - - /** - * paramRecordSetting - */ - private HashMap paramRecordSetting = new HashMap<>(); - - /** - * clipboard - */ - private Clipboard clipboard; - - /** - * deviceIPPortInfo - */ - private DeviceIPPortInfo deviceIPPortInfo = null; - - /** - * checkBoxState - * - * @param rbScheduling rbScheduling - * @param rbCpu rbCpu - * @param rbSyscalls rbSyscalls - * @param rbBoard rbBoard - */ - public void checkBoxState(JCheckBox rbScheduling, JCheckBox rbCpu, JCheckBox rbSyscalls, JCheckBox rbBoard) { - rbScheduling.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbSchedulingIsSelect = rbScheduling.isSelected(); - } - }); - rbCpu.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbCpuIsSelect = rbCpu.isSelected(); - } - }); - rbSyscalls.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbSyscallsIsSelect = rbSyscalls.isSelected(); - } - }); - rbBoard.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbBoardIsSelect = rbBoard.isSelected(); - } - }); - } - - /** - * checkBoxStateLeft - * - * @param rbFrequency rbFrequency - * @param rbLowMemory rbLowMemory - * @param rbAtrace rbAtrace - */ - public void checkBoxStateLeft(JCheckBox rbFrequency, JCheckBox rbLowMemory, JCheckBox rbAtrace) { - rbFrequency.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbFrequencyIsSelect = rbFrequency.isSelected(); - } - }); - rbLowMemory.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbLowMemoryIsSelect = rbLowMemory.isSelected(); - } - }); - rbAtrace.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - rbAtraceIsSelect = rbAtrace.isSelected(); - } - }); - } - - /** - * getUserCheckBox - */ - public void getUserCheckBox() { - paramRecordSetting.clear(); - paramRecordSetting.put("inMemoryValue", inMemoryValue); - paramRecordSetting.put("maxDuration", maxDuration); - paramRecordSetting.put("maxFileSize", maxFileSize); - paramRecordSetting.put("flushOnDisk", flushOnDisk); - param.clear(); - if (rbSchedulingIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_SCHEDULING_DETAIL_FTRACE); - } - if (rbCpuIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_CPU_FREQUENCY_FTRACE); - } - if (rbSyscallsIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_SYSCALLS_FTRACE); - } - if (rbBoardIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_BOARD_VOLTAGES_FTRACE); - } - if (rbFrequencyIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_HIGH_FREQUENCY_FTRACE); - } - if (rbLowMemoryIsSelect) { - getParamListFromString(param, - SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_LOW_MEMORY_FTRACE); - } - if (rbSchedulingIsSelect || rbCpuIsSelect || rbBoardIsSelect) { - getParamListFromString(param, SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_CONTAIN_SHARE_FTRACE_LABLE); - } - } - - /** - * getUserCheckBoxForPerfetto - */ - public void getUserCheckBoxForPerfetto() { - getUserCheckBoxForPerfettoStr = ""; - if (rbSchedulingIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_SCHEDULING_DETAIL_FTRACE); - } - if (rbCpuIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_CPU_FREQUENCY_FTRACE); - } - if (rbSyscallsIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_SYSCALLS_FTRACE); - } - if (rbBoardIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_BOARD_VOLTAGES_FTRACE); - } - if (rbFrequencyIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_HIGH_FREQUENCY_FTRACE); - } - if (rbLowMemoryIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_SECOND_MIDDLE_LOW_MEMORY_FTRACE); - } - if (rbSchedulingIsSelect || rbCpuIsSelect || rbBoardIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr - .concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_CONTAIN_SHARE_FTRACE_LABLE); - } - } - - /** - * Get user checkBox ForBytrace - */ - private void getUserCheckBoxForBytrace() { - getUserCheckBoxForPerfettoStr = ""; - if (rbSchedulingIsSelect || rbCpuIsSelect || rbBoardIsSelect || rbFrequencyIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr.concat(";") - .concat(SystemTunningProbesCheckbox.CPU_FREQUENCY_BYTRACE_ONE_AND_TWO_AND_FOUR); - } - if (rbSchedulingIsSelect || rbLowMemoryIsSelect) { - getUserCheckBoxForPerfettoStr = getUserCheckBoxForPerfettoStr.concat(";") - .concat(SystemTunningProbesCheckbox.SCHEDULING_DETAIL_BYTRACE_ONE_AND_SIX); - } - } - - /** - * startTask - * - * @param taskSystemTunningPanel taskSystemTunningPanel - * @param jTaskPanel jTaskPanel - */ - public void startTask(SystemTunningConfigPanel taskSystemTunningPanel, TaskPanel jTaskPanel) { - taskSystemTunningPanel.getJButtonStartTask().addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseClicked(MouseEvent mouseEvent) { - // create system tunning load dialog object - SystemTunningLoadDialog taskSystemLoad = new SystemTunningLoadDialog(); - super.mouseClicked(mouseEvent); - try { - if (differentRequests == 0) { - getUserCheckBoxForBytrace(); - sessionId = new TraceManager() - .createSessionByTraceRequest(deviceIPPortInfo, getUserCheckBoxForPerfettoStr, maxDuration, - inMemoryValue, false); - } - if (differentRequests == 1) { - getUserCheckBoxForPerfetto(); - getStrResultForPerfetto(); - sessionId = new TraceManager() - .createSessionRequestPerfetto(deviceIPPortInfo, getUserCheckBoxForPerfettoStr, maxDuration, - false); - } - taskSystemLoad.load(jTaskPanel, differentRequests, maxDuration, sessionId, deviceIPPortInfo); - } catch (GrpcException grpcException) { - grpcException.printStackTrace(); - } - jTaskPanel.getOptionJPanel().repaint(); - } - }); - } - - /** - * getStrResultForPerfetto - */ - public void getStrResultForPerfetto() { - getUserCheckBoxForPerfettoStr = SystemTunningProbesCheckbox.PERFETTO_DURATION_MS_ONE - .concat(String.valueOf(maxDuration * SystemTunningProbesCheckbox.SECOND_TO_MS)).concat("\n") - .concat(SystemTunningProbesCheckbox.PERFETTO_DURATION_MS_TWO) - .concat(String.valueOf(inMemoryValue * SystemTunningProbesCheckbox.MEMORY_MB_TO_KB)).concat("\n") - .concat(SystemTunningProbesCheckbox.PERFETTO_DURATION_MS_THREE).concat(getUserCheckBoxForPerfettoStr) - .concat(SystemTunningProbesCheckbox.PERFETTO_DURATION_MS_FOUT); - } - - /** - * lastStep - * - * @param taskSystemTunningPanel taskSystemTunningPanel - * @param jTaskPanel jTaskPanel - */ - public void lastStep(SystemTunningConfigPanel taskSystemTunningPanel, TaskPanel jTaskPanel) { - taskSystemTunningPanel.getJButtonLastStep().addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - jTaskPanel.getOptionJPanel().remove(taskSystemTunningPanel); - jTaskPanel.getOptionJPanelContent().setVisible(true); - jTaskPanel.getOptionJPanel().repaint(); - } - }); - } - - /** - * listenerJPanelSouth - * - * @param taskSystemTunningPanel taskSystemTunningPanel - */ - public void listenerJPanelSouth(SystemTunningConfigPanel taskSystemTunningPanel) { - taskSystemTunningPanel.getJPanelSouth().addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param componentEvent componentEvent - */ - public void componentResized(ComponentEvent componentEvent) { - int width = taskSystemTunningPanel.getJPanelSouth().getWidth(); - taskSystemTunningPanel.getJButtonLastStep() - .setBounds(LayoutConstants.NUMBER_STEP + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_HEIGHT, LayoutConstants.DEVICE_ADD_WIDTH, - LayoutConstants.CHOOSE_HEIGHT); - taskSystemTunningPanel.getJButtonStartTask() - .setBounds(LayoutConstants.POSITION_TASK_X + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_HEIGHT, LayoutConstants.DEVICE_ADD_WIDTH, - LayoutConstants.CHOOSE_HEIGHT); - } - }); - } - - /** - * recordSetting - * - * @param recordSettingLabel recordSettingLabel - * @param traceCommandLabel traceCommandLabel - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param jPanelCenterSouthWest jPanelCenterSouthWest - */ - public void recordSetting(JLabel recordSettingLabel, JLabel traceCommandLabel, JPanel jPanelCenterSouthRight, - JPanel jPanelCenterSouthWest) { - recordSettingLabelRightShow(jPanelCenterSouthRight); - recordSettingLabel.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - recordSettingLabel.setOpaque(true); - traceCommandLabel.setOpaque(false); - recordSettingLabelRightShow(jPanelCenterSouthRight); - jPanelCenterSouthWest.updateUI(); - jPanelCenterSouthWest.repaint(); - } - }); - } - - /** - * radioButton - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param rb1 rb1 - * @param rb2 rb2 - * @param rb3 rb3 - */ - public void radioButton(JPanel jPanelCenterSouthRight, JRadioButton rb1, JRadioButton rb2, JRadioButton rb3) { - jPanelCenterSouthRight.removeAll(); - rb1.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rb2.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rb3.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - JLabel jLabel = new JLabel("Record model:"); - jLabel.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_RECORD_MODEL_LABLE_INTT_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - ButtonGroup buttonGroup = new ButtonGroup(); - buttonGroup.add(rb1); - rb1.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_RADIO_INTT_X, LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y, - LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_RADIO_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rb2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_RADIO_DECOND_INTT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y, LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_RADIO_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rb3.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_RADIO_THREE_INTT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y, LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_RADIO_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthRight.add(jLabel); - jPanelCenterSouthRight.add(rb1); - } - - /** - * recordSettingLabelRightShow - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - */ - public void recordSettingLabelRightShow(JPanel jPanelCenterSouthRight) { - // 单选按钮、进度条等 - JRadioButton rb1 = new JRadioButton("Stop when full", true); - JRadioButton rb2 = new JRadioButton("Ring buffer"); // 创建JRadioButton对象 - JRadioButton rb3 = new JRadioButton("Long trace"); - radioButton(jPanelCenterSouthRight, rb1, rb2, rb3); - // Long trace 选中显示 - JLabel memoryLabel3 = new JLabel("Max file size:"); - memoryLabel3.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_FILE_SIZE_SLIDE_INT_LABEL_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - JSlider sliderMaxFileSize = new JSlider(LayoutConstants.DEFAULT_NUMBER, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_IN_MEMORY_NUMBER); - sliderMaxFileSize.setValue(LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER); - // memoryThree - JLabel memoryThree = this.memoryThreeAttribute(); - JLabel memoryLabel4 = new JLabel("Flush on disk every:"); - memoryLabel4.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_FLUSH_ON_DISK_SLIDE_INT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - JSlider sliderFLushOnDisk = new JSlider(LayoutConstants.DEFAULT_NUMBER, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_IN_MEMORY_NUMBER); - sliderFLushOnDisk.setValue(LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER); - // memoryFLushOnDisk - JLabel memoryFLushOnDisk = this.memoryFLushOnDisk(); - // Long trace 选中显示---结束 - rb1.addActionListener(new ActionListener() { - /** - * actionPerformed - * - * @param actionEvent actionEvent - */ - @Override - public void actionPerformed(ActionEvent actionEvent) { - jPanelCenterSouthRight.remove(memoryLabel3); - jPanelCenterSouthRight.remove(memoryThree); - jPanelCenterSouthRight.remove(sliderMaxFileSize); - jPanelCenterSouthRight.remove(memoryLabel4); - jPanelCenterSouthRight.remove(memoryFLushOnDisk); - jPanelCenterSouthRight.remove(sliderFLushOnDisk); - jPanelCenterSouthRight.updateUI(); - jPanelCenterSouthRight.repaint(); - } - }); - jPanelCenterSouthRightAddInMemory(jPanelCenterSouthRight); - jPanelCenterSouthRightAddMaxDuration(jPanelCenterSouthRight); - jPanelCenterSouthRight.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - jPanelCenterSouthRight.updateUI(); - jPanelCenterSouthRight.repaint(); - } - - /** - * memoryThreeAttribute - * - * @return JLabel - */ - public JLabel memoryThreeAttribute() { - JLabel memoryThree = - new JLabel("" + LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER + " MB", JLabel.CENTER); - memoryThree.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryThree.setForeground(Color.white); - memoryThree.setVerticalTextPosition(JLabel.CENTER); - memoryThree.setHorizontalTextPosition(JLabel.CENTER); - memoryThree.setOpaque(true); - memoryThree.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_FILE_SIZE_SLIDE_LABEL_INT_LABEL_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_WIDTH, - LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_SLIDE_LABEL); - return memoryThree; - } - - /** - * memoryFLushOnDisk - * - * @return JLabel - */ - public JLabel memoryFLushOnDisk() { - JLabel memoryFLushOnDisk = - new JLabel("" + LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER + " ms", JLabel.CENTER); - memoryFLushOnDisk.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryFLushOnDisk.setForeground(Color.white); - memoryFLushOnDisk.setVerticalTextPosition(JLabel.CENTER); - memoryFLushOnDisk.setHorizontalTextPosition(JLabel.CENTER); - memoryFLushOnDisk.setOpaque(true); - memoryFLushOnDisk.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_FLUSH_ON_DISK_SLIDE_LABEL_INT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_WIDTH, - LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_SLIDE_LABEL); - return memoryFLushOnDisk; - } - - /** - * jPanelCenterSouthRightAddInMemory - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - */ - public void jPanelCenterSouthRightAddInMemory(JPanel jPanelCenterSouthRight) { - JLabel memoryLabel2 = new JLabel("In-memory buffer size:"); - memoryLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y + LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthRight.add(memoryLabel2); - // memoryTWO - JLabel memoryTWO = - new JLabel("" + LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER + " MB", JLabel.CENTER); - memoryTWO.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryTWO.setForeground(Color.white); - memoryTWO.setVerticalTextPosition(JLabel.CENTER); - memoryTWO.setHorizontalTextPosition(JLabel.CENTER); - memoryTWO.setOpaque(true); - memoryTWO.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_RIGHT_LABEL_INT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_WIDTH, - LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_SLIDE_LABEL); - jPanelCenterSouthRight.add(memoryTWO); - jProgressBarInMemory(jPanelCenterSouthRight, memoryTWO); - } - - /** - * jPanelCenterSouthRightAddMaxDuration - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - */ - public void jPanelCenterSouthRightAddMaxDuration(JPanel jPanelCenterSouthRight) { - JLabel durationLabel = new JLabel("Max duration:"); - durationLabel.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_LABEL, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthRight.add(durationLabel); - // durationTWO - JLabel durationTWO = new JLabel( - "00:00:" + LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MIN_DURATION_NUMBER + " h:m:s ", - JLabel.CENTER); - durationTWO.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - durationTWO.setForeground(Color.white); - durationTWO.setVerticalTextPosition(JLabel.CENTER); - durationTWO.setHorizontalTextPosition(JLabel.CENTER); - durationTWO.setOpaque(true); - durationTWO.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_LABEL_INIT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SHOW_NUMBER_INTI_WIDTH, - LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_SLIDE_LABEL); - jPanelCenterSouthRight.add(durationTWO); - jProgressBarDuration(jPanelCenterSouthRight, durationTWO); - } - - /** - * jProgressBarInMemory - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param memoryTWO memoryTWO - * @return JSlider - */ - public JSlider jProgressBarInMemory(JPanel jPanelCenterSouthRight, JLabel memoryTWO) { - JSlider slider = new JSlider(LayoutConstants.DEFAULT_NUMBER, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_IN_MEMORY_NUMBER); - slider.setValue(LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER); - slider.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_INTI_Y, - LayoutConstants.DEFAULT_NUMBER)); - slider.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_HIGHT); - jPanelCenterSouthRight.add(slider); - slider.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent changeEvent) { - memoryTWO.setText("" + slider.getValue() + " MB"); - memoryTWO.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryTWO.setForeground(Color.white); - memoryTWO.setVerticalTextPosition(JLabel.CENTER); - memoryTWO.setHorizontalTextPosition(JLabel.CENTER); - inMemoryValue = slider.getValue(); - } - }); - return slider; - } - - /** - * jProgressBarMaxFileSize - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param memoryThree memoryThree - * @param sliderMaxFileSize sliderMaxFileSize - * @return JSlider - */ - public JSlider jProgressBarMaxFileSize(JPanel jPanelCenterSouthRight, JLabel memoryThree, - JSlider sliderMaxFileSize) { - sliderMaxFileSize.setValue(LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER); - sliderMaxFileSize.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_INTI_Y, - LayoutConstants.DEFAULT_NUMBER)); - sliderMaxFileSize.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_FILE_SIZE_SLIDE_INT_LABEL_Y - + LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_AND_LABEL_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_HIGHT); - jPanelCenterSouthRight.add(sliderMaxFileSize); - sliderMaxFileSize.addChangeListener(new ChangeListener() { - /** - * stateChanged - * - * @param changeEvent changeEvent - */ - @Override - public void stateChanged(ChangeEvent changeEvent) { - memoryThree.setText("" + sliderMaxFileSize.getValue() + " MB"); - memoryThree.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryThree.setForeground(Color.white); - memoryThree.setVerticalTextPosition(JLabel.CENTER); - memoryThree.setHorizontalTextPosition(JLabel.CENTER); - maxFileSize = sliderMaxFileSize.getValue(); - } - }); - return sliderMaxFileSize; - } - - /** - * jProgressBarFLushOnDisk - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param memoryFLushOnDisk memoryFLushOnDisk - * @param sliderFLushOnDisk sliderFLushOnDisk - * @return JSlider - */ - public JSlider jProgressBarFLushOnDisk(JPanel jPanelCenterSouthRight, JLabel memoryFLushOnDisk, - JSlider sliderFLushOnDisk) { - sliderFLushOnDisk.setValue(LayoutConstants.SYSTEM_TUNNING_RECORD_SETTING_DEFAULT_NUMBER); - sliderFLushOnDisk.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_INTI_Y, - LayoutConstants.DEFAULT_NUMBER)); - sliderFLushOnDisk.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_FLUSH_ON_DISK_SLIDE_INT_Y - + LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_AND_LABEL_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_HIGHT); - jPanelCenterSouthRight.add(sliderFLushOnDisk); - sliderFLushOnDisk.addChangeListener(new ChangeListener() { - /** - * stateChanged - * - * @param changeEvent changeEvent - */ - @Override - public void stateChanged(ChangeEvent changeEvent) { - memoryFLushOnDisk.setText("" + sliderFLushOnDisk.getValue() + " ms"); - memoryFLushOnDisk - .setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - memoryFLushOnDisk.setForeground(Color.white); - memoryFLushOnDisk.setVerticalTextPosition(JLabel.CENTER); - memoryFLushOnDisk.setHorizontalTextPosition(JLabel.CENTER); - flushOnDisk = sliderFLushOnDisk.getValue(); - } - }); - return sliderFLushOnDisk; - } - - /** - * jProgressBarDuration - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param durationTWO durationTWO - * @return JSlider - */ - public JSlider jProgressBarDuration(JPanel jPanelCenterSouthRight, JLabel durationTWO) { - JSlider slider = new JSlider(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MIN_DURATION_NUMBER, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MAX_DURATION_NUMBER); - slider.setValue(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_MIN_DURATION_NUMBER); - slider.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_INTI_Y, - LayoutConstants.DEFAULT_NUMBER)); - slider.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_MAX_DURATION_LABEL - + LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_AND_LABEL_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_HIGHT); - jPanelCenterSouthRight.add(slider); - slider.addChangeListener(new ChangeListener() { - /** - * stateChanged - * - * @param changeEvent changeEvent - */ - @Override - public void stateChanged(ChangeEvent changeEvent) { - seconds = slider.getValue() % SystemTunningProbesCheckbox.TIME_CONVERSION_UNIT; - minutes = (slider.getValue() / SystemTunningProbesCheckbox.TIME_CONVERSION_UNIT) - % SystemTunningProbesCheckbox.TIME_CONVERSION_UNIT; - hours = slider.getValue() / (SystemTunningProbesCheckbox.TIME_CONVERSION_UNIT - * SystemTunningProbesCheckbox.TIME_CONVERSION_UNIT); - durationTWO.setText(" " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + String - .format(Locale.ENGLISH, "%02d", minutes) + ":" + String.format(Locale.ENGLISH, "%02d", seconds) - + " h:m:s "); - durationTWO.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT)); - durationTWO.setForeground(Color.white); - durationTWO.setVerticalTextPosition(JLabel.CENTER); - durationTWO.setHorizontalTextPosition(JLabel.CENTER); - maxDuration = slider.getValue(); - } - }); - return slider; - } - - /** - * traceCommand - * - * @param recordSettingLabel recordSettingLabel - * @param traceCommandLabel traceCommandLabel - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @param jPanelCenterSouthWest jPanelCenterSouthWest - */ - public void traceCommand(JLabel recordSettingLabel, JLabel traceCommandLabel, JPanel jPanelCenterSouthRight, - JPanel jPanelCenterSouthWest) { - traceCommandLabel.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - recordSettingLabel.setOpaque(false); - traceCommandLabel.setOpaque(true); - try { - traceCommandLabelRightShow(jPanelCenterSouthRight); - } catch (GrpcException ex) { - ex.printStackTrace(); - } - jPanelCenterSouthWest.updateUI(); - jPanelCenterSouthWest.repaint(); - } - }); - } - - /** - * traceCommandLabelRightShow - * - * @param jPanelCenterSouthRight jPanelCenterSouthRight - * @throws GrpcException GrpcException - */ - public void traceCommandLabelRightShow(JPanel jPanelCenterSouthRight) throws GrpcException { - jPanelCenterSouthRight.removeAll(); - String str = SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_NO_SELECT_HEAD; - // 获得用户选中的复选框 - getUserCheckBox(); - // 走perfetto from siwei - getUserCheckBoxForPerfetto(); - getStrResultForPerfetto(); - str = str.concat(new TraceManager() - .createSessionRequestPerfetto(deviceIPPortInfo, getUserCheckBoxForPerfettoStr, maxDuration, true)); - if (str == null) { - str = ""; - } - str = str.concat(SystemTunningProbesCheckbox.SYSTEM_TUNNING_PROBES_NO_SELECT_END); - JTextArea jta = new JTextArea(str); - jta.setLineWrap(true); // 设置文本域中的文本为自动换行 - jta.setForeground(Color.gray); // 设置组件的背景色 - jta.setEditable(false); - jta.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); // 设置按钮背景色 - JScrollPane jsp = new JScrollPane(jta); // 将文本域放入滚动窗口 - jsp.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_TEXT_AREA_INTT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_TEXT_AREA_INTT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_TEXTAREA_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_TEXTAREA_HEIGHT); - jPanelCenterSouthRight.add(jsp); - JButton jButtonSave = new JButton(new ImageIcon( - SystemTunningConfigEvent.class.getClassLoader().getResource("images/copy.png"))); - jButtonSave.setOpaque(true); - jButtonSave.setCursor(new Cursor(LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_CURSOR)); - jButtonSave.setBounds(LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_INIT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_TEXT_AREA_INTT_Y, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_INIT_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_COMMAND_COPY_FUNCTION_INIT_WIDTH); - jButtonSave.setBorderPainted(false); - jButtonSave.addActionListener(new ActionListener() { - /** - * actionPerformed - * - * @param actionEvent actionEvent - */ - @Override - public void actionPerformed(ActionEvent actionEvent) { - clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - StringSelection contents = new StringSelection(jta.getText()); - clipboard.setContents(contents, SystemTunningConfigEvent.this); - } - }); - jPanelCenterSouthRight.add(jButtonSave); - jPanelCenterSouthRight.repaint(); - } - - /** - * getParamListFromString - * - * @param param param - * @param str str - */ - public void getParamListFromString(HashMap> param, String str) { - if (str != null && !str.isEmpty()) { - String[] oneCheckBoxArray = str.split("\n"); - for (int i = 0; i < oneCheckBoxArray.length; i++) { - if (oneCheckBoxArray[i] != null && !oneCheckBoxArray[i].isEmpty()) { - String[] everyLine = oneCheckBoxArray[i].split(":"); - if (oneCheckBoxArray[i].contains(everyLine[0].trim())) { - if (param.get(everyLine[0].trim()) != null) { - param.get(everyLine[0].trim()).add(oneCheckBoxArray[i]); - } else { - ArrayList everyList = new ArrayList<>(); - everyList.add(oneCheckBoxArray[i]); - param.put(everyLine[0].trim(), everyList); - } - } - } - } - } - } - - /** - * devicesInfoJComboBoxUpdate - * - * @param taskSystemTunningPanel taskSystemTunningPanel - */ - public void devicesInfoJComboBoxUpdate(SystemTunningConfigPanel taskSystemTunningPanel) { - QuartzManager.getInstance().addExecutor(DEVICEREFRESH, new Runnable() { - /** - * run - */ - @Override - public void run() { - List deviceInfos = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - taskSystemTunningPanel.setDeviceInfos(deviceInfos); - Vector items = new Vector<>(); - deviceInfos.forEach(deviceInfo -> { - items.add(deviceInfo.getDeviceName()); - }); - if (!oldDevice.equals(items)) { - oldDevice = items; - taskSystemTunningPanel.getJComboBoxPhone().setModel(new DefaultComboBoxModel(items)); - } - } - }); - QuartzManager.getInstance() - .startExecutor(DEVICEREFRESH, LayoutConstants.DEFAULT_NUMBER, LayoutConstants.NUMBER_THREAD); - } - - /** - * itemStateChanged - * - * @param taskSystemTunningPanel taskSystemTunningPanel - */ - public void itemStateChanged(SystemTunningConfigPanel taskSystemTunningPanel) { - taskSystemTunningPanel.getJComboBoxPhone().addItemListener(new ItemListener() { - /** - * itemStateChanged - * - * @param itemEvent itemEvent - */ - @Override - public void itemStateChanged(ItemEvent itemEvent) { - // 获取选中项,设置对象信息用于查询对应的进程信息 - for (DeviceIPPortInfo deviceInfo : taskSystemTunningPanel.getDeviceInfos()) { - if (deviceInfo.getDeviceName() - .equals(taskSystemTunningPanel.getJComboBoxPhone().getSelectedItem())) { - deviceIPPortInfo = deviceInfo; - } - } - } - }); - if (taskSystemTunningPanel.getDeviceInfos() != null && taskSystemTunningPanel.getDeviceInfos().size() > 0 - && deviceIPPortInfo == null) { - deviceIPPortInfo = taskSystemTunningPanel.getDeviceInfos().get(0); - } - } - - /** - * lostOwnership - * - * @param clipboard clipboard - * @param contents contents - */ - @Override - public void lostOwnership(Clipboard clipboard, Transferable contents) { - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelEvent.java deleted file mode 100644 index 4841e63ef..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelEvent.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Common; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.swing.SystemTunningConfigPanel; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskPanelWelcome; -import ohos.devtools.views.layout.swing.TaskScenePanel; - -/** - * 设备进程容器 - * - * @version 1.0 - * @date 2021/03/02 - **/ -public class TaskPanelEvent { - private static final Logger LOGGER = LogManager.getLogger(TaskPanelEvent.class); - - private Common common = new Common(); - - /** - * AddClick - * - * @param jTaskPanel jTaskPanel - * @param taskPanel taskPanel - * @param taskPanelWelcome taskPanelWelcome - */ - public void jButtonAddClick(TaskPanel jTaskPanel, JPanel taskPanel, TaskPanelWelcome taskPanelWelcome) { - jTaskPanel.getJButtonAdd().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - taskPanel.removeAll(); - if (Constant.jtasksTab == null || (Constant.jtasksTab != null - && Constant.jtasksTab.getTabCount() == 0)) { - Constant.jtasksTab = new JTabbedPane(); - } - new TaskPanel(taskPanel, taskPanelWelcome); - // 更新所有的run -- of -- - common.updateNum(Constant.jtasksTab); - taskPanel.getParent().getParent().getParent().getParent().setVisible(true); - } - }); - } - - /** - * When the total length of the tab label is too long, the size of each label is automatically - * changed so that all the labels are in one line - * - * @param jButton jButton - * @param taskPanel taskPanel - */ - private void tabAdaptive(JButton jButton, JPanel taskPanel) { - int countX = Constant.jtasksTab.getTabCount() * LayoutConstants.NUMBER_X; - if (countX > taskPanel.getWidth()) { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Constant.jtasksTab.getTabComponentAt(index).setPreferredSize(new Dimension( - ((taskPanel.getWidth() - LayoutConstants.APP_BUT_X) / Constant.jtasksTab.getTabCount()) - - LayoutConstants.TASK_DEC_NUM, LayoutConstants.JAVA_HEIGHT)); - jButton.setBounds(taskPanel.getWidth() - LayoutConstants.TASK_LABEL_X, LayoutConstants.NUMBER_Y, - LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } else { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Component taskTable = Constant.jtasksTab.getTabComponentAt(index); - if (taskTable instanceof JPanel) { - JPanel taskTablePanel = (JPanel) taskTable; - taskTablePanel.getComponents()[0] - .setPreferredSize(new Dimension(LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.JAVA_HEIGHT)); - } - Constant.jtasksTab.getTabComponentAt(index) - .setPreferredSize(new Dimension(LayoutConstants.JPA_LABEL_WIDTH, LayoutConstants.JAVA_HEIGHT)); - jButton.setBounds(LayoutConstants.NUMBER_X_ADD * Constant.jtasksTab.getTabCount(), - LayoutConstants.NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } - } - - /** - * XButton to add close tab function - * - * @param jTaskPanel jTaskPanel - * @param taskPanel taskPanel - * @param taskPanelWelcome taskPanelWelcome - */ - public void clickClose(TaskPanel jTaskPanel, JPanel taskPanel, TaskPanelWelcome taskPanelWelcome) { - jTaskPanel.getJLabelClose().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - // 清除Constant.tracePath - Constant.tracePath = ""; - jTaskPanel.removeAll(); - taskPanel.removeAll(); - Constant.jtasksTab.remove(Constant.jtasksTab.indexOfTabComponent(jTaskPanel.getJPanelTabLabel())); - // 移除现有组件重新添加,解决+号位置问题 - JButton jButton = jTaskPanel.getJButtonAdd(); - // 当选项卡标签总长度过长时自动改变每个标签的大小使所有的标签在一行 - tabAdaptive(jButton, taskPanel); - jTaskPanel.setjButtonAdd(jButton); - jTaskPanel.add(jButton); - jTaskPanel.add(Constant.jtasksTab); - taskPanel.add(jTaskPanel); - taskPanel.repaint(); - // 更新所有的run -- of -- - common.updateNum(Constant.jtasksTab); - // 移除页面更新信息 - if (Constant.jtasksTab.getTabCount() == 0) { - Long localSessionId = jTaskPanel.getLocalSessionId(); - if (localSessionId != null && localSessionId != 0L) { - SessionManager sessionManager = SessionManager.getInstance(); - sessionManager.deleteSession(localSessionId); - } - taskPanel.removeAll(); - Constant.jtasksTab = null; - // 添加首页 - taskPanel.add(taskPanelWelcome); - taskPanel.updateUI(); - taskPanel.repaint(); - } - } - }); - } - - /** - * XAdd the button to move the mouse into the display close button - * - * @param jTaskPanel jTaskPanel - */ - public void mouseEntered(TaskPanel jTaskPanel) { - jTaskPanel.getJLabelClose().addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - jTaskPanel.getJLabelClose().setText("X"); - } - }); - } - - /** - * X button is added when the mouse moves out without showing the close button - * - * @param jTaskPanel jTaskPanel - */ - public void mouseExited(TaskPanel jTaskPanel) { - jTaskPanel.getJLabelClose().addMouseListener(new MouseAdapter() { - @Override - public void mouseExited(MouseEvent mouseEvent) { - jTaskPanel.getJLabelClose().setText(""); - } - }); - } - - /** - * Add a click event to the figure JButtonApplyTun - * - * @param taskPanel taskPanel - * @param jTaskPanel jTaskPanel - */ - public void pplyTunMouseListener(JPanel taskPanel, TaskPanel jTaskPanel) { - jTaskPanel.getJButtonApplyTun().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - jTaskPanel.getJLabelTaskTun().setText( - "Application tuning

Tune application Launch performance with " - + "a 5 second time profile and a thread state trace."); - jTaskPanel.getjLabelIcon().setIcon(new ImageIcon( - TaskPanelEvent.class.getClassLoader().getResource("images/application_tuning.png"))); - taskPanel.repaint(); - } - }); - } - - /** - * Add a click event to the figure JButtonSystemTun - * - * @param taskPanel taskPanel - * @param jTaskPanel jTaskPanel - */ - public void addSystemMouseListener(JPanel taskPanel, TaskPanel jTaskPanel) { - jTaskPanel.getJButtonSystemTun().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - jTaskPanel.getJLabelTaskTun().setText( - "System tuning

A comprehensive view of what’s happing in the " - + "operating system. See how threads are being scheduled across CPUs."); - jTaskPanel.getjLabelIcon().setIcon(new ImageIcon( - TaskPanelEvent.class.getClassLoader().getResource("images/system_tuning.png"))); - taskPanel.repaint(); - } - }); - } - - /** - * Add a click event to the Choose button - * - * @param jTaskPanel jTaskPanel - */ - public void applicationTuningClickListener(TaskPanel jTaskPanel) { - jTaskPanel.getChooseButton().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - // 选项卡页面移除场景选择并添加三级页面 - jTaskPanel.getOptionJPanelContent().setVisible(false); - if (jTaskPanel.getJLabelTaskTun().getText().contains("System tuning")) { - SystemTunningConfigPanel taskSystemTuningPanel = new SystemTunningConfigPanel(jTaskPanel); - // 将三级界面添加进二级界面容器 - jTaskPanel.getOptionJPanel().setLayout(new BorderLayout()); - jTaskPanel.getOptionJPanel().add(taskSystemTuningPanel); - } else { - TaskScenePanel taskScenePanel = new TaskScenePanel(jTaskPanel); - // 将三级界面添加进二级界面容器 - jTaskPanel.getOptionJPanel().setLayout(new BorderLayout()); - jTaskPanel.getOptionJPanel().add(taskScenePanel); - } - // 刷新页面 - jTaskPanel.getOptionJPanel().repaint(); - } - }); - } - - /** - * Monitor window size changes to make graphicsJpanel size adaptive - * - * @param taskPanel taskPanel - * @param graphicsJpanel graphicsJpanel - */ - public void listenerGraphicsJpanel(JPanel graphicsJpanel, TaskPanel taskPanel) { - taskPanel.getOptionJPanelContent().addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param exception exception - */ - public void componentResized(ComponentEvent exception) { - graphicsJpanel.setBounds(0, LayoutConstants.WIDTHSUPEN, taskPanel.getOptionJPanelContent().getWidth(), - LayoutConstants.JAVA_WIDTH); - } - }); - } - - /** - * Monitor the size of taskPanel, and link the size of jTabbedPane to it - * - * @param taskPanel taskPanel - * @param jButtonAdd jButtonAdd - */ - public void listenerTaskPanel(JPanel taskPanel, JButton jButtonAdd) { - taskPanel.addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param exception exception - */ - public void componentResized(ComponentEvent exception) { - int width = taskPanel.getWidth(); - int height = taskPanel.getHeight(); - Constant.jtasksTab.setBounds(LayoutConstants.DEVICE_PRO_Y, LayoutConstants.DEVICE_PRO_Y, - LayoutConstants.WINDOW_WIDTH + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.WINDOW_HEIGHT + (height - LayoutConstants.WINDOW_HEIGHT)); - double result = Constant.jtasksTab.getTabCount() * LayoutConstants.NUMBER_X; - if (result > taskPanel.getWidth()) { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Component taskTable = Constant.jtasksTab.getTabComponentAt(index); - if (taskTable instanceof JPanel) { - JPanel taskTablePanel = (JPanel) taskTable; - taskTablePanel.getComponents()[0].setPreferredSize(new Dimension( - (((taskPanel.getWidth() - LayoutConstants.APP_BUT_X) - / Constant.jtasksTab.getTabCount()) - LayoutConstants.TASK_DEC_NUM) - - LayoutConstants.JAVA_HEIGHT, LayoutConstants.JAVA_HEIGHT)); - } - Constant.jtasksTab.getTabComponentAt(index).setPreferredSize(new Dimension( - ((taskPanel.getWidth() - LayoutConstants.APP_BUT_X) / Constant.jtasksTab.getTabCount()) - - LayoutConstants.TASK_DEC_NUM, LayoutConstants.JAVA_HEIGHT)); - jButtonAdd - .setBounds(taskPanel.getWidth() - LayoutConstants.TASK_LABEL_X, LayoutConstants.NUMBER_Y, - LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } else { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Object tabObj = Constant.jtasksTab.getTabComponentAt(index); - if (tabObj instanceof JPanel) { - ((JPanel) tabObj).getComponents()[0].setPreferredSize( - new Dimension(LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.JAVA_HEIGHT)); - } - Constant.jtasksTab.getTabComponentAt(index).setPreferredSize( - new Dimension(LayoutConstants.JPA_LABEL_WIDTH, LayoutConstants.JAVA_HEIGHT)); - jButtonAdd.setBounds(LayoutConstants.NUMBER_X_ADD * Constant.jtasksTab.getTabCount(), - LayoutConstants.NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } - } - }); - listenerTabPanel(taskPanel, jButtonAdd); - } - - /** - * Tab listening event - * - * @param taskPanel taskPanel - * @param jButtonAdd jButtonAdd - */ - private void listenerTabPanel(JPanel taskPanel, JButton jButtonAdd) { - Constant.jtasksTab.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent exception) { - double result = Constant.jtasksTab.getTabCount() * LayoutConstants.NUMBER_X; - if (result > taskPanel.getWidth()) { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Object tabObj = Constant.jtasksTab.getTabComponentAt(index); - if (tabObj instanceof JPanel) { - ((JPanel) tabObj).getComponents()[0].setPreferredSize(new Dimension( - (((taskPanel.getWidth() - LayoutConstants.APP_BUT_X) - / Constant.jtasksTab.getTabCount()) - LayoutConstants.TASK_DEC_NUM) - - LayoutConstants.JAVA_HEIGHT, LayoutConstants.JAVA_HEIGHT)); - } - Constant.jtasksTab.getTabComponentAt(index).setPreferredSize(new Dimension( - ((taskPanel.getWidth() - LayoutConstants.APP_BUT_X) / Constant.jtasksTab.getTabCount()) - - LayoutConstants.TASK_DEC_NUM, LayoutConstants.JAVA_HEIGHT)); - jButtonAdd - .setBounds(taskPanel.getWidth() - LayoutConstants.TASK_LABEL_X, - LayoutConstants.NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } else { - jButtonAdd.setBounds(LayoutConstants.NUMBER_X_ADD * Constant.jtasksTab.getTabCount(), - LayoutConstants.NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } - }); - } - - /** - * 场景选择,添加选择样式。 - * - * @param taskPanel 二级界面 - */ - public void sigleClick(TaskPanel taskPanel) { - taskPanel.getJButtonApplyTun().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - taskPanel.getJButtonApplyTun().setBackground(ColorConstants.APPLYTUN_COLOR); - taskPanel.getJButtonSystemTun().setBackground(ColorConstants.SYSTEM_COLOR); - taskPanel.getJButtonHadoop().setBackground(ColorConstants.SYSTEM_COLOR); - } - }); - taskPanel.getJButtonSystemTun().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - taskPanel.getJButtonApplyTun().setBackground(ColorConstants.SYSTEM_COLOR); - taskPanel.getJButtonSystemTun().setBackground(ColorConstants.APPLYTUN_COLOR); - taskPanel.getJButtonHadoop().setBackground(ColorConstants.SYSTEM_COLOR); - } - }); - taskPanel.getJButtonHadoop().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - taskPanel.getJButtonApplyTun().setBackground(ColorConstants.SYSTEM_COLOR); - taskPanel.getJButtonSystemTun().setBackground(ColorConstants.SYSTEM_COLOR); - taskPanel.getJButtonHadoop().setBackground(ColorConstants.APPLYTUN_COLOR); - } - }); - } - - /** - * 监听窗体大小改变组件位置 - * - * @param taskPanel taskPanel - * @param jTaskPanel jTaskPanel - */ - public void listenerWindow(JPanel taskPanel, TaskPanel jTaskPanel) { - taskPanel.addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param exception exception - */ - public void componentResized(ComponentEvent exception) { - int width = taskPanel.getWidth(); - int height = taskPanel.getHeight(); - jTaskPanel.getChooseButton() - .setBounds(LayoutConstants.CHOSSE_X + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.CHOOSE_Y + (height - LayoutConstants.WINDOW_HEIGHT), - LayoutConstants.DEVICES_WIDTH, LayoutConstants.CHOOSE_HEIGHT); - jTaskPanel.getTraceButton().setBounds(LayoutConstants.TASK_SCENE_X, - LayoutConstants.CHOOSE_Y + (height - LayoutConstants.WINDOW_HEIGHT), LayoutConstants.CHOOSE_WIDTH, - LayoutConstants.CHOOSE_HEIGHT); - } - }); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelWelcomeEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelWelcomeEvent.java deleted file mode 100644 index a4a9239ed..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskPanelWelcomeEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.views.common.Common; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskPanelWelcome; - -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * 二级欢迎界面事件处理对象 - * - * @version 1.0 - * @date 2021/03/01 15:20 - **/ -public class TaskPanelWelcomeEvent { - // 初始化公共方法类 - private Common common = new Common(); - - /** - * 给新增实时任务按钮添加事件 - * - * @param taskPanelWelcome taskPanelWelcome - * @date 2021/03/01 15:20 - */ - public void clickAddTask(TaskPanelWelcome taskPanelWelcome) { - taskPanelWelcome.getJNewButton().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - // 获取Jframe和taskPanel二级界面容器 - JPanel taskPanel = null; - Object obj = taskPanelWelcome.getParent(); - if (obj instanceof JPanel) { - taskPanel = (JPanel) obj; - taskPanel.remove(taskPanelWelcome); - if (Constant.jtasksTab == null || (Constant.jtasksTab != null - && Constant.jtasksTab.getTabCount() == 0)) { - Constant.jtasksTab = new JTabbedPane(); - } - new TaskPanel(taskPanel, taskPanelWelcome); - // 更新所有的run -- of -- - common.updateNum(Constant.jtasksTab); - taskPanel.updateUI(); - taskPanel.repaint(); - } - } - - }); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelChartEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelChartEvent.java index d3cef41c2..04448f510 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelChartEvent.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelChartEvent.java @@ -1,677 +1,801 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.services.memory.ChartDataCache; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.charts.utils.ChartUtils; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosDialog; -import ohos.devtools.views.common.hoscomp.HosJButton; -import ohos.devtools.views.common.hoscomp.HosJComboBox; -import ohos.devtools.views.common.hoscomp.HosJLabel; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.CountingThread; -import ohos.devtools.views.layout.swing.SampleDialogWrapper; -import ohos.devtools.views.layout.swing.SaveTraceDialog; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.UIManager; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import static ohos.devtools.views.common.ViewConstants.NUM_10; -import static ohos.devtools.views.common.ViewConstants.NUM_2; - -/** - * 任务场景面板图事件类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class TaskScenePanelChartEvent { - private boolean flagLeft = false; - private boolean flag = false; - private Container obj = null; - private boolean buttonAvailable = true; - private boolean resultDelete = false; - - /** - * 点击删除 - * - * @param taskScenePanelChart taskScenePanelChart - */ - public void clickDelete(TaskScenePanelChart taskScenePanelChart) { - taskScenePanelChart.getJButtonDelete().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - long localSessionId = taskScenePanelChart.getJButtonDelete().getSessionId(); - Font font = new Font("", 0, LayoutConstants.SIXTEEN); - UIManager.put("OptionPane.messageFont", font); - if (localSessionId < 0) { - new SampleDialogWrapper("prompt", "Please select the task to delete first !").show(); - return; - } - SampleDialogWrapper sampleDialogWrapper = - new SampleDialogWrapper("prompt", "Are you sure you want to delete this task ?"); - boolean flags = sampleDialogWrapper.showAndGet(); - if (flags) { - // 调用SessionManager的删除sessionId - if (!SessionManager.getInstance().deleteSession(localSessionId)) { - return; - } - CountingThread countingThread = taskScenePanelChart.getCounting(); - countingThread.setStopFlag(true); - // 容器中销毁char和Session的panel - // 删除界面cards的Session - deleteSession(localSessionId, taskScenePanelChart); - // 删除界面char - deleteChart(localSessionId, taskScenePanelChart); - taskScenePanelChart.getJButtonDelete().setSessionId(Constant.ABNORMAL); - taskScenePanelChart.repaint(); - // 清除sessionid,保存trace文件时根据这个判断是否可以保存 - taskScenePanelChart.getjButtonSave().setSessionId(0); - - taskScenePanelChart.getjButtonRun().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/over.png"))); - taskScenePanelChart.getjButtonStop().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/suspended.png"))); - resultDelete = true; - } - } - }); - } - - /** - * Delete interface chart - * - * @param localSessionId localSessionId - * @param taskScenePanelChart taskScenePanelChart - */ - private void deleteChart(long localSessionId, TaskScenePanelChart taskScenePanelChart) { - Component[] carts = taskScenePanelChart.getCards().getComponents(); - for (Component cart : carts) { - if (cart instanceof JPanel) { - Component[] jcardsPanels = ((JPanel) cart).getComponents(); - for (Component item : jcardsPanels) { - ProfilerChartsView profilerView = null; - if (item instanceof ProfilerChartsView) { - profilerView = (ProfilerChartsView) item; - if (profilerView.getSessionId() == localSessionId) { - ((JPanel) cart).remove(profilerView); - } - } - } - } - } - } - - /** - * Delete Session - * - * @param localSessionId localSessionId - * @param taskScenePanelChart taskScenePanelChart - */ - private void deleteSession(long localSessionId, TaskScenePanelChart taskScenePanelChart) { - JPanel jScrollCardsPanelInner = taskScenePanelChart.getJScrollCardsPanelInner(); - Component[] innerJpanel = jScrollCardsPanelInner.getComponents(); - for (Component inner : innerJpanel) { - Component[] innerLable = null; - if (inner instanceof JPanel) { - innerLable = ((JPanel) inner).getComponents(); - for (Component item : innerLable) { - if (item instanceof HosJLabel && localSessionId == ((HosJLabel) item).getSessionId()) { - jScrollCardsPanelInner.remove(inner); - } - } - } - } - } - - /** - * clickUpAndNext - * - * @param taskScenePanelChart taskScenePanelChart - */ - public void clickUpAndNext(TaskScenePanelChart taskScenePanelChart) { - // 给上一个页面按钮添加点击事件 - taskScenePanelChart.getjButtonUp().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (Constant.jtasksTab.getSelectedIndex() > 0) { - Constant.jtasksTab.setSelectedIndex(Constant.jtasksTab.getSelectedIndex() - 1); - } - } - }); - // 给下一个页面按钮添加点击事件 - taskScenePanelChart.getjButtonNext().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (Constant.jtasksTab.getSelectedIndex() != Constant.jtasksTab.getTabCount() - 1) { - Constant.jtasksTab.setSelectedIndex(Constant.jtasksTab.getSelectedIndex() + 1); - } - } - }); - } - - private void stopTask(ProfilerChartsView profilerView, HosJButton stopButton, - TaskScenePanelChart taskScenePanelChart) { - profilerView.getObserver().stopRefresh(false); - stopButton.setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/over.png"))); - taskScenePanelChart.getjButtonStop().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/suspended.png"))); - buttonAvailable = false; - CountingThread countingThread = taskScenePanelChart.getCounting(); - countingThread.setStopFlag(true); - stopButton.setToolTipText("启动"); - SessionManager.getInstance().endSession(stopButton.getSessionId()); - ChartDataCache.getInstance().clearDataCache(String.valueOf(stopButton.getSessionId())); - profilerView.setStopFlag(true); - profilerView.setFlagEnd(true); - } - - private void startTask(ProfilerChartsView profilerView, HosJButton stopButton, - TaskScenePanelChart taskScenePanelChart) { - stopButton.setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/button_record.png"))); - taskScenePanelChart.getjButtonStop().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/button_stop.png"))); - buttonAvailable = true; - stopButton.setToolTipText("停止"); - // Set the icon change after the pause button is clicked Open the session to get data - long sessionId = stopButton.getSessionId(); - SessionManager sessionManager = SessionManager.getInstance(); - sessionManager.startSession(sessionId, true); - sessionManager.fetchData(sessionId); - if (profilerView.getObserver().isScrollbarShow()) { - profilerView.removeScrollbar(); - } - JLabel jTextArea = taskScenePanelChart.getjTextArea(); - CountingThread counting = new CountingThread(jTextArea); - taskScenePanelChart.setCounting(counting); - counting.start(); - // The "Pause/Resume" button will change accordingly - profilerView.getTimeline().removeTablePanel(); - profilerView.setFlagDown(false); - // Clear the selected time after restarting - profilerView.getObserver().getStandard().clearSelectedRange(); - profilerView.showLoading(); - profilerView.setStopFlag(false); - profilerView.setFlagEnd(false); - } - - /** - * clickRunAndStop - * - * @param taskScenePanelChart taskScenePanelChart - * @param profilerView profilerView - */ - public void clickRunAndStop(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { - HosJButton stopButton = taskScenePanelChart.getjButtonRun(); - stopButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (resultDelete) { - return; - } - if (profilerView.isLoading()) { - return; - } - if (!profilerView.isStopFlag()) { - stopTask(profilerView, stopButton, taskScenePanelChart); - } else { - startTask(profilerView, stopButton, taskScenePanelChart); - } - } - }); - pauseButtonEvent(taskScenePanelChart, profilerView); - } - - /** - * Pause button event - * - * @param taskScenePanelChart taskScenePanelChart - * @param profilerView profilerView - */ - private void pauseButtonEvent(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { - taskScenePanelChart.getjButtonStop().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (resultDelete) { - return; - } - if (profilerView.isLoading()) { - return; - } - if (buttonAvailable) { - if (!profilerView.isFlagEnd()) { - taskScenePanelChart.getjButtonStop().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/suspended.png"))); - taskScenePanelChart.getjButtonStop().setToolTipText("开始"); - profilerView.getObserver().pauseRefresh(); - profilerView.setFlagEnd(true); - } else { - taskScenePanelChart.getjButtonStop().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader().getResource("images/button_stop.png"))); - taskScenePanelChart.getjButtonBottom().setIcon(new ImageIcon( - TaskScenePanelChartEvent.class.getClassLoader() - .getResource("images/button_bottom_bar_grey.png"))); - taskScenePanelChart.getjButtonStop().setToolTipText("暂停"); - profilerView.getObserver().restartRefresh(); - profilerView.getTimeline().removeTablePanel(); - profilerView.setFlagDown(false); - profilerView.setFlagEnd(false); - } - } - } - }); - } - - /** - * clickBottom - * - * @param taskScenePanelChart taskScenePanelChart - * @param profilerView profilerView - */ - public void clickBottom(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { - taskScenePanelChart.getjButtonBottom().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (!profilerView.isAbleUnfoldTable()) { - return; - } - if (!profilerView.isFlagDown()) { - if (profilerView.isFlagEnd() && profilerView.isChartLevel()) { - profilerView.getTimeline().removeTablePanel(); - } - } else { - if (profilerView.isFlagEnd() && profilerView.isChartLevel()) { - profilerView.getTimeline().addTablePanel(); - } - } - } - }); - } - - /** - * splitPaneChange - * - * @param taskScenePanelChart taskScenePanelChart - * @param numberSum numberSum - */ - public void splitPaneChange(TaskScenePanelChart taskScenePanelChart, int numberSum) { - taskScenePanelChart.getSplitPane().addPropertyChangeListener(new java.beans.PropertyChangeListener() { - /** - * propertyChange - * - * @param evt evt - */ - public void propertyChange(java.beans.PropertyChangeEvent evt) { - if (evt.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { - int numEvt = 0; - for (int index = 0; index < numberSum; index++) { - JPanel jPanel = null; - Object objNew = taskScenePanelChart.getJScrollCardsPanelInner().getComponentAt(0, numEvt); - if (objNew instanceof JPanel) { - jPanel = (JPanel) objNew; - jPanel.setBounds(0, numEvt, - LayoutConstants.RIGHT_BUN_WIDTH + Integer.parseInt(evt.getNewValue().toString()) - - LayoutConstants.RIGHT_BUN_WIDTH, LayoutConstants.HEIGHT); - numEvt += LayoutConstants.HEIGHT; - jPanel.updateUI(); - jPanel.repaint(); - } - } - } - } - }); - } - - /** - * clickLeft - * - * @param taskScenePanelChart taskScenePanelChart - */ - public void clickLeft(TaskScenePanelChart taskScenePanelChart) { - taskScenePanelChart.getjButtonLeft().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent exception) { - if (!flagLeft) { - taskScenePanelChart.getSplitPane().setDividerLocation(1); - taskScenePanelChart.getSplitPane().updateUI(); - taskScenePanelChart.getSplitPane().repaint(); - flagLeft = true; - } else { - taskScenePanelChart.getSplitPane().setDividerLocation(LayoutConstants.CHOOSE_WIDTH); - flagLeft = false; - taskScenePanelChart.getSplitPane().updateUI(); - taskScenePanelChart.getSplitPane().repaint(); - } - } - }); - taskScenePanelChart.addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param exception exception - */ - public void componentResized(ComponentEvent exception) { - if (flagLeft) { - taskScenePanelChart.getSplitPane().setDividerLocation(1); - taskScenePanelChart.getSplitPane().updateUI(); - taskScenePanelChart.getSplitPane().repaint(); - flagLeft = true; - } else { - taskScenePanelChart.getSplitPane() - .setDividerLocation(taskScenePanelChart.getSplitPane().getDividerLocation()); - taskScenePanelChart.getSplitPane().updateUI(); - taskScenePanelChart.getSplitPane().repaint(); - } - } - }); - } - - /** - * bindSessionId - * - * @param taskScenePanelChart taskScenePanelChart - * @param jLabelRight jLabelRight - * @param jMultiplePanel jMultiplePanel - */ - private void bindSessionId(TaskScenePanelChart taskScenePanelChart, HosJLabel jLabelRight, JPanel jMultiplePanel) { - taskScenePanelChart.getjButtonRun().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjButtonStop().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjButtonSave().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjButtonSave().setDeviceName(jLabelRight.getDeviceName()); - taskScenePanelChart.getjButtonSave().setProcessName(jLabelRight.getProcessName()); - taskScenePanelChart.getJButtonDelete().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getJButtonDelete().setDeviceName(jLabelRight.getDeviceName()); - taskScenePanelChart.getJButtonDelete().setProcessName(jLabelRight.getProcessName()); - taskScenePanelChart.getjButtonInsert().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjButtonBottom().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjButtonLeft().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getjComboBox().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getTimeJComboBox().setSessionId(jLabelRight.getSessionId()); - taskScenePanelChart.getJScrollCardsPanelInner().remove(jMultiplePanel); - taskScenePanelChart.getJScrollCardsPanelInner().repaint(); - } - - /** - * clickEvery - * - * @param taskScenePanelChart taskScenePanelChart - * @param jLabelRight jLabelRight - * @param numberSum numberSum - * @param jLabelSelect jLabelSelect - * @param jMultiplePanel jMultiplePanel - */ - public void clickEvery(TaskScenePanelChart taskScenePanelChart, HosJLabel jLabelRight, int numberSum, - String jLabelSelect, JPanel jMultiplePanel) { - jLabelRight.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - // 绑定sessionId - bindSessionId(taskScenePanelChart, jLabelRight, jMultiplePanel); - // 获取其他jlabel设置背景色 - Component[] component = taskScenePanelChart.getJScrollCardsPanelInner().getComponents(); - for (Component componentEvery : component) { - JPanel jPanelEvery = null; - if (componentEvery instanceof JPanel) { - jPanelEvery = (JPanel) componentEvery; - Component[] componentjPanelEvery = jPanelEvery.getComponents(); - for (Component componentjPanelEverySet : componentjPanelEvery) { - JLabel jLabelEvery = null; - if (componentjPanelEverySet instanceof JLabel) { - jLabelEvery = (JLabel) componentjPanelEverySet; - jLabelEvery.setBackground(ColorConstants.BLACK_COLOR); - jLabelEvery.setForeground(Color.gray); - } - } - } - } - taskScenePanelChart.getJScrollCardsPanelInner().add(jMultiplePanel); - taskScenePanelChart.getJScrollCardsPanelInner().repaint(); - jLabelRight.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jLabelRight.setForeground(Color.white); - taskScenePanelChart.getjLabelLeft().setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - int numy = 0; - // 循环确定擦片布局显示哪个页面 - for (int index = 0; index < numberSum; index++) { - JPanel jPanel = null; - Object innerObj = taskScenePanelChart.getJScrollCardsPanelInner().getComponentAt(0, numy); - if (innerObj instanceof JPanel) { - jPanel = (JPanel) innerObj; - numy += LayoutConstants.HEIGHT; - Color colorBack = jPanel.getComponent(0).getBackground(); - if (colorBack == Color.black) { - taskScenePanelChart.getCardLayout().show(taskScenePanelChart.getCards(), "card" + index); - } - } - } - // Replace the content of the tab with the content of the clicked device information - replaceDevicesInfo(jLabelSelect); - } - }); - } - - /** - * Replace device information - * - * @param jLabelSelect Selected jLabel - */ - private void replaceDevicesInfo(String jLabelSelect) { - JPanel jCompent = null; - Object tabComObj = Constant.jtasksTab.getTabComponentAt(Constant.jtasksTab.getSelectedIndex()); - if (tabComObj instanceof JPanel) { - jCompent = (JPanel) tabComObj; - JPanel jCompentLeft = null; - Object componentObj = jCompent.getComponent(0); - if (componentObj instanceof JPanel) { - jCompentLeft = (JPanel) componentObj; - Object leftObj = jCompentLeft.getComponent(0); - if (leftObj instanceof JLabel) { - ((JLabel) leftObj).setText(jLabelSelect); - } - } - } - } - - /** - * 按钮增加点击时间触发时间刻度的选择 - * - * @param jComboBox jComboBox - * @param profilerView profilerView - */ - public void clickZoomEvery(HosJComboBox jComboBox, ProfilerChartsView profilerView) { - jComboBox.addItemListener(event -> { - long sessionId = jComboBox.getSessionId(); - int newSizeTime = 0; - if (event.getStateChange() == 1) { - // 获取点击时间选择的时间刻度间隔 - String[] msTime = jComboBox.getSelectedItem().toString().split("m"); - newSizeTime = Integer.parseInt(msTime[0]); - } - ChartStandard standard = profilerView.getObserver().getStandard(); - if (standard != null) { - checkNewTime(standard, newSizeTime, profilerView); - } - }); - } - - /** - * 检查频率切换后的时间是否需要修正 - * - * @param standard ChartStandard - * @param newSizeTime 新的时间大小 - * @param view ProfilerChartsView - */ - private void checkNewTime(ChartStandard standard, int newSizeTime, ProfilerChartsView view) { - int oldStart = standard.getDisplayRange().getStartTime(); - // 获取刻度间隔对应的最小时间单位值 - int minSize = ChartUtils.divideInt(newSizeTime, NUM_10) * NUM_2; - // 刷新绘图标准的最大展示时间和最小时间单位 - int newMaxDisplay = newSizeTime * NUM_10; - int lastTime = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - - int newStart; - int newEnd; - // 场景1:频率切换后oldStart + newDisplay超过了lastTime,这时要修正start - if (oldStart + newMaxDisplay > lastTime) { - // 场景1.1:切换后newDisplay > lastTime,这时就变成任务刚启动时,Chart没有铺满的场景,start为0,end为lastTime - // 场景1.2:切换后newDisplay < lastTime,修正start为lastTime - display - newStart = Math.max(lastTime - newMaxDisplay, 0); - newEnd = lastTime; - } else { - // 场景2:切换后oldStart + newDisplay未超过lastTime,说明可以正常显示,无需修正start - newStart = oldStart; - newEnd = oldStart + newMaxDisplay; - } - - standard.updateSizeTime(newSizeTime); - view.getObserver().msTimeZoom(newMaxDisplay, minSize, newStart, newEnd); - // 如果newDisplay > lastTime,这时候要隐藏滚动条 - if (newMaxDisplay > lastTime) { - view.removeScrollbar(); - view.revalidate(); - } else { - if (view.getHorizontalBar() == null) { - view.initScrollbar(); - } - view.getHorizontalBar().resizeAndReposition(); - } - } - - /** - * showSuspension - * - * @param taskScenePanelChart taskScenePanelChart - * @param jTaskPanel jTaskPanel - * @param jButtonSuspen jButtonSuspen - */ - public void showSuspension(TaskScenePanelChart taskScenePanelChart, TaskPanel jTaskPanel, JButton jButtonSuspen) { - jButtonSuspen.addActionListener(new ActionListener() { - /** - * actionPerformed - * - * @param exception exception - */ - @Override - public void actionPerformed(ActionEvent exception) { - if (!flag) { - taskScenePanelChart.getjPanelSuspension().setBackground(Color.RED); - taskScenePanelChart.getjPanelSuspension().setBounds( - LayoutConstants.WINDOW_HEIGHT + (jTaskPanel.getWidth() - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_WIDTH + (jTaskPanel.getHeight() - LayoutConstants.WINDOW_HEIGHT), - LayoutConstants.WIDTHSUPEN, LayoutConstants.DEVICE_PRO_WIDTH); - jTaskPanel.add(taskScenePanelChart.getjPanelSuspension(), JLayeredPane.DRAG_LAYER); - flag = true; - jTaskPanel.repaint(); - } else { - jTaskPanel.remove(taskScenePanelChart.getjPanelSuspension()); - flag = false; - jTaskPanel.repaint(); - } - } - }); - } - - /** - * setSceneSize - * - * @param jTaskPanel jTaskPanel - * @param taskScenePanelChart taskScenePanelChart - */ - public void setSceneSize(TaskPanel jTaskPanel, TaskScenePanelChart taskScenePanelChart) { - jTaskPanel.addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param event event - */ - public void componentResized(ComponentEvent event) { - int width = jTaskPanel.getWidth(); - int height = jTaskPanel.getHeight(); - taskScenePanelChart.getjPanelSuspension() - .setBounds(LayoutConstants.WINDOW_HEIGHT + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_WIDTH + (height - LayoutConstants.WINDOW_HEIGHT), - LayoutConstants.WIDTHSUPEN, LayoutConstants.DEVICE_PRO_WIDTH); - } - }); - } - - /** - * 点击保存 - * - * @param jButton jButton - */ - public void clickSave(HosJButton jButton) { - jButton.addActionListener(new ActionListener() { - /** - * actionPerformed - * - * @param event event - */ - @Override - public void actionPerformed(ActionEvent event) { - if (jButton.getSessionId() == 0) { - new SampleDialogWrapper("prompt", "Please select a process record !").show(); - return; - } - new SaveTraceDialog().showCustomDialog(jButton); - } - }); - } - - /** - * Memory新增配置项 - * - * @param taskScenePanelChart taskScenePanelChart - * @param profilerView profilerView - */ - public void clickConfig(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { - obj = taskScenePanelChart; - taskScenePanelChart.getjButtonInsert().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent exception) { - if (!profilerView.isAddItemFlag()) { - super.mouseClicked(exception); - long sessionId = taskScenePanelChart.getjButtonInsert().getSessionId(); - new HosDialog(sessionId, profilerView); - } - } - }); - } -} +/* + * 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. + */ + +package ohos.devtools.views.layout.event; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.services.cpu.CpuDataCache; +import ohos.devtools.services.memory.memoryservice.MemoryDataCache; +import ohos.devtools.views.applicationtrace.AppTracePanel; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.charts.utils.ChartUtils; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.Constant; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomComboBox; +import ohos.devtools.views.common.customcomp.CustomJButton; +import ohos.devtools.views.common.customcomp.CustomJLabel; +import ohos.devtools.views.layout.chartview.PerformanceIndexPopupMenu; +import ohos.devtools.views.layout.chartview.SubSessionListJBPanel; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.CountingThread; +import ohos.devtools.views.layout.dialog.ExportFileChooserDialog; +import ohos.devtools.views.layout.dialog.SampleDialog; +import ohos.devtools.views.layout.TaskPanel; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JLayeredPane; +import javax.swing.JPanel; +import javax.swing.JSplitPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; + +/** + * 任务场景面板图事件类 + */ +public class TaskScenePanelChartEvent { + private static final int NUM_2 = 2; + private static final int NUM_10 = 10; + private static final Long ABNORMAL = -1L; + private boolean flagLeft = false; + private boolean flag = false; + private Container obj = null; + private boolean buttonAvailable = true; + private boolean resultDelete = false; + + /** + * 点击删除 + * + * @param taskScenePanelChart taskScenePanelChart + */ + public void clickDelete(TaskScenePanelChart taskScenePanelChart) { + taskScenePanelChart.getJButtonDelete().addActionListener(new ActionListener() { + /** + * actionPerformed + * + * @param event event + */ + @Override + public void actionPerformed(ActionEvent event) { + if (taskScenePanelChart.isGreyFlag()) { + return; + } + long localSessionId = taskScenePanelChart.getJButtonDelete().getSessionId(); + Font font = new Font("", 0, LayoutConstants.SIXTEEN); + UIManager.put("OptionPane.messageFont", font); + if (localSessionId < 0) { + new SampleDialog("prompt", "Please select the task to delete first !").show(); + return; + } + SampleDialog sampleDialogWrapper = + new SampleDialog("prompt", "Are you sure you want to delete this task ?"); + boolean flags = sampleDialogWrapper.showAndGet(); + if (flags) { + // 调用SessionManager的删除sessionId + if (!SessionManager.getInstance().endSession(localSessionId)) { + return; + } + CountingThread countingThread = taskScenePanelChart.getCounting(); + countingThread.setStopFlag(true); + // 容器中销毁char和Session的panel + // 删除界面cards的Session + deleteSession(localSessionId, taskScenePanelChart); + // 删除界面char + deleteChart(localSessionId, taskScenePanelChart); + // After deleting the chart list, there are sub options that should be displayed + List list = taskScenePanelChart.getDumpOrHookSessionList(); + if (list.size() > 0) { + taskScenePanelChart.showSubSessionList(list); + } + taskScenePanelChart.getJButtonDelete().setSessionId(ABNORMAL); + taskScenePanelChart.repaint(); + // 清除sessionid,保存trace文件时根据这个判断是否可以保存 + taskScenePanelChart.getjButtonSave().setSessionId(0); + taskScenePanelChart.getjButtonRun() + .setIcon(IconLoader.getIcon("/images/breakpoint_grey.png", getClass())); + taskScenePanelChart.getjButtonStop().setIcon(AllIcons.Process.ProgressResumeHover); + resultDelete = true; + clearTimeCounting(taskScenePanelChart); + } + } + }); + } + + /** + * Delete interface chart + * + * @param localSessionId localSessionId + * @param taskScenePanelChart taskScenePanelChart + */ + private void deleteChart(long localSessionId, TaskScenePanelChart taskScenePanelChart) { + Component[] carts = taskScenePanelChart.getCards().getComponents(); + for (Component cart : carts) { + if (cart instanceof JPanel) { + Component[] jcardsPanels = ((JPanel) cart).getComponents(); + for (Component item : jcardsPanels) { + ProfilerChartsView profilerView = null; + if (item instanceof ProfilerChartsView) { + profilerView = (ProfilerChartsView) item; + if (profilerView.getSessionId() == localSessionId) { + ((JPanel) cart).remove(profilerView); + } + } + } + } + } + } + + /** + * Delete Session + * + * @param localSessionId localSessionId + * @param taskScenePanelChart taskScenePanelChart + */ + private void deleteSession(long localSessionId, TaskScenePanelChart taskScenePanelChart) { + JPanel jScrollCardsPanelInner = taskScenePanelChart.getJScrollCardsPanelInner(); + Component[] innerJpanel = jScrollCardsPanelInner.getComponents(); + for (Component inner : innerJpanel) { + Component[] innerLable = null; + if (inner instanceof JPanel) { + innerLable = ((JPanel) inner).getComponents(); + for (Component item : innerLable) { + if (item instanceof CustomJLabel && localSessionId == ((CustomJLabel) item).getSessionId()) { + jScrollCardsPanelInner.remove(inner); + } + } + } + } + } + + /** + * clickUpAndNext + * + * @param taskScenePanelChart taskScenePanelChart + */ + public void clickUpAndNext(TaskScenePanelChart taskScenePanelChart) { + // 给上一个页面按钮添加点击事件 + taskScenePanelChart.getjButtonUp().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent exception) { + if (Constant.jtasksTab.getSelectedIndex() > 0) { + Constant.jtasksTab.setSelectedIndex(Constant.jtasksTab.getSelectedIndex() - 1); + } + } + }); + // 给下一个页面按钮添加点击事件 + taskScenePanelChart.getjButtonNext().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent exception) { + if (Constant.jtasksTab.getSelectedIndex() != Constant.jtasksTab.getTabCount() - 1) { + Constant.jtasksTab.setSelectedIndex(Constant.jtasksTab.getSelectedIndex() + 1); + } + } + }); + } + + /** + * saveButtonAddClick + * + * @param labelSave labelSave + * @param name name + */ + public void saveButtonAddClick(CustomJLabel labelSave, String name) { + labelSave.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + String fileType = ""; + if (name.contains("Native Hook")) { + fileType = "nativehook"; + } else { + fileType = "hprof"; + } + ExportFileChooserDialog fileChooserDialogWrapper = + new ExportFileChooserDialog("Export As", fileType); + boolean showAndGet = fileChooserDialogWrapper.showAndGet(); + if (showAndGet) { + String exportFileName = labelSave.getName(); + boolean saveResult = + SessionManager.getInstance().exportDumpOrHookFile(exportFileName, fileChooserDialogWrapper); + if (saveResult) { + new SampleDialog("prompt", "Save Successfully !").show(); + } else { + new SampleDialog("prompt", "Save failure !").show(); + } + } + } + + @Override + public void mouseEntered(MouseEvent event) { + labelSave.setBorder(BorderFactory.createTitledBorder("")); + } + + @Override + public void mouseExited(MouseEvent event) { + labelSave.setBorder(null); + } + }); + } + + /** + * dumpPanelAddClick + * + * @param dumpPanel dumpPanel + * @param taskScenePanelChart taskScenePanelChart + */ + public void sessionListPanelAddClick(SubSessionListJBPanel dumpPanel, TaskScenePanelChart taskScenePanelChart) { + dumpPanel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + taskScenePanelChart.setButtonEnable(true, dumpPanel.getPanelName()); + if (dumpPanel.getPanelName().contains("traceApp") || dumpPanel.getPanelName().contains("nativePerf")) { + Component[] components = taskScenePanelChart.getCards().getComponents(); + for (Component component : components) { + if (component instanceof AppTracePanel) { + taskScenePanelChart.getCards().remove(component); + } + } + if (dumpPanel.getPanelName().contains("traceApp")) { + taskScenePanelChart + .showAppTrace(dumpPanel.getDbPath(), taskScenePanelChart.getjButtonRun().getSessionId()); + } + taskScenePanelChart.setButtonEnable(true, dumpPanel.getDbPath()); + } else { + taskScenePanelChart.getCardLayout().show(taskScenePanelChart.getCards(), dumpPanel.getPanelName()); + } + taskScenePanelChart.setGreyFlag(true); + dumpPanel.setBackground(ColorConstants.SELECTED_COLOR); + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseExited(MouseEvent event) { + } + }); + } + + private void stopTask(ProfilerChartsView profilerView, CustomJButton stopButton, + TaskScenePanelChart taskScenePanelChart) { + profilerView.getPublisher().stopRefresh(false); + stopButton.setIcon(IconLoader.getIcon("/images/breakpoint.png", getClass())); + taskScenePanelChart.getjButtonStop().setIcon(AllIcons.Process.ProgressResumeHover); + buttonAvailable = false; + CountingThread countingThread = taskScenePanelChart.getCounting(); + countingThread.setStopFlag(true); + stopButton.setToolTipText("Start"); + SessionManager.getInstance().endSession(stopButton.getSessionId()); + // Clear cache of all monitor items + MemoryDataCache.getInstance().clearCacheBySession(stopButton.getSessionId()); + CpuDataCache.getInstance().clearCacheBySession(stopButton.getSessionId()); + profilerView.setStop(true); + profilerView.setPause(true); + } + + private void startTask(ProfilerChartsView profilerView, CustomJButton stopButton, + TaskScenePanelChart taskScenePanelChart) { + stopButton.setIcon(AllIcons.Debugger.Db_set_breakpoint); + taskScenePanelChart.getjButtonStop().setIcon(AllIcons.Process.ProgressPauseHover); + buttonAvailable = true; + stopButton.setToolTipText("Stop"); + // Set the icon change after the pause button is clicked Open the session to get data + long sessionId = stopButton.getSessionId(); + SessionManager sessionManager = SessionManager.getInstance(); + sessionManager.startSession(sessionId, true); + sessionManager.fetchData(sessionId); + if (profilerView.getPublisher().isDisplayScrollbar()) { + profilerView.removeScrollbar(); + } + JLabel jTextArea = taskScenePanelChart.getjTextArea(); + CountingThread counting = new CountingThread(jTextArea); + taskScenePanelChart.setCounting(counting); + counting.start(); + // Clear the selected time after restarting + profilerView.getPublisher().getStandard().clearAllSelectedRanges(); + profilerView.showLoading(); + profilerView.setStop(false); + profilerView.setPause(false); + } + + /** + * clickRunAndStop + * + * @param taskScenePanelChart taskScenePanelChart + * @param profilerView profilerView + */ + public void clickRunAndStop(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { + CustomJButton stopButton = taskScenePanelChart.getjButtonRun(); + stopButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent exception) { + if (taskScenePanelChart.isGreyFlag()) { + return; + } + if (resultDelete) { + return; + } + if (profilerView.isLoading()) { + return; + } + if (!profilerView.isStop()) { + stopTask(profilerView, stopButton, taskScenePanelChart); + } else { + startTask(profilerView, stopButton, taskScenePanelChart); + } + } + }); + pauseButtonEvent(taskScenePanelChart, profilerView); + } + + /** + * Pause button event + * + * @param taskScenePanelChart taskScenePanelChart + * @param profilerView profilerView + */ + private void pauseButtonEvent(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { + taskScenePanelChart.getjButtonStop().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent exception) { + if (taskScenePanelChart.isGreyFlag()) { + return; + } + if (resultDelete) { + return; + } + if (profilerView.isLoading()) { + return; + } + if (buttonAvailable) { + if (!profilerView.isPause()) { + taskScenePanelChart.getjButtonStop().setIcon(AllIcons.Process.ProgressResumeHover); + taskScenePanelChart.getjButtonStop().setToolTipText("Start"); + profilerView.getPublisher().pauseRefresh(); + profilerView.setPause(true); + } else { + taskScenePanelChart.getjButtonStop().setIcon(AllIcons.Process.ProgressPauseHover); + taskScenePanelChart.getjButtonBottom() + .setIcon(IconLoader.getIcon("/images/previewDetailsVertically_grey.png", getClass())); + taskScenePanelChart.getjButtonStop().setToolTipText("Suspend"); + profilerView.getPublisher().restartRefresh(); + profilerView.setPause(false); + } + } + } + }); + } + + /** + * splitPaneChange + * + * @param taskScenePanelChart taskScenePanelChart + * @param numberSum numberSum + */ + public void splitPaneChange(TaskScenePanelChart taskScenePanelChart, int numberSum) { + taskScenePanelChart.getSplitPane().addPropertyChangeListener(new java.beans.PropertyChangeListener() { + /** + * propertyChange + * + * @param evt evt + */ + public void propertyChange(java.beans.PropertyChangeEvent evt) { + if (evt.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { + int numEvt = 0; + for (int index = 0; index < numberSum; index++) { + JPanel jPanel = null; + Object objNew = taskScenePanelChart.getJScrollCardsPanelInner().getComponentAt(0, numEvt); + if (objNew instanceof JPanel) { + jPanel = (JPanel) objNew; + if (Integer.parseInt(evt.getNewValue().toString()) + < LayoutConstants.SESSION_LIST_DIVIDER_WIDTH) { + jPanel.setBounds(0, numEvt, LayoutConstants.SESSION_LIST_DIVIDER_WIDTH, + LayoutConstants.SIXTY); + } else { + jPanel.setBounds(0, numEvt, LayoutConstants.SESSION_LIST_DIVIDER_WIDTH + Integer + .parseInt(evt.getNewValue().toString()) + - LayoutConstants.SESSION_LIST_DIVIDER_WIDTH, LayoutConstants.SIXTY); + } + + numEvt += LayoutConstants.SIXTY; + jPanel.updateUI(); + jPanel.repaint(); + } + } + } + } + }); + } + + /** + * clickLeft + * + * @param taskScenePanelChart taskScenePanelChart + * @param hosJLabelList hosJLabelList + */ + public void clickLeft(TaskScenePanelChart taskScenePanelChart, List hosJLabelList) { + taskScenePanelChart.getjButtonLeft().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent exception) { + if (!flagLeft) { + taskScenePanelChart.getSplitPane().setDividerLocation(1); + taskScenePanelChart.getSplitPane().updateUI(); + taskScenePanelChart.getSplitPane().repaint(); + flagLeft = true; + } else { + if (hosJLabelList.size() > 0 && hosJLabelList.get(0).isOnline()) { + taskScenePanelChart.getSplitPane() + .setDividerLocation(LayoutConstants.SESSION_LIST_DIVIDER_WIDTH); + } else { + taskScenePanelChart.getSplitPane().setDividerLocation(LayoutConstants.NUM_200); + } + flagLeft = false; + taskScenePanelChart.getSplitPane().updateUI(); + taskScenePanelChart.getSplitPane().repaint(); + } + } + }); + taskScenePanelChart.addComponentListener(new ComponentAdapter() { + /** + * componentResized + * + * @param exception exception + */ + public void componentResized(ComponentEvent exception) { + if (flagLeft) { + taskScenePanelChart.getSplitPane().setDividerLocation(1); + taskScenePanelChart.getSplitPane().updateUI(); + taskScenePanelChart.getSplitPane().repaint(); + flagLeft = true; + } else { + taskScenePanelChart.getSplitPane() + .setDividerLocation(taskScenePanelChart.getSplitPane().getDividerLocation()); + taskScenePanelChart.getSplitPane().updateUI(); + taskScenePanelChart.getSplitPane().repaint(); + } + } + }); + } + + /** + * bindSessionId + * + * @param taskScenePanelChart taskScenePanelChart + * @param jLabelRight jLabelRight + * @param jMultiplePanel jMultiplePanel + */ + private void bindSessionId(TaskScenePanelChart taskScenePanelChart, CustomJLabel jLabelRight, + JPanel jMultiplePanel) { + taskScenePanelChart.getjButtonRun().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjButtonStop().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjButtonSave().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjButtonSave().setDeviceName(jLabelRight.getDeviceName()); + taskScenePanelChart.getjButtonSave().setProcessName(jLabelRight.getProcessName()); + taskScenePanelChart.getJButtonDelete().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getJButtonDelete().setDeviceName(jLabelRight.getDeviceName()); + taskScenePanelChart.getJButtonDelete().setProcessName(jLabelRight.getProcessName()); + taskScenePanelChart.getConfigButton().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjButtonBottom().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjButtonLeft().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getjComboBox().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getTimeJComboBox().setSessionId(jLabelRight.getSessionId()); + taskScenePanelChart.getJScrollCardsPanelInner().remove(jMultiplePanel); + taskScenePanelChart.getJScrollCardsPanelInner().repaint(); + } + + /** + * clickEvery + * + * @param taskScenePanelChart taskScenePanelChart + * @param jLabelRight jLabelRight + * @param numberSum numberSum + * @param jLabelSelect jLabelSelect + * @param jMultiplePanel jMultiplePanel + */ + public void clickEvery(TaskScenePanelChart taskScenePanelChart, CustomJLabel jLabelRight, int numberSum, + String jLabelSelect, JPanel jMultiplePanel) { + jLabelRight.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + // 绑定sessionId + bindSessionId(taskScenePanelChart, jLabelRight, jMultiplePanel); + // 获取其他jlabel设置背景色 + Component[] component = taskScenePanelChart.getJScrollCardsPanelInner().getComponents(); + for (Component componentEvery : component) { + JPanel jPanelEvery = null; + if (componentEvery instanceof JPanel) { + jPanelEvery = (JPanel) componentEvery; + Component[] componentjPanelEvery = jPanelEvery.getComponents(); + for (Component componentjPanelEverySet : componentjPanelEvery) { + JLabel jLabelEvery = null; + if (componentjPanelEverySet instanceof JLabel) { + jLabelEvery = (JLabel) componentjPanelEverySet; + jLabelEvery.setBackground(ColorConstants.BLACK_COLOR); + jLabelEvery.setForeground(Color.gray); + } + } + } + } + taskScenePanelChart.getJScrollCardsPanelInner().add(jMultiplePanel); + taskScenePanelChart.getJScrollCardsPanelInner().repaint(); + jLabelRight.setBackground(ColorConstants.SELECTED_COLOR); + if (jLabelRight.getLeft() != null) { + jLabelRight.getLeft().setBackground(ColorConstants.SELECTED_COLOR); + } + jLabelRight.setForeground(Color.white); + int numy = 0; + // 循环确定擦片布局显示哪个页面 + for (int index = 0; index < numberSum; index++) { + JPanel jPanel = null; + Object innerObj = taskScenePanelChart.getJScrollCardsPanelInner().getComponentAt(0, numy); + if (innerObj instanceof JPanel) { + jPanel = (JPanel) innerObj; + numy += LayoutConstants.HEIGHT; + Color colorBack = jPanel.getComponent(0).getBackground(); + if (colorBack == ColorConstants.SELECTED_COLOR) { + taskScenePanelChart.getCardLayout().show(taskScenePanelChart.getCards(), "card" + index); + taskScenePanelChart.add(taskScenePanelChart.getPanelTop(), BorderLayout.NORTH); + } + } + } + taskScenePanelChart.setButtonEnable(false, ""); + taskScenePanelChart.setGreyFlag(false); + // Replace the content of the tab with the content of the clicked device information + replaceDevicesInfo(jLabelSelect); + } + }); + } + + /** + * Replace device information + * + * @param jLabelSelect Selected jLabel + */ + private void replaceDevicesInfo(String jLabelSelect) { + JPanel jCompent = null; + Object tabComObj = Constant.jtasksTab.getTabComponentAt(Constant.jtasksTab.getSelectedIndex()); + if (tabComObj instanceof JPanel) { + jCompent = (JPanel) tabComObj; + JPanel jCompentLeft = null; + Object componentObj = jCompent.getComponent(0); + if (componentObj instanceof JPanel) { + jCompentLeft = (JPanel) componentObj; + Object leftObj = jCompentLeft.getComponent(0); + if (leftObj instanceof JLabel) { + ((JLabel) leftObj).setText(jLabelSelect); + } + } + } + } + + /** + * 按钮增加点击时间触发时间刻度的选择 + * + * @param jComboBox jComboBox + * @param profilerView profilerView + */ + public void clickZoomEvery(CustomComboBox jComboBox, ProfilerChartsView profilerView) { + jComboBox.addItemListener(event -> { + long sessionId = jComboBox.getSessionId(); + int newSizeTime = 0; + if (event.getStateChange() == 1) { + // 获取点击时间选择的时间刻度间隔 + String[] msTime = jComboBox.getSelectedItem().toString().split("m"); + newSizeTime = Integer.parseInt(msTime[0]); + } + ChartStandard standard = profilerView.getPublisher().getStandard(); + if (standard != null) { + checkNewTime(standard, newSizeTime, profilerView); + } + }); + } + + /** + * 检查频率切换后的时间是否需要修正 + * + * @param standard ChartStandard + * @param newSizeTime 新的时间大小 + * @param view ProfilerChartsView + */ + private void checkNewTime(ChartStandard standard, int newSizeTime, ProfilerChartsView view) { + int oldStart = standard.getDisplayRange().getStartTime(); + // 获取刻度间隔对应的最小时间单位值 + int minSize = ChartUtils.divideInt(newSizeTime, NUM_10) * NUM_2; + // 刷新绘图标准的最大展示时间和最小时间单位 + int newMaxDisplay = newSizeTime * NUM_10; + int lastTime = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); + + int newStart; + int newEnd; + // 场景1:频率切换后oldStart + newDisplay超过了lastTime,这时要修正start + if (oldStart + newMaxDisplay > lastTime) { + // 场景1.1:切换后newDisplay > lastTime,这时就变成任务刚启动时,Chart没有铺满的场景,start为0,end为lastTime + // 场景1.2:切换后newDisplay < lastTime,修正start为lastTime - display + newStart = Math.max(lastTime - newMaxDisplay, 0); + newEnd = lastTime; + } else { + // 场景2:切换后oldStart + newDisplay未超过lastTime,说明可以正常显示,无需修正start + newStart = oldStart; + newEnd = oldStart + newMaxDisplay; + } + + view.getPublisher().msTimeZoom(newMaxDisplay, minSize, newStart, newEnd); + // 如果newDisplay > lastTime,这时候要隐藏滚动条 + if (newMaxDisplay > lastTime) { + view.removeScrollbar(); + view.revalidate(); + } else { + if (view.getHorizontalBar() == null) { + view.initScrollbar(); + } + view.getHorizontalBar().resizeAndReposition(); + } + } + + /** + * showSuspension + * + * @param taskScenePanelChart taskScenePanelChart + * @param jTaskPanel jTaskPanel + * @param jButtonSuspen jButtonSuspen + */ + public void showSuspension(TaskScenePanelChart taskScenePanelChart, TaskPanel jTaskPanel, JButton jButtonSuspen) { + jButtonSuspen.addActionListener(new ActionListener() { + /** + * actionPerformed + * + * @param exception exception + */ + @Override + public void actionPerformed(ActionEvent exception) { + if (!flag) { + taskScenePanelChart.getjPanelSuspension().setBackground(Color.RED); + taskScenePanelChart.getjPanelSuspension().setBounds( + LayoutConstants.WINDOW_HEIGHT + (jTaskPanel.getWidth() - LayoutConstants.WINDOW_WIDTH), + LayoutConstants.DEVICES_WIDTH + (jTaskPanel.getHeight() - LayoutConstants.WINDOW_HEIGHT), + LayoutConstants.WIDTHSUPEN, LayoutConstants.DEVICE_PRO_WIDTH); + jTaskPanel.add(taskScenePanelChart.getjPanelSuspension(), JLayeredPane.DRAG_LAYER); + flag = true; + jTaskPanel.repaint(); + } else { + jTaskPanel.remove(taskScenePanelChart.getjPanelSuspension()); + flag = false; + jTaskPanel.repaint(); + } + } + }); + } + + /** + * setSceneSize + * + * @param jTaskPanel jTaskPanel + * @param taskScenePanelChart taskScenePanelChart + */ + public void setSceneSize(TaskPanel jTaskPanel, TaskScenePanelChart taskScenePanelChart) { + jTaskPanel.addComponentListener(new ComponentAdapter() { + /** + * componentResized + * + * @param event event + */ + public void componentResized(ComponentEvent event) { + int width = jTaskPanel.getWidth(); + int height = jTaskPanel.getHeight(); + taskScenePanelChart.getjPanelSuspension() + .setBounds(LayoutConstants.WINDOW_HEIGHT + (width - LayoutConstants.WINDOW_WIDTH), + LayoutConstants.DEVICES_WIDTH + (height - LayoutConstants.WINDOW_HEIGHT), + LayoutConstants.WIDTHSUPEN, LayoutConstants.DEVICE_PRO_WIDTH); + } + }); + } + + /** + * Memory新增配置项 + * + * @param taskScenePanelChart taskScenePanelChart + * @param profilerView profilerView + */ + public void clickConfig(TaskScenePanelChart taskScenePanelChart, ProfilerChartsView profilerView) { + obj = taskScenePanelChart; + } + + /** + * click Performance analysis index configuration + * + * @param configButton configButton + * @param itemMenu itemMenu + */ + public void clickIndexConfig(CustomJButton configButton, PerformanceIndexPopupMenu itemMenu) { + configButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + itemMenu.showItemMenu(mouseEvent); + } + }); + } + + /** + * click save + * + * @param jButton jButton + * @param taskScenePanelChart taskScenePanelChart + */ + public void clickSave(CustomJButton jButton, TaskScenePanelChart taskScenePanelChart) { + jButton.addActionListener(new ActionListener() { + /** + * actionPerformed + * + * @param event event + */ + @Override + public void actionPerformed(ActionEvent event) { + if (taskScenePanelChart.isGreyFlag()) { + return; + } + if (jButton.getSessionId() == 0) { + new SampleDialog("prompt", "Please select a process record !").show(); + return; + } + ExportFileChooserDialog fileChooserDialogWrapper = + new ExportFileChooserDialog("Export As", UtConstant.FILE_TYPE_TRACE); + boolean showAndGet = fileChooserDialogWrapper.showAndGet(); + if (showAndGet) { + fileChooserDialogWrapper.saveDataToFile(jButton); + } + } + }); + } + + private void clearTimeCounting(TaskScenePanelChart taskScenePanelChart) { + JLabel jTextArea = taskScenePanelChart.getjTextArea(); + while (taskScenePanelChart.getCounting().isAlive()) { + SwingUtilities.invokeLater(new Runnable() { + /** + * run + */ + public void run() { + jTextArea.setText("Run 1 of 1 | 00:00:00"); + } + }); + } + SwingUtilities.invokeLater(new Runnable() { + /** + * run + */ + public void run() { + jTextArea.setText("Run 1 of 1 | 00:00:00"); + } + }); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelEvent.java deleted file mode 100644 index cf56c0e16..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/event/TaskScenePanelEvent.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import com.alibaba.fastjson.JSONObject; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.common.Common; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJLabel; -import ohos.devtools.views.layout.swing.DeviceProcessJpanel; -import ohos.devtools.views.layout.swing.SampleDialogWrapper; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskScenePanel; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.JComboBox; -import javax.swing.JPanel; -import javax.swing.JTextField; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import static ohos.devtools.views.common.Constant.DEVICEREFRESH; - -/** - * 设备进程容器 - * - * @version 1.0 - * @date 2021/03/02 - **/ -public class TaskScenePanelEvent { - private static final Logger LOGGER = LogManager.getLogger(TaskScenePanelEvent.class); - - /** - * 设备进程容器标题计数 - */ - private int numDevices = LayoutConstants.INDEX_ONE; - - private int num = LayoutConstants.DEVICE_PRO_Y; - - private boolean flag = false; - - private Common common = new Common(); - - /** - * startTask - * - * @param taskScenePanel taskScenePanel - * @param jTaskPanel jTaskPanel - */ - public void startTask(TaskScenePanel taskScenePanel, TaskPanel jTaskPanel) { - taskScenePanel.getJButtonStartTask().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - - // 判断设备下拉框是否有数据 - int itemCount = taskScenePanel.getDeviceProcessJpanel().getJComboBoxPhone().getItemCount(); - if (itemCount == 0) { - new SampleDialogWrapper("prompt", "Device list is empty !").show(); - return; - } - - // 判断进程是否选择 - if ("Please select the device process !" - .equals(taskScenePanel.getDeviceProcessJpanel().getLabelName().getText())) { - new SampleDialogWrapper("prompt", "Please select the device process !").show(); - return; - } - - boolean isSelected = - taskScenePanel.getCheckBoxMemoryJava().isSelected() || taskScenePanel.getCheckBoxGpuMemoryNative() - .isSelected() || taskScenePanel.getCheckBoxGraphics().isSelected() || taskScenePanel - .getCheckBoxStack().isSelected() || taskScenePanel - .getCheckBoxCode().isSelected() || taskScenePanel.getCheckBoxOthers().isSelected(); - if (!isSelected) { - new SampleDialogWrapper("prompt", "please choose Monitor Items !").show(); - return; - } - // 获取所有进程设备信息map。用于请求后端接口 - List hosJLabels = obtainMap(taskScenePanel, jTaskPanel); - if (!hosJLabels.isEmpty()) { - // 移除三级页面,添加新的三级页面 - jTaskPanel.getOptionJPanel().removeAll(); - QuartzManager.getInstance().endExecutor(DEVICEREFRESH); - TaskScenePanelChart taskScenePanelChart = new TaskScenePanelChart(jTaskPanel, hosJLabels); - jTaskPanel.getOptionJPanel().add(taskScenePanelChart); - // 更新所有的run -- of -- - common.updateNum(Constant.jtasksTab); - jTaskPanel.getOptionJPanel().repaint(); - } - } - }); - } - - /** - * Get the value of the drop-down box - * - * @param taskScenePanel taskScenePanel - * @return JSONObject - */ - private JSONObject getValueJCheckBoxs(TaskScenePanel taskScenePanel) { - JSONObject memoryObject = new JSONObject(); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_ONE].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_ONE].isSelected()); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_TWO].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_TWO].isSelected()); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_THREE].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_THREE].isSelected()); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_FOUR].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_FOUR].isSelected()); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_FIVE].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_FIVE].isSelected()); - memoryObject.put(taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_SIX].getText(), - taskScenePanel.getJCheckBoxs()[LayoutConstants.INDEX_SIX].isSelected()); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Memory", memoryObject); - return jsonObject; - } - - /** - * obtainMap - * - * @param taskScenePanel taskScenePanel - * @param jTaskPanel jTaskPanel - * @return List - */ - public List obtainMap(TaskScenePanel taskScenePanel, TaskPanel jTaskPanel) { - // 获取下拉框的值 - JSONObject jsonObject = getValueJCheckBoxs(taskScenePanel); - SessionManager sessionManager = SessionManager.getInstance(); - Collection> selectMaps = Constant.map.values(); - if (selectMaps.isEmpty()) { - return new ArrayList(); - } - ArrayList hosJLabels = new ArrayList<>(); - for (Map seMap : selectMaps) { - for (Map.Entry entry : seMap.entrySet()) { - DeviceIPPortInfo mapKey = null; - Object keyObj = entry.getKey(); - if (keyObj instanceof DeviceIPPortInfo) { - mapKey = (DeviceIPPortInfo) keyObj; - } - ProcessInfo mapValue = null; - Object valueObj = entry.getValue(); - if (valueObj instanceof ProcessInfo) { - mapValue = (ProcessInfo) valueObj; - } - - if (mapKey != null && mapValue != null) { - Long localSessionID = sessionManager.createSession(mapKey, mapValue, 1, jsonObject); - if (localSessionID == ohos.devtools.datasources.utils.common.Constant.ABNORMAL - || localSessionID == null) { - return new ArrayList(); - } - jTaskPanel.setLocalSessionId(localSessionID); - HosJLabel hosJLabel = new HosJLabel(); - hosJLabel.setSessionId(localSessionID); - hosJLabel.setDeviceName(mapKey.getDeviceName()); - hosJLabel.setProcessName(mapValue.getProcessName() + "(" + mapValue.getProcessId() + ")"); - // 开启session - sessionManager.startSession(localSessionID, false); - // 获取数据 - long date = DateTimeUtil.getNowTimeLong(); - sessionManager.fetchData(localSessionID); - hosJLabel.setFirstStamp(date); - hosJLabels.add(hosJLabel); - } - } - } - return hosJLabels; - } - - /** - * Get device process information in the drop-down box for display - * - * @param scrollPane scrollPane - * @return String - */ - public String gain(JPanel scrollPane) { - String processName = ""; - Component[] component = scrollPane.getComponents(); - for (Component componentOut : component) { - if (componentOut instanceof JPanel) { - JPanel jPanel = (JPanel) componentOut; - Component[] componentInner = jPanel.getComponents(); - processName = judgCompontent(componentInner, processName); - } - } - return processName; - } - - /** - * judgCompontent - * - * @param componentInner componentInner - * @param processName processName - * @return String - */ - public String judgCompontent(Component[] componentInner, String processName) { - String processNameNew = processName; - for (Component componentAll : componentInner) { - if (componentAll instanceof JComboBox) { - JComboBox jComboBox = (JComboBox) componentAll; - processNameNew = processName + jComboBox.getSelectedItem().toString() + ","; - } - if (componentAll instanceof JPanel) { - JPanel jPanelText = (JPanel) componentAll; - Component[] componentText = jPanelText.getComponents(); - for (Component componentTextFile : componentText) { - if (componentTextFile instanceof JTextField) { - JTextField jTextField = (JTextField) componentTextFile; - processNameNew = processName + jTextField.getText() + ","; - } - } - } - } - return processNameNew; - } - - /** - * lastStep - * - * @param taskScenePanel taskScenePanel - * @param jTaskPanel jTaskPanel - */ - public void lastStep(TaskScenePanel taskScenePanel, TaskPanel jTaskPanel) { - taskScenePanel.getJButtonLastStep().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - super.mouseClicked(event); - jTaskPanel.getOptionJPanel().remove(taskScenePanel); - jTaskPanel.getOptionJPanelContent().setVisible(true); - jTaskPanel.getOptionJPanel().repaint(); - } - }); - } - - /** - * 监听器 - * - * @param taskScenePanel taskScenePanel - */ - public void listenerJPanelSouth(TaskScenePanel taskScenePanel) { - taskScenePanel.getJPanelSouth().addComponentListener(new ComponentAdapter() { - /** - * componentResized - * - * @param exception exception - */ - public void componentResized(ComponentEvent exception) { - int width = taskScenePanel.getJPanelSouth().getWidth(); - taskScenePanel.getJButtonLastStep() - .setBounds(LayoutConstants.NUMBER_STEP + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_HEIGHT, LayoutConstants.DEVICE_ADD_WIDTH, - LayoutConstants.CHOOSE_HEIGHT); - taskScenePanel.getJButtonStartTask() - .setBounds(LayoutConstants.POSITION_TASK_X + (width - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.DEVICES_HEIGHT, LayoutConstants.DEVICE_ADD_WIDTH, - LayoutConstants.CHOOSE_HEIGHT); - } - }); - } - - /** - * 复选框选取 - * - * @param taskScenePanel taskScenePanel - */ - public void checkBoxSelect(TaskScenePanel taskScenePanel) { - taskScenePanel.getCheckBoxSelectAll().addItemListener(new ItemListener() { - /** - * itemStateChanged - * - * @param event event - */ - @Override - public void itemStateChanged(ItemEvent event) { - if (taskScenePanel.getCheckBoxSelectAll().isSelected()) { - taskScenePanel.getCheckBoxMemoryJava().setSelected(true); - taskScenePanel.getCheckBoxGpuMemoryNative().setSelected(true); - taskScenePanel.getCheckBoxGraphics().setSelected(true); - taskScenePanel.getCheckBoxStack().setSelected(true); - taskScenePanel.getCheckBoxCode().setSelected(true); - taskScenePanel.getCheckBoxOthers().setSelected(true); - } else { - taskScenePanel.getCheckBoxMemoryJava().setSelected(false); - taskScenePanel.getCheckBoxGpuMemoryNative().setSelected(false); - taskScenePanel.getCheckBoxGraphics().setSelected(false); - taskScenePanel.getCheckBoxStack().setSelected(false); - taskScenePanel.getCheckBoxCode().setSelected(false); - taskScenePanel.getCheckBoxOthers().setSelected(false); - } - } - }); - } - - /** - * Add device - * - * @param taskScenePanel taskScenePanel - * @param taskScenePanelEvent taskScenePanelEvent - */ - public void clickAddDevice(TaskScenePanel taskScenePanel, TaskScenePanelEvent taskScenePanelEvent) { - taskScenePanel.getJButtonAddDevice().addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - numDevices++; - num += LayoutConstants.WIDTHS; - DeviceProcessJpanel deviceProcessJpanel = - new DeviceProcessJpanel(taskScenePanelEvent, taskScenePanel.getScrollPane(), taskScenePanel); - taskScenePanel.getScrollPane().add(deviceProcessJpanel); - taskScenePanel.getScrollPane() - .setPreferredSize(new Dimension(LayoutConstants.DEVICE_PRO_WIDTH, LayoutConstants.WIDTHS + num)); - taskScenePanel.getScrollPane().updateUI(); - taskScenePanel.getScrollPane().repaint(); - } - }); - } - - /** - * getNumDevices - * - * @return int - */ - public int getNumDevices() { - return numDevices; - } - - /** - * setNumDevices - * - * @param numDevices numDevices - */ - public void setNumDevices(int numDevices) { - this.numDevices = numDevices; - } - - /** - * getNum - * - * @return int - */ - public int getNum() { - return num; - } - - /** - * setNum - * - * @param num num - */ - public void setNum(int num) { - this.num = num; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/DeviceProcessJpanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/DeviceProcessJpanel.java deleted file mode 100644 index 33a8a18a2..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/DeviceProcessJpanel.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.process.service.ProcessManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.event.DeviceProcessJpanelEvent; -import ohos.devtools.views.layout.event.TaskScenePanelEvent; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.DefaultTableModel; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridLayout; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Vector; - -/** - * 设备进程面板 - * - * @version 1.0 - * @date 2021/03/02 - **/ -public class DeviceProcessJpanel extends JPanel { - /** - * 设备描述 - */ - private JLabel jLabelDevice = new JLabel("Device"); - - /** - * 设备连接方式下拉框(usb,wifi,蓝牙) - */ - private JComboBox jComboBoxConnect = new JComboBox(); - - /** - * 设备名称下拉框 - */ - private JComboBox jComboBoxPhone = new JComboBox(); - - /** - * 设备信息集合 - */ - private List deviceInfos = null; - - /** - * 进程信息集合 - */ - private List proinfos = null; - - /** - * 进程描述 - */ - private JLabel jLabelApply = new JLabel("Application"); - - /** - * 进程信息输入框容器 - */ - private JPanel selectPanel = new JPanel(new GridLayout()); - - /** - * 进程信息输入框 - */ - private JTextFieldTable labelName = new JTextFieldTable("device"); - - /** - * 进程信息搜索框 - */ - private JTextFieldTable textField = new JTextFieldTable("press"); - - /** - * 进程信息下拉箭头 - */ - private JLabel labelSvg = new JLabel(); - - /** - * 进程信息下拉列表容器 - */ - private JPanel jPanelProcess = new JPanel(new BorderLayout()); - - /** - * 进程信息下拉列表容器top容器 - */ - private JPanel jPanelProcessTop = new JPanel(new GridLayout()); - - /** - * 进程信息下拉列表容器Center容器 - */ - private JPanel jPanelProcessCenter = new JPanel(new GridLayout()); - - /** - * 进程信息列表 - */ - private JTable table = new JTable(); - - /** - * 进程信息列表滚动条 - */ - private JScrollPane jScrollPane = new JScrollPane(); - - private DeviceProcessJpanelEvent deviceProcessJpanelEvent = new DeviceProcessJpanelEvent(); - - private TaskScenePanelEvent taskScenePanelEvent = new TaskScenePanelEvent(); - - /** - * DeviceProcessJpanel - * - * @param taskScenePanelEvent taskScenePanelEvent - * @param scrollPane scrollPane - * @param taskScenePanel taskScenePanel - */ - public DeviceProcessJpanel(TaskScenePanelEvent taskScenePanelEvent, JPanel scrollPane, - TaskScenePanel taskScenePanel) { - this.setLayout(null); - this.setOpaque(true); - this.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - this.setBounds(LayoutConstants.DEVICE_PRO_X, taskScenePanelEvent.getNum(), LayoutConstants.DEVICE_PRO_WIDTH, - LayoutConstants.WIDTHS); - Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.DEVICES_FONT); - JLabel jLabelDeviceNum = - new JLabel("Devices " + String.format(Locale.ENGLISH, "%02d", taskScenePanelEvent.getNumDevices())); - jLabelDeviceNum.setFont(fontTaskTun); - jLabelDeviceNum.setForeground(Color.white); - jLabelDeviceNum - .setBounds(LayoutConstants.CHOOSE_HEIGHT, LayoutConstants.JP_RIGHT_WIDTH, LayoutConstants.DEVICES_WIDTH, - LayoutConstants.DEVICES_HEIGHT); - // 属性设置 - setAttributes(taskScenePanelEvent, scrollPane, taskScenePanel); - DeviceIPPortInfo deviceIPPortInfo; - // 进程下拉列表 - if (deviceInfos.isEmpty()) { - deviceIPPortInfo = new DeviceIPPortInfo(); - } else { - deviceIPPortInfo = deviceInfos.get(0); - } - createProcessList(deviceIPPortInfo, jLabelDeviceNum.getText(), scrollPane, taskScenePanel); - // 获取add device按钮 - taskScenePanel.getJButtonAddDevice() - .setBounds(LayoutConstants.APP_LABEL_Y1, LayoutConstants.TWO_HUNDRED_TEN, LayoutConstants.DEVICE_ADD_WIDTH, - LayoutConstants.DEVICE_ADD_HEIGHT); - this.add(jLabelDeviceNum); - this.add(jLabelDevice); - this.add(jComboBoxConnect); - this.add(jComboBoxPhone); - this.add(jLabelApply); - this.add(selectPanel); - } - - /** - * Process drop-down list - * - * @param deviceInfo deviceInfo - * @param deviceNum deviceNum - * @param scrollPane scrollPane - * @param taskScenePanel taskScenePanel - */ - public void createProcessList(DeviceIPPortInfo deviceInfo, String deviceNum, JPanel scrollPane, - TaskScenePanel taskScenePanel) { - jPanelProcess - .setBounds(LayoutConstants.SELECT_ALL_Y, LayoutConstants.PRECCE_HEIGHT_Y, LayoutConstants.PRECCE_WIDTH, - LayoutConstants.SE_PANEL_WIDTH); - jPanelProcessTop - .setPreferredSize(new Dimension(LayoutConstants.SE_PANEL_WIDTH, LayoutConstants.DEVICE_ADD_HEIGHT)); - jPanelProcessCenter.setPreferredSize(new Dimension(LayoutConstants.PRECCE_WIDTH, LayoutConstants.TASK_DEC_X)); - jPanelProcess.add(jPanelProcessTop, BorderLayout.NORTH); - jPanelProcess.add(jPanelProcessCenter, BorderLayout.CENTER); - textField.setPreferredSize(new Dimension(LayoutConstants.TASK_DEC_X, LayoutConstants.DEVICE_ADD_HEIGHT)); - jPanelProcessTop.add(textField); - // 创建列表 - Vector columnNames = new Vector(); - columnNames.add(""); - // 根据设备信息获取进程信息 - Vector processNames = new Vector<>(); - for (int i = 0; i < proinfos.size(); i++) { - ProcessInfo processInfo = proinfos.get(i); - Vector vector = new Vector(); - vector.add(processInfo.getProcessName() + "(" + processInfo.getProcessId() + ")"); - processNames.add(vector); - } - if (!proinfos.isEmpty()) { - // 更新map - Map mapObject = new HashMap<>(); - mapObject.put(deviceInfo, proinfos.get(0)); - Constant.map.put(deviceNum, mapObject); - } - DefaultTableModel model = new DefaultTableModel(processNames, columnNames); - table.setModel(model); - table.getTableHeader().setVisible(false); - table.setRowHeight(LayoutConstants.DEVICE_ADD_HEIGHT); - DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); - renderer.setPreferredSize(new Dimension(0, 0)); - table.getTableHeader().setDefaultRenderer(renderer); - // table鼠标悬停效果 - deviceProcessJpanelEvent.mouseEffectTable(table); - jScrollPane.setViewportView(table); - jPanelProcessCenter.add(jScrollPane); - // table点击获取选中值 - deviceProcessJpanelEvent.clickTable(this, deviceNum, deviceInfo, scrollPane, taskScenePanel); - // 搜索按钮添加搜索事件 - deviceProcessJpanelEvent.searchJButtonSelect(this, proinfos); - } - - private void setComponent() { - jLabelDevice.setBounds(LayoutConstants.SELECT_ALL_Y, LayoutConstants.DEVICE_PRO_X, LayoutConstants.APP_BUT_X, - LayoutConstants.DEVICES_HEIGHT); - jComboBoxConnect.addItem("USB"); - jComboBoxConnect - .setBounds(LayoutConstants.CHOOSE_HEIGHT, LayoutConstants.JLABEL_SIZE, LayoutConstants.CON_BOX_WIDTH, - LayoutConstants.TASK_SCENE_Y); - jComboBoxPhone - .setBounds(LayoutConstants.RIGHT_BUN_WIDTH, LayoutConstants.JLABEL_SIZE, LayoutConstants.HEIGHT_PRESSE, - LayoutConstants.TASK_SCENE_Y); - jLabelApply - .setBounds(LayoutConstants.APP_NAME_X, LayoutConstants.EMB_BUT_HEIGHT, LayoutConstants.APP_NAME_WIDTH, - LayoutConstants.APP_NAME_HEIGHT); - selectPanel.setBounds(LayoutConstants.SELECT_ALL_Y, LayoutConstants.BUTTON_WIDTH, LayoutConstants.PRECCE_WIDTH, - LayoutConstants.TASK_SCENE_Y); - labelName.setEditable(false); - selectPanel.add(labelName); - } - - /** - * Property setting - * - * @param taskScenePanelEvent taskScenePanelEvent - * @param scrollPane scrollPane - * @param taskScenePanel taskScenePanel - */ - public void setAttributes(TaskScenePanelEvent taskScenePanelEvent, JPanel scrollPane, - TaskScenePanel taskScenePanel) { - setComponent(); - deviceInfos = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - deviceProcessJpanelEvent.devicesInfoJComboBoxUpdate(this); - if (deviceInfos.isEmpty()) { - proinfos = new ArrayList<>(); - } else { - proinfos = ProcessManager.getInstance().getProcessList(deviceInfos.get(0)); - Map mapObject = new HashMap<>(); - if (!proinfos.isEmpty()) { - mapObject.put(deviceInfos.get(0), proinfos.get(0)); - } - Constant.map.put("Devices " + String.format(Locale.ENGLISH, "%02d", taskScenePanelEvent.getNumDevices()), - mapObject); - } - if (!proinfos.isEmpty()) { - labelName.setText(proinfos.get(0).getProcessName() + "(" + proinfos.get(0).getProcessId() + ")"); - } else { - labelName.setText("Please select the device process !"); - labelName.setForeground(ColorConstants.TOP_PANEL_APPLICATION); - } - // 设备和进程信息联动 - deviceProcessJpanelEvent.itemStateChanged(this, taskScenePanel, - "Devices " + String.format(Locale.ENGLISH, "%02d", taskScenePanelEvent.getNumDevices()), scrollPane); - // 给进程列表框添加点击事件,点击后展开进程列表 - deviceProcessJpanelEvent.addClickListener(this, scrollPane, taskScenePanelEvent, taskScenePanel, - "Devices " + String.format(Locale.ENGLISH, "%02d", taskScenePanelEvent.getNumDevices())); - } - - /** - * getTable - * - * @return JTable - */ - public JTable getTable() { - return table; - } - - /** - * getLabelName - * - * @return JTextField - */ - public JTextField getLabelName() { - return labelName; - } - - /** - * setDeviceInfos - * - * @param deviceInfos deviceInfos - */ - public void setDeviceInfos(List deviceInfos) { - this.deviceInfos = deviceInfos; - } - - /** - * getDeviceInfos - * - * @return List - */ - public List getDeviceInfos() { - return deviceInfos; - } - - /** - * getProinfos - * - * @return List - */ - public List getProinfos() { - return proinfos; - } - - /** - * setProinfos - * - * @param proinfos proinfos - */ - public void setProinfos(List proinfos) { - this.proinfos = proinfos; - } - - /** - * getJComboBoxPhone - * - * @return JComboBox - */ - public JComboBox getJComboBoxPhone() { - return jComboBoxPhone; - } - - /** - * getTextField - * - * @return JTextField - */ - public JTextField getTextField() { - return textField; - } - - /** - * getLabelSvg - * - * @return JLabel - */ - public JLabel getLabelSvg() { - return labelSvg; - } - - /** - * getJPanelProcess - * - * @return JPanel - */ - public JPanel getJPanelProcess() { - return jPanelProcess; - } - - public TaskScenePanelEvent getTaskScenePanelEvent() { - return taskScenePanelEvent; - } - - public void setTaskScenePanelEvent(TaskScenePanelEvent taskScenePanelEvent) { - this.taskScenePanelEvent = taskScenePanelEvent; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/GraphicsJpanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/GraphicsJpanel.java deleted file mode 100644 index 21c54bea9..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/GraphicsJpanel.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; - -import javax.swing.JPanel; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.Line2D; - -/** - * @Description GraphicsJpanel - * @Date 2021/4/13 13:15 - **/ -public class GraphicsJpanel extends JPanel { - private TaskPanel taskPanel; - - /** - * GraphicsJpanel - * - * @param taskPanel taskPanel - */ - public GraphicsJpanel(TaskPanel taskPanel) { - this.setOpaque(false); - this.setLayout(null); - this.taskPanel = taskPanel; - } - - /** - * 直线绘制 - * - * @param graphics graphics - */ - public void paint(Graphics graphics) { - super.paint(graphics); - graphics.setColor(ColorConstants.TOP_COLOR); - Graphics2D graphicsTop = (Graphics2D) graphics; - Graphics2D graphicsBottom = null; - if (graphics instanceof Graphics2D) { - graphicsBottom = (Graphics2D) graphics; - } - Line2D linTop = new Line2D.Float(LayoutConstants.THIRTY, 0, this.getWidth() - LayoutConstants.THIRTY, 0); - Line2D linBottom = new Line2D.Float(LayoutConstants.THIRTY, LayoutConstants.JP_LEFT_WIDTH, - this.getWidth() - LayoutConstants.THIRTY, LayoutConstants.JP_LEFT_WIDTH); - graphicsTop.draw(linTop); - if (graphicsBottom != null) { - graphicsBottom.draw(linBottom); - } - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/HomeWindow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/HomeWindow.java deleted file mode 100644 index 9c597499d..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/HomeWindow.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.event.HomeWindowEvent; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridLayout; - -import static ohos.devtools.views.common.LayoutConstants.FONT_SIZE; -import static ohos.devtools.views.common.LayoutConstants.WINDOW_HEIGHT; -import static ohos.devtools.views.common.LayoutConstants.WINDOW_WIDTH; - -/** - * 主界面 - * - * @version 1.0 - * @date 2021/02/27 11:07 - **/ -public class HomeWindow extends JPanel { - // 菜单栏 - private static JPanel menuPanel = new JPanel(new BorderLayout()); - - // 存放二级界面的容器 - private static JPanel taskPanel = new JPanel(new GridLayout()); - - private static JMenu jFileMenu = new JMenu("File"); - - private static JMenu jViewMenu = new JMenu("View"); - - private static JMenu jSetMenu = new JMenu("Setting"); - - private static JMenu jHelpMenu = new JMenu("Help"); - - private static JMenuItem jNewRealTimeTaskJMenuItem = new JMenuItem("New Task"); - - private static JMenuItem jImportFilesJMenuItem = new JMenuItem("Open File"); - - private static JMenuItem jSaveTaskJMenuItem = new JMenuItem("Save as"); - - private static JMenuItem jQuitJMenuItem = new JMenuItem("Quit"); - - private static JMenuItem jLogSwitch = new JMenuItem("Path to Log"); - - private HomeWindowEvent homeWindowEvent = new HomeWindowEvent(); - - private TaskPanelWelcome taskPanelWelcome = new TaskPanelWelcome(); - - /** - * HomeWindow - */ - public HomeWindow() { - this.setLayout(new BorderLayout()); - this.setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT)); - initComponents(); - } - - /** - * 初始化一级界面 - */ - private void initComponents() { - JLabel logo = new JLabel("HosProfiler ", JLabel.RIGHT); - logo.setIcon(new ImageIcon(HomeWindow.class.getClassLoader().getResource("images/logo.png"))); - logo.setBackground(ColorConstants.HOME_PANE); - logo.setForeground(Color.WHITE); - Font fontZhu = new Font(Font.DIALOG, Font.BOLD, FONT_SIZE); - logo.setFont(fontZhu); - jFileMenu.add(jNewRealTimeTaskJMenuItem); - jSetMenu.add(jLogSwitch); - JMenuBar jMenuBar = new JMenuBar(); - JLabel logoKong = new JLabel(" ", JLabel.RIGHT); - jMenuBar.setFont(fontZhu); - jMenuBar.add(logoKong); - jMenuBar.add(logo); - jMenuBar.add(jSetMenu); - menuPanel.add(jMenuBar); - jFileMenu.setBackground(ColorConstants.TOP_COLOR); - jSetMenu.setBackground(ColorConstants.TOP_COLOR); - jMenuBar.setBackground(ColorConstants.TOP_COLOR); - menuPanel.setPreferredSize(new Dimension(LayoutConstants.WINDOW_WIDTH, LayoutConstants.SVGWIDTH_FOUR)); - // 将二级界面面板添加到主界面中 - this.add(menuPanel, BorderLayout.NORTH); - this.add(taskPanel, BorderLayout.CENTER); - this.setBackground(ColorConstants.CENTER_COLOR); - homeWindowEvent.clickUpdateLogLevel(this); - this.addTaskPanel(taskPanelWelcome); - } - - /** - * 将二级界面添加到二级界面的面板中 - * - * @param jPanel 二级界面 - */ - public void addTaskPanel(JPanel jPanel) { - taskPanel.add(jPanel); - if (jPanel instanceof TaskPanelWelcome) { - taskPanelWelcome = (TaskPanelWelcome) jPanel; - } - // 刷新页面 - this.setVisible(true); - } - - /** - * getJNewRealTimeTaskJMenuItem - * - * @return JMenuItem - */ - public JMenuItem getJNewRealTimeTaskJMenuItem() { - return jNewRealTimeTaskJMenuItem; - } - - /** - * getJLogSwitch - * - * @return JMenuItem - */ - public static JMenuItem getJLogSwitch() { - return jLogSwitch; - } - - /** - * getTaskPanel - * - * @return JPanel - */ - public JPanel getTaskPanel() { - return taskPanel; - } - - /** - * getTaskPanelWelcome - * - * @return TaskPanelWelcome - */ - public TaskPanelWelcome getTaskPanelWelcome() { - return taskPanelWelcome; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LevelTablePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LevelTablePanel.java deleted file mode 100644 index 9ee294398..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/LevelTablePanel.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.services.memory.ClassInfoManager; -import ohos.devtools.services.memory.MemoryHeapInfo; -import ohos.devtools.services.memory.MemoryHeapManager; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.chart.treetable.DataNode; -import ohos.devtools.views.common.chart.treetable.DataNodeCompares; -import ohos.devtools.views.common.chart.treetable.AgentDataModel; -import ohos.devtools.views.common.chart.treetable.JTreeTable; -import ohos.devtools.views.common.chart.treetable.TreeTableModel; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.BorderFactory; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.RowSorter; -import javax.swing.SwingConstants; -import javax.swing.SwingWorker; -import javax.swing.UIManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.RowSorterEvent; -import javax.swing.event.RowSorterListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; -import javax.swing.text.Position; -import javax.swing.tree.TreePath; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Label; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.ExecutionException; - -/** - * 层级面板 - * - * @version 1.0 - * @date 2021/02/27 15:31 - **/ -public class LevelTablePanel extends JPanel { - private static final Logger LOGGER = LogManager.getLogger(LevelTablePanel.class); - - private boolean flag = false; - private JPanel suspensionTable = null; - private long sessionId; - private JTreeTable treeTable; - - /** - * getSuspensionTable - * - * @return JPanel - */ - public JPanel getSuspensionTable() { - return suspensionTable; - } - - /** - * setSuspensionTable - * - * @param suspensionTable suspensionTable - */ - public void setSuspensionTable(JPanel suspensionTable) { - this.suspensionTable = suspensionTable; - } - - private SuspensionTablePanel suspensionTablePanel = new SuspensionTablePanel(); - - /** - * LevelTablePanel - * - * @param jpanelSupenn jpanelSupenn - * @param sessionId long - */ - public LevelTablePanel(JPanel jpanelSupenn, long sessionId) { - this.setLayout(new BorderLayout()); - this.setOpaque(true); - this.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpanelSupenn.setBackground(ColorConstants.TRACE_TABLE_COLOR); - SwingWorker task = new SwingWorker<>() { - /** - * doInBackground - * - * @return JTreeTable - * @throws Exception Exception - */ - @Override - protected JTreeTable doInBackground() { - JTreeTable table = null; - try { - table = createTable(jpanelSupenn, sessionId); - return table; - } catch (Exception exception) { - LOGGER.error("createTable Exception {}", exception.getMessage()); - } - return table; - } - - /** - * done - */ - @Override - protected void done() { - // 此方法将在后台任务完成后在事件调度线程中被回调 - JTreeTable table = null; - try { - // 获取计算结果 - table = get(); - if (table == null) { - return; - } - if (treeTable == null && (table != null)) { - treeTable = table; - } - DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); - tcr.setHorizontalAlignment(SwingConstants.CENTER); - treeTable.setDefaultRenderer(Object.class, tcr); - // 初始化层级table - RowSorter sorter = new TableRowSorter(treeTable.getModel()); - treeTable.setRowSorter(sorter); - sorter.addRowSorterListener(new RowSorterListener() { - @Override - public void sorterChanged(RowSorterEvent event) { - if (!sorter.getSortKeys().isEmpty()) { - List keys = sorter.getSortKeys(); - AgentDataModel treeTableModel = null; - TreeTableModel treeTModel = treeTable.treeTableModel; - if (treeTModel instanceof AgentDataModel) { - treeTableModel = (AgentDataModel) treeTModel; - } - DataNode rootNode = treeTableModel.getDataNode(); - - ArrayList datNode = rootNode.getChildren(); - RowSorter.SortKey key = keys.get(0); - String sortOrder = key.getSortOrder().name(); - Comparator comparator = - new DataNodeCompares().chooseCompare(key.getColumn(), sortOrder); - if (comparator != null) { - Collections.sort(datNode, comparator); - } - rootNode.setChildren(datNode); - AgentDataModel agentDataModel = new AgentDataModel(rootNode); - treeTable.treeTableModel = agentDataModel; - treeTable.treeTableCellRenderer = treeTable.new TreeTableCellRenderer(agentDataModel); - treeTable.treeTableCellRenderer.setRowHeight(treeTable.getRowHeight()); - treeTable.setDefaultRenderer(TreeTableModel.class, treeTable.treeTableCellRenderer); - } - } - }); - JScrollPane jScrollPane = new JScrollPane(treeTable); - jScrollPane.getViewport().setOpaque(true); - jScrollPane.getViewport().setBackground(ColorConstants.TRACE_TABLE_COLOR); - jScrollPane.setBorder(BorderFactory.createEmptyBorder()); - jScrollPane.setBackground(ColorConstants.BLACK_COLOR); - treeTable.setBackground(ColorConstants.TRACE_TABLE_COLOR); - LevelTablePanel.this.add(jScrollPane, BorderLayout.CENTER); - // 这块,初始化模糊查询 - JPanel jPanel = selectData(treeTable); - LevelTablePanel.this.add(jPanel, BorderLayout.NORTH); - } catch (InterruptedException | ExecutionException exception) { - LOGGER.error(" Exception {}", exception.getMessage()); - } - } - }; - task.execute(); - } - - /** - * 创建表格 - * - * @param jpanelSupenn jpanelSupenn - * @param sessionId long - * @return JTreeTable - */ - public JTreeTable createTable(JPanel jpanelSupenn, long sessionId) { - Icon icon1 = new ImageIcon(LevelTablePanel.class.getClassLoader().getResource("images/right.png")); - Icon icon2 = new ImageIcon(LevelTablePanel.class.getClassLoader().getResource("images/down.png")); - Icon icon3 = new ImageIcon(""); - UIManager.put("Tree.collapsedIcon", icon1); - UIManager.put("Tree.textBackground", ColorConstants.TRACE_TABLE_COLOR); - UIManager.put("Tree.expandedIcon", icon2); - UIManager.put("Tree.openIcon", icon3); - UIManager.put("Tree.closedIcon", icon3); - UIManager.put("Tree.leafIcon", icon3); - AgentDataModel agentDataModel = new AgentDataModel(initData(sessionId)); - JTreeTable treeTables = new JTreeTable(agentDataModel); - treeTables.getTableHeader().setBackground(ColorConstants.TRACE_TABLE_COLOR); - treeTables.treeTableCellRenderer.putClientProperty("JTree.lineStyle", "None"); - treeTables.treeTableCellRenderer.addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent treeSelectionEvent) { - // 获取被选中的相关节点 - TreePath path = treeSelectionEvent.getPath(); - } - }); - treeTables.addMouseListener(new MouseAdapter() { - /** - * mouseClicked - * - * @param mouseEvent mouseEvent - */ - public void mouseClicked(MouseEvent mouseEvent) { - treeTables.repaint(); - if (mouseEvent.getClickCount() == 1) { - // 单击悬浮展示table 页面 - jpanelSupenn - .setPreferredSize(new Dimension(LayoutConstants.THREE_HUNDRED, LayoutConstants.THREE_HUNDRED)); - // 获取选中行 - int selectedRow = treeTables.getSelectedRow(); - Object className = treeTables.getValueAt(selectedRow, 0); - if (className instanceof String) { - String clazzName = (String) className; - int cid = new ClassInfoManager().getClassIdByClassName(clazzName); - suspensionTable = - suspensionTablePanel.createSuspensionTable(jpanelSupenn, cid, sessionId, clazzName); - suspensionTable.revalidate(); - suspensionTable.setVisible(true); - } - } - } - }); - return treeTables; - } - - /** - * 初始化treeTable数据 - * - * @param sessionId long - * @return DataNode - */ - public DataNode initData(long sessionId) { - MemoryHeapManager memoryHeapManager = new MemoryHeapManager(); - ChartStandard standard = ProfilerChartsView.sessionMap.get(sessionId).getObserver().getStandard(); - ChartDataRange selectedRang = standard.getSelectedRange(); - long firstTime = standard.getFirstTimestamp(); - long startTimeNew = firstTime + selectedRang.getStartTime(); - long endTimeNew = firstTime + selectedRang.getEndTime(); - - List memoryHeapInfos = - memoryHeapManager.getMemoryHeapInfos(sessionId, startTimeNew, endTimeNew); - DataNode dataNode = new DataNode(); - Integer totalAllocations = 0; - Integer totalDeallocations = 0; - Integer totalTotalCount = 0; - Long totalShallowSize = 0L; - for (MemoryHeapInfo meInfo : memoryHeapInfos) { - dataNode.addChildren(buildClassNode(meInfo)); - totalAllocations = totalAllocations + meInfo.getAllocations(); - totalDeallocations = totalDeallocations + meInfo.getDeallocations(); - totalTotalCount = totalTotalCount + meInfo.getTotalCount(); - totalShallowSize = totalShallowSize + meInfo.getShallowSize(); - } - dataNode.setClassName("app heap"); - dataNode.setAllocations(totalAllocations); - dataNode.setDeallocations(totalDeallocations); - dataNode.setTotalCount(totalTotalCount); - dataNode.setShallowSize(totalShallowSize); - return dataNode; - } - - /** - * 初始化treeTable数据 - * - * @param sessionId long - * @return DataNode - */ - public DataNode reData(long sessionId) { - MemoryHeapManager memoryHeapManager = new MemoryHeapManager(); - ChartStandard standard = ProfilerChartsView.sessionMap.get(sessionId).getObserver().getStandard(); - long firstTime = standard.getFirstTimestamp(); - ChartDataRange selectedRange = standard.getSelectedRange(); - long startTimeNew = selectedRange.getStartTime() + firstTime; - long endTimeNew = selectedRange.getEndTime() + firstTime; - List memoryHeapInfos = - memoryHeapManager.getMemoryHeapInfos(standard.getSessionId(), startTimeNew, endTimeNew); - DataNode dataNode = new DataNode(); - Integer totalAllocations = 0; - Integer totalDeallocations = 0; - Integer totalTotalCount = 0; - Long totalShallowSize = 0L; - for (MemoryHeapInfo meInfo : memoryHeapInfos) { - dataNode.addChildren(buildClassNode(meInfo)); - totalAllocations = totalAllocations + meInfo.getAllocations(); - totalDeallocations = totalDeallocations + meInfo.getDeallocations(); - totalTotalCount = totalTotalCount + meInfo.getTotalCount(); - totalShallowSize = totalShallowSize + meInfo.getShallowSize(); - } - dataNode.setClassName("app heap"); - dataNode.setAllocations(totalAllocations); - dataNode.setDeallocations(totalDeallocations); - dataNode.setTotalCount(totalTotalCount); - dataNode.setShallowSize(totalShallowSize); - return dataNode; - } - - /** - * buildClassNode - * - * @param mhi mhi - * @return DataNode - */ - public DataNode buildClassNode(MemoryHeapInfo mhi) { - if (mhi == null) { - return new DataNode(); - } - DataNode dataNode = new DataNode(); - dataNode.setId(mhi.getId()); - dataNode.setcId(mhi.getcId()); - dataNode.setHeapId(mhi.getHeapId()); - dataNode.setSessionId(mhi.getSessionId()); - dataNode.setClassName(mhi.getClassName()); - dataNode.setAllocations(mhi.getAllocations()); - dataNode.setDeallocations(mhi.getDeallocations()); - dataNode.setTotalCount(mhi.getTotalCount()); - dataNode.setShallowSize(mhi.getShallowSize()); - return dataNode; - } - - /** - * 选取数据 - * - * @param treeTable treeTable - * @return JPanel - */ - public JPanel selectData(JTreeTable treeTable) { - JPanel jpanel = new JPanel(null); - jpanel.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.DEVICE_Y)); - JTextFieldTable jTextField = new JTextFieldTable("level"); - jTextField.setBounds(LayoutConstants.SEARCH_NUM, 0, LayoutConstants.DEVICE_NAME_X, LayoutConstants.DEVICE_Y); - jpanel.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - super.componentResized(event); - jTextField.setBounds(LayoutConstants.SEARCH_NUM + (jpanel.getWidth() - LayoutConstants.WINDOW_WIDTH), 0, - LayoutConstants.DEVICE_NAME_X, LayoutConstants.DEVICE_Y); - } - }); - Label lb = new Label("Table"); - lb.setBounds(LayoutConstants.JP_RIGHT_WIDTH, 0, LayoutConstants.DEVICES_WIDTH, LayoutConstants.DEVICE_Y); - jpanel.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpanel.add(jTextField); - jpanel.add(lb); - jTextField.getDocument().addDocumentListener(new DocumentListener() { - /** - * insertUpdate - * - * @param exception exception - */ - @Override - public void insertUpdate(DocumentEvent exception) { - TreePath pathForRow = treeTable.treeTableCellRenderer.getPathForRow(treeTable.getSelectedRow()); - TreePath com1 = treeTable.treeTableCellRenderer - .getNextMatch(jTextField.getText(), LayoutConstants.NEGATIVE_ONE, Position.Bias.Forward); - treeTable.treeTableCellRenderer.setSelectionPath(com1); - } - - /** - * removeUpdate - * - * @param exception exception - */ - @Override - public void removeUpdate(DocumentEvent exception) { - } - - /** - * changedUpdate - * - * @param exception exception - */ - @Override - public void changedUpdate(DocumentEvent exception) { - } - }); - jTextField.addActionListener(new ActionListener() { - /** - * actionPerformed - * - * @param actionEvent actionEvent - */ - @Override - public void actionPerformed(ActionEvent actionEvent) { - TreePath pathForRow = treeTable.treeTableCellRenderer.getPathForRow(treeTable.getSelectedRow()); - TreePath com1 = treeTable.treeTableCellRenderer - .getNextMatch(jTextField.getText(), treeTable.getSelectedRow(), Position.Bias.Forward); - treeTable.treeTableCellRenderer.setSelectionPath(com1); - } - }); - return jpanel; - } - - /** - * setTreeData - * - * @param sessionId long - * @return FileSystemModel - */ - public AgentDataModel getTreeDataModel(long sessionId) { - DataNode data = reData(sessionId); - return new AgentDataModel(data); - } - - /** - * getTreeTable - * - * @return JTreeTable - */ - public JTreeTable getTreeTable() { - return treeTable; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SuspensionTablePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SuspensionTablePanel.java deleted file mode 100644 index 946d5a340..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SuspensionTablePanel.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import com.intellij.ui.components.JBScrollPane; -import com.intellij.ui.table.JBTable; -import ohos.devtools.services.memory.MemoryInstanceDetailsInfo; -import ohos.devtools.services.memory.MemoryInstanceDetailsManager; -import ohos.devtools.services.memory.MemoryInstanceInfo; -import ohos.devtools.services.memory.MemoryInstanceManager; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.event.TaskScenePanelChartEvent; - -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.RowSorter; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.table.DefaultTableModel; -import javax.swing.table.TableColumnModel; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Label; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Vector; -import java.util.concurrent.TimeUnit; - -/** - * 悬浮table 展示 - * - * @version 1.0 - * @date 2021/3/12 18:44 - **/ -public class SuspensionTablePanel extends TaskScenePanelChartEvent { - private boolean flag = false; - - private JTable jTable; - private JPanel jp = new JPanel(new BorderLayout()); - - /** - * 设置悬浮table - * - * @param jpanelSupenn Supen jpanel - * @param cId cId - * @param sessionId sessionId - * @param className Name class - * @return JPanel - */ - public JPanel createSuspensionTable(JPanel jpanelSupenn, Integer cId, long sessionId, String className) { - jpanelSupenn.setLayout(new BorderLayout()); - Vector columnNames = new Vector<>(); - columnNames.add("instance"); - columnNames.add("allocTime"); - columnNames.add("DealloTime"); - columnNames.add("ID"); - columnNames.add("InstanceId"); - DefaultTableModel model = new DefaultTableModel(); - model.setColumnIdentifiers(columnNames); - initData(model, cId, className, sessionId); - JBTable table = new JBTable(model); - setExtracted(model, table); - JBScrollPane jScrollPane = new JBScrollPane(table); - jScrollPane.setBorder(BorderFactory.createEmptyBorder()); - JPanel jpTop = getTopJPanel(); - JLabel jb = - new JLabel(new ImageIcon(SuspensionTablePanel.class.getClassLoader().getResource("images/close.png"))); - jb.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - jpanelSupenn.setVisible(false); - } - }); - - JPanel jPanel = new JPanel(new BorderLayout()); - jpTop.add(jb, BorderLayout.EAST); - jPanel.add(jpTop, BorderLayout.NORTH); - - JLayeredPane jLayeredPane = new JLayeredPane(); - - jPanel.add(jScrollPane, BorderLayout.CENTER); - jPanel.setBounds(0, 0, LayoutConstants.THREE_HUNDRED, LayoutConstants.THREE_HUNDRED); - jLayeredPane.add(jPanel, JLayeredPane.PALETTE_LAYER); - jpanelSupenn.removeAll(); - jpanelSupenn.add(jLayeredPane); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - flag = true; - if (mouseEvent.getClickCount() == 1) { - getJTable(table, jpanelSupenn, jLayeredPane); - } - } - }); - return jpanelSupenn; - } - - /** - * get JTable - * - * @param table table - * @param jPanelSuspension jPanelSuspension - * @param jLayeredPane jLayeredPane - */ - private void getJTable(JBTable table, JPanel jPanelSuspension, JLayeredPane jLayeredPane) { - int selectedRow = table.getSelectedRow(); - RowSorter rowSorter = null; - Object sorterObj = table.getRowSorter(); - if (sorterObj instanceof RowSorter) { - rowSorter = (RowSorter) sorterObj; - DefaultTableModel detailModel = null; - Object modelObj = rowSorter.getModel(); - if (modelObj instanceof DefaultTableModel) { - detailModel = (DefaultTableModel) modelObj; - Vector detailModeldatas = detailModel.getDataVector(); - Vector detailModeldata = detailModeldatas.get(selectedRow); - Integer instanceId = 0; - Object dataObj = detailModeldata.get(4); - if (dataObj instanceof Integer) { - instanceId = (Integer) dataObj; - jTable = createChildTable(instanceId, flag, jPanelSuspension, jLayeredPane); - } - } - } - } - - private void setExtracted(DefaultTableModel model, JBTable table) { - TableColumnModel tcm = table.getColumnModel(); - table.removeColumn(tcm.getColumn(4)); - table.removeColumn(tcm.getColumn(3)); - table.getTableHeader().setBackground(ColorConstants.TRACE_TABLE_COLOR); - jp.setBackground(ColorConstants.TRACE_TABLE_COLOR); - table.setShowHorizontalLines(false); - table.setBackground(ColorConstants.TRACE_TABLE_COLOR); - RowSorter sorter = new TableRowSorter(model); - table.setRowSorter(sorter); - } - - private JPanel getTopJPanel() { - JLabel label = new JLabel("instanceView"); - label.setOpaque(true); - label.setBackground(ColorConstants.TRACE_TABLE_COLOR); - label.setPreferredSize(new Dimension(LayoutConstants.TASK_DEC_X, LayoutConstants.THIRTY)); - JPanel jpTop = new JPanel(new BorderLayout()); - jpTop.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpTop.add(label, BorderLayout.WEST); - return jpTop; - } - - /** - * 初始化table 表格 - * - * @param model model - * @param cId cId - * @param className className - * @param sessionId long - */ - public void initData(DefaultTableModel model, Integer cId, String className, long sessionId) { - MemoryInstanceManager memoryInstanceManager = new MemoryInstanceManager(); - ChartStandard standard = ProfilerChartsView.sessionMap.get(sessionId).getObserver().getStandard(); - long firstTime = standard.getFirstTimestamp(); - ChartDataRange selectedRange = standard.getSelectedRange(); - long startTime = selectedRange.getStartTime() + firstTime; - long endTime = selectedRange.getEndTime() + firstTime; - List memoryInstanceInfos = - memoryInstanceManager.getMemoryInstanceInfos(cId, startTime, endTime); - memoryInstanceInfos.forEach(memoryInstanceInfo -> { - long deallocTime = memoryInstanceInfo.getDeallocTime(); - long alloc = TimeUnit.MILLISECONDS.toMicros(memoryInstanceInfo.getAllocTime() - firstTime); - String allocTime = getSemiSimplifiedClockString(alloc); - String dellTime = "-- : -- : --"; - if (deallocTime != 0) { - long delloc = TimeUnit.MILLISECONDS.toMicros(memoryInstanceInfo.getDeallocTime() - firstTime); - dellTime = getSemiSimplifiedClockString(delloc); - } - Integer id = memoryInstanceInfo.getId(); - Integer instanceId = memoryInstanceInfo.getInstanceId(); - Vector rowData = new Vector<>(); - rowData.add(className); - rowData.add(allocTime); - rowData.add(dellTime); - rowData.add(id); - rowData.add(instanceId); - model.addRow(rowData); - }); - } - - /** - * Return a formatted time String in the form of "hh:mm:ss.sss". - * Default format for Range description. - * - * @param micro micro - * @return String - */ - public String getFullClockString(long micro) { - long micros = Math.max(0, micro); - long milli = TimeUnit.MICROSECONDS.toMillis(micros) % TimeUnit.SECONDS.toMillis(1); - long sec = TimeUnit.MICROSECONDS.toSeconds(micros) % TimeUnit.MINUTES.toSeconds(1); - long min = TimeUnit.MICROSECONDS.toMinutes(micros) % TimeUnit.HOURS.toMinutes(1); - long hour = TimeUnit.MICROSECONDS.toHours(micros); - return String.format(Locale.ENGLISH, "%02d:%02d:%02d.%03d", hour, min, sec, milli); - } - - /** - * Return a formatted time String in the form of "hh:mm:ss.sss"". - * Hide hours value if both hours and minutes value are zero. - * Default format for Tooltips. - * - * @param micro micro - * @return String - */ - public String getSemiSimplifiedClockString(long micro) { - long micros = Math.max(0, micro); - String result = getFullClockString(micros); - return result.startsWith("00:00:") ? result.substring(3) : result; - } - - /** - * 根据筛选填充table 表格 - * - * @param model model - */ - public void selectData(DefaultTableModel model) { - // 获取初始化数据,根目录 - Vector rowDat = new Vector<>(); - rowDat.add("John"); - model.addRow(rowDat); - } - - /** - * select Data - * - * @return JPanel - */ - public JPanel selectData() { - JPanel jpanel = new JPanel(new BorderLayout()); - JTextField jTextField = new JTextField(); - jTextField.setBackground(ColorConstants.TRACE_TABLE_COLOR); - Label lb = new Label("Table"); - lb.setPreferredSize(new Dimension(LayoutConstants.FORTY, LayoutConstants.TWENTY)); - jpanel.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpanel.add(jTextField, BorderLayout.EAST); - jpanel.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpanel.add(lb, BorderLayout.WEST); - jTextField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent exception) { - } - - @Override - public void removeUpdate(DocumentEvent exception) { - } - - @Override - public void changedUpdate(DocumentEvent exception) { - } - }); - return jpanel; - } - - /** - * 层级展示table 表格 - * - * @param model model - * @param id id - * @param sp sp - */ - public void insertData(DefaultTableModel model, String id, String sp) { - // 根据父亲id,获取子项 - String space = sp + " "; - Vector rowDate = new Vector<>(); - rowDate.add(space + "John"); - rowDate.add(LayoutConstants.EIGHTY); - rowDate.add(LayoutConstants.SEVENTY); - rowDate.add(LayoutConstants.SIXTY); - rowDate.add(LayoutConstants.TWO_HUNDRED_TEN); - rowDate.add(Math.random()); - rowDate.add(id); - rowDate.add("n"); - model.addRow(rowDate); - } - - /** - * 子悬浮table - * - * @param instanceId instanceId - * @param flag flag - * @param jpanelSupenn jpanelSupenn - * @param jLayeredPane jLayeredPane - * @return JTable - */ - public JTable createChildTable(Integer instanceId, boolean flag, JPanel jpanelSupenn, JLayeredPane jLayeredPane) { - Vector columnNames = new Vector<>(); - columnNames.add(""); - DefaultTableModel model = new DefaultTableModel(); - model.setColumnIdentifiers(columnNames); - JTable table = new JTable(model); - table.getTableHeader().setBackground(ColorConstants.TRACE_TABLE_COLOR); - table.setBackground(ColorConstants.TRACE_TABLE_COLOR); - MemoryInstanceDetailsManager detailsManager = new MemoryInstanceDetailsManager(); - ArrayList detailsInfos = detailsManager.getMemoryInstanceDetailsInfos(instanceId); - detailsInfos.forEach(detailsInfo -> { - Vector rowData = new Vector<>(); - rowData.add( - detailsInfo.getClassName() + "::" + detailsInfo.getMethodName() + " " + detailsInfo.getLineNumber() - + " " + detailsInfo.getFieldName()); - model.addRow(rowData); - }); - table.setShowHorizontalLines(false); - JScrollPane jScrollPane = new JScrollPane(table); - jScrollPane.getViewport().setOpaque(true); - jScrollPane.getViewport().setBackground(ColorConstants.TRACE_TABLE_COLOR); - jScrollPane.setBorder(BorderFactory.createEmptyBorder()); - jScrollPane.setBackground(ColorConstants.TRACE_TABLE_COLOR); - JLabel label = new JLabel("Allocation Call Stack "); - label.setPreferredSize(new Dimension(LayoutConstants.TASK_DEC_X, LayoutConstants.THIRTY)); - label.setOpaque(true); - label.setBackground(ColorConstants.TRACE_TABLE_COLOR); - JPanel jpTop = new JPanel(new BorderLayout()); - jpTop.setBackground(ColorConstants.TRACE_TABLE_COLOR); - jpTop.add(label, BorderLayout.WEST); - JLabel jb = - new JLabel(new ImageIcon(SuspensionTablePanel.class.getClassLoader().getResource("images/close.png"))); - jb.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - jLayeredPane.remove(jp); - } - }); - jpTop.add(jb, BorderLayout.EAST); - jp.removeAll(); - jp.add(jpTop, BorderLayout.NORTH); - jp.add(jScrollPane, BorderLayout.CENTER); - jp.setBounds(0, LayoutConstants.THREE_HUNDRED, LayoutConstants.THREE_HUNDRED, - LayoutConstants.THREE_HUNDRED_TWENTY); - jLayeredPane.add(jp, JLayeredPane.DRAG_LAYER); - jLayeredPane.revalidate(); - return table; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningConfigPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningConfigPanel.java deleted file mode 100644 index 49558a4a0..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningConfigPanel.java +++ /dev/null @@ -1,500 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.datatransfer.Clipboard; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.event.SystemTunningConfigEvent; - -/** - * 三级System tuning场景界面 - * - * @version 1.0 - * @date 2021/03/8 11:11 - **/ -public class SystemTunningConfigPanel extends JPanel { - Clipboard clipboard; - /** - * 三级界面边框布局管理器,top容器 - */ - private JPanel jPanelNorth = new JPanel(null); - - /** - * 设备连接方式下拉框(usb,wifi,蓝牙) - */ - private JComboBox jComboBoxConnect = new JComboBox(); - - /** - * 设备名称下拉框 - */ - private JComboBox jComboBoxPhone = new JComboBox(); - - /** - * 设备信息集合 - */ - private List deviceInfos = null; - - /** - * 三级界面边框布局管理器,Center容器 - */ - private JPanel jPanelCenter = new JPanel(new BorderLayout()); - - /** - * 三级界面边框布局管理器,South容器 - */ - private JPanel jPanelSouth = new JPanel(null); - - /** - * top容器中文本描述 - */ - private JLabel jLabelTaskTun = new JLabel("Trace config & Probes"); - - /** - * top容器中文本描述 - */ - private JLabel jLabelDeviceSet = new JLabel("Task scene: System tuning"); - - /** - * Center容器中,Monitor Items页面复选框容器 - */ - private JPanel jPanelRightMemory = new JPanel(null); - - /** - * Monitor Items页面复选框存放数组 - */ - private JCheckBox[] jCheckBoxs = new JCheckBox[LayoutConstants.INDEX_SEVEN]; - - /** - * 三级页面事件类 - */ - private SystemTunningConfigEvent taskSystemTunningPanelEvent = new SystemTunningConfigEvent(); - - /** - * Center容器中,左边布局滚动条容器 - */ - private JPanel scrollPane = new JPanel(null); - - /** - * 返回上一页按钮 - */ - private JButton jButtonLastStep = new JButton("Last Step"); - - /** - * 开始任务按钮 - */ - private JButton jButtonStartTask = new JButton("Start Task"); - - public SystemTunningConfigPanel(TaskPanel jTaskPanel) { - // 设置三级界面布局方式为边框布局管理 - this.setLayout(new BorderLayout()); - // 设置top容器,Center容器,South容器的属性 - setAttributes(); - // Center容器设置 - setjPanelCenter(); - // South容器设置 - setJPanelSouth(jTaskPanel); - } - - /** - * 设置top容器,Center容器,South容器的属性 - */ - public void setAttributes() { - jPanelNorth.setOpaque(true); - jPanelNorth.setBackground(ColorConstants.TOP_PANEL); - jPanelCenter.setOpaque(true); - jPanelCenter.setBackground(ColorConstants.TOP_PANEL); - jPanelSouth.setOpaque(true); - jPanelSouth.setBackground(ColorConstants.TOP_PANEL); - jPanelNorth.setPreferredSize(new Dimension(LayoutConstants.TOP_SOUTH_WIDTH, - LayoutConstants.SYSTEM_TUNNING_TRACE_RECORDING_SETTING_SLIDE_INT_Y)); - jPanelSouth.setPreferredSize(new Dimension(LayoutConstants.WINDOW_WIDTH, LayoutConstants.TOP_SOUTH_HEIGHT)); - this.add(jPanelNorth, BorderLayout.NORTH); - this.add(jPanelCenter, BorderLayout.CENTER); - this.add(jPanelSouth, BorderLayout.SOUTH); - - JLabel jLabelDeviceNum = new JLabel("Device"); - Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TASK_LABEL_FONT); - jLabelDeviceNum.setFont(fontTaskTun); - jLabelDeviceNum.setForeground(Color.white); - jLabelDeviceNum - .setBounds(LayoutConstants.CHOOSE_HEIGHT, LayoutConstants.JP_RIGHT_WIDTH, LayoutConstants.TASK_LABEL_WIDTH, - LayoutConstants.TASK_LABEL_HEIGHT); - jComboBoxConnect.addItem("USB"); - jComboBoxConnect - .setBounds(LayoutConstants.CHOOSE_HEIGHT, LayoutConstants.SYSTEM_TUNNING_DEVICE_COMBOX_EQUIPMENT_INIT_Y, - LayoutConstants.CON_BOX_WIDTH, LayoutConstants.TASK_SCENE_Y); - deviceInfos = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - taskSystemTunningPanelEvent.devicesInfoJComboBoxUpdate(this); - jComboBoxPhone - .setBounds(LayoutConstants.RIGHT_BUN_WIDTH, LayoutConstants.SYSTEM_TUNNING_DEVICE_COMBOX_EQUIPMENT_INIT_Y, - LayoutConstants.HEIGHT_PRESSE, LayoutConstants.TASK_SCENE_Y); - taskSystemTunningPanelEvent.itemStateChanged(this); - - jLabelTaskTun.setBounds(LayoutConstants.SYSTEM_TUNNING_CENTER_LEFT_AND_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_TRACE_CONFIG_AND_PROBES_INIT_Y, LayoutConstants.TASK_LABEL_WIDTH, - LayoutConstants.SYSTEM_TUNNING_ALL_LABEL_INIT_HEIGHT); - jLabelTaskTun.setFont(fontTaskTun); - jLabelTaskTun.setForeground(Color.WHITE); - jPanelNorth.add(jLabelDeviceNum); - jPanelNorth.add(jComboBoxConnect); - jPanelNorth.add(jComboBoxPhone); - jPanelNorth.add(jLabelTaskTun); - Font fontDeviceSet = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TASK_DEC_FONT); - jLabelDeviceSet.setFont(fontDeviceSet); - jLabelDeviceSet.setBounds(LayoutConstants.TASK_DEC_X, LayoutConstants.SYSTEM_TUNNING_SAMLL_TASH_SCENEINIT_Y, - LayoutConstants.TASK_DEC_WIDTH, LayoutConstants.TASK_DEC_HEIGHT); - jPanelNorth.add(jLabelDeviceSet); - } - - /** - * setDeviceInfos - * - * @param deviceInfos deviceInfos - */ - public void setDeviceInfos(List deviceInfos) { - this.deviceInfos = deviceInfos; - } - - /** - * getJComboBoxPhone - * - * @return JComboBox - */ - public JComboBox getJComboBoxPhone() { - return jComboBoxPhone; - } - - /** - * getDeviceInfos - * - * @return List - */ - public List getDeviceInfos() { - return deviceInfos; - } - - /** - * system tunning 设置页面 - */ - public void setjPanelCenter() { - // 左右黑色边框 - JPanel jPanelCenterLeft = new JPanel(); - jPanelCenterLeft.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_CENTER_LEFT_AND_RIGHT_X, LayoutConstants.DEFAULT_NUMBER)); - jPanelCenterLeft.setBackground(ColorConstants.SYSTEM_TUNNING_SETTING_BACK); - JPanel jPanelCenterEast = new JPanel(); - jPanelCenterEast.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_CENTER_LEFT_AND_RIGHT_X, LayoutConstants.DEFAULT_NUMBER)); - jPanelCenterEast.setBackground(ColorConstants.SYSTEM_TUNNING_SETTING_BACK); - - JLabel traceConfig = new JLabel("Trace config", JLabel.CENTER); - traceConfig.setForeground(Color.white); - traceConfig - .setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_FONT)); - traceConfig.setPreferredSize(new Dimension(LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_WIDTH_INIT, - LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_HEIGHT_INIT)); - JLabel probes = new JLabel("Probes", JLabel.CENTER); - probes.setForeground(Color.white); - probes.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_FONT)); - probes.setPreferredSize(new Dimension(LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_WIDTH_INIT, - LayoutConstants.SYSTEM_TUNNING_TABBEDPANE_TRACE_CONFIG_HEIGHT_INIT)); - - JPanel traceConfigTab = new JPanel(new BorderLayout()); - traceConfigTab.add(traceConfig); - JPanel probesTab = new JPanel(new BorderLayout()); - JTabbedPane tab = new JTabbedPane(); - tab.addTab("", traceConfigTab); - tab.addTab("", probesTab); - tab.setTabComponentAt(tab.indexOfComponent(traceConfigTab), traceConfig); - tab.setTabComponentAt(tab.indexOfComponent(probesTab), probes); - - JPanel jPanelCenterTop = new JPanel(new BorderLayout()); - jPanelCenterTop.add(tab); - jPanelCenterTop.setBackground(ColorConstants.SYSTEM_TUNNING_SETTING_CENTER); - JPanel jPanelCenterSouthWest = new JPanel(null); - JPanel jPanelCenterSouthRight = new JPanel(null); - traceConfig(jPanelCenterSouthWest, jPanelCenterSouthRight); - traceConfigTab.add(jPanelCenterSouthWest, BorderLayout.WEST); - traceConfigTab.add(jPanelCenterSouthRight, BorderLayout.CENTER); - JPanel jPanelCenterSouthWestP2 = new JPanel(null); - JPanel jPanelCenterSouthEastP2 = new JPanel(null); - systemTunningProbes(jPanelCenterSouthWestP2, jPanelCenterSouthEastP2); - probesTab.add(jPanelCenterSouthWestP2, BorderLayout.WEST); - probesTab.add(jPanelCenterSouthEastP2, BorderLayout.CENTER); - jPanelCenter.add(jPanelCenterLeft, BorderLayout.WEST); - jPanelCenter.add(jPanelCenterTop, BorderLayout.CENTER); - jPanelCenter.add(jPanelCenterEast, BorderLayout.EAST); - } - - /** - * traceConfig - * - * @param jPanelCenterSouthWest jPanelCenterSouthWest - * @param jPanelCenterSouthRight jPanelCenterSouthRight - */ - public void traceConfig(JPanel jPanelCenterSouthWest, JPanel jPanelCenterSouthRight) { - JLabel recordSettingLabel = new JLabel( - "

Record Setting

" - + "

Buffer mode.size and duration

", JLabel.CENTER); - recordSettingLabel.setOpaque(true); - - recordSettingLabel.setBounds(LayoutConstants.DEFAULT_NUMBER, LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_SLIDE_LABLE_HEIGHT); - JLabel traceCommandLabel = new JLabel("

Trace command

Manually record trace

", JLabel.CENTER); - traceCommandLabel.setBounds(LayoutConstants.DEFAULT_NUMBER, - LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y + LayoutConstants.SYSTEM_TUNNING_SLIDE_LABLE_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_SLIDE_LABLE_HEIGHT); - - taskSystemTunningPanelEvent - .recordSetting(recordSettingLabel, traceCommandLabel, jPanelCenterSouthRight, jPanelCenterSouthWest); - taskSystemTunningPanelEvent - .traceCommand(recordSettingLabel, traceCommandLabel, jPanelCenterSouthRight, jPanelCenterSouthWest); - - jPanelCenterSouthWest.add(recordSettingLabel); - jPanelCenterSouthWest.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.DEFAULT_NUMBER)); - jPanelCenterSouthWest.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - } - - /** - * systemTunningProbes - * - * @param jPanelCenterSouthWestP2 jPanelCenterSouthWestP2 - * @param jPanelCenterSouthEastP2 jPanelCenterSouthEastP2 - */ - public void systemTunningProbes(JPanel jPanelCenterSouthWestP2, JPanel jPanelCenterSouthEastP2) { - JLabel probesCpu = new JLabel("

probes config

CPU usage,scheduling," + "
" + "wakeups

", JLabel.CENTER); - probesCpu.setOpaque(true); - probesCpu.setBounds(LayoutConstants.DEFAULT_NUMBER, LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_SLIDE_LABLE_HEIGHT); - systemTunningProbesCpuRightShow(jPanelCenterSouthEastP2); - jPanelCenterSouthWestP2.add(probesCpu); - jPanelCenterSouthWestP2.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, LayoutConstants.DEFAULT_NUMBER)); - jPanelCenterSouthWestP2.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - } - - /** - * jPanelCenterSouthEastP2 settings - * - * @param jPanelCenterSouthEastP2 jPanelCenterSouthEastP2 - */ - public void systemTunningProbesCpuRightShow(JPanel jPanelCenterSouthEastP2) { - jPanelCenterSouthEastP2.removeAll(); - // 右边四个、左侧三个复选框 - jCheckBoxAttributeRight(jPanelCenterSouthEastP2); - jCheckBoxAttributeLeft(jPanelCenterSouthEastP2); - JLabel memoryLabel2 = new JLabel( - "

" - + "enables high-detailed tracking of scheduling events" + "

", JLabel.LEFT); - memoryLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_SCHEDULING_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthEastP2.add(memoryLabel2); - JLabel cPUFrequencyLabel2 = cPUFrequencyLabel2(); - jPanelCenterSouthEastP2.add(cPUFrequencyLabel2); - JLabel syscallsLabel2 = new JLabel("

" - + "Tracks the enter and exit of all syscalls" + "

", JLabel.LEFT); - syscallsLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_SYSCALLS_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - JLabel boardVoltagesLabel2 = new JLabel("

" - + "Tracks voltage and frequency changes from board sensors " + "

", JLabel.LEFT); - boardVoltagesLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_SCHEDULING_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, - LayoutConstants.SYSTEM_TUNNING_CHECKBOX_LABLE_HEIGHT); - jPanelCenterSouthEastP2.add(boardVoltagesLabel2); - JLabel highFrequencyLabel2 = new JLabel("

" - + "Allows to track short memory splikes and transitories through ftrace's mm_event. " - + "rss_stat and ion events. Available only on recent system kernels" + "

", JLabel.LEFT); - highFrequencyLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_HIGH_FREQUENCY_MEMORY_LABEL_INIT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, LayoutConstants.SYSTEM_TUNNING_CHECKBOX_LABLE_HEIGHT); - JLabel lowMemoryLabel2 = new JLabel("

" - + "Record LMK events. Works both with the old in kernel LMK and " - + "the newer userspace Imkd. It also tracks OOM score adjustments " + "

", JLabel.LEFT); - lowMemoryLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_LOW_MEMORY_KILLER_LABEL_INIT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, LayoutConstants.SYSTEM_TUNNING_CHECKBOX_LABLE_HEIGHT); - jPanelCenterSouthEastP2.add(lowMemoryLabel2); - JLabel atraceUserspaceLabel2 = new JLabel("

" - + "Enables C++ / Java codebase annotations (ATRACE_BEGIN() / os.Trace())" + "

", JLabel.LEFT); - atraceUserspaceLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_ATRACE_USERSPACE_ANNOTATIONS_LABEL_INIT_Y, - LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthEastP2.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - jPanelCenterSouthEastP2.repaint(); - } - - /** - * cPUFrequencyLabel2 - * - * @return JLabel - */ - public JLabel cPUFrequencyLabel2() { - JLabel cPUFrequencyLabel2 = new JLabel( - "

" - + "Records cpu frequency and idle state change viaftrace" + "

", JLabel.LEFT); - cPUFrequencyLabel2.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE_INTT_X, - LayoutConstants.SYSTEM_TUNNING_PROBES_CPU_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_DESCRIBE, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - return cPUFrequencyLabel2; - } - - /** - * jCheckBoxAttributeRight - * - * @param jPanelCenterSouthEastP2 jPanelCenterSouthEastP2 - */ - public void jCheckBoxAttributeRight(JPanel jPanelCenterSouthEastP2) { - JLabel label1 = new JLabel("Record model"); - - label1.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_RECORD_MODEL_LABLE_INTT_Y, LayoutConstants.SYSTEM_TUNNING_LABLE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - // 创建JCheckBox对象 - JCheckBox rbScheduling = new JCheckBox("Scheduling details", true); - JCheckBox rbCpu = new JCheckBox("CPU Frequency and idle states", true); - JCheckBox rbSyscalls = new JCheckBox("Syscalls", false); - JCheckBox rbBoard = new JCheckBox("Board voltages & frequency", false); - rbScheduling.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbCpu.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbSyscalls.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbBoard.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - - rbScheduling.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbCpu.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbSyscalls.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbBoard.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbScheduling - .setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rbCpu.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y + LayoutConstants.SYSTEM_TUNNING_PROBES_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rbSyscalls.setBounds(LayoutConstants.SYSTEM_TUNNING_LABEL_INTT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y + LayoutConstants.SYSTEM_TUNNING_PROBES_DOUBLE_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rbBoard.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthEastP2.add(label1); - jPanelCenterSouthEastP2.add(rbScheduling); - jPanelCenterSouthEastP2.add(rbCpu); - jPanelCenterSouthEastP2.add(rbBoard); - taskSystemTunningPanelEvent.checkBoxState(rbScheduling, rbCpu, rbSyscalls, rbBoard); - } - - /** - * jCheckBoxAttributeLeft - * - * @param jPanelCenterSouthEastP2 jPanelCenterSouthEastP2 - */ - public void jCheckBoxAttributeLeft(JPanel jPanelCenterSouthEastP2) { - JCheckBox rbFrequency = new JCheckBox("High frequency memory", false); - JCheckBox rbLowMemory = new JCheckBox("Low memory killer", false); - JCheckBox rbAtrace = new JCheckBox("Atrace userspace annotations", false); - // 右侧三个复选框 - rbFrequency.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbLowMemory.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbAtrace.setFont(new Font(Font.DIALOG, Font.BOLD, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_FONT)); - rbFrequency.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbLowMemory.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbAtrace.setBackground(ColorConstants.SYSTEM_TUNNING_WEST_LABEL); - rbFrequency.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rbLowMemory.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y + LayoutConstants.SYSTEM_TUNNING_PROBES_SPACING_Y, - LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - rbAtrace.setBounds(LayoutConstants.SYSTEM_TUNNING_LABLE_INTT_RIGHT_X, - LayoutConstants.SYSTEM_TUNNING_LABLE_SPACING_Y + LayoutConstants.SYSTEM_TUNNING_PROBES_DOUBLE_SPACING_Y - + LayoutConstants.SYSTEM_TUNNING_PROBES_SPACING_Y, LayoutConstants.SYSTEM_TUNNING_JCHECKBOX_LABLE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LABLE_HEIGHT); - jPanelCenterSouthEastP2.add(rbLowMemory); - taskSystemTunningPanelEvent.checkBoxStateLeft(rbFrequency, rbLowMemory, rbAtrace); - } - - /** - * SouthContainer settings - * - * @param jTaskPanel jTaskPanel - */ - public void setJPanelSouth(TaskPanel jTaskPanel) { - jButtonLastStep.setBounds((int) (LayoutConstants.NUMBER_STEP + (jPanelSouth.getPreferredSize().getWidth() - - LayoutConstants.WINDOW_WIDTH)), LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.DEVICES_WIDTH, - LayoutConstants.DEVICE_X); - jButtonLastStep.setBackground(ColorConstants.BLACK_COLOR); - jButtonLastStep.setFocusPainted(false); - jButtonStartTask.setForeground(Color.white); - - jButtonStartTask.setBounds((int) (LayoutConstants.POSITION_TASK_X + (jPanelSouth.getPreferredSize().getWidth() - - LayoutConstants.WINDOW_WIDTH)), LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.DEVICES_WIDTH, - LayoutConstants.DEVICE_X); - jButtonStartTask.setBackground(ColorConstants.ADD_DEVICE_BUN); - jButtonStartTask.setFocusPainted(false); - jPanelSouth.add(jButtonLastStep); - jPanelSouth.add(jButtonStartTask); - // 监听jPanelSouth大小变化并改变按钮位置 - taskSystemTunningPanelEvent.listenerJPanelSouth(this); - // jButtonLastStep添加事件返回上一页 - taskSystemTunningPanelEvent.lastStep(this, jTaskPanel); - // jButtonStartTask添加事件开始任务 - taskSystemTunningPanelEvent.startTask(this, jTaskPanel); - } - - public JPanel getScrollPane() { - return scrollPane; - } - - public JPanel getJPanelSouth() { - return jPanelSouth; - } - - public JButton getJButtonLastStep() { - return jButtonLastStep; - } - - public JButton getJButtonStartTask() { - return jButtonStartTask; - } - - public JCheckBox[] getJCheckBoxs() { - return jCheckBoxs; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningLoadDialog.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningLoadDialog.java deleted file mode 100644 index 3d5d16162..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/SystemTunningLoadDialog.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.datasources.utils.trace.service.TraceManager; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.SystemTunningProbesCheckbox; -import ohos.devtools.views.layout.event.SystemTunningDialogEvent; -import ohos.devtools.views.trace.component.AnalystPanel; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.Timer; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.Date; -import java.util.Locale; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @Description TaskSystemLoad - * @Date 2021/4/10 15:16 - **/ -public class SystemTunningLoadDialog implements ActionListener { - private static final Logger LOGGER = LogManager.getLogger(SystemTunningLoadDialog.class); - private Date executeArrivalToTime = null; - private int bytraceFileSize; - private int hours = 0; - private int minutes = 0; - private int seconds = 0; - private int maxDurationParam = 0; - private String sessionId; - private DeviceIPPortInfo deviceIPPortInfo; - private int differentRequests = 0; - private Boolean pullBytraceFileState = false; - private Boolean analysisState = false; - /** - * loading - */ - private int hoursLoading = 0; - private int minutesLoading = 0; - private int secondsLoading = 0; - - private TaskPanel jTaskPanel = null; - - private JPanel jPanel = new JPanel(null); - - private JLabel statusJLabel = new JLabel("Status"); - - private JLabel durationJLabel = new JLabel("Duration"); - - private JLabel recordingJLabel = new JLabel("Recording"); - - private JLabel timeJLabel = new JLabel(); - - private JButton stopJButton = new JButton("Stop"); - - private SystemTunningDialogEvent systemTunningDialogEvent; - - private Timer timer = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); - - private Timer timerLoading = null; - - private JLabel statusAnalysisJLabel = new JLabel("Status"); - - private JLabel durationAnalysisJLabel = new JLabel("Duration"); - - private JLabel loadingJLabel = new JLabel("Loading"); - - private JLabel loadingInitTimeJLabel = new JLabel(" 00:00:00"); - - /** - * load - * - * @param jTaskPanel jTaskPanel - * @param differentRequestsPram differentRequestsPram - * @param maxDurationParam maxDurationParam - * @param sessionIdParam sessionIdParam - * @param deviceIPPortInfoParam deviceIPPortInfoParam - */ - public void load(TaskPanel jTaskPanel, int differentRequestsPram, int maxDurationParam, String sessionIdParam, - DeviceIPPortInfo deviceIPPortInfoParam) { - // 当前时间大于大于采集的时间、小于采集加解析的时间 - if (timer.isRepeats()) { - timer.stop(); - } - timer = new Timer(LayoutConstants.NUMBER_THREAD, this::actionPerformed); - systemTunningDialogEvent = new SystemTunningDialogEvent("Prompt", jPanel); - stopJButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - timer.stop(); - systemTunningDialogEvent.close(1); - new TraceManager().stopAndDestroySession(deviceIPPortInfo, sessionId); - } - }); - this.jTaskPanel = jTaskPanel; - this.maxDurationParam = maxDurationParam; - this.sessionId = sessionIdParam; - this.deviceIPPortInfo = deviceIPPortInfoParam; - this.differentRequests = differentRequestsPram; - jPanel.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_LOADING_WIDTH, LayoutConstants.SYSTEM_TUNNING_LOADING_HEIGHT)); - statusJLabel.setForeground(Color.white); - durationJLabel.setForeground(Color.white); - recordingJLabel.setForeground(Color.white); - timeJLabel.setForeground(Color.white); - this.setLableAttribute(statusJLabel, durationJLabel, recordingJLabel, timeJLabel); - timeJLabel.setText(" 00:00:00"); - jPanel.add(statusJLabel); - jPanel.add(durationJLabel); - jPanel.add(recordingJLabel); - jPanel.add(timeJLabel); - jPanel.add(stopJButton); - timer.start(); - systemTunningDialogEvent.show(); - } - - /** - * actionPerformed - * - * @param actionEvent actionEvent - */ - public void actionPerformed(ActionEvent actionEvent) { - if ((hours * SystemTunningProbesCheckbox.MINUTE_TO_S * SystemTunningProbesCheckbox.MINUTE_TO_S - + minutes * SystemTunningProbesCheckbox.MINUTE_TO_S + seconds) > maxDurationParam) { - timer.stop(); - // 加载展示页面 - this.loading(); - } - if (seconds <= LayoutConstants.NUMBER_SECONDS) { - timeJLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hours) + ":" + String - .format(Locale.ENGLISH, "%02d", minutes) + ":" + String.format(Locale.ENGLISH, "%02d", seconds)); - seconds++; - if (seconds > LayoutConstants.NUMBER_SECONDS) { - seconds = 0; - minutes++; - if (minutes > LayoutConstants.NUMBER_SECONDS) { - minutes = 0; - hours++; - } - } - } - } - - /** - * loading - */ - public void loading() { - pullBytraceFileState = true; - timerLoading = new Timer(LayoutConstants.NUMBER_THREAD, this::actionLoadingPerformed); - jPanel.setPreferredSize( - new Dimension(LayoutConstants.SYSTEM_TUNNING_LOADING_WIDTH, LayoutConstants.SYSTEM_TUNNING_LOADING_HEIGHT)); - statusAnalysisJLabel.setForeground(Color.white); - durationAnalysisJLabel.setForeground(Color.white); - loadingJLabel.setForeground(Color.white); - loadingInitTimeJLabel.setForeground(Color.white); - this.setLableAttribute(statusAnalysisJLabel, durationAnalysisJLabel, loadingJLabel, loadingInitTimeJLabel); - jPanel.removeAll(); - jPanel.add(statusAnalysisJLabel); - jPanel.add(durationAnalysisJLabel); - jPanel.add(loadingJLabel); - jPanel.add(loadingInitTimeJLabel); - timerLoading.start(); - systemTunningDialogEvent.repaint(); - } - - - /** - * actionLoadingPerformed - * - * @param actionEvent actionEvent - */ - public void actionLoadingPerformed(ActionEvent actionEvent) { - if (secondsLoading <= LayoutConstants.NUMBER_SECONDS) { - loadingInitTimeJLabel.setText(" " + String.format(Locale.ENGLISH, "%02d", hoursLoading) + ":" + String - .format(Locale.ENGLISH, "%02d", minutesLoading) + ":" + String - .format(Locale.ENGLISH, "%02d", secondsLoading)); - secondsLoading++; - if (secondsLoading > LayoutConstants.NUMBER_SECONDS) { - secondsLoading = 0; - minutesLoading++; - if (minutesLoading > LayoutConstants.NUMBER_SECONDS) { - minutesLoading = 0; - hoursLoading++; - } - } - int num = secondsLoading % 2; - if (pullBytraceFileState && num == 0) { - String getBytraceFileInfoCmd = "hdc shell du /data/local/tmp/hiprofiler_data.bytrace "; - String bytraceFileInfo = HdcWrapper.getInstance().getHdcStringResult(getBytraceFileInfoCmd); - if (bytraceFileInfo != null && bytraceFileInfo.length() > 0) { - String[] bytraceFileInfoArray = bytraceFileInfo.split("\t"); - if (bytraceFileSize != 0 && bytraceFileSize == Integer.valueOf(bytraceFileInfoArray[0])) { - pullBytraceFileState = false; - pullAndAnalysisBytraceFile(); - }else { - bytraceFileSize = Integer.valueOf(bytraceFileInfoArray[0]); - } - } - } - } - if (analysisState) { - timerLoading.stop(); - systemTunningDialogEvent.close(1); - } - } - - /** - * pull and analysis bytrace file - * - */ - public void pullAndAnalysisBytraceFile() { - ExecutorService executor = Executors.newSingleThreadExecutor(); - executor.execute(new Runnable() { - @Override - public void run() { - getBytraceFile(); - String baseDir = SessionManager.getInstance().getPluginPath() + "trace_streamer\\"; - String dbPath = baseDir + "systrace.db"; - File file = new File(baseDir); - String cmd = baseDir + "trace_streamer.exe"; - if (differentRequests == 0) { - cmd = cmd + " " + baseDir + "hiprofiler_data.bytrace"; - } - if (differentRequests == 1) { - cmd = cmd + " " + baseDir + "hiprofiler_data.ptrace"; - } - cmd = cmd + " -e " + dbPath; - LOGGER.info("cmd: {}", cmd); - HdcWrapper.getInstance().getHdcStringResult(cmd); - jTaskPanel.getOptionJPanel().removeAll(); - AnalystPanel component = new AnalystPanel(); - component.load(dbPath, true); - jTaskPanel.getOptionJPanel().add(component); - jTaskPanel.repaint(); - analysisState = true; - } - }); - } - - /** - * get bytrace file - * - */ - public void getBytraceFile() { - String pluginPath = SessionManager.getInstance().getPluginPath() + "trace_streamer\\"; - LOGGER.info("start >>> hdc file recv /data/local/tmp/hiprofiler_data.bytrace"); - String cmd = null; - if (differentRequests == 0) { - cmd = "hdc file recv /data/local/tmp/hiprofiler_data.bytrace " + pluginPath; - } - if (differentRequests == 1) { - cmd = "hdc file recv /data/local/tmp/hiprofiler_data.ptrace " + pluginPath; - } - HdcWrapper.getInstance().execCmdBy(cmd, LayoutConstants.TEN); - - // 抓取数据结束,获取ptrace数据到本地过后,stopSession、destroySession - new TraceManager().stopAndDestroySession(deviceIPPortInfo, sessionId); - LOGGER.info("end >>> hdc file recv /data/local/tmp/hiprofiler_data.ptrace"); - } - - /** - * set Label Attribute - * - * @param statusJLabelParam statusJLabelParam - * @param durationJLabelParam durationJLabelParam - * @param recordingJLabelParam recordingJLabelParam - * @param timeJLabelParam timeJLabelParam - */ - public void setLableAttribute(JLabel statusJLabelParam, JLabel durationJLabelParam, - JLabel recordingJLabelParam, JLabel timeJLabelParam) { - statusJLabelParam.setBounds(LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_X, - LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_INITLINE_ONE_Y, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT); - recordingJLabelParam.setBounds(LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_LINE_TWO_X, - LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_INITLINE_ONE_Y, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT); - durationJLabelParam.setBounds(LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_X, - LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_INITLINE_TWO_Y, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT); - timeJLabelParam.setBounds(LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_LINE_TWO_X, - LayoutConstants.SYSTEM_TUNNING_LOADING_INIT_INITLINE_TWO_Y, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT); - stopJButton - .setBounds(LayoutConstants.SYSTEM_TUNNING_LOADING_HEIGHT, LayoutConstants.SYSTEM_TUNNING_LOADING_BUTTON_Y, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_WIDTH, - LayoutConstants.SYSTEM_TUNNING_LOADING_INITLINE_ONE_HEIGHT); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanel.java deleted file mode 100644 index 6625873f4..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanel.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.datasources.transport.hdc.HdcWrapper; -import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJLabel; -import ohos.devtools.views.layout.event.TaskPanelEvent; -import ohos.devtools.views.trace.component.AnalystPanel; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import javax.swing.SwingWorker; -import javax.swing.UIManager; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridLayout; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.ExecutionException; - -/** - * 二级界面 - * - * @version 1.0 - * @date 2021/02/27 11:09 - **/ -public class TaskPanel extends JLayeredPane { - /** - * 全局日志 - */ - private static final Logger LOGGER = LogManager.getLogger(TaskPanel.class); - - /** - * 二级界面选项卡容器 - */ - private JPanel optionJPanel = new JPanel(new BorderLayout()); - - /** - * 二级界面选项卡内容容器 - */ - private JPanel optionJPanelContent = new JPanel(); - - /** - * 多配置界面选项卡标签 - */ - private JPanel jPanelTabLabel = new JPanel(); - - /** - * 多配置界面选项卡标签左侧 - */ - private JPanel jPanelLeft = new JPanel(); - - /** - * 多配置界面选项卡标签右侧 - */ - private JPanel jPanelRight = new JPanel(); - - /** - * 配置界面选项卡标签命名 - */ - private JLabel jLabelSetting = new JLabel("NewTask-Configure"); - - /** - * 多配置界面选项卡标签关闭按钮 - */ - private JLabel jLabelClose = new JLabel("x"); - - private TaskPanelEvent taskPanelEvent = new TaskPanelEvent(); - - private JLabel jButtonApplyTun = new JLabel(new ImageIcon(TaskPanel.class.getClassLoader() - .getResource("images/application_tuning.png"))); - private JLabel jButtonSystemTun = - new JLabel(new ImageIcon(TaskPanel.class.getClassLoader().getResource("images/system_tuning.png"))); - private JLabel jButtonHadoop = new JLabel( - new ImageIcon(TaskPanel.class.getClassLoader().getResource("images/distributed_scenario.png"))); - - private JLabel jLabelIcon = new JLabel(); - - private JLabel jLabelTaskTun = new JLabel("Application tuning

Tune application Launch perfoam" - + "ace with a 5 second time profile and a thread state trace."); - - private JLabel chooseButton = new JLabel("Choose", JLabel.CENTER); - - private JLabel traceButton = new JLabel("Open Trace File", JLabel.CENTER); - - private JButton jButtonAdd = new JButton("+"); - - private Long localSessionId; - - private TransferringWindow jProgressBar = null; - - /** - * 运行可执行文件将数据源转为db文件的是否成功结果 - */ - private Boolean traceAnalysisResult = true; - - /** - * Task Panel - */ - public TaskPanel() { - } - - /** - * Task Panel - * - * @param taskPanel task Panel - * @param taskPanelWelcome task Panel Welcome - */ - public TaskPanel(JPanel taskPanel, TaskPanelWelcome taskPanelWelcome) { - // 设置多配置界面 选项卡窗体大小 - this.setPreferredSize(new Dimension(LayoutConstants.OPT_WIDTH, LayoutConstants.OPT_HEIGHT)); - // 设置背景不透明 - this.setOpaque(true); - this.setBackground(ColorConstants.TOP_COLOR); - // 将选项卡内容容器添加到选项卡容器 - optionJPanel.add(optionJPanelContent); - // 设置属性 - setAttributes(taskPanel); - // 实现可新增多任务功能 - Constant.jtasksTab.addTab("", optionJPanel); - Constant.jtasksTab.setTabComponentAt(Constant.jtasksTab.indexOfComponent(optionJPanel), jPanelTabLabel); - taskLabel(jButtonApplyTun, jButtonSystemTun, jButtonHadoop); - taskPanel.setLayout(new BorderLayout()); - jButtonAdd.setBackground(ColorConstants.HOME_PANE); - jButtonAdd.setForeground(Color.GRAY); - Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.DEVICES_HEIGHT); - jButtonAdd.setFont(font); - jButtonAdd.setBorderPainted(false); - jButtonAdd.setBounds(LayoutConstants.NUMBER_X_ADD * Constant.jtasksTab.getTabCount(), LayoutConstants - .NUMBER_Y, LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - Constant.jtasksTab.setBounds(0, 0, taskPanel.getWidth(), taskPanel.getHeight()); - this.add(Constant.jtasksTab); - taskPanel.add(this); - double result = Constant.jtasksTab.getTabCount() * LayoutConstants.NUMBER_X; - // 当选项卡标签总长度过长时自动改变每个标签的大小使所有的标签在一行 - if (result > taskPanel.getWidth()) { - for (int index = 0; index < Constant.jtasksTab.getTabCount(); index++) { - Object tabObj = Constant.jtasksTab.getTabComponentAt(index); - if (tabObj instanceof JPanel) { - ((JPanel) tabObj).getComponents()[0].setPreferredSize(new Dimension( - (((taskPanel.getWidth() - LayoutConstants.MEMORY_WIDTH) / Constant.jtasksTab - .getTabCount()) - LayoutConstants.TASK_DEC_NUM) - LayoutConstants.JAVA_HEIGHT, - LayoutConstants.JAVA_HEIGHT)); - } - Constant.jtasksTab.getTabComponentAt(index).setPreferredSize(new Dimension( - ((taskPanel.getWidth() - LayoutConstants.MEMORY_WIDTH) / - Constant.jtasksTab.getTabCount()) - - LayoutConstants.TASK_DEC_NUM, LayoutConstants.JAVA_HEIGHT)); - jButtonAdd.setBounds(taskPanel.getWidth() - LayoutConstants.TASK_LABEL_X, - LayoutConstants.NUMBER_Y, - LayoutConstants.BUTTON_HEIGHT, LayoutConstants.BUTTON_HEIGHT); - } - } - optionJPanelContent.add(chooseButton); - // 关闭选项卡事件 - taskPanelEvent.clickClose(this, taskPanel, taskPanelWelcome); - // 选择不同场景对应显示 - taskPanelEvent.pplyTunMouseListener(taskPanel, this); - taskPanelEvent.addSystemMouseListener(taskPanel, this); - // chooseButton按钮添加点击事件 - taskPanelEvent.applicationTuningClickListener(this); - // 监听taskPanel大小,将jTabbedPane大小于其联动 - taskPanelEvent.listenerTaskPanel(taskPanel, jButtonAdd); - // jButtonAdd事件添加配置页面 - // 点击不同场景,出现选择状态 - taskPanelEvent.sigleClick(this); - // 监听窗体大小改变组件位置 - taskPanelEvent.listenerWindow(taskPanel, this); - } - - /** - * 设置属性 - * - * @param taskPanel taskPanel - */ - public void setAttributes(JPanel taskPanel) { - if (taskPanel == null) { - return; - } - optionJPanelContent.setLayout(null); - // 设置背景不透明 - optionJPanelContent.setOpaque(true); - optionJPanelContent.setBackground(ColorConstants.SCROLL_PANE); - jPanelTabLabel.setOpaque(false); - jPanelTabLabel.setPreferredSize(new Dimension(LayoutConstants.JPA_LABEL_WIDTH, LayoutConstants.DEVICES_HEIGHT)); - jPanelLeft.setOpaque(false); - jPanelRight.setOpaque(false); - jPanelTabLabel.setLayout(new BorderLayout()); - jPanelLeft.setLayout(null); - jPanelRight.setLayout(new GridLayout()); - jPanelLeft.setPreferredSize(new Dimension(LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.JP_LEFT_HEIGHT)); - jPanelRight.setPreferredSize(new Dimension(LayoutConstants.JP_RIGHT_WIDTH, LayoutConstants.JP_RIGHT_HEIGHT)); - jPanelTabLabel.add(jPanelLeft, BorderLayout.WEST); - jPanelTabLabel.add(jPanelRight, BorderLayout.CENTER); - // 给jPanelLeft添加标题 - jLabelSetting.setBounds(0, 0, LayoutConstants.JP_SET_WIDTH, LayoutConstants.JP_SET_HEIGHT); - jPanelLeft.add(jLabelSetting); - jPanelRight.add(jLabelClose); - jLabelClose.setHorizontalAlignment(JLabel.RIGHT); - jLabelIcon.setIcon(new ImageIcon(TaskPanel.class.getClassLoader() - .getResource("images/application_tuning.png"))); - jLabelIcon.setBounds(LayoutConstants.DEVICES_X, LayoutConstants.DESCRIPTION_NUMBER, LayoutConstants.HIGTHSCEECS, - LayoutConstants.HIGTHSCEECS); - jLabelTaskTun - .setBounds(LayoutConstants.JAVA_WIDTH, LayoutConstants.DESCRIPTION_NUMBER, LayoutConstants.APP_LABEL_WIDTH, - LayoutConstants.JLABEL_SIZE); - Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TUN_LABEL_FONT); - jLabelTaskTun.setFont(fontTaskTun); - jLabelTaskTun.setForeground(Color.WHITE); - Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT); - setButtonAttributter(font, taskPanel); - JPanel graphicsJpanel = new GraphicsJpanel(this); - graphicsJpanel.setBounds(0, LayoutConstants.WIDTHSUPEN, taskPanel.getWidth(), LayoutConstants.JAVA_WIDTH); - // Monitor window size changes to make graphicsJpanel size adaptive - taskPanelEvent.listenerGraphicsJpanel(graphicsJpanel, this); - optionJPanelContent.add(jLabelIcon); - optionJPanelContent.add(jLabelTaskTun); - optionJPanelContent.add(graphicsJpanel); - optionJPanelContent.add(traceButton); - } - - private void setButtonAttributter(Font font, JPanel taskPanel) { - chooseButton.setBounds(LayoutConstants.CHOSSE_X + (taskPanel.getWidth() - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.CHOOSE_Y + (taskPanel.getHeight() - LayoutConstants.WINDOW_HEIGHT), - LayoutConstants.DEVICES_WIDTH, LayoutConstants.CHOOSE_HEIGHT); - chooseButton.setOpaque(true); - chooseButton.setBackground(ColorConstants.CHOOSE_BUTTON); - chooseButton.setFont(font); - chooseButton.setForeground(Color.WHITE); - traceButton.setFont(font); - traceButton.setOpaque(true); - traceButton.setBounds(LayoutConstants.TASK_SCENE_X, - LayoutConstants.CHOOSE_Y + (taskPanel.getHeight() - LayoutConstants.WINDOW_HEIGHT), - LayoutConstants.CHOOSE_WIDTH, LayoutConstants.CHOOSE_HEIGHT); - traceButton.setBackground(ColorConstants.CHOOSE_BUTTON); - traceButton.setForeground(Color.WHITE); - traceButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent mouseEvent) { - super.mouseClicked(mouseEvent); - showFileOpenDialog(optionJPanelContent); - } - }); - } - - /** - * 打开trace文件 - * - * @param parent parent - */ - private void showFileOpenDialog(JPanel parent) { - JFileChooser fileChooser = new JFileChooser(); - if (StringUtils.isNotBlank(Constant.path)) { - fileChooser.setCurrentDirectory(new File(Constant.path)); - } else { - fileChooser.setCurrentDirectory(new File(".")); - } - UIManager.put("FileChooser.cancelButtonText", "Cancel"); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setMultiSelectionEnabled(false); - fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter()); - fileChooser.setDialogTitle("Select a Trace File"); - fileChooser.setApproveButtonText("Open"); - fileChooser.setControlButtonsAreShown(false); - SampleDialogWrapper sampleDialog = new SampleDialogWrapper("Select a Trace File", fileChooser); - boolean flag = sampleDialog.showAndGet(); - if (flag) { - if (fileChooser.getSelectedFile() == null || fileChooser.getSelectedFile().isDirectory()) { - new SampleDialogWrapper("Prompt", "Please select the trace file !").show(); - return; - } - jProgressBar = new TransferringWindow(parent); - // 移除按钮显示滚动条 - parent.remove(chooseButton); - parent.remove(traceButton); - // 监听JProgressBar的大小 - parent.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - super.componentResized(event); - jProgressBar.setBounds(LayoutConstants.TEN, parent.getHeight() - LayoutConstants.FORTY, - parent.getWidth() - LayoutConstants.TWENTY, LayoutConstants.THIRTY); - } - }); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - loadOfflineFile(parent, TaskPanel.this, fileChooser, optionJPanel); - } - }); - } - } - - /** - * 加载离线文件 - * - * @param optionJPanelContent optionJPanelContent - * @param taskPanel taskPanel - * @param fileChooser fileChooser - * @param optionJPanel optionJPanel - */ - private void loadOfflineFile(JPanel optionJPanelContent, TaskPanel taskPanel, JFileChooser fileChooser, - JPanel optionJPanel) { - SwingWorker, Object> task = new SwingWorker, Object>() { - /** - * doInBackground - * - * @return Optional - * @throws Exception Exception - */ - @Override - protected Optional doInBackground() throws Exception { - File file = fileChooser.getSelectedFile(); - Constant.path = fileChooser.getCurrentDirectory().getPath(); - Optional deviceProcessInfo = - SessionManager.getInstance().localSessionDataFromFile(jProgressBar, file); - return deviceProcessInfo; - } - - /** - * done - */ - @Override - protected void done() { - Optional deviceProcessInfo = null; - try { - deviceProcessInfo = get(); - } catch (InterruptedException | ExecutionException exception) { - exception.printStackTrace(); - } - if (deviceProcessInfo != null && deviceProcessInfo.isPresent()) { - DeviceProcessInfo deviceInfo = deviceProcessInfo.get(); - HosJLabel hosJLabel = new HosJLabel(); - hosJLabel.setProcessName(deviceInfo.getProcessName()); - hosJLabel.setSessionId(deviceInfo.getLocalSessionId()); - hosJLabel.setDeviceName(deviceInfo.getDeviceName()); - hosJLabel.setDeviceType(true); - hosJLabel.setStartTime(deviceInfo.getStartTime()); - hosJLabel.setEndTime(deviceInfo.getEndTime()); - List hosJLabels = new ArrayList(); - hosJLabels.add(hosJLabel); - optionJPanel.removeAll(); - TaskScenePanelChart taskScenePanelChart = new TaskScenePanelChart(taskPanel, hosJLabels); - TaskPanel.this.setLocalSessionId(deviceInfo.getLocalSessionId()); - optionJPanel.add(taskScenePanelChart); - } else { - loadSystemTurningFile(optionJPanelContent, fileChooser, optionJPanel); - return; - } - } - }; - task.execute(); - } - - /** - * load systrace file - * - * @param optionJPanelContent optionJPanelContent - * @param fileChooser fileChooser - * @param optionJPanel optionJPanel - */ - private void loadSystemTurningFile(JPanel optionJPanelContent, JFileChooser fileChooser, JPanel optionJPanel) { - SwingWorker task = new SwingWorker() { - @Override - protected String doInBackground() throws Exception { - File directory = new File(""); - traceAnalysisResult = true; - String courseFile = directory.getCanonicalPath(); - String pluginPath = SessionManager.getInstance().getPluginPath(); - String logPath = pluginPath + "trace_streamer/trace_streamer.log"; - File logFile = new File(logPath); - if (logFile.exists()) { - logFile.delete(); - } - // 将数据源转为db文件 - String baseDir = pluginPath + "trace_streamer\\"; - String dbPath = baseDir + "systrace.db"; - File file = fileChooser.getSelectedFile(); - String[] cmd = {baseDir + "trace_streamer.exe", file.getPath(), "-e", dbPath}; - HdcWrapper.getInstance().getHdcStringArrayResult(cmd); - // 获取.log日志(存放在根目录) - randomFile(logFile); - jProgressBar.setValue(LayoutConstants.FIFTY); - return dbPath; - } - - /** - * done - */ - @Override - protected void done() { - if (!traceAnalysisResult) { - optionJPanelContent.remove(jProgressBar); - optionJPanelContent.add(chooseButton); - optionJPanelContent.add(traceButton); - optionJPanelContent.repaint(); - new SampleDialogWrapper("Warring", - "The system cannot parse the file properly. Please import the legal file.").show(); - } - try { - if (traceAnalysisResult) { - String dbPath = get(); - optionJPanel.removeAll(); - AnalystPanel component = new AnalystPanel(); - component.load(dbPath, true); - jProgressBar.setValue(LayoutConstants.HUNDRED); - optionJPanel.add(component); - } - } catch (Exception exception) { - LOGGER.error("loadSystemTurningFile exception:{}", exception.getMessage()); - } - } - }; - task.execute(); - } - - /** - * random File - * - * @param logFile log File - * @throws IOException IOException - */ - private void randomFile(File logFile) throws IOException { - RandomAccessFile randomFile = null; - try { - if (logFile.exists()) { - randomFile = new RandomAccessFile(logFile, "r"); - String tmp = null; - while ((tmp = randomFile.readLine()) != null) { - if (Integer.valueOf(tmp.split(":")[1]) != 0) { - traceAnalysisResult = false; - } - } - } - } catch (FileNotFoundException fileNotFoundException) { - LOGGER.error("randomFile exception:{}", fileNotFoundException.getMessage()); - } catch (IOException iOException) { - LOGGER.error("randomFile exception:{}", iOException.getMessage()); - } finally { - if (randomFile != null) { - randomFile.close(); - } - } - } - - /** - * 新建描述图标 - * - * @param jButtonApplyTun jButtonApplyTun - * @param jButtonSystemTun jButtonSystemTun - * @param jButtonHadoop jButtonHadoop - */ - public void taskLabel(JLabel jButtonApplyTun, JLabel jButtonSystemTun, JLabel jButtonHadoop) { - if (jButtonApplyTun == null || jButtonSystemTun == null || jButtonHadoop == null) { - return; - } - // 新建描述图标 - JLabel jLabelRealTimeTaskZhu = new JLabel("Task scene"); - jLabelRealTimeTaskZhu.setForeground(Color.white); - JLabel jLabelRealTimeTaskCi = new JLabel("Choose the most suitable scene."); - Font fontZhu = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TASK_FONT); - Font fontCi = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.APP_BUT_FONT); - jLabelRealTimeTaskZhu.setFont(fontZhu); - jLabelRealTimeTaskCi.setFont(fontCi); - jLabelRealTimeTaskCi.setForeground(ColorConstants.BORDER_COLOR); - jLabelRealTimeTaskZhu - .setBounds(LayoutConstants.TASK_SCENE_X, LayoutConstants.TASK_SCENE_Y, LayoutConstants.TASK_WIDTH, - LayoutConstants.TASK_HEIGHT); - jLabelRealTimeTaskCi - .setBounds(LayoutConstants.CH_TASK_X, LayoutConstants.CH_TASK_Y, LayoutConstants.CH_TASK_WIDTH, - LayoutConstants.CH_TASK_HEIGHT); - jButtonApplyTun - .setBounds(LayoutConstants.APP_BUT_X, LayoutConstants.APP_BUT_Y, LayoutConstants.TWO_HUNDRED_EIGHTEEN, - LayoutConstants.HUNDRED_FIFTY_FIVE); - jButtonApplyTun.setText("Application tuning"); - Font fontAll = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.APP_BUT_FONT); - jButtonApplyTun.setFont(fontAll); - jButtonApplyTun.setOpaque(true); - jButtonApplyTun.setVerticalTextPosition(JLabel.BOTTOM); - jButtonApplyTun.setHorizontalTextPosition(JLabel.CENTER); - jButtonApplyTun.setBackground(ColorConstants.APPLYTUN_COLOR); - jButtonSystemTun.setBounds(LayoutConstants.LABEL_NAME_WIDTH, LayoutConstants.SYS_BUT_Y, - LayoutConstants.TWO_HUNDRED_EIGHTEEN, LayoutConstants.HUNDRED_FIFTY_FIVE); - jButtonSystemTun.setText("System tuning"); - jButtonSystemTun.setFont(fontAll); - jButtonSystemTun.setOpaque(true); - jButtonSystemTun.setVerticalTextPosition(JLabel.BOTTOM); - jButtonSystemTun.setHorizontalTextPosition(JLabel.CENTER); - jButtonSystemTun.setBackground(ColorConstants.SYSTEM_COLOR); - jButtonHadoop - .setBounds(LayoutConstants.EMB_BUT_X, LayoutConstants.EMB_BUT_Y, LayoutConstants.TWO_HUNDRED_EIGHTEEN, - LayoutConstants.HUNDRED_FIFTY_FIVE); - jButtonHadoop.setText("Embrace scene"); - jButtonHadoop.setFont(fontAll); - jButtonHadoop.setOpaque(true); - jButtonHadoop.setVerticalTextPosition(JLabel.BOTTOM); - jButtonHadoop.setHorizontalTextPosition(JLabel.CENTER); - jButtonHadoop.setBackground(ColorConstants.SYSTEM_COLOR); - optionJPanelContent.add(jLabelRealTimeTaskZhu); - optionJPanelContent.add(jLabelRealTimeTaskCi); - optionJPanelContent.add(jButtonApplyTun); - optionJPanelContent.add(jButtonSystemTun); - } - - public JLabel getJLabelClose() { - return jLabelClose; - } - - public JPanel getJPanelTabLabel() { - return jPanelTabLabel; - } - - public JLabel getJLabelTaskTun() { - return jLabelTaskTun; - } - - public JLabel getChooseButton() { - return chooseButton; - } - - public JLabel getJButtonApplyTun() { - return jButtonApplyTun; - } - - public JLabel getJButtonSystemTun() { - return jButtonSystemTun; - } - - public JLabel getJButtonHadoop() { - return jButtonHadoop; - } - - public JPanel getOptionJPanel() { - return optionJPanel; - } - - public JPanel getOptionJPanelContent() { - return optionJPanelContent; - } - - public JLabel getJLabelSetting() { - return jLabelSetting; - } - - public JPanel getJPanelRight() { - return jPanelRight; - } - - public JPanel getJPanelLeft() { - return jPanelLeft; - } - - public JButton getJButtonAdd() { - return jButtonAdd; - } - - public void setjButtonAdd(JButton jButtonAdd) { - this.jButtonAdd = jButtonAdd; - } - - public JLabel getjLabelIcon() { - return jLabelIcon; - } - - public JLabel getTraceButton() { - return traceButton; - } - - public void setLocalSessionId(Long localSessionId) { - this.localSessionId = localSessionId; - } - - public Long getLocalSessionId() { - return localSessionId; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanelWelcome.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanelWelcome.java deleted file mode 100644 index c888fabde..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskPanelWelcome.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.event.TaskPanelWelcomeEvent; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; - -/** - * 二级欢迎界面 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class TaskPanelWelcome extends JPanel { - /** - * 新建实时任务按钮 - */ - private static JLabel jNewButton = new JLabel("+ New Task", JLabel.CENTER); - - /** - * 新建按钮区域背景面板 - */ - private static JPanel colorJPanel = new JPanel(null); - - /** - * 欢迎页面面板 - */ - private static JPanel welcomeJPanel = new JPanel(new BorderLayout()); - - /** - * 欢迎语 - */ - private static JLabel jLabelWelcome = new JLabel("

Welcome HosProfiler


Click New Sessions Bu!on to process or load a capture.

", JLabel.CENTER); - - private TaskPanelWelcomeEvent taskPanelWelcomeEvent = new TaskPanelWelcomeEvent(); - - public TaskPanelWelcome() { - // 添加新建按钮背景面板和欢迎页面面板 - this.setLayout(new BorderLayout()); - this.add(colorJPanel, BorderLayout.NORTH); - this.add(welcomeJPanel, BorderLayout.CENTER); - // 设置新建按钮背景面板大小和颜色 - colorJPanel.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.DEVICE_WIDTH)); - colorJPanel.setBackground(ColorConstants.TOP_COLOR); - // 将新建按钮添加进背景面板和欢迎图片标语添加进欢迎面板 - jNewButton.setOpaque(true); - jNewButton.setBounds(LayoutConstants.MEMORY_X_TESTING, LayoutConstants.MEMORY_Y, LayoutConstants.JP_LEFT_WIDTH, - LayoutConstants.CON_BOX_Y); - Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.SYSTEM_TUNNING_LABEL_FONT); - jNewButton.setFont(font); - jNewButton.setBackground(ColorConstants.CENTER_COLOR); - jNewButton.setForeground(Color.white); - colorJPanel.add(jNewButton); - jLabelWelcome.setIcon(new ImageIcon(TaskPanelWelcome.class.getClassLoader().getResource("images/pic.png"))); - jLabelWelcome.setVerticalTextPosition(JLabel.BOTTOM); - jLabelWelcome.setHorizontalTextPosition(JLabel.CENTER); - welcomeJPanel.setBackground(ColorConstants.CENTER_COLOR); - welcomeJPanel.add(jLabelWelcome); - // +号新建实时任务按钮事件 - taskPanelWelcomeEvent.clickAddTask(this); - } - - /** - * 获取JNewButton按钮 - * - * @return JButton - */ - public JLabel getJNewButton() { - return jNewButton; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanel.java deleted file mode 100644 index e3436d1b2..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanel.java +++ /dev/null @@ -1,402 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.event.TaskScenePanelEvent; - -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; - -/** - * 三级场景界面 - * - * @version 1.0 - * @date 2021/02/27 11:11 - **/ -public class TaskScenePanel extends JPanel { - /** - * 三级界面边框布局管理器,top容器 - */ - private JPanel jPanelNorth = new JPanel(null); - - /** - * 三级界面边框布局管理器,Center容器 - */ - private JPanel jPanelCenter = new JPanel(new BorderLayout()); - - /** - * 三级界面边框布局管理器,South容器 - */ - private JPanel jPanelSouth = new JPanel(null); - - /** - * top容器中文本描述 - */ - private JLabel jLabelTaskTun = new JLabel("Devices & Applications"); - - /** - * top容器中文本描述 - */ - private JLabel jLabelDeviceSet = new JLabel("Task scene: Application tuning"); - - /** - * Center容器中,左边容器 - */ - private JPanel jPanelCenterWest = new JPanel(new BorderLayout()); - - /** - * Center容器中,右边容器 - */ - private JPanel jPanelCenterRight = new JPanel(null); - - /** - * Center容器中,Monitor Items页面复选框容器 - */ - private JPanel jPanelRightMemory = new JPanel(null); - - /** - * Monitor Items页面复选框存放数组 - */ - private JCheckBox[] jCheckBoxs = new JCheckBox[LayoutConstants.INDEX_SEVEN]; - - /** - * 三级页面事件类 - */ - private TaskScenePanelEvent taskScenePanelEvent = new TaskScenePanelEvent(); - - /** - * Center容器左边部分边框布局top容器 - */ - private JPanel jPanelCenterWestTop = new JPanel(new BorderLayout()); - - /** - * Center容器左边部分边框布局center容器 - */ - private JPanel jPanelCenterWestCenter = new JPanel(new BorderLayout()); - - /** - * Center容器左边部分边框布局center容器中左边容器,用于布局按钮位置 - */ - private JPanel jPanelCenterWestCenterLeft = new JPanel(); - - /** - * Center容器左边部分边框布局center容器中右边容器,用于添加 Add Device按钮 - */ - private JPanel jPanelCenterWestCenterRight = new JPanel(null); - - /** - * Add Device按钮,添加设备 - */ - private JLabel jButtonAddDevice = new JLabel("Add Device", JLabel.CENTER); - - /** - * Monitor Items页面复选框内容 - */ - private JLabel jLabelMemory = new JLabel("Memory"); - private JCheckBox checkBoxSelectAll = new JCheckBox("Select All"); - private JCheckBox checkBoxMemoryJava = new JCheckBox("Java"); - private JCheckBox checkBoxGpuMemoryNative = new JCheckBox("Native"); - private JCheckBox checkBoxGraphics = new JCheckBox("Graphics"); - private JCheckBox checkBoxStack = new JCheckBox("Stack"); - private JCheckBox checkBoxCode = new JCheckBox("Code"); - private JCheckBox checkBoxOthers = new JCheckBox("Others"); - - /** - * Center容器中,左边布局滚动条容器 - */ - private JPanel scrollPane = new JPanel(null); - - /** - * 返回上一页按钮 - */ - private JLabel jButtonLastStep = new JLabel("Last Step", JLabel.CENTER); - - /** - * 开始任务按钮 - */ - private JLabel jButtonStartTask = new JLabel("Start Task", JLabel.CENTER); - - private JScrollPane jScrollPane = - new JScrollPane(scrollPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - private DeviceProcessJpanel deviceProcessJpanel; - - /** - * Task Scene Panel - */ - public TaskScenePanel() { - } - - /** - * TaskScenePanel - * - * @param jTaskPanel jTaskPanel - */ - public TaskScenePanel(TaskPanel jTaskPanel) { - // 设置三级界面布局方式为边框布局管理 - this.setLayout(new BorderLayout()); - // 设置top容器,Center容器,South容器的属性 - setAttributes(); - // 给Center容器分为左右边框布局 - setBorderLeftRight(); - // Center容器左边部分分为上下边框布局 - setBorderTopCenter(); - // 三级页面中Monitor Items页面设置 - setJPanelCenterRight(); - // 添加复选框 - addCheckBox(); - // South容器设置 - setJPanelSouth(jTaskPanel); - } - - /** - * SouthContainer settings - * - * @param jTaskPanel jTaskPanel - */ - public void setJPanelSouth(TaskPanel jTaskPanel) { - Font font = new Font(Font.DIALOG, Font.PLAIN, LayoutConstants.OPTION_FONT); - jButtonLastStep.setFont(font); - jButtonLastStep.setBorder(BorderFactory.createLineBorder(ColorConstants.BORDER_COLOR)); - jButtonLastStep.setOpaque(true); - jButtonLastStep.setBounds(LayoutConstants.NUMBER_STEP + (jPanelSouth.getWidth() - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.DEVICE_X); - jButtonLastStep.setBackground(ColorConstants.CENTER_COLOR); - jButtonStartTask.setForeground(Color.white); - jButtonStartTask.setOpaque(true); - jButtonStartTask - .setBounds(LayoutConstants.POSITION_TASK_X + (jPanelSouth.getWidth() - LayoutConstants.WINDOW_WIDTH), - LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.JP_LEFT_WIDTH, LayoutConstants.DEVICE_X); - jButtonStartTask.setBackground(ColorConstants.CHOOSE_BUTTON); - jButtonStartTask.setFont(font); - jPanelSouth.add(jButtonLastStep); - jPanelSouth.add(jButtonStartTask); - // 监听jPanelSouth大小变化并改变按钮位置 - taskScenePanelEvent.listenerJPanelSouth(this); - // jButtonLastStep添加事件返回上一页 - taskScenePanelEvent.lastStep(this, jTaskPanel); - // jButtonStartTask添加事件开始任务 - taskScenePanelEvent.startTask(this, jTaskPanel); - } - - /** - * Center容器左边部分分为边框布局上下两个部分 - */ - public void setBorderTopCenter() { - scrollPane.setBackground(ColorConstants.SCROLL_PANE); - jScrollPane.setBorder(null); - // 设置鼠标滚轮速度 - jScrollPane.getVerticalScrollBar().setUnitIncrement(LayoutConstants.SCROLL_UNIT_INCREMENT); - jPanelCenterWest.add(jScrollPane); - // Add Device按钮事件 - taskScenePanelEvent.clickAddDevice(this, taskScenePanelEvent); - deviceProcessJpanel = new DeviceProcessJpanel(taskScenePanelEvent, scrollPane, this); - scrollPane.add(deviceProcessJpanel); - } - - /** - * Monitor Items页面,添加复选框 - */ - public void addCheckBox() { - jCheckBoxs[LayoutConstants.INDEX_ZERO] = checkBoxSelectAll; - jCheckBoxs[LayoutConstants.INDEX_ONE] = checkBoxMemoryJava; - jCheckBoxs[LayoutConstants.INDEX_TWO] = checkBoxGpuMemoryNative; - jCheckBoxs[LayoutConstants.INDEX_THREE] = checkBoxGraphics; - jCheckBoxs[LayoutConstants.INDEX_FOUR] = checkBoxStack; - jCheckBoxs[LayoutConstants.INDEX_FIVE] = checkBoxCode; - jCheckBoxs[LayoutConstants.INDEX_SIX] = checkBoxOthers; - // 默认全选 - checkBoxSelectAll.setSelected(true); - checkBoxMemoryJava.setSelected(true); - checkBoxGpuMemoryNative.setSelected(true); - checkBoxGraphics.setSelected(true); - checkBoxStack.setSelected(true); - checkBoxCode.setSelected(true); - checkBoxOthers.setSelected(true); - jLabelMemory.setBounds(LayoutConstants.MEMORY_X, LayoutConstants.MEMORY_Y, LayoutConstants.MEMORY_WIDTH, - LayoutConstants.MEMORY_HEIGHT); - checkBoxSelectAll - .setBounds(LayoutConstants.SELECT_ALL_X, LayoutConstants.SELECT_ALL_Y, LayoutConstants.SELECT_ALL_WIDTH, - LayoutConstants.SELECT_ALL_HEIGHT); - checkBoxMemoryJava.setBounds(LayoutConstants.JAVA_X, LayoutConstants.JAVA_Y, LayoutConstants.JAVA_WIDTH, - LayoutConstants.JAVA_HEIGHT); - checkBoxGpuMemoryNative - .setBounds(LayoutConstants.NATIVE_X, LayoutConstants.NATIVE_Y, LayoutConstants.NATIVE_WIDTH, - LayoutConstants.NATIVE_HEIGHT); - checkBoxGraphics - .setBounds(LayoutConstants.GRAPHICS_X, LayoutConstants.GRAPHICS_Y, LayoutConstants.GRAPHICS_WIDTH, - LayoutConstants.GRAPHICS_HEIGHT); - checkBoxStack.setBounds(LayoutConstants.STACK_X, LayoutConstants.STACK_Y, LayoutConstants.STACK_WIDTH, - LayoutConstants.STACK_HEIGHT); - checkBoxCode.setBounds(LayoutConstants.CODE_X, LayoutConstants.CODE_Y, LayoutConstants.CODE_WIDTH, - LayoutConstants.CODE_HEIGHT); - checkBoxOthers.setBounds(LayoutConstants.OTHERS_X, LayoutConstants.OTHERS_Y, LayoutConstants.OTHERS_WIDTH, - LayoutConstants.OTHERS_HEIGHT); - jPanelRightMemory.add(jLabelMemory); - jPanelRightMemory.add(checkBoxSelectAll); - jPanelRightMemory.add(checkBoxMemoryJava); - jPanelRightMemory.add(checkBoxGpuMemoryNative); - jPanelRightMemory.add(checkBoxGraphics); - jPanelRightMemory.add(checkBoxStack); - jPanelRightMemory.add(checkBoxCode); - jPanelRightMemory.add(checkBoxOthers); - // 复选框选中事件 - taskScenePanelEvent.checkBoxSelect(this); - } - - /** - * 三级页面中Monitor Items页面设置 - */ - public void setJPanelCenterRight() { - JPanel jPanelRightTop = new JPanel(null); - jPanelRightTop.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jPanelRightTop.setBounds(LayoutConstants.MONITOR_PANEL_X, LayoutConstants.MONITOR_PANEL_Y, - LayoutConstants.MONITOR_PANEL_WIDTH, LayoutConstants.MONITOR_PANEL_HEIGHT); - JLabel jLabel = new JLabel("Monitor Items"); - Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.MONITOR_BUN_FONT); - jLabel.setFont(fontTaskTun); - jLabel.setForeground(Color.WHITE); - jLabel - .setBounds(LayoutConstants.MONITOR_BUN_X, LayoutConstants.MONITOR_BUN_Y, LayoutConstants.MONITOR_BUN_WIDTH, - LayoutConstants.MONITOR_BUN_HEIGHT); - jPanelRightTop.add(jLabel); - jPanelRightMemory - .setBounds(LayoutConstants.MONITOR_OPT_X, LayoutConstants.MONITOR_OPT_Y, LayoutConstants.MONITOR_OPT_WIDTH, - LayoutConstants.MONITOR_OPT_HEIGHT); - jPanelRightMemory.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jPanelCenterRight.add(jPanelRightTop); - jPanelCenterRight.add(jPanelRightMemory); - - // 设置背景色 - checkBoxSelectAll.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxMemoryJava.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxGpuMemoryNative.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxGraphics.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxStack.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxCode.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - checkBoxOthers.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - } - - /** - * 给Center容器分为左右边框布局 - */ - public void setBorderLeftRight() { - jPanelCenterWest.setOpaque(false); - jPanelCenterRight.setOpaque(false); - jPanelCenterWest - .setPreferredSize(new Dimension(LayoutConstants.WEST_LABEL_WIDTH, LayoutConstants.WEST_LABEL_HEIGHT)); - jPanelCenterRight - .setPreferredSize(new Dimension(LayoutConstants.EAST_LABEL_WIDTH, LayoutConstants.EAST_LABEL_HEIGHT)); - jPanelCenter.add(jPanelCenterWest, BorderLayout.WEST); - jPanelCenter.add(jPanelCenterRight, BorderLayout.CENTER); - } - - /** - * 设置top容器,Center容器,South容器的属性 - */ - public void setAttributes() { - jPanelNorth.setOpaque(true); - jPanelNorth.setBackground(ColorConstants.TOP_PANEL); - jPanelCenter.setOpaque(true); - jPanelCenter.setBackground(ColorConstants.TOP_PANEL); - jPanelSouth.setOpaque(true); - jPanelSouth.setBackground(ColorConstants.TOP_PANEL); - jPanelNorth.setPreferredSize(new Dimension(LayoutConstants.TOP_SOUTH_WIDTH, LayoutConstants.TOP_SOUTH_HEIGHT)); - jPanelSouth.setPreferredSize(new Dimension(LayoutConstants.TOP_SOUTH_WIDTH, LayoutConstants.TOP_SOUTH_HEIGHT)); - this.add(jPanelNorth, BorderLayout.NORTH); - this.add(jPanelCenter, BorderLayout.CENTER); - this.add(jPanelSouth, BorderLayout.SOUTH); - jLabelTaskTun - .setBounds(LayoutConstants.TASK_LABEL_X, LayoutConstants.TASK_LABEL_Y, LayoutConstants.TASK_LABEL_WIDTH, - LayoutConstants.TASK_LABEL_HEIGHT); - Font fontTaskTun = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TASK_LABEL_FONT); - jLabelTaskTun.setFont(fontTaskTun); - jLabelTaskTun.setForeground(Color.WHITE); - jPanelNorth.add(jLabelTaskTun); - Font fontDeviceSet = new Font(Font.DIALOG, Font.BOLD, LayoutConstants.TASK_DEC_FONT); - jLabelDeviceSet.setFont(fontDeviceSet); - jLabelDeviceSet.setForeground(ColorConstants.BORDER_COLOR); - jLabelDeviceSet - .setBounds(LayoutConstants.TASK_DEC_X, LayoutConstants.TASK_DEC_Y, LayoutConstants.TASK_DEC_WIDTH, - LayoutConstants.TASK_DEC_HEIGHT); - jPanelNorth.add(jLabelDeviceSet); - } - - public JCheckBox getCheckBoxSelectAll() { - return checkBoxSelectAll; - } - - public JCheckBox getCheckBoxMemoryJava() { - return checkBoxMemoryJava; - } - - public JCheckBox getCheckBoxGpuMemoryNative() { - return checkBoxGpuMemoryNative; - } - - public JCheckBox getCheckBoxGraphics() { - return checkBoxGraphics; - } - - public JCheckBox getCheckBoxStack() { - return checkBoxStack; - } - - public JCheckBox getCheckBoxCode() { - return checkBoxCode; - } - - public JCheckBox getCheckBoxOthers() { - return checkBoxOthers; - } - - public JLabel getJButtonAddDevice() { - return jButtonAddDevice; - } - - public JPanel getScrollPane() { - return scrollPane; - } - - public JPanel getJPanelSouth() { - return jPanelSouth; - } - - public JLabel getJButtonLastStep() { - return jButtonLastStep; - } - - public JLabel getJButtonStartTask() { - return jButtonStartTask; - } - - public JCheckBox[] getJCheckBoxs() { - return jCheckBoxs; - } - - public DeviceProcessJpanel getDeviceProcessJpanel() { - return deviceProcessJpanel; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanelChart.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanelChart.java deleted file mode 100644 index c8cd32766..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskScenePanelChart.java +++ /dev/null @@ -1,736 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJButton; -import ohos.devtools.views.common.hoscomp.HosJComboBox; -import ohos.devtools.views.common.hoscomp.HosJLabel; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.event.TaskScenePanelChartEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.util.List; -import java.awt.LayoutManager; - -import static ohos.devtools.views.common.ProfilerMonitorItem.MEMORY; -import static ohos.devtools.views.common.ViewConstants.NUM_1000; -import static ohos.devtools.views.common.ViewConstants.NUM_4; - -/** - * chart监测页面三级容器 - * - * @version 1.0 - * @date 2021/03/02 - **/ -public class TaskScenePanelChart extends JPanel { - private static final Logger LOGGER = LogManager.getLogger(TaskScenePanelChart.class); - private Component add; - - /** - * Task Scene Panel Chart - */ - public TaskScenePanelChart() { - } - - /** - * 整体页面top容器 - */ - private JPanel panelTop = new JPanel(new BorderLayout()); - - /** - * 整体页面center容器 - */ - private JPanel panelMiddle = new JPanel(new BorderLayout()); - - /** - * 整体页面Bottom容器 - */ - private JPanel panelBottom = new JPanel(new BorderLayout()); - - /** - * panelTop中,west容器 - */ - private JPanel jPanelWest = new JPanel(); - - /** - * panelTop中,Center容器 - */ - private JPanel jPanelCenter = new JPanel(); - - /** - * panelTop中,East容器 - */ - private JPanel jPanelEast = new JPanel(); - - /** - * 选项卡标签命名 - */ - private JLabel jLabelSetting = new JLabel(); - - /** - * 停止按钮 - */ - private HosJButton jButtonRun = new HosJButton( - new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_record.png")), "停止任务"); - - /** - * 暂停按钮 - */ - private HosJButton jButtonStop = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_stop.png")), - "暂停任务"); - - /** - * 保存任务按钮 - */ - private HosJButton jButtonSave = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_save.png")), - "保存任务"); - - /** - * 删除任务按钮 - */ - private HosJButton jButtonDelete = new HosJButton( - new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_delete.png")), "删除任务"); - - /** - * 新增配置项按钮 - */ - private HosJButton jButtonInsert = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_add.png")), - "新增配置项"); - - /** - * 向下扩展页面按钮 - */ - private HosJButton jButtonBottom = new HosJButton( - new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_bottom_bar_grey.png")), - "向下扩展"); - - /** - * 帮助按钮 - */ - private HosJButton jButtonHelp = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_help.png")), - "帮助"); - - /** - * 向左扩展页面按钮 - */ - private HosJButton jButtonLeft = new HosJButton( - new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/button_left_bar.png")), "向左扩展"); - - /** - * 切换上一页按钮 - */ - private HosJButton jButtonUp = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/left_grey.png")), - "上一页"); - - /** - * 切换下一页按钮 - */ - private HosJButton jButtonNext = - new HosJButton(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/right_grey.png")), - "下一页"); - - /** - * Run xx of xx 信息文本 - */ - private JLabel jLabelMidde = new JLabel(); - - /** - * 00:24:27 chart计时容器 - */ - private JPanel jPanelLabel = new JPanel(new GridLayout()); - - /** - * 计时器文字显示 - */ - private JLabel jTextArea = new JLabel(); - - /** - * panelMiddle容器中左边容器 - */ - private JPanel jPanelMiddleLeft = new JPanel(); - - /** - * panelMiddle容器中右边容器 - */ - private JPanel jPanelMiddleRight = new JPanel(); - - /** - * panelMiddle容器分割线 - */ - private JSplitPane splitPane = new JSplitPane(); - - /** - * jPanelMiddleLeft容器子容器 - */ - private JPanel jScrollCardsPanel = new JPanel(new BorderLayout()); - - /** - * jScrollCardsPanel容器子容器 - */ - private JPanel jScrollCardsPanelInner = new JPanel(); - - /** - * jPanelMiddleLeft滚动条 - */ - private JScrollPane jScrollPane = new JScrollPane(jScrollCardsPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - /** - * 卡片式布局的面板,用于多个chart页面 - */ - private JPanel cards = new JPanel(new CardLayout()); - - /** - * 卡片模型对象 - */ - private CardLayout cardLayout; - - /** - * 用于jPanelMiddleLeft布局和内容显示 - */ - private int number = 0; - - private int numberJlabel = 0; - - private TaskScenePanelChartEvent taskScenePanelChartEvent = new TaskScenePanelChartEvent(); - - private JLabel jLabelLeft = new JLabel(); - - private CountingThread counting; - - private ProfilerChartsView profilerView; - - /** - * 悬浮框 - */ - private JPanel jPanelSuspension = new JPanel(); - - private JPanel jpanelSupen = new JPanel(); - - private HosJComboBox jComboBox = new HosJComboBox(); - - private HosJComboBox timeJComboBox = new HosJComboBox(); - - /** - * getCardLayout - * - * @param cards cards - */ - private void getCardLayout(JPanel cards) { - if (cards != null) { - LayoutManager layout = cards.getLayout(); - if (layout instanceof CardLayout) { - cardLayout = (CardLayout) layout; - } - } - } - - /** - * chart监测页面三级容器 - * - * @param jTaskPanel jTaskPanel - * @param hosJLabelList hosJLabelList - */ - public TaskScenePanelChart(TaskPanel jTaskPanel, List hosJLabelList) { - getCardLayout(cards); - // 整体页面布局设置 - setLayAttributes(jTaskPanel, hosJLabelList); - // 设置按钮属性 - setButtonAttributes(); - // 布局panelTop容器,添加按钮 - setPanelTopAttributes(); - // 设置标签页标题滚动显示 - new DynamicThread().start(); - // 布局panelBigTwo中间容器 - panelMiddle.setLayout(new BorderLayout()); - // 创建页面分割事件 - createSplitPanel(); - // 布局jPanelMiddleLeft容器 - setScrollPane(); - jPanelMiddleRight.add(cards); - // 获取有多少个设备开始了任务,并循环设置 - int numberSum = hosJLabelList.size(); - int sum = 0; - setTaskLoop(numberSum, sum, hosJLabelList); - // 初始化绘图标准刻度间隔 - refreshTime(); - // 默认显示第一页 - cardLayout.show(cards, "card0"); - // 监听窗体大小使悬浮窗紧贴窗体 - taskScenePanelChartEvent.setSceneSize(jTaskPanel, this); - // 给删除按钮添加点击事件 - taskScenePanelChartEvent.clickDelete(this); - // 给上一个页面按钮,下一个页面按钮添加点击事件 - taskScenePanelChartEvent.clickUpAndNext(this); - // 给jButtonBottom按钮添加点击事件,向下放大页面 - taskScenePanelChartEvent.clickBottom(this, profilerView); - // 给jsplitPane添加监听事件 - taskScenePanelChartEvent.splitPaneChange(this, numberSum); - // 给jButtonLeft按钮添加点击事件,向左放大页面 - taskScenePanelChartEvent.clickLeft(this); - // 给jButton按钮添加点击时间,保存trace文件 - taskScenePanelChartEvent.clickSave(jButtonSave); - // memory配置项新增点击事件 - taskScenePanelChartEvent.clickConfig(this, profilerView); - // trace导入,不需要这些按钮 - if (hosJLabelList.get(0).getDeviceType()) { - jPanelWest.removeAll(); - } else { - // 开始计时 - counting = new CountingThread(jTextArea); - counting.start(); - } - // 刷新页面 - jTaskPanel.getOptionJPanel().repaint(); - } - - /** - * 创建表格 - * - * @param panelBottom panelBottom - * @param jTaskPanel jTaskPanel - */ - public void createTable(JPanel panelBottom, TaskPanel jTaskPanel) { - JButton jButtonSuspen = new JButton("悬浮框"); - panelBottom.add(jButtonSuspen); - taskScenePanelChartEvent.showSuspension(this, jTaskPanel, jButtonSuspen); - } - - private void refreshTime() { - long sessionId = jComboBox.getSessionId(); - ProfilerChartsView view = ProfilerChartsView.sessionMap.get(sessionId); - if (view != null) { - view.getObserver().getStandard().updateSizeTime(NUM_1000); - } - } - - /** - * chart display - * - * @param num num - * @param jcardsPanel jcardsPanel - * @param hosJLabel hosJLabel - */ - private void chartDisplay(int num, JPanel jcardsPanel, HosJLabel hosJLabel) { - // sessionId绑定按钮 - if (num == 0) { - jButtonRun.setSessionId(hosJLabel.getSessionId()); - jButtonStop.setSessionId(hosJLabel.getSessionId()); - jButtonSave.setSessionId(hosJLabel.getSessionId()); - jButtonSave.setDeviceName(hosJLabel.getDeviceName()); - jButtonSave.setProcessName(hosJLabel.getProcessName()); - jButtonDelete.setSessionId(hosJLabel.getSessionId()); - jButtonDelete.setDeviceName(hosJLabel.getDeviceName()); - jButtonDelete.setProcessName(hosJLabel.getProcessName()); - jButtonInsert.setSessionId(hosJLabel.getSessionId()); - jButtonBottom.setSessionId(hosJLabel.getSessionId()); - jButtonLeft.setSessionId(hosJLabel.getSessionId()); - jComboBox.setSessionId(hosJLabel.getSessionId()); - timeJComboBox.setSessionId(hosJLabel.getSessionId()); - } - // 判断是导入还是实时 - if (hosJLabel.getDeviceType()) { - // 添加chart - profilerView = new ProfilerChartsView(hosJLabel.getSessionId(), true, this); - jcardsPanel.add(profilerView); - profilerView.addMonitorItemView(MEMORY); - profilerView.getObserver().showTraceResult(hosJLabel.getStartTime(), hosJLabel.getEndTime()); - taskScenePanelChartEvent.clickZoomEvery(timeJComboBox, profilerView); - } else { - // 添加chart - profilerView = new ProfilerChartsView(hosJLabel.getSessionId(), false, this); - jcardsPanel.add(profilerView); - profilerView.addMonitorItemView(MEMORY); - // 显示Loading标识,等数据库初始化完成时再显示chart - profilerView.showLoading(); - taskScenePanelChartEvent.clickZoomEvery(timeJComboBox, profilerView); - // 给开始暂停按钮添加点击事件 - taskScenePanelChartEvent.clickRunAndStop(this, profilerView); - } - } - - /** - * Set PanelMidder container layout and content cyclically - * - * @param numberSum numberSum - * @param sum sum - * @param hosJLabelList hosJLabelList - */ - public void setTaskLoop(int numberSum, int sum, List hosJLabelList) { - int sumInt = sum; - for (int index = 0; index < numberSum; index++) { - sumInt += LayoutConstants.HEIGHT; - JPanel jcardsPanel = new JPanel(new BorderLayout()); - jcardsPanel.setOpaque(true); - HosJLabel hosJLabel = hosJLabelList.get(index); - // sessionId绑定按钮,判断是导入还是实时 - chartDisplay(index, jcardsPanel, hosJLabel); - // 显示设备进程名称 - HosJLabel jLabelRight = new HosJLabel( - "

" + hosJLabel.getProcessName() + "
" + "(" + hosJLabel - .getDeviceName() + ")" + "

"); - // 绑定sessionid,进程设备信息 - jLabelRight.setSessionId(hosJLabel.getSessionId()); - jLabelRight.setDeviceName(hosJLabel.getDeviceName()); - jLabelRight.setProcessName(hosJLabel.getProcessName()); - jLabelRight.setOpaque(true); - // 显示颜色 - JLabel jLabelLefts = new JLabel(); - // 判断显示具体颜色布局 - judge(index, jLabelLefts, jLabelRight); - // 每个设备进程信息用jpanel包围 - JPanel jMultiplePanel = new JPanel(new BorderLayout()); - jMultiplePanel.setBounds(0, number, LayoutConstants.HEIGHT_Y, LayoutConstants.HEIGHT); - number += LayoutConstants.HEIGHT; - numberJlabel += LayoutConstants.INDEX_THREE; - - jMultiplePanel.add(jLabelRight, BorderLayout.CENTER); - jScrollCardsPanelInner.add(jMultiplePanel); - cards.add(jcardsPanel, "card" + index); - // 存放点击选择的进程信息用于标签动态展示 - String jLabelSelect = hosJLabel.getProcessName() + "(" + hosJLabel.getDeviceName() + ")"; - // 给每个jpanel添加点击事件 - taskScenePanelChartEvent.clickEvery(this, jLabelRight, numberSum, jLabelSelect, jMultiplePanel); - } - if (sumInt > LayoutConstants.SCROPNUM) { - jScrollCardsPanelInner.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, sumInt)); - } - } - - /** - * Determine the specific color layout - * - * @param index index - * @param jLabelLeft jLabelLeft - * @param jLabelRight jLabelRight - */ - public void judge(int index, JLabel jLabelLeft, JLabel jLabelRight) { - if (index == 0) { - jLabelRight.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jLabelRight.setForeground(Color.WHITE); - jLabelRight.setPreferredSize(new Dimension(LayoutConstants.WIDTH, LayoutConstants.HEIGHT)); - jLabelLeft.setOpaque(true); - jLabelLeft.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jLabelLeft.setPreferredSize(new Dimension(LayoutConstants.DEVICE_ADD_X, LayoutConstants.HEIGHT)); - } else { - jLabelRight.setBackground(ColorConstants.SCROLL_PANE); - jLabelRight.setForeground(Color.gray); - jLabelRight.setPreferredSize(new Dimension(LayoutConstants.WIDTH, HEIGHT)); - jLabelLeft.setOpaque(true); - jLabelLeft.setBackground(ColorConstants.SCROLL_PANE); - jLabelLeft.setPreferredSize(new Dimension(LayoutConstants.DEVICE_ADD_X, LayoutConstants.HEIGHT)); - } - jLabelRight - .setIcon(new ImageIcon(TaskScenePanelChart.class.getClassLoader().getResource("images/icon_usb.png"))); - } - - /** - * 布局jPanelMiddleLeft容器 - */ - public void setScrollPane() { - jPanelMiddleLeft.setLayout(new BorderLayout()); - jScrollCardsPanelInner.setOpaque(true); - jScrollCardsPanelInner.setBackground(ColorConstants.BLACK_COLOR); - jScrollPane.setBorder(null); - jScrollPane.getVerticalScrollBar().setUnitIncrement(LayoutConstants.MEMORY_Y); - jScrollCardsPanel.add(jScrollCardsPanelInner); - jScrollCardsPanelInner.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.SCROPNUM)); - jPanelMiddleLeft.add(jScrollPane); - jScrollCardsPanelInner.setLayout(null); - } - - /** - * 创建页面分割事件 - */ - public void createSplitPanel() { - jPanelMiddleLeft.setMinimumSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.JAVA_WIDTH)); - jPanelMiddleRight.setMinimumSize(new Dimension(0, LayoutConstants.JAVA_WIDTH)); - - jpanelSupen.setPreferredSize(new Dimension(0, LayoutConstants.HUNDRED)); - jPanelMiddleLeft.setLayout(new GridLayout()); - jPanelMiddleRight.setLayout(new GridLayout()); - jPanelMiddleLeft.setOpaque(true); - jPanelMiddleRight.setOpaque(true); - jPanelMiddleLeft.setBackground(ColorConstants.BLACK_COLOR); - jPanelMiddleRight.setBackground(Color.white); - jPanelMiddleLeft.setPreferredSize(new Dimension(LayoutConstants.HEIGHT_Y, LayoutConstants.JAVA_WIDTH)); - // 让分割线显示出箭头 - splitPane.setOneTouchExpandable(false); - splitPane.setContinuousLayout(true); - // 设定分割线的距离左边的位置. - splitPane.setDividerLocation(LayoutConstants.HEIGHT_Y); - splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); - splitPane.setDividerSize(1); - splitPane.setLeftComponent(jPanelMiddleLeft); - splitPane.setRightComponent(jPanelMiddleRight); - panelMiddle.add(splitPane); - panelMiddle.add(jpanelSupen, BorderLayout.EAST); - } - - /** - * 使用内部类完成标签移动操作 - */ - private class DynamicThread extends Thread { - @Override - public void run() { - while (true) { - for (int index = 0; index < LayoutConstants.NUMBER_FOR; index++) { - try { - Thread.sleep(LayoutConstants.NUMBER_SLEEEP); - } catch (InterruptedException exception) { - LOGGER.error(exception.getMessage()); - } - jLabelSetting.setLocation(-index, 0); - } - } - } - } - - /** - * 布局panelTop容器,添加按钮 - */ - public void setPanelTopAttributes() { - timeJComboBox.setBorder(BorderFactory.createLineBorder(Color.black)); - timeJComboBox.setPreferredSize(new Dimension(LayoutConstants.SE_PANEL_Y_TWO, LayoutConstants.APP_LABEL_X)); - timeJComboBox.addItem("200ms"); - timeJComboBox.addItem("400ms"); - timeJComboBox.addItem("600ms"); - timeJComboBox.addItem("800ms"); - timeJComboBox.addItem("1000ms"); - timeJComboBox.setSelectedIndex(NUM_4); - jPanelWest.setLayout( - new FlowLayout(FlowLayout.LEADING, LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.JP_LABEL_HEIGHT)); - jPanelEast.setLayout( - new FlowLayout(FlowLayout.LEADING, LayoutConstants.JP_LABEL_HEIGHT, LayoutConstants.JP_LABEL_HEIGHT)); - jButtonRun.setPreferredSize(new Dimension(LayoutConstants.BUTTON_WIDTHS, LayoutConstants.BUTTON_SIZE)); - jButtonStop.setPreferredSize(new Dimension(LayoutConstants.BUTTON_WIDTHS, LayoutConstants.BUTTON_SIZE)); - jPanelWest.add(jButtonRun); - jPanelWest.add(jButtonStop); - jPanelWest.add(jButtonUp); - jPanelWest.add(jLabelMidde); - jPanelWest.add(jPanelLabel); - jPanelWest.add(jButtonNext); - jPanelWest.add(jButtonSave); - jPanelWest.add(jButtonDelete); - jPanelEast.add(timeJComboBox); - jPanelEast.add(jButtonInsert); - jPanelEast.add(jButtonBottom); - jPanelEast.add(jButtonLeft); - jPanelEast.add(jButtonHelp); - } - - /** - * 设置按钮属性 - */ - public void setButtonAttributes() { - jButtonUp.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonUp.setFocusPainted(false); - jButtonUp.setBorderPainted(false); - jButtonUp.setToolTipText("上一页"); - jButtonNext.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonNext.setFocusPainted(false); - jButtonNext.setBorderPainted(false); - jButtonNext.setToolTipText("下一页"); - jButtonRun.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonRun.setFocusPainted(false); - jButtonRun.setBorderPainted(false); - jButtonRun.setToolTipText("停止"); - jButtonStop.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonStop.setFocusPainted(false); - jButtonStop.setBorderPainted(false); - jButtonStop.setToolTipText("暂停"); - jButtonSave.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonSave.setFocusPainted(false); - jButtonSave.setBorderPainted(false); - jButtonSave.setToolTipText("保存当前任务"); - jButtonDelete.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonDelete.setFocusPainted(false); - jButtonDelete.setBorderPainted(false); - jButtonDelete.setToolTipText("删除当前任务"); - jButtonInsert.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonInsert.setFocusPainted(false); - jButtonInsert.setBorderPainted(false); - jButtonInsert.setToolTipText("新增配置"); - jButtonBottom.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonBottom.setFocusPainted(false); - jButtonBottom.setBorderPainted(false); - jButtonBottom.setToolTipText("向下展开页面"); - jButtonHelp.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonHelp.setFocusPainted(false); - jButtonHelp.setBorderPainted(false); - jButtonHelp.setToolTipText("帮助"); - jButtonLeft.setBackground(ColorConstants.DEVICE_PROCESS_PANEL); - jButtonLeft.setFocusPainted(false); - jButtonLeft.setBorderPainted(false); - jButtonLeft.setToolTipText("向左展开页面"); - } - - /** - * Overall page layout settings - * - * @param jTaskPanel jTaskPanel - * @param hosJLabelList hosJLabelList - */ - public void setLayAttributes(TaskPanel jTaskPanel, List hosJLabelList) { - this.setLayout(new BorderLayout()); - panelTop.setBackground(ColorConstants.BLACK_COLOR); - panelTop.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.APP_LABEL_HIGHT)); - // 页面中间部分 - panelMiddle.setBackground(Color.white); - panelMiddle.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.JAVA_WIDTH)); - // 页面下面部分 - panelBottom.setBackground(ColorConstants.BLACK_COLOR); - panelBottom.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.LABEL_NAME_WIDTH)); - this.add(panelTop, BorderLayout.NORTH); - this.add(panelMiddle, BorderLayout.CENTER); - jPanelWest.setOpaque(false); - jPanelCenter.setOpaque(false); - jPanelEast.setOpaque(false); - jPanelWest.setPreferredSize(new Dimension(LayoutConstants.EAST_LABEL_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); - jPanelCenter.setPreferredSize(new Dimension(LayoutConstants.DEVICES_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); - jPanelEast.setPreferredSize(new Dimension(LayoutConstants.TASK_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT)); - panelTop.add(jPanelWest, BorderLayout.WEST); - panelTop.add(jPanelCenter, BorderLayout.CENTER); - panelTop.add(jPanelEast, BorderLayout.EAST); - HosJLabel hosJLabel = hosJLabelList.get(0); - jLabelSetting = new JLabel(hosJLabel.getProcessName() + "(" + hosJLabel.getDeviceName() + ")"); - - jLabelSetting.setBounds(0, 0, LayoutConstants.EAST_LABEL_WIDTH, LayoutConstants.LABEL_NAME_HEIGHT); - jTaskPanel.getJPanelLeft().removeAll(); - jTaskPanel.getJPanelRight().removeAll(); - jTaskPanel.getJPanelLeft().add(jLabelSetting); - jTaskPanel.getJPanelRight().add(jTaskPanel.getJLabelClose()); - jTextArea.setOpaque(true); - jTextArea.setBackground(ColorConstants.BLACK_COLOR); - jPanelLabel.add(jTextArea); - } - - public HosJButton getJButtonDelete() { - return jButtonDelete; - } - - public HosJButton getjButtonRun() { - return jButtonRun; - } - - public HosJButton getjButtonStop() { - return jButtonStop; - } - - public HosJButton getjButtonSave() { - return jButtonSave; - } - - public HosJButton getjButtonInsert() { - return jButtonInsert; - } - - public HosJButton getjButtonBottom() { - return jButtonBottom; - } - - public JButton getjButtonHelp() { - return jButtonHelp; - } - - public HosJButton getjButtonLeft() { - return jButtonLeft; - } - - public JButton getjButtonUp() { - return jButtonUp; - } - - public JButton getjButtonNext() { - return jButtonNext; - } - - public JPanel getPanelBottom() { - return panelBottom; - } - - public JSplitPane getSplitPane() { - return splitPane; - } - - public JPanel getJScrollCardsPanelInner() { - return jScrollCardsPanelInner; - } - - public JLabel getjLabelLeft() { - return jLabelLeft; - } - - public JPanel getCards() { - return cards; - } - - public CardLayout getCardLayout() { - return cardLayout; - } - - public JPanel getjPanelSuspension() { - return jPanelSuspension; - } - - public HosJComboBox getjComboBox() { - return jComboBox; - } - - public HosJComboBox getTimeJComboBox() { - return timeJComboBox; - } - - public CountingThread getCounting() { - return counting; - } - - public void setCounting(CountingThread counting) { - this.counting = counting; - } - - public JLabel getjTextArea() { - return jTextArea; - } - - public JPanel getJpanelSupen() { - return jpanelSupen; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskSystemTunningByTracePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskSystemTunningByTracePanel.java deleted file mode 100644 index 7ff0e4766..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/swing/TaskSystemTunningByTracePanel.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import java.awt.BorderLayout; -import java.util.List; - -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.views.layout.event.SystemTunningByTraceConfigEvent; - -/** - * @Description TaskSystemTunningByTracePanel - * @Date 2021/4/9 13:15 - **/ -public class TaskSystemTunningByTracePanel extends JPanel { - /** - * 设备信息集合 - */ - private List deviceInfos = null; - - /** - * 设备名称下拉框 - */ - private JComboBox jComboBoxPhone = new JComboBox(); - - /** - * 三级页面事件类 - */ - private SystemTunningByTraceConfigEvent taskSystemTunningByTracePanelEvent = new SystemTunningByTraceConfigEvent(); - - /** - * TaskSystemTunningByTracePanel - * - * @param jTaskPanel jTaskPanel - */ - public TaskSystemTunningByTracePanel(TaskPanel jTaskPanel) { - // 设置三级界面布局方式为边框布局管理 - this.setLayout(new BorderLayout()); - // 设置top容器,Center容器,South容器的属性 - // Center容器设置 - setjPanelCenter(); - // South容器设置 - } - - /** - * setjPanelCenter - */ - public void setjPanelCenter() { - taskSystemTunningByTracePanelEvent.devicesInfoJComboBoxUpdate(this); - } - - /** - * setDeviceInfos - * - * @param deviceInfos deviceInfos - */ - public void setDeviceInfos(List deviceInfos) { - this.deviceInfos = deviceInfos; - } - - /** - * getJComboBoxPhone - * - * @return JComboBox - */ - public JComboBox getJComboBoxPhone() { - return jComboBoxPhone; - } - - /** - * getDeviceInfos - * - * @return List - */ - public List getDeviceInfos() { - return deviceInfos; - } - -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/ColorTableCellRenderer.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/ColorTableCellRenderer.java deleted file mode 100644 index b2f5e298e..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/ColorTableCellRenderer.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.util; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Color; -import java.awt.Component; - -/** - * ColorTableCellRenderer - * - * @version 1.0 - * @date 2021/3/4 10:55 - **/ -public class ColorTableCellRenderer extends DefaultTableCellRenderer { - /** - * getTableCellRendererComponent - * - * @param table table - * @param value value - * @param isSelected isSelected - * @param hasFocus hasFocus - * @param row row - * @param column column - * @return Component - */ - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, - int row, int column) { - Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - - Object selectedValue = table.getModel().getValueAt(row, column); - if ("E".equals(selectedValue.toString())) { - comp.setForeground(Color.RED); - } else if ("D".equals(selectedValue.toString())) { - comp.setForeground(Color.blue); - } else if ("I".equals(selectedValue.toString())) { - comp.setForeground(Color.GREEN); - } else if ("V".equals(selectedValue.toString())) { - comp.setForeground(Color.WHITE); - } else if ("W".equals(selectedValue.toString())) { - comp.setForeground(Color.orange); - } else { - return comp; - } - return comp; - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/FileUtil.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/FileUtil.java deleted file mode 100644 index 50b42c711..000000000 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/util/FileUtil.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Writer; - -/** - * 文件工具类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class FileUtil { - // 日志 - private static final Logger LOGGER = LogManager.getLogger(FileUtil.class); - - /** - * 保存日志内容到txt中 - * - * @param path path - * @param content content - */ - public void writeFile(String path, String content) { - File writefile; - // 通过这个对象来判断是否向文本文件中追加内容 - writefile = new File(path); - // 如果文本文件不存在则创建它 - if (!writefile.exists()) { - try { - writefile.createNewFile(); - writefile = new File(path); - } catch (IOException exception) { - LOGGER.error("createNewFile" + exception.getMessage()); - } - } - try (FileOutputStream fw = new FileOutputStream(writefile, true); - Writer out = new OutputStreamWriter(fw, "utf-8")) { - // 重新实例化 - out.write(content); - String newline = System.getProperty("line.separator"); - // 写入换行 - out.write(newline); - } catch (IOException exception) { - LOGGER.error("createNewFile" + exception.getMessage()); - } - } - - /** - * 读txt 文件 - * - * @param filePath filePath - * @return String - */ - public String readTxtFile(String filePath) { - String end = null; - InputStreamReader read = null; - try { - String encoding = "utf-8"; - String lineTxt = null; - File file = new File(filePath); - if (file.isFile() && file.exists()) { - // 判断文件是否存在 - read = new InputStreamReader(new FileInputStream(file), encoding); - // 考虑到编码格式 - try (BufferedReader bufferedReader = new BufferedReader(read)) { - lineTxt = bufferedReader.readLine(); - while (lineTxt != null) { - end = end + lineTxt + File.separator; - lineTxt = bufferedReader.readLine(); - } - } - read.close(); - } - } catch (IOException exception) { - LOGGER.error(exception.getMessage()); - } finally { - try { - if (read != null) { - read.close(); - } - } catch (IOException exception) { - LOGGER.error("createNewFile" + exception.getMessage()); - } - } - return end.toString(); - } -} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/OpenFileDialogUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/OpenFileDialogUtils.java new file mode 100644 index 000000000..73e6181f8 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/OpenFileDialogUtils.java @@ -0,0 +1,413 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.utils; + +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.ui.ValidationInfo; +import com.intellij.ui.ColoredListCellRenderer; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBList; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.transport.hdc.HdcWrapper; +import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.applicationtrace.AppTracePanel; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.UtConstant; +import ohos.devtools.views.common.customcomp.CustomJLabel; +import ohos.devtools.views.common.customcomp.CustomProgressBar; +import ohos.devtools.views.layout.SystemPanel; +import ohos.devtools.views.layout.TaskPanel; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import ohos.devtools.views.layout.dialog.ImportFileChooserDialog; +import ohos.devtools.views.layout.dialog.SampleDialog; +import ohos.devtools.views.trace.component.AnalystPanel; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.DefaultListModel; +import javax.swing.JComponent; +import javax.swing.JList; +import javax.swing.SwingWorker; +import java.awt.BorderLayout; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.RandomAccessFile; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ExecutionException; + +import static ohos.devtools.datasources.transport.hdc.HdcCmdList.TRACE_STREAMER_LOAD; +import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand; + +/** + * OpenFileDialogUtil + */ +public class OpenFileDialogUtils { + private static OpenFileDialogUtils instance = new OpenFileDialogUtils(); + private static TaskPanel taskPanel; + private static CustomProgressBar progressBar; + private static final Logger LOGGER = LogManager.getLogger(OpenFileDialogUtils.class); + private static final String BYTRACE_TYPE_VALUE = "TRACE"; + private static final String HTRACE_TYPE_VALUE = "OHOSPROF"; + private static final String TRACE_FILE = "TraceFileInfo"; + private Boolean traceAnalysisResult = true; + private String path = ""; + + private OpenFileDialogUtils() { + } + + /** + * Get the current OpenFileDialogUtils object + * + * @return Db + */ + public static OpenFileDialogUtils getInstance() { + if (instance == null) { + instance = new OpenFileDialogUtils(); + } + return instance; + } + + /** + * showFileOpenDialog + * + * @param tabItem tabItem + * @param contentPanel contentPanel + */ + public void showFileOpenDialog(JBPanel tabItem, TaskPanel contentPanel) { + ImportFileChooserDialog fileChooserDialogWrapper = new ImportFileChooserDialog("Open File"); + boolean showAndGet = fileChooserDialogWrapper.showAndGet(); + if (showAndGet) { + taskPanel = contentPanel; + progressBar = new CustomProgressBar(tabItem); + tabItem.remove(taskPanel.getBtnPanel()); + // JProgressBar Listener + tabItem.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + super.componentResized(event); + progressBar.setBounds(LayoutConstants.TEN, tabItem.getHeight() - LayoutConstants.FORTY, + tabItem.getWidth() - LayoutConstants.TWENTY, LayoutConstants.THIRTY); + } + }); + BufferedReader bufferedReader = null; + try { + String fileName = fileChooserDialogWrapper.getImportFilePath(); + bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "GBK")); + String readLineStr = null; + while ((readLineStr = bufferedReader.readLine()) != null) { + break; + } + File selectedFile = new File(fileName); + if (readLineStr == null) { + showWarningDialog(tabItem); + return; + } + loadOfflineFiles(tabItem, readLineStr, selectedFile); + } catch (UnsupportedEncodingException unsupportedEncodingException) { + LOGGER.error(unsupportedEncodingException.getMessage()); + } catch (FileNotFoundException fileNotFoundException) { + LOGGER.error(fileNotFoundException.getMessage()); + } catch (IOException ioException) { + LOGGER.error(ioException.getMessage()); + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ioException) { + LOGGER.error(ioException.getMessage()); + } + } + } + } else { + tabItem.requestFocus(false); + } + } + + /** + * load offline files + * + * @param tabItem tabItem + * @param readLineStr readLineStr + * @param selectedFile selectedFile + */ + private void loadOfflineFiles(JBPanel tabItem, String readLineStr, File selectedFile) { + if (readLineStr.contains(BYTRACE_TYPE_VALUE) || readLineStr.contains(HTRACE_TYPE_VALUE)) { + loadOfflineFile(tabItem, taskPanel, selectedFile, taskPanel.getTabContainer()); + } else if (readLineStr.contains(TRACE_FILE)) { + loadOfflineFile(tabItem, taskPanel, selectedFile, taskPanel.getTabContainer()); + } else { + showWarningDialog(tabItem); + } + } + + /** + * loadOfflineFile + * + * @param optionJPanelContent optionJPanelContent + * @param taskPanel taskPanel + * @param selectedFile selectedFile + * @param optionJPanel optionJPanel + */ + private void loadOfflineFile(JBPanel optionJPanelContent, TaskPanel taskPanel, File selectedFile, + JBPanel optionJPanel) { + SwingWorker, Object> task = new SwingWorker, Object>() { + /** + * doInBackground + * + * @return Optional + */ + @Override + protected Optional doInBackground() { + path = selectedFile.getPath(); + Optional deviceProcessInfo = + SessionManager.getInstance().localSessionDataFromFile(progressBar, selectedFile); + return deviceProcessInfo; + } + + /** + * done + */ + @Override + protected void done() { + try { + Optional deviceProcessInfo = get(); + if (deviceProcessInfo != null && deviceProcessInfo.isPresent()) { + DeviceProcessInfo deviceInfo = deviceProcessInfo.get(); + CustomJLabel hosJLabel = new CustomJLabel(); + hosJLabel.setProcessName(deviceInfo.getProcessName()); + hosJLabel.setSessionId(deviceInfo.getLocalSessionId()); + hosJLabel.setDeviceName(deviceInfo.getDeviceName()); + hosJLabel.setOnline(false); + hosJLabel.setFileType(UtConstant.FILE_TYPE_TRACE); + hosJLabel.setStartTime(deviceInfo.getStartTime()); + hosJLabel.setEndTime(deviceInfo.getEndTime()); + List hosJLabels = new ArrayList(); + hosJLabels.add(hosJLabel); + optionJPanel.removeAll(); + TaskScenePanelChart taskScenePanelChart = new TaskScenePanelChart(taskPanel, hosJLabels); + taskPanel.getTabContainer().setBackground(JBColor.background()); + taskPanel.setLocalSessionId(deviceInfo.getLocalSessionId()); + optionJPanel.add(taskScenePanelChart); + } else { + ChooseTraceTypeDialogWrapper chooseTraceTypeDialogWrapper = + new ChooseTraceTypeDialogWrapper(optionJPanelContent, selectedFile, optionJPanel); + boolean result = chooseTraceTypeDialogWrapper.showAndGet(); + if (!result) { + optionJPanelContent.remove(progressBar); + optionJPanelContent.add(taskPanel.getBtnPanel()); + optionJPanelContent.repaint(); + } + } + } catch (InterruptedException | ExecutionException exception) { + exception.printStackTrace(); + } + } + }; + task.execute(); + } + + /** + * loadTrace + * + * @param optionJPanelContent optionJPanelContent + * @param selectedFile selectedFile + * @param optionJPanel optionJPanel + * @param isAppTrace isAppTrace + */ + public void loadTrace(JBPanel optionJPanelContent, File selectedFile, JBPanel optionJPanel, boolean isAppTrace) { + SwingWorker task = new SwingWorker() { + @Override + protected String doInBackground() throws Exception { + traceAnalysisResult = true; + String logPath = TraceStreamerUtils.getInstance().getLogPath(); + File logFile = new File(logPath); + if (logFile.exists()) { + logFile.delete(); + } + String baseDir = TraceStreamerUtils.getInstance().getBaseDir(); + String dbPath = TraceStreamerUtils.getInstance().getDbPath(); + HdcWrapper.getInstance().getHdcStringResult(conversionCommand(TRACE_STREAMER_LOAD, + baseDir + TraceStreamerUtils.getInstance().getTraceStreamerApp(), selectedFile.getPath(), dbPath)); + randomFile(logFile); + progressBar.setValue(LayoutConstants.FIFTY); + return dbPath; + } + + /** + * done + */ + @Override + protected void done() { + if (!traceAnalysisResult) { + optionJPanelContent.remove(progressBar); + optionJPanelContent.add(taskPanel.getBtnPanel()); + optionJPanelContent.repaint(); + new SampleDialog("Warring", + "The system cannot parse the file properly. Please import the legal file.").show(); + } + try { + if (traceAnalysisResult) { + String dbPath = get(); + addOptionJPanel(dbPath, optionJPanel, isAppTrace); + } + } catch (InterruptedException interruptedException) { + LOGGER.error(interruptedException.getMessage()); + } catch (ExecutionException executionException) { + LOGGER.error(executionException.getMessage()); + } + } + }; + task.execute(); + } + + /** + * addOptionJPanel + * + * @param dbPath dbPath + * @param optionJPanel optionJPanel + * @param isAppTrace isAppTrace + */ + private void addOptionJPanel(String dbPath, JBPanel optionJPanel, boolean isAppTrace) { + optionJPanel.removeAll(); + if (isAppTrace) { + AppTracePanel component = new AppTracePanel(); + component.load(dbPath, null, null, true); + taskPanel.getTabContainer().setBackground(JBColor.background()); + progressBar.setValue(LayoutConstants.HUNDRED); + optionJPanel.add(component); + } else { + AnalystPanel component = new AnalystPanel(); + component.load(dbPath, true); + taskPanel.getTabContainer().setBackground(JBColor.background()); + progressBar.setValue(LayoutConstants.HUNDRED); + SystemPanel systemTuningPanel = new SystemPanel(optionJPanel, component); + optionJPanel.add(systemTuningPanel, BorderLayout.NORTH); + optionJPanel.add(component, BorderLayout.CENTER); + } + } + + /** + * random File + * + * @param logFile log File + * @throws IOException IOException + */ + private void randomFile(File logFile) throws IOException { + RandomAccessFile randomFile = null; + try { + if (logFile.exists()) { + randomFile = new RandomAccessFile(logFile, "r"); + String tmp = null; + while ((tmp = randomFile.readLine()) != null) { + if (Integer.valueOf(tmp.split(":")[1]) != 0) { + traceAnalysisResult = false; + } + } + } + } catch (FileNotFoundException fileNotFoundException) { + LOGGER.error("randomFile exception:{}", fileNotFoundException.getMessage()); + } catch (IOException iOException) { + LOGGER.error("randomFile exception:{}", iOException.getMessage()); + } finally { + if (randomFile != null) { + randomFile.close(); + } + } + } + + private void showWarningDialog(JBPanel tabItem) { + tabItem.remove(progressBar); + tabItem.add(taskPanel.getBtnPanel()); + tabItem.repaint(); + new SampleDialog("prompt", "Please select the right file!").show(); + } + + /** + * ChooseTraceTypeDialogWrapper + */ + private class ChooseTraceTypeDialogWrapper extends DialogWrapper { + private static final String DIALOG_TITLE = "Please Choose the type"; + private static final String SYSTEM_TYPE = "1.System Trace"; + private static final String APPLICATION_TYPE = "2.Application Trace"; + private JBPanel optionJPanelContent; + private JBPanel optionJPanel; + private File selectedFile; + private JBList typeList; + private DefaultListModel listModel; + + /** + * ChooseTraceTypeDialogWrapper + * + * @param optionJPanelContent + * @param selectedFile + * @param optionJPanel + */ + ChooseTraceTypeDialogWrapper(JBPanel optionJPanelContent, File selectedFile, JBPanel optionJPanel) { + super(true); + this.optionJPanelContent = optionJPanelContent; + this.selectedFile = selectedFile; + this.optionJPanel = optionJPanel; + init(); + setTitle(DIALOG_TITLE); + } + + @Nullable + @Override + protected JComponent createCenterPanel() { + listModel = new DefaultListModel<>(); + listModel.add(0, SYSTEM_TYPE); + listModel.add(1, APPLICATION_TYPE); + typeList = new JBList<>(listModel); + ColoredListCellRenderer listCellRenderer = new ColoredListCellRenderer() { + @Override + protected void customizeCellRenderer(@NotNull JList jList, String value, int index, + boolean selected, boolean hasFocus) { + append(value); + } + }; + typeList.setCellRenderer(listCellRenderer); + typeList.setSelectedIndex(0); + return typeList; + } + + @Nullable + @Override + protected ValidationInfo doValidate() { + String value = typeList.getSelectedValue(); + if (value != null) { + if (value.equals(SYSTEM_TYPE)) { + loadTrace(optionJPanelContent, selectedFile, optionJPanel, false); + } + if (value.equals(APPLICATION_TYPE)) { + loadTrace(optionJPanelContent, selectedFile, optionJPanel, true); + } + } + return null; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/TraceStreamerUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/TraceStreamerUtils.java new file mode 100644 index 000000000..fd0775445 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/layout/utils/TraceStreamerUtils.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.utils; + +import ohos.devtools.datasources.utils.session.service.SessionManager; + +import java.io.File; +import java.util.Locale; + +/** + * TraceStreamerUtils + */ +public class TraceStreamerUtils { + private static TraceStreamerUtils traceStreamerUtils; + private static final String DIR_STR = "trace_streamer" + File.separator; + private static final String LOG_STR = "trace_streamer" + File.separator + "trace_streamer.log"; + private static final String DB_NAME = "trace_streamer.db"; + private static final String WIN_APP = "trace_streamer.exe"; + private static final String MAC_APP = "trace_streamer"; + + /** + * getInstance + * + * @return TraceStreamerUtils + */ + public static TraceStreamerUtils getInstance() { + if (traceStreamerUtils == null) { + traceStreamerUtils = new TraceStreamerUtils(); + } + return traceStreamerUtils; + } + + /** + * getBaseDir + * + * @return String + */ + public String getBaseDir() { + String pluginPath = SessionManager.getInstance().getPluginPath(); + return pluginPath + DIR_STR; + } + + /** + * getLogPath + * + * @return String + */ + public String getLogPath() { + String pluginPath = SessionManager.getInstance().getPluginPath(); + String logPath = pluginPath + LOG_STR; + return logPath; + } + + /** + * getDbPath + * + * @return String + */ + public String getDbPath() { + String dbPath = getBaseDir() + DB_NAME; + return dbPath; + } + + /** + * getDbPath + * + * @param dbName dbName + * @return String + */ + public String getDbPath(String dbName) { + String dbPath = getBaseDir() + dbName; + return dbPath; + } + + /** + * getTraceStreamerApp + * + * @return String + */ + public String getTraceStreamerApp() { + String traceStreamerApp = WIN_APP; + if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("mac")) { + traceStreamerApp = MAC_APP; + } + return traceStreamerApp; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractNode.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractNode.java new file mode 100644 index 000000000..21dcc4361 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractNode.java @@ -0,0 +1,104 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.components.JBPanel; + +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.util.List; + +/** + * Abstract Node + * + * @date: 2021/5/14 14:54 + */ +public abstract class AbstractNode { + /** + * current Rectangle + */ + protected Rectangle rect = new Rectangle(); + + /** + * boolean is Mouse In this node + */ + protected boolean isMouseIn; + + /** + * edge inspect + * + * @return return the current Rectangle + */ + public Rectangle getRect() { + return rect; + } + + /** + * set the Rectangle + * + * @param rect rect + */ + public void setRect(Rectangle rect) { + this.rect = rect; + } + + /** + * node draw function + * + * @param paint Graphics2D + */ + public abstract void draw(Graphics2D paint); + + /** + * get the string list + * + * @param time String + * @return string list + */ + public abstract List getStringList(String time); + + /** + * when the mouse move into this node + * + * @param point point + * @param content content + */ + public void moveIn(Point point, JBPanel content) { + isMouseIn = true; + content.repaint(getRect()); + } + + /** + * when the mouse move out from this node + * + * @param point point + * @param content content + */ + public void moveOut(Point point, JBPanel content) { + isMouseIn = false; + content.repaint(getRect()); + } + + /** + * when the node click + * + * @param event event + */ + public void onClick(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractRow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractRow.java new file mode 100644 index 000000000..3ce52e200 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/AbstractRow.java @@ -0,0 +1,603 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.icons.AllIcons; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.util.Consumer; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.applicationtrace.bean.Cpu; +import ohos.devtools.views.applicationtrace.bean.CpuFreq; +import ohos.devtools.views.applicationtrace.bean.Frame; +import ohos.devtools.views.applicationtrace.bean.Func; +import ohos.devtools.views.applicationtrace.bean.Thread; +import ohos.devtools.views.applicationtrace.bean.VsyncAppBean; +import ohos.devtools.views.applicationtrace.util.TimeUtils; + +import javax.swing.Icon; +import javax.swing.JButton; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseEvent; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * AbstractRow + * + * @date: 2021/5/20 15:50 + */ +public abstract class AbstractRow extends JBPanel { + /** + * current row content JBPanel + */ + public JBPanel content; + + /** + * current row startNS + */ + protected long startNS; + + /** + * current row endNS + */ + protected long endNS; + + /** + * current row isLoading + */ + protected AtomicBoolean isLoading = new AtomicBoolean(false); + + /** + * current row MigLayout layout + */ + protected MigLayout layout = new MigLayout("inset 0", "0[110!,left]0[grow,fill]0", "0[grow,fill,center]0"); + + /** + * current row JBLabel nameLabel + */ + protected JBLabel nameLabel = new JBLabel(); + + /** + * current row MouseEvent Consumer nameLabelClickConsumer + */ + protected Consumer nameLabelClickConsumer; + + /** + * current row JButton expandBtn + */ + protected JButton expandBtn = new JButton(); + + private Icon myExpandIcon = AllIcons.General.ArrowRight; + private Icon myCollapseIcon = AllIcons.General.ArrowDown; + private boolean myIsInitialized; + private boolean myIsCollapsed; + private int threadHeight = 14; + private int funcHeight = 20; + private int maxDept = 1; + private final String rowName; + private final int collapsedNodeHeight = 1; + + /** + * fresh the Notify data by startNS and endNS + * + * @param name name + * @param hasExpand hasExpand + * @param defaultExpand defaultExpand + */ + public AbstractRow(String name, boolean hasExpand, boolean defaultExpand) { + this.rowName = name; + setLayout(layout); + expandBtn.setBorderPainted(false); + expandBtn.setContentAreaFilled(false); + expandBtn.setBackground(new Color(0, 0, 0, 0)); + expandBtn.setMaximumSize(new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight())); + expandBtn.setFocusable(true); + nameLabel.setText(name); + if (hasExpand) { + add(expandBtn, "split 2,w 5!,gapleft 15,gapright 5"); + add(nameLabel, "gapleft 10,w 80!"); + } else { + add(nameLabel, "gapleft 15,w 90!"); + } + content = new JBPanel() { + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + contentPaint(graphics); + } + }; + content.setBackground(JBColor.background().darker()); + add(content, "growx,pushx"); + setCollapsed(!defaultExpand); + expandBtn.addActionListener(event -> setCollapsed(!myIsCollapsed)); + } + + /** + * isCollapsed + * @return isCollapsed + */ + public boolean isCollapsed(){ + return myIsCollapsed; + } + + /** + * getStartNS + * + * @return long startNS + */ + public long getStartNS() { + return startNS; + } + + /** + * getEndNS + * + * @return long endNS + */ + public long getEndNS() { + return endNS; + } + + /** + * get Row Name + * + * @return String rowName + */ + public String getRowName() { + return rowName; + } + + /** + * fresh the row data by startNS and endNS + * + * @param startNS startNS + * @param endNS endNS + */ + public void refresh(long startNS, long endNS) { + this.startNS = startNS; + this.endNS = endNS; + content.repaint(); + refreshNotify(); + } + + /** + * fresh the Notify data by startNS and endNS + */ + public void refreshNotify() { + } + + /** + * fresh the Notify data by startNS and endNS + * + * @return return the Rectangle from the content + */ + public Rectangle getContentBounds() { + return content.getBounds(); + } + + /** + * get the max height + * + * @return return the max height + */ + protected int evalHeight() { + int maxHeight = maxDept * getFuncHeight() + getFuncHeight(); + if (maxHeight < 30) { + maxHeight = 30; + } + return maxHeight; + } + + /** + * Set whether to expand + * + * @param isCollapsed isCollapsed + */ + public void setCollapsed(boolean isCollapsed) { + setCollapsed(isCollapsed, null); + } + + /** + * Set whether to expand + * @param isCollapsed isCollapsed + * @param finish null + */ + public void setCollapsed(boolean isCollapsed, Consumer finish) { + int defHeight = getBounds().height; + if (Objects.nonNull(finish)) { + addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + super.componentResized(e); + if (defHeight != e.getComponent().getBounds().height) { + finish.consume(e.getComponent().getBounds()); + } + } + }); + } + try { + if (isCollapsed) { + setFuncHeight(collapsedNodeHeight); + setThreadHeight(collapsedNodeHeight); + } else { + setFuncHeight(20); + setThreadHeight(14); + } + if (getParent() != null && getParent().getLayout() instanceof MigLayout) { + MigLayout migLayout = (MigLayout) getParent().getLayout(); + migLayout.setComponentConstraints(this, "growx,pushx,h " + evalHeight() + "!"); + } + myIsCollapsed = isCollapsed; + Icon icon = myIsCollapsed ? myExpandIcon : myCollapseIcon; + if (icon != null) { + expandBtn.setIcon(icon); + expandBtn.setBorder(null); + expandBtn.setBorderPainted(false); + } + if (isCollapsed) { + expandBtn.requestFocusInWindow(); + expandBtn.setSelected(true); + } else { + content.requestFocusInWindow(); + } + revalidate(); + repaint(); + } finally { + myIsInitialized = true; + } + } + + /** + * get the threadHeight + * + * @return return the current threadHeight + */ + public int getThreadHeight() { + return threadHeight; + } + + /** + * set the threadHeight + * + * @param threadHeight threadHeight + */ + public void setThreadHeight(int threadHeight) { + this.threadHeight = threadHeight; + } + + /** + * get the FuncHeight + * + * @return return the current FuncHeight + */ + public int getFuncHeight() { + return funcHeight; + } + + /** + * set the FuncHeight + * + * @param funcHeight funcHeight + */ + public void setFuncHeight(int funcHeight) { + this.funcHeight = funcHeight; + } + + /** + * get the Name + * + * @return return the current nameLabel text + */ + public String getName() { + return nameLabel.getText(); + } + + /** + * contentPaint paint content + * + * @param graphics graphics + */ + public abstract void contentPaint(Graphics graphics); + + /** + * load data + */ + public abstract void loadData(); + + /** + * set the Point + * + * @param point point + */ + public void mouseMoveHandler(Point point) { + } + + /** + * get the time by x Coordinates + * + * @param xCoordinates xCoordinates + * @return time string + */ + public String getTimeByX(int xCoordinates) { + double width = (getEndNS() - getStartNS()) * xCoordinates * 1.0 / getContentBounds().getWidth(); + return TimeUtils.getTimeFormatString((long) width + getStartNS()); + } + + /** + * get the func is in this row + * + * @param func func + * @return return the row is contains func + */ + public boolean contains(Func func) { + return func.getStartTs() + func.getDur() > getStartNS() && func.getStartTs() < getEndNS(); + } + + /** + * get the threadData is in this row + * + * @param threadData threadData + * @return return the row is contains threadData + */ + public boolean contains(Thread threadData) { + return threadData.getStartTime() + threadData.getDuration() > getStartNS() + && threadData.getStartTime() < getEndNS(); + } + + /** + * get the cpu is in this row + * + * @param cpu cpu + * @return return the row is contains Cpu + */ + public boolean contains(Cpu cpu) { + return cpu.getStartTime() + cpu.getDuration() > getStartNS() && cpu.getStartTime() < getEndNS(); + } + + /** + * get the CpuFreq is in this row + * + * @param item item + * @return return the row is contains CpuFreq + */ + public boolean contains(CpuFreq item) { + return item.getStartTime() + item.getDuration() > getStartNS() && item.getStartTime() < getEndNS(); + } + + /** + * get the VsyncAppBean is in this row + * + * @param item item + * @return return the row is contains VsyncAppBean + */ + public boolean contains(VsyncAppBean item) { + return item.getStartTime() + item.getDuration() > getStartNS() && item.getStartTime() < getEndNS(); + } + + /** + * get the Frame is in this row + * + * @param item item + * @return return the row is contains Frame + */ + public boolean contains(Frame item) { + return item.getStartNs() + item.getDur() > getStartNS() && item.getStartNs() < getEndNS(); + } + + /** + * get the Object is in this row + * + * @param obj obj + * @return return the row is contains obj + */ + public boolean contains(Object obj) { + if (obj instanceof CpuFreq) { + return contains((CpuFreq) obj); + } else if (obj instanceof Cpu) { + return contains((Cpu) obj); + } else if (obj instanceof Thread) { + return contains((Thread) obj); + } else if (obj instanceof Func) { + return contains((Func) obj); + } else if (obj instanceof VsyncAppBean) { + return contains((VsyncAppBean) obj); + } else if (obj instanceof Frame) { + return contains((Frame) obj); + } else { + return false; + } + } + + /** + * get the Rectangle by Cpu node + * + * @param node node + * @param padding Rectangle padding + * @return return Rectangle + */ + public Rectangle getRectByNode(Cpu node, int padding) { + double x1; + double x2; + if (node.getStartTime() < getStartNS()) { + x1 = 0; + } else { + x1 = Common.ns2x(node.getStartTime(), getContentBounds()); + } + if (node.getStartTime() + node.getDuration() > getEndNS()) { + x2 = getContentBounds().getWidth(); + } else { + x2 = Common.ns2x(node.getStartTime() + node.getDuration(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = new Rectangle((int) x1, (int) (getContentBounds().getY() + padding), (int) getV, + (int) (getContentBounds().getHeight() - padding * 2)); + return rectangle; + } + + /** + * get the Rectangle by Thread node + * + * @param node node + * @param height Rectangle height + * @return return Rectangle + */ + public Rectangle getRectByNode(Thread node, int height) { + double x1; + double x2; + if (node.getStartTime() < getStartNS()) { + x1 = Common.ns2x(getStartNS(), getContentBounds()); + } else { + x1 = Common.ns2x(node.getStartTime(), getContentBounds()); + } + if (node.getStartTime() + node.getDuration() > getEndNS()) { + x2 = Common.ns2x(getEndNS(), getContentBounds()); + } else { + x2 = Common.ns2x(node.getStartTime() + node.getDuration(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = new Rectangle((int) x1, (int) (getContentBounds().getY()), (int) getV, height); + return rectangle; + } + + /** + * get the Rectangle by Func node + * + * @param node node + * @param height Rectangle height + * @param paddingTop Rectangle paddingTop + * @return return Rectangle + */ + public Rectangle getRectByNode(Func node, int paddingTop, int height) { + double x1; + double x2; + if (node.getStartTs() < getStartNS()) { + x1 = Common.ns2x(getStartNS(), getContentBounds()); + } else { + x1 = Common.ns2x(node.getStartTs(), getContentBounds()); + } + if (node.getStartTs() + node.getDur() > getEndNS()) { + x2 = Common.ns2x(getEndNS(), getContentBounds()); + } else { + x2 = Common.ns2x(node.getStartTs() + node.getDur(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = + new Rectangle((int) x1, (int) (getContentBounds().getY() + node.getDepth() * height + paddingTop), + (int) getV, height); + return rectangle; + } + + /** + * get the Rectangle by CpuFreq node + * + * @param node node + * @return return Rectangle + */ + public Rectangle getRectByNode(CpuFreq node) { + double x1; + double x2; + if (node.getStartTime() < getStartNS()) { + x1 = Common.ns2x(getStartNS(), getContentBounds()); + } else { + x1 = Common.ns2x(node.getStartTime(), getContentBounds()); + } + if (node.getStartTime() + node.getDuration() > getEndNS()) { + x2 = Common.ns2x(getEndNS(), getContentBounds()); + } else { + x2 = Common.ns2x(node.getStartTime() + node.getDuration(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = + new Rectangle((int) x1, (int) (getContentBounds().getY()), (int) getV, getContentBounds().height); + return rectangle; + } + + /** + * get the Rectangle by VsyncAppBean node + * + * @param node node + * @return return Rectangle + */ + public Rectangle getRectByNode(VsyncAppBean node) { + double x1; + double x2; + if (node.getStartTime() < getStartNS()) { + x1 = Common.ns2x(getStartNS(), getContentBounds()); + } else { + x1 = Common.ns2x(node.getStartTime(), getContentBounds()); + } + if (node.getStartTime() + node.getDuration() > getEndNS()) { + x2 = Common.ns2x(getEndNS(), getContentBounds()); + } else { + x2 = Common.ns2x(node.getStartTime() + node.getDuration(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = + new Rectangle((int) x1, (int) (getContentBounds().getY()), (int) getV, getContentBounds().height); + return rectangle; + } + + /** + * get the Rectangle by Frame node + * + * @param node node + * @param height Rectangle height + * @return return Rectangle + */ + public Rectangle getRectByNode(Frame node, int height) { + double x1; + double x2; + if (node.getStartNs() < getStartNS()) { + x1 = Common.ns2x(getStartNS(), getContentBounds()); + } else { + x1 = Common.ns2x(node.getStartNs(), getContentBounds()); + } + if (node.getStartNs() + node.getDur() > getEndNS()) { + x2 = Common.ns2x(getEndNS(), getContentBounds()); + } else { + x2 = Common.ns2x(node.getStartNs() + node.getDur(), getContentBounds()); + } + double getV = x2 - x1 <= 1 ? 1 : x2 - x1; + Rectangle rectangle = new Rectangle((int) x1, (int) (getContentBounds().getY() + 5), (int) getV, height); + return rectangle; + } + + /** + * get the maxDept + * + * @return maxDept maxDept + */ + public int getMaxDept() { + return this.maxDept; + } + + /** + * set the maxDept + * + * @param maxDept maxDept + */ + public void setMaxDept(int maxDept) { + this.maxDept = maxDept; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Common.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Common.java new file mode 100644 index 000000000..51781710d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Common.java @@ -0,0 +1,223 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import ohos.devtools.views.trace.util.Utils; + +import java.awt.AlphaComposite; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.geom.Rectangle2D; + +import static ohos.devtools.views.trace.TracePanel.DURATION; +import static ohos.devtools.views.trace.TracePanel.endNS; +import static ohos.devtools.views.trace.TracePanel.startNS; + +/** + * Common util + * + * @date: 2021/5/13 16:40 + */ +public class Common { + private static final int LEN = 3; + private static final int LEFT_PADDING = 2; + private static final int RIGHT_PADDING = 2; + + /** + * Get the string Rect + * + * @param str str + * @param graphics graphics + * @return Rectangle2D + */ + public static Rectangle2D getStringRect(Graphics graphics, String str) { + Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); + return bounds; + } + + /** + * x coordinate to time (unit ns) + * + * @param coordX coordX + * @param rect rect + * @return long time + */ + public static long x2ns(final int coordX, Rectangle rect) { + return x2ns(coordX, rect, DURATION); + } + + /** + * x coordinate to time (unit ns) + * + * @param coordX coordX + * @param rect rect + * @param duration duration + * @return long time + */ + public static long x2ns(final int coordX, Rectangle rect, long duration) { + long ns = (long) ((coordX - rect.getX()) * duration / (rect.getWidth() - Utils.getX(rect))); + return ns; + } + + /** + * time to x coordinate + * + * @param ns ns + * @param rect rect + * @return double x coordinate + */ + public static double ns2x(long ns, Rectangle rect) { + return ns2x(ns, rect, DURATION); + } + + /** + * time to x coordinate + * + * @param ns ns + * @param rect rect + * @param duration duration + * @return double x coordinate + */ + public static double ns2x(long ns, Rectangle rect, long duration) { + if (endNS == 0) { + endNS = duration; + } + double xSize = (ns - startNS) * rect.getWidth() / (endNS - startNS); + if (xSize < 0) { + xSize = 0; + } + if (xSize > rect.getWidth()) { + xSize = rect.getWidth(); + } + return xSize; + } + + /** + * time to x coordinate by duration + * + * @param ns ns + * @param rect rect + * @param duration duration + * @return double x coordinate + */ + public static double nsToXByDur(long ns, Rectangle rect, long duration) { + double xSize = ns * rect.getWidth() / duration; + if (xSize < 0) { + xSize = 0; + } + if (xSize > rect.getWidth()) { + xSize = rect.getWidth(); + } + return xSize; + } + + /** + * set alpha + * + * @param g2 g2 + * @param alpha alpha + */ + public static void setAlpha(Graphics2D g2, float alpha) { + g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); + } + + /** + * draw String in the Center + * + * @param graphics graphics + * @param str str + * @param rectangle rectangle + */ + public static void drawStringCenter(Graphics2D graphics, String str, final Rectangle rectangle) { + Rectangle2D minBound = + graphics.getFontMetrics(graphics.getFont()).getStringBounds("m...", graphics); // show string min rect + if (rectangle.width < minBound.getWidth() || rectangle.height < minBound.getHeight()) { + return; + } + Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); + double chartWidth = bounds.getWidth() / str.length(); // The width of each character + + // How many characters can be displayed in the rectangle + double chartNum = (rectangle.width - LEFT_PADDING - RIGHT_PADDING) / chartWidth; + int mY = (int) (rectangle.getY() + rectangle.height / 2 + bounds.getHeight() / 2); + if (chartNum >= str.length()) { + graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); + } else if (chartNum >= LEN + 1) { + graphics.drawString(str.substring(0, (int) chartNum - LEN) + "...", (int) (rectangle.getX() + LEFT_PADDING), + mY); + } else if (chartNum > 1 && chartNum < LEN) { // If only one character can be displayed + graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); + } else { + graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); + } + } + + /** + * Draw strings centered vertically and horizontally, + * using this method when graphics are passed in from a single component. + * + * @param graphics graphics + * @param str str + * @param rectangle rectangle + */ + public static void drawStringVHCenter(Graphics2D graphics, String str, final Rectangle rectangle) { + if (rectangle.width < 5 || rectangle.height < 5) { + return; + } + Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); + double chartWidth = bounds.getWidth() / str.length(); // The width of each character + // How many characters can be displayed in the rectangle + double chartNum = (rectangle.width - LEFT_PADDING - RIGHT_PADDING) / chartWidth; + int mY = (int) (rectangle.height / 2 + bounds.getHeight() / 2); + if (chartNum >= str.length()) { + graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); + } else if (chartNum >= LEN + 1) { + graphics.drawString(str.substring(0, (int) chartNum - LEN) + "...", (int) (rectangle.getX() + LEFT_PADDING), + mY); + } else if (chartNum > 1 && chartNum < LEN) { // If only one character can be displayed + graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); + } else { + graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); + } + } + + /** + * Draw strings middle height vertically and horizontally, + * using this method when graphics are passed in from a single component. + * + * @param g2 g2 + * @param str str + * @param rect rect + */ + public static void drawStringMiddleHeight(Graphics2D g2, String str, final Rectangle rect) { + Rectangle2D bounds = g2.getFontMetrics().getStringBounds(str, g2); + double chartWidth = bounds.getWidth() / str.length(); + double chartNum = (rect.width - LEFT_PADDING - RIGHT_PADDING) / chartWidth; + if (chartNum >= str.length()) { + g2.drawString(str, Utils.getX(rect), + (float) (Utils.getY(rect) + rect.height / 2 + bounds.getHeight() / 2 - 3)); + } else { + if (chartNum >= LEN + 1) { + g2.drawString(str.substring(0, (int) chartNum - LEN) + "...", Utils.getX(rect), + (float) (Utils.getY(rect) + rect.height / 2 + bounds.getHeight() / 2 - 3)); + } else if (chartNum > 1 && chartNum < LEN) { + g2.drawString(str.substring(0, 1), Utils.getX(rect), + (float) (Utils.getY(rect) + rect.height / 2 + bounds.getHeight() / 2 - 3)); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/CpuDb.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/CpuDb.java new file mode 100644 index 000000000..422c0cdfd --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/CpuDb.java @@ -0,0 +1,296 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import ohos.devtools.views.trace.util.DataUtils; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.Charset; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * CpuDb data + * + * @date 2021/04/22 12:25 + */ +public final class CpuDb { + private static boolean isLocal; + private static volatile CpuDb db = new CpuDb(); + private static String dbName; + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + private LinkedBlockingQueue pool = new LinkedBlockingQueue<>(); + + private CpuDb() { + } + + /** + * Gets the value of dbName . + * + * @return the value of java.lang.String + */ + public static String getDbName() { + return dbName; + } + + /** + * Sets the dbName . + *

You can use getDbName() to get the value of dbName

+ * + * @param dbName dbName + */ + public static void setDbName(final String dbName) { + CpuDb.dbName = dbName; + } + + /** + * Load the database file according to the file location variable + * + * @param isLocal isLocal + */ + public static void load(final boolean isLocal) { + CpuDb.isLocal = isLocal; + final int maxConnNum = 10; + try { + Class.forName("org.sqlite.JDBC"); + for (Connection connection : db.pool) { + connection.close(); + } + db.pool.clear(); + for (int size = 0; size < maxConnNum; size++) { + db.newConn().ifPresent(connection -> { + try { + db.pool.put(connection); + } catch (InterruptedException interruptedException) { + interruptedException.printStackTrace(); + } + }); + } + db.newConn().ifPresent(con -> { + try { + Statement statement = con.createStatement(); + String views = getSql("Views"); + for (String view : views.split(";")) { + statement.execute(view + ";"); + } + statement.close(); + con.close(); + } catch (SQLException exception) { + exception.printStackTrace(); + } + }); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } catch (ClassNotFoundException classNotFoundException) { + classNotFoundException.printStackTrace(); + } + } + + /** + * Get the current current db object + * + * @return CpuDb + */ + public static CpuDb getInstance() { + if (db == null) { + db = new CpuDb(); + } + return db; + } + + /** + * Read the sql directory under resource + * + * @param sqlName sqlName + * @return String sql + */ + public static String getSql(String sqlName) { + String path = "sql-app/" + sqlName + ".txt"; + try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) { + return IOUtils.toString(STREAM, Charset.forName("UTF-8")); + } catch (UnsupportedEncodingException exception) { + exception.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + return ""; + } + + /** + * Get database connection + * + * @return Connection + */ + public Connection getConn() { + Connection connection = null; + try { + connection = pool.take(); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + return connection; + } + + /** + * Return the connection to the database connection pool after use + * + * @param conn conn + */ + public void free(final Connection conn) { + try { + pool.put(conn); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + } + + private Optional newConn() { + URL path = URLClassLoader.getSystemClassLoader().getResource(dbName); + Connection conn = null; + try { + if (isLocal) { + conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); + } else { + conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + return Optional.ofNullable(conn); + } + + /** + * query data by sql str + * + * @param em em + * @param res res + * @param args args + * @param T + */ + public void query(Sql em, List res, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + query(sql, res); + } + + /** + * query data by sql str + * + * @param sql sql + * @param res res + * @param T + */ + public void query(String sql, List res) { + Statement stat = null; + ResultSet rs = null; + Connection conn = getConn(); + Type argument = getType(res); + try { + Class aClass = (Class) Class.forName(argument.getTypeName()); + stat = conn.createStatement(); + rs = stat.executeQuery(sql); + ArrayList columnList = new ArrayList<>(); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + for (int count = 1; count <= columnCount; count++) { + columnList.add(rsMeta.getColumnName(count)); + } + while (rs.next()) { + T data = aClass.getConstructor().newInstance(); + for (Field declaredField : aClass.getDeclaredFields()) { + declaredField.setAccessible(true); + DField annotation = declaredField.getAnnotation(DField.class); + if (Objects.nonNull(annotation) && columnList.contains(annotation.name())) { + setData(declaredField, data, rs, annotation); + } + } + res.add(data); + } + } catch (ClassNotFoundException | SQLException | InstantiationException + | IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + } + + private void setData(Field declaredField, T data, ResultSet rs, DField annotation) + throws SQLException, IllegalAccessException { + if (declaredField.getType() == Long.class || declaredField.getType() == long.class) { + declaredField.set(data, rs.getLong(annotation.name())); + } else if (declaredField.getType() == Integer.class || declaredField.getType() == int.class) { + declaredField.set(data, rs.getInt(annotation.name())); + } else if (declaredField.getType() == Double.class || declaredField.getType() == double.class) { + declaredField.set(data, rs.getDouble(annotation.name())); + } else if (declaredField.getType() == Float.class || declaredField.getType() == float.class) { + declaredField.set(data, rs.getFloat(annotation.name())); + } else if (declaredField.getType() == Boolean.class || declaredField.getType() == boolean.class) { + declaredField.set(data, rs.getBoolean(annotation.name())); + } else if (declaredField.getType() == Blob.class) { + declaredField.set(data, rs.getBytes(annotation.name())); + } else { + declaredField.set(data, rs.getObject(annotation.name())); + } + } + + private Type getType(List res) { + Type clazz = res.getClass().getGenericSuperclass(); + ParameterizedType pt = null; + if (clazz instanceof ParameterizedType) { + pt = (ParameterizedType) clazz; + } + if (pt == null) { + return clazz; + } + Type argument = pt.getActualTypeArguments()[0]; + return argument; + } + + private void release(ResultSet rs, Statement stat, Connection conn) { + try { + if (Objects.nonNull(rs)) { + rs.close(); + } + if (Objects.nonNull(stat)) { + stat.close(); + } + if (Objects.nonNull(conn)) { + free(conn); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/DField.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/DField.java new file mode 100644 index 000000000..abf3d31dd --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/DField.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * DField + * + * @date: 2021/5/26 15:40 + */ +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface DField { + String name() default ""; +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Db.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Db.java new file mode 100644 index 000000000..4a54ef3a0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Db.java @@ -0,0 +1,335 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import ohos.devtools.views.trace.util.DataUtils; +import ohos.devtools.views.trace.util.Final; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.Charset; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Database operation class + * + * @date 2021/04/22 12:25 + */ +public final class Db { + private static boolean isLocal; + private static volatile Db db = new Db(); + private static String dbName = "trace.db"; + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + private LinkedBlockingQueue pool = new LinkedBlockingQueue<>(); + + private Db() { + } + + /** + * Gets the value of dbName . + * + * @return String + */ + public static String getDbName() { + return dbName; + } + + /** + * Sets the dbName.You can use getDbName() to get the value of dbName

+ * + * @param dbName dbName + */ + public static void setDbName(final String dbName) { + Db.dbName = dbName; + } + + /** + * Load the database file according to the file location variable + * + * @param isLocal isLocal + */ + public static void load(final boolean isLocal) { + Db.isLocal = isLocal; + final int maxConnNum = 10; + try { + Class.forName("org.sqlite.JDBC"); + for (Connection connection : db.pool) { + connection.close(); + } + db.pool.clear(); + for (int size = 0; size < maxConnNum; size++) { + db.newConn().ifPresent(connection -> { + try { + db.pool.put(connection); + } catch (InterruptedException interruptedException) { + interruptedException.printStackTrace(); + } + }); + } + db.newConn().ifPresent(connection -> { + try { + Statement statement = connection.createStatement(); + String views = getSql("Views"); + for (String view : views.split(";")) { + statement.execute(view + ";"); + } + statement.close(); + connection.close(); + } catch (SQLException exception) { + exception.printStackTrace(); + } + }); + } catch (SQLException | ClassNotFoundException throwables) { + throwables.printStackTrace(); + } + } + + /** + * Get the current current db object + * + * @return Db + */ + public static Db getInstance() { + if (db == null) { + db = new Db(); + } + return db; + } + + /** + * Read the sql directory under resource + * + * @param sqlName sqlName + * @return String sql + */ + public static String getSql(String sqlName) { + String tmp = Final.OHOS ? "-self/" : "/"; + String path = "sql-app" + tmp + sqlName + ".txt"; + try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) { + return IOUtils.toString(STREAM, Charset.forName("UTF-8")); + } catch (IOException exception) { + exception.printStackTrace(); + } + return ""; + } + + /** + * Get database connection + * + * @return Connection + */ + public Connection getConn() { + Connection connection = null; + try { + connection = pool.take(); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + return connection; + } + + /** + * Return the connection to the database connection pool after use + * + * @param conn conn + */ + public void free(final Connection conn) { + try { + pool.put(conn); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + } + + private Optional newConn() { + URL path = URLClassLoader.getSystemClassLoader().getResource(dbName); + Connection conn = null; + try { + if (isLocal) { + conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); + } else { + conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + return Optional.ofNullable(conn); + } + + /** + * query sql count + * + * @param em em + * @param args args + * @return count int + */ + public int queryCount(Sql em, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + return queryCount(sql); + } + + /** + * query count from sql + * + * @param sql sql + * @return count int + */ + public int queryCount(String sql) { + Statement stat = null; + ResultSet rs = null; + int count = 0; + Connection conn = getConn(); + if (Objects.isNull(conn)) { + return 0; + } + try { + stat = conn.createStatement(); + String tSql = sql.trim(); + if (sql.trim().endsWith(";")) { + tSql = sql.trim().substring(0, sql.trim().length() - 1); + } + rs = stat.executeQuery("select count(1) as count from (" + tSql + ");"); + while (rs.next()) { + count = rs.getInt("count"); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + return count; + } + + /** + * Read the sql directory under resource + * + * @param em em + * @param res res + * @param args args + * @param return type + */ + public void query(Sql em, List res, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + query(sql, res); + } + + /** + * Read the sql directory under resource + * + * @param return type + * @param res res + * @param sql sql + */ + public void query(String sql, List res) { + Statement stat = null; + ResultSet rs = null; + Connection conn = getConn(); + Type argument = getType(res); + try { + Class aClass = (Class) Class.forName(argument.getTypeName()); + stat = conn.createStatement(); + rs = stat.executeQuery(sql); + ArrayList columnList = new ArrayList<>(); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + for (int index = 1; index <= columnCount; index++) { + columnList.add(rsMeta.getColumnName(index)); + } + while (rs.next()) { + T data = aClass.getConstructor().newInstance(); + for (Field declaredField : aClass.getDeclaredFields()) { + declaredField.setAccessible(true); + DField annotation = declaredField.getAnnotation(DField.class); + if (Objects.nonNull(annotation) && columnList.contains(annotation.name())) { + setData(declaredField, data, rs, annotation); + } + } + res.add(data); + } + } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + } + + private void setData(Field declaredField, T data, ResultSet rs, DField annotation) + throws SQLException, IllegalAccessException { + if (declaredField.getType() == Long.class || declaredField.getType() == long.class) { + declaredField.set(data, rs.getLong(annotation.name())); + } else if (declaredField.getType() == Integer.class || declaredField.getType() == int.class) { + declaredField.set(data, rs.getInt(annotation.name())); + } else if (declaredField.getType() == Double.class || declaredField.getType() == double.class) { + declaredField.set(data, rs.getDouble(annotation.name())); + } else if (declaredField.getType() == Float.class || declaredField.getType() == float.class) { + declaredField.set(data, rs.getFloat(annotation.name())); + } else if (declaredField.getType() == Boolean.class || declaredField.getType() == boolean.class) { + declaredField.set(data, rs.getBoolean(annotation.name())); + } else if (declaredField.getType() == Blob.class) { + declaredField.set(data, rs.getBlob(annotation.name())); + } else { + declaredField.set(data, rs.getObject(annotation.name())); + } + } + + private Type getType(List res) { + Type clazz = res.getClass().getGenericSuperclass(); + ParameterizedType pt = null; + if (clazz instanceof ParameterizedType) { + pt = (ParameterizedType) clazz; + } + if (pt == null) { + return clazz; + } + Type argument = pt.getActualTypeArguments()[0]; + return argument; + } + + private void release(ResultSet rs, Statement stat, Connection conn) { + try { + if (Objects.nonNull(rs)) { + rs.close(); + } + if (Objects.nonNull(stat)) { + stat.close(); + } + if (Objects.nonNull(conn)) { + free(conn); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventDispatcher.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventDispatcher.java new file mode 100644 index 000000000..a6e21bd9d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventDispatcher.java @@ -0,0 +1,173 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * event dispatcher class + * + * @date: 2021/5/24 12:00 + */ +public class EventDispatcher { + private static List clickEvents = new CopyOnWriteArrayList<>(); + private static List rangeEvents = new CopyOnWriteArrayList<>(); + private static List threadEvents = new CopyOnWriteArrayList<>(); + private static List funcChanges = new CopyOnWriteArrayList<>(); + + /** + * remove current RangeListener + * + * @param event event + */ + public static void removeRangeListener(ITimeRange event) { + rangeEvents.remove(event); + } + + /** + * remove current thread RangeListener + * + * @param event event + */ + public static void removeThreadRangeListener(IThreadRange event) { + threadEvents.remove(event); + } + + /** + * dispatcher the time Range + * + * @param startNS startNS + * @param endNS endNS + * @param scale scale + */ + public static void dispatcherRange(long startNS, long endNS, long scale) { + Iterator iterator = rangeEvents.iterator(); + long endTimeNs = endNS; + while (iterator.hasNext()) { + ITimeRange event = iterator.next(); + if (endNS == 0) { + endTimeNs = TracePanel.endNS; + } + event.change(startNS, endTimeNs, scale); + } + } + + /** + * dispatcherThreadRange + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds List + */ + public static void dispatcherThreadRange(long startNS, long endNS, List threadIds) { + Iterator iterator = threadEvents.iterator(); + while (iterator.hasNext()) { + IThreadRange event = iterator.next(); + event.change(startNS, endNS, threadIds); + } + } + + /** + * dispatcherClickListener + * + * @param node node + */ + public static void dispatcherClickListener(AbstractNode node) { + Iterator iterator = clickEvents.iterator(); + while (iterator.hasNext()) { + IFuncClick event = iterator.next(); + event.change(node); + } + } + + /** + * add Range Listener + * + * @param listener listener + */ + public static void addRangeListener(ITimeRange listener) { + if (!rangeEvents.contains(listener)) { + rangeEvents.add(listener); + } + } + + /** + * add Thread Range Listener + * + * @param listener listener + */ + public static void addThreadRangeListener(IThreadRange listener) { + if (!threadEvents.contains(listener)) { + threadEvents.add(listener); + } + } + + /** + * add Click Listener + * + * @param listener listener + */ + public static void addClickListener(IFuncClick listener) { + if (!clickEvents.contains(listener)) { + clickEvents.add(listener); + } + } + + /** + * clear Data + */ + public static void clearData() { + if (Objects.nonNull(clickEvents)) { + clickEvents.clear(); + } + if (Objects.nonNull(rangeEvents)) { + rangeEvents.clear(); + } + if (Objects.nonNull(threadEvents)) { + threadEvents.clear(); + } + if (Objects.nonNull(funcChanges)) { + funcChanges.clear(); + } + } + + /** + * add func select change listener + * + * @param listener select range change listener + */ + public static void addFuncSelectChange(IFuncChange listener) { + if (!funcChanges.contains(listener)) { + funcChanges.add(listener); + } + } + + /** + * dispatcherClickListener + * + * @param id id + */ + public static void dispatcherFuncChangeListener(Integer id) { + Iterator iterator = funcChanges.iterator(); + while (iterator.hasNext()) { + IFuncChange event = iterator.next(); + event.change(id); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventPanel.java new file mode 100644 index 000000000..ab9647633 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/EventPanel.java @@ -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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.components.JBPanel; + +import javax.swing.event.AncestorEvent; +import javax.swing.event.AncestorListener; + +/** + * EventPanel + * + * @date: 2021/5/24 12:22 + */ +public abstract class EventPanel extends JBPanel implements ITimeRange, IThreadRange, AncestorListener { + /** + * EventPanel + */ + public EventPanel() { + addAncestorListener(this); + } + + @Override + public void ancestorAdded(AncestorEvent event) { + EventDispatcher.addRangeListener(this); + EventDispatcher.addThreadRangeListener(this); + EventDispatcher.dispatcherRange(TracePanel.startNS, TracePanel.endNS, 50L); + if (TracePanel.rangeStartNS != null && TracePanel.rangeEndNS != null) { + EventDispatcher.dispatcherThreadRange(TracePanel.rangeStartNS, TracePanel.rangeEndNS, + TracePanel.currentSelectThreadIds); + } + } + + @Override + public void ancestorRemoved(AncestorEvent event) { + EventDispatcher.removeRangeListener(this); + EventDispatcher.removeThreadRangeListener(this); + } + + @Override + public void ancestorMoved(AncestorEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ExpandPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ExpandPanel.java new file mode 100644 index 000000000..6e629a4f8 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ExpandPanel.java @@ -0,0 +1,259 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.icons.AllIcons; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; + +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * ExpandPanel + * + * @date: 2021/5/19 16:39 + */ +public class ExpandPanel extends JBPanel { + private JComponent myContent; + private Icon myExpandIcon; + private Icon myCollapseIcon; + private JButton myToggleCollapseButton; + private JBLabel myTitleLabel; + private boolean myIsInitialized; + private boolean myIsCollapsed; + + /** + * Constructor + * + * @param title title + */ + public ExpandPanel(String title) { + super(new MigLayout("insets 0", "0[grow,fill]0", "0[grow,fill]0")); + myContent = new JBPanel(); + myContent.setLayout(new MigLayout("insets 0,wrap 1", "0[]0", "0[]0")); + myExpandIcon = AllIcons.General.ArrowRight; + myCollapseIcon = AllIcons.General.ArrowDown; + setBackground(JBColor.background().brighter()); + myToggleCollapseButton = new JButton(); + myToggleCollapseButton.setBorderPainted(false); + myToggleCollapseButton.setContentAreaFilled(false); + myToggleCollapseButton.setBackground(new Color(0, 0, 0, 0)); + myToggleCollapseButton.setMaximumSize(new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight())); + myToggleCollapseButton.setFocusable(true); + add(myToggleCollapseButton, "split 2 ,w 5!,gapleft 5,gapright 5"); + if (title != null) { + myTitleLabel = new JBLabel(title); + myTitleLabel.setToolTipText(title); + add(myTitleLabel, "h 30!,align center,wrap"); + } + myToggleCollapseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + setCollapsed(!myIsCollapsed); + } + }); + setCollapsed(false); + } + + /** + * Constructor + * + * @param title title + * @param labelWidth labelWidth + */ + public ExpandPanel(String title, int labelWidth) { + super(new MigLayout("insets 0", "0[" + labelWidth + "!]0[grow,fill]0", "0[grow,fill]0")); + myContent = new JBPanel(); + myContent.setLayout(new MigLayout("insets 0,wrap 1", "0[]0", "0[]0")); + myExpandIcon = AllIcons.General.ArrowRight; + myCollapseIcon = AllIcons.General.ArrowDown; + myToggleCollapseButton = new JButton(); + myToggleCollapseButton.setBorderPainted(false); + myToggleCollapseButton.setContentAreaFilled(false); + myToggleCollapseButton.setBackground(new Color(0, 0, 0, 0)); + myToggleCollapseButton.setMaximumSize(new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight())); + myToggleCollapseButton.setFocusable(true); + add(myToggleCollapseButton, "split 2,w 5!,gapleft 5,gapright 5"); + if (title != null) { + myTitleLabel = new JBLabel(title); + JBPanel rPanel = new JBPanel(); + add(myTitleLabel, "h 30!,w " + (labelWidth - 15) + "!,align left"); + add(rPanel, "h 30!,pushx,growx,wrap"); + rPanel.setBackground(JBColor.background().darker()); + } + myToggleCollapseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + setCollapsed(!myIsCollapsed); + } + }); + setCollapsed(false); + } + + /** + * Constructor + * + * @param content content + * @param isCollapsed isCollapsed + * @param collapseIcon collapseIcon + * @param expandIcon expandIcon + * @param title title + */ + public ExpandPanel(JComponent content, boolean isCollapsed, Icon collapseIcon, Icon expandIcon, String title) { + super(new MigLayout("insets 0", "0[grow,fill]0", "0[grow,fill]0")); + myContent = content; + myExpandIcon = expandIcon; + myCollapseIcon = collapseIcon; + setBackground(JBColor.background().brighter()); + myToggleCollapseButton = new JButton(); + myToggleCollapseButton.setBorderPainted(false); + myToggleCollapseButton.setContentAreaFilled(false); + myToggleCollapseButton.setBackground(new Color(0, 0, 0, 0)); + myToggleCollapseButton.setMaximumSize(new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight())); + myToggleCollapseButton.setFocusable(true); + add(myToggleCollapseButton, "split 2,w 5!,gapleft 5,gapright 5"); + if (title != null) { + myTitleLabel = new JBLabel(title); + add(myTitleLabel, "h 30!,align center,wrap"); + } + myToggleCollapseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + setCollapsed(!myIsCollapsed); + } + }); + setCollapsed(isCollapsed); + } + + /** + * get title + * + * @return title text + */ + public String getTitle() { + return myTitleLabel.getText(); + } + + /** + * set title + * + * @param title title + */ + public void setTitle(String title) { + myTitleLabel.setText(title); + } + + /** + * add TraceRow + * + * @param row row + */ + public void addTraceRow(AbstractRow row) { + myContent.add(row, "pushx,growx,h 30::"); + } + + /** + * add TraceRow + * + * @param row row + * @param constraints constraints + */ + public void addTraceRow(AbstractRow row, String constraints) { + myContent.add(row, constraints); + } + + /** + * add component + * + * @param component component + * @param constraints constraints + */ + public void addRow(JComponent component, String constraints) { + myContent.add(component, constraints); + } + + /** + * get myContent + * + * @return myContent + */ + public JComponent getContent() { + return myContent; + } + + /** + * fresh myContent + * + * @param startNS startNS + * @param endNS endNS + */ + public void refresh(long startNS, long endNS) { + if (!myIsCollapsed) { + for (Component component : myContent.getComponents()) { + if (component instanceof AbstractRow) { + ((AbstractRow) component).refresh(startNS, endNS); + } + } + } + } + + /** + * is collapsed + * + * @return isCollapsed + */ + public boolean isCollapsed() { + return myIsCollapsed; + } + + private void setCollapsed(boolean isCollapsed) { + try { + if (isCollapsed) { + if (myIsInitialized) { + remove(myContent); + } + } else { + add(myContent, "span 2 1,pushx,growx,wrap"); + } + myIsCollapsed = isCollapsed; + Icon icon = myIsCollapsed ? myExpandIcon : myCollapseIcon; + if (icon != null) { + myToggleCollapseButton.setIcon(icon); + myToggleCollapseButton.setBorder(null); + myToggleCollapseButton.setBorderPainted(false); + } + if (isCollapsed) { + myToggleCollapseButton.requestFocusInWindow(); + myToggleCollapseButton.setSelected(true); + } else { + myContent.requestFocusInWindow(); + } + revalidate(); + repaint(); + } finally { + myIsInitialized = true; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/FolderPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/FolderPanel.java new file mode 100644 index 000000000..a61f71a28 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/FolderPanel.java @@ -0,0 +1,365 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import com.intellij.ui.UtilUiBundle; +import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.ui.StartupUiUtil; +import com.intellij.util.ui.UIUtil; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; + +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.Icon; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.KeyStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Label; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.Collection; + +/** + * FolderPanel + * + * @date: 2021/5/18 23:18 + */ +public class FolderPanel extends JPanel { + /** + * LEFT_KEY_STROKE + */ + public static final KeyStroke LEFT_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0); + + /** + * LEFT_KEY_STROKE + */ + public static final KeyStroke RIGHT_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0); + + /** + * expand word + */ + @NonNls + public static final String EXPAND = "expand"; + + /** + * collapse word + */ + @NonNls + public static final String COLLAPSE = "collapse"; + private final JButton myToggleCollapseButton; + private final JComponent myContent; + private final Collection myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); + private final Icon myExpandIcon; + private final Icon myCollapseIcon; + private boolean myIsCollapsed; + private boolean myIsInitialized = false; + private Label myTitleLabel; + + /** + * structure + * + * @param content content + * @param collapseButtonAtLeft collapseButtonAtLeft + * @param isCollapsed isCollapsed + * @param collapseIcon collapseIcon + * @param expandIcon expandIcon + * @param title title + */ + public FolderPanel(JComponent content, boolean collapseButtonAtLeft, boolean isCollapsed, Icon collapseIcon, + Icon expandIcon, String title) { + super(new GridBagLayout()); + myContent = content; + setBackground(content.getBackground()); + myExpandIcon = expandIcon; + myCollapseIcon = collapseIcon; + myToggleCollapseButton = new JButton(); + myToggleCollapseButton.setOpaque(false); + myToggleCollapseButton.setBorderPainted(false); + myToggleCollapseButton.setBackground(new Color(0, 0, 0, 0)); + final Dimension buttonDimension = getButtonDimension(); + myToggleCollapseButton.setSize(buttonDimension); + myToggleCollapseButton.setPreferredSize(buttonDimension); + myToggleCollapseButton.setMinimumSize(buttonDimension); + myToggleCollapseButton.setMaximumSize(buttonDimension); + myToggleCollapseButton.setFocusable(true); + myToggleCollapseButton.getActionMap().put(COLLAPSE, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent event) { + collapse(); + } + }); + myToggleCollapseButton.getActionMap().put(EXPAND, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent event) { + expand(); + } + }); + myToggleCollapseButton.getInputMap().put(LEFT_KEY_STROKE, COLLAPSE); + myToggleCollapseButton.getInputMap().put(RIGHT_KEY_STROKE, EXPAND); + final int iconAnchor = collapseButtonAtLeft ? GridBagConstraints.WEST : GridBagConstraints.EAST; + add(myToggleCollapseButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, iconAnchor, GridBagConstraints.CENTER, + new Insets(0, collapseButtonAtLeft ? 0 : 5, 0, collapseButtonAtLeft ? 0 : 0), 0, 0)); + if (title != null) { + myTitleLabel = new Label(title); + myTitleLabel.setFont(StartupUiUtil.getLabelFont().deriveFont(Font.BOLD)); + myTitleLabel.setBackground(content.getBackground()); + add(myTitleLabel, + new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(0, 20, 0, 0), 0, 0)); + } + myToggleCollapseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + setCollapsed(!myIsCollapsed); + } + }); + setCollapsed(isCollapsed); + } + + /** + * structure + * + * @param content content + * @param collapseButtonAtLeft collapseButtonAtLeft + */ + public FolderPanel(JComponent content, boolean collapseButtonAtLeft) { + this(content, collapseButtonAtLeft, false, null, null, null); + } + + private Dimension getButtonDimension() { + if (myExpandIcon == null) { + return new Dimension(7, 7); + } else { + return new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight()); + } + } + + private String getToggleButtonToolTipText() { + if (myIsCollapsed) { + return UtilUiBundle.message("collapsible.panel.collapsed.state.tooltip.text"); + } else { + return UtilUiBundle.message("collapsible.panel.expanded.state.tooltip.text"); + } + } + + private Icon getIcon() { + if (myIsCollapsed) { + return myExpandIcon; + } else { + return myCollapseIcon; + } + } + + private void notifyListeners() { + for (CollapsingListener listener : myListeners) { + listener.onCollapsingChanged(this, isCollapsed()); + } + } + + /** + * addCollapsingListener + * + * @param listener listener + */ + public void addCollapsingListener(CollapsingListener listener) { + myListeners.add(listener); + } + + /** + * removeCollapsingListener + * + * @param listener listener + */ + public void removeCollapsingListener(CollapsingListener listener) { + myListeners.remove(listener); + } + + /** + * get myIsCollapsed + * + * @return isCollapsed + */ + public boolean isCollapsed() { + return myIsCollapsed; + } + + /** + * set the collapse + * + * @param collapse collapse + */ + protected void setCollapsed(boolean collapse) { + try { + if (collapse) { + if (myIsInitialized) { + remove(myContent); + } + } else { + add(myContent, + new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + } + myIsCollapsed = collapse; + Icon icon = getIcon(); + if (icon != null) { + myToggleCollapseButton.setIcon(icon); + myToggleCollapseButton.setBorder(null); + myToggleCollapseButton.setBorderPainted(false); + myToggleCollapseButton.setToolTipText(getToggleButtonToolTipText()); + } + if (collapse) { + setFocused(true); + setSelected(true); + } else { + myContent.requestFocusInWindow(); + } + notifyListeners(); + revalidate(); + repaint(); + } finally { + myIsInitialized = true; + } + } + + /** + * expand + */ + public void expand() { + if (myIsCollapsed) { + setCollapsed(false); + } + } + + /** + * collapse + */ + public void collapse() { + if (!myIsCollapsed) { + setCollapsed(true); + } + } + + /** + * setFocused + * + * @param focused focused + */ + public void setFocused(boolean focused) { + myToggleCollapseButton.requestFocusInWindow(); + } + + /** + * setSelected + * + * @param selected selected + */ + public void setSelected(boolean selected) { + myToggleCollapseButton.setSelected(selected); + } + + /** + * getCollapsibleActionMap + * + * @return InputMap + */ + public ActionMap getCollapsibleActionMap() { + return myToggleCollapseButton.getActionMap(); + } + + /** + * getCollapsibleInputMap + * + * @return InputMap + */ + public InputMap getCollapsibleInputMap() { + return myToggleCollapseButton.getInputMap(); + } + + @Override + protected void paintComponent(Graphics graphics) { + updatePanel(); + super.paintComponent(graphics); + } + + private void updatePanel() { + if (paintAsSelected()) { + setBackground(UIUtil.getTableSelectionBackground(true)); + } else { + setBackground(myContent.getBackground()); + } + } + + @Override + protected void paintChildren(Graphics graphics) { + if (myTitleLabel != null) { + updateTitle(); + } + updateToggleButton(); + super.paintChildren(graphics); + } + + private void updateToggleButton() { + if (paintAsSelected()) { + myToggleCollapseButton.setBackground(JBColor.background().brighter()); + } else { + myToggleCollapseButton.setBackground(myContent.getBackground()); + } + } + + private void updateTitle() { + if (paintAsSelected()) { + myTitleLabel.setForeground(JBColor.foreground()); + myTitleLabel.setBackground(JBColor.background().brighter()); + } else { + myTitleLabel.setForeground(JBColor.foreground()); + myTitleLabel.setBackground(JBColor.background().brighter()); + } + } + + private boolean paintAsSelected() { + return myToggleCollapseButton.hasFocus() && isCollapsed(); + } + + /** + * CollapsingListener + * + * @version 1.0 + * @date: 2021/5/18 23:18 + */ + public interface CollapsingListener { + /** + * onCollapsingChanged + * + * @param panel panel + * @param newValue newValue + */ + void onCollapsingChanged(@NotNull FolderPanel panel, boolean newValue); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncChange.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncChange.java new file mode 100644 index 000000000..9681ed8db --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncChange.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace; + +/** + * IFuncClick + */ +@FunctionalInterface +public interface IFuncChange { + /** + * change + * + * @param id id + */ + void change(Integer id); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncClick.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncClick.java new file mode 100644 index 000000000..6e7bc84d4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IFuncClick.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +/** + * IFuncClick + * + * @date: 2021/5/13 16:40 + */ +@FunctionalInterface +public interface IFuncClick { + /** + * change + * + * @param abstractNode abstractNode + */ + void change(AbstractNode abstractNode); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IThreadRange.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IThreadRange.java new file mode 100644 index 000000000..85cdf08c5 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/IThreadRange.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace; + +import java.util.List; + +/** + * IThreadRange + * + * @date: 2021/5/27 16:18 + */ +@FunctionalInterface +public interface IThreadRange { + /** + * change + * + * @param startNS startNS + * @param endNS endNS + * @param threadIds threadIds + */ + void change(long startNS, long endNS, List threadIds); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ITimeRange.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ITimeRange.java new file mode 100644 index 000000000..c7e59876b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/ITimeRange.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace; + +/** + * ITimeRange + * + * @date: 2021/5/24 12:11 + */ +@FunctionalInterface +public interface ITimeRange { + /** + * change + * + * @param startNS startNS + * @param endNS endNS + * @param scale scale + */ + void change(long startNS, long endNS, long scale); +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Ruler.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Ruler.java new file mode 100644 index 000000000..35d93b095 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Ruler.java @@ -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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.trace.util.TimeUtils; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * PrefSample from db file + * + * @date: 2021/5/12 16:34 + */ +public class Ruler extends JBPanel { + private final long duration; + private int degreeCount = 55; + + /** + * Ruler constructor + * + * @param duration duration + */ + public Ruler(long duration) { + this.duration = duration; + } + + private String[] getDegreeText(long ns) { + String[] dtArr = new String[6]; + dtArr[0] = "0"; + for (int index = 1; index < 6; index++) { + dtArr[index] = TimeUtils.getSecondFromNSecond(index * 10 * ns); + } + return dtArr; + } + + @Override + public void paint(final Graphics graphics) { + int width = getWidth(); + int height = getHeight(); + int range = width / degreeCount; + String[] dtArr = getDegreeText((duration / width) * range); + if (graphics instanceof Graphics2D) { + Graphics2D g2d = (Graphics2D) graphics; + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setFont(getFont().deriveFont(11.0f)); + int xx = 0; + g2d.setColor(JBColor.background().darker()); + g2d.drawLine(xx, 0, xx, height); + g2d.setColor(getForeground()); + g2d.drawString(dtArr[0], xx + 3, 15); + int model = width % degreeCount; + for (int index = 1; index <= degreeCount; index++) { + xx = index < model ? xx + range + 1 : xx + range; + if ((index % 10) == 0) { + g2d.setColor(JBColor.background().darker()); + g2d.drawLine(xx, 0, xx, height); + g2d.setColor(getForeground()); + g2d.drawString(dtArr[index / 10], xx + 3, 15); + } else { + if (xx <= width) { + g2d.setColor(JBColor.background().darker()); + g2d.drawLine(xx, 0, xx, 5); + } + } + } + g2d.setColor(JBColor.background().darker()); + g2d.drawLine(0, 0, getWidth(), 0); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Sql.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Sql.java new file mode 100644 index 000000000..acb33406f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Sql.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +/** + * sql text file path + * + * @date: 2021/5/27 12:03 + */ +public enum Sql { + QUERY_TOTAL_TIME("QueryTotalTime"), + QUERY_PROCESS("QueryProcess"), + QUERY_VSYNC_APP("QueryVSYNCAPP"), + QUERY_THREAD_DATA("QueryThreadData"), + QUERY_THREADS_BY_PID("QueryThreadsByPid"), + GET_FUN_DATA_BY_TID("GetFunDataByTid"), + QUERY_CPU_DATA("QueryCpuData"), + QUERY_CPU_DATA_LIMIT("QueryCpuDataLimit"), + QUERY_CPU_DATA_COUNT("QueryCpuDataCount"), + GET_THREAD_FUNC_BY_NAME("GetThreadFuncByName"), + QUERY_CPU_FREQ_DATA("QueryCpuFreqData"), + QUERY_CPU_MAX("QueryCpuMax"), + QUERY_CPU_MAX_FREQ("QueryCpuMaxFreq"), + QUERY_PREF_TOTAL_TIME("QueryPrefTotalTime"), + QUERY_PERF_FUNC("QueryPerfFunc"), + QUERY_PERF_FILES("QueryPerfFiles"), + QUERY_PERF_THREAD("QueryPerfThread"), + QUERY_CPU_SCALE("QueryCpuScale"), + + SYS_GET_TAB_COUNTERS("GetTabCounters"), + SYS_GET_TAB_PROCESS_BY_CPU("GetTabCpuByProcess"), + SYS_GET_TAB_THREAD_BY_CPU("GetTabCpuByThread"), + SYS_GET_TAB_THREAD_STATES("GetTabThreadStates"), + SYS_GET_TAB_SLICES("GetTabSlices"), + SYS_GET_WAKEUP_TIME("QueryWakeUpThread_WakeTime"), + SYS_GET_WAKEUP_THREAD("QueryWakeUpThread_WakeThread"), + SYS_GET_FUN_DATA_BY_TID("GetFunDataByTid"), + SYS_GET_PROCESS_MEM_DATA("QueryProcessMemData"), + SYS_GET_PROCESS_MEM("QueryProcessMem"), + SYS_GET_CPU_UTILIZATION_RATE("GetCpuUtilizationRate"), + SYS_QUERY_THREAD_DATA("QueryThreadData"), + SYS_QUERY_PROCESS_DATA("QueryProcessData"), + SYS_QUERY_PROCESS_THREADS("QueryProcessThreads"), + SYS_QUERY_PROCESS_THREADS_NORDER("QueryProcessThreadsNOrder"), + SYS_QUERY_PROCESS("QueryProcess"), + SYS_QUERY_PROCESS_NORDER("QueryProcessNOrder"), + SYS_QUERY_CPU_FREQ_DATA("QueryCpuFreqData"), + SYS_QUERY_CPU_MAX_FREQ("QueryCpuMaxFreq"), + SYS_QUERY_CPU_DATA("QueryCpuData"), + SYS_QUERY_CPU_DATA_COUNT("QueryCpuDataCount"), + SYS_QUERY_CPU_DATA_LIMIT("QueryCpuDataLimit"), + SYS_QUERY_CPU_MAX("QueryCpuMax"), + SYS_QUERY_CPU_FREQ("QueryCpuFreq"), + SYS_QUERY_TOTAL_TIME("QueryTotalTime"), + SYS_GET_ASYNC_EVENTS("GetAsyncEvents"), + SYS_QUERY_CLOCK_LIST("QueryClockList"), + SYS_QUERY_CLOCK_FREQUENCY("QueryClockFrequency"), + SYS_QUERY_CLOCK_STATE("QueryClockState"), + SYS_QUERY_SCREEN_STATE("QueryScreenState"), + + DISTRIBUTED_QUERY_TOTAL_TIME("DistributedQueryTotalTime"), + DISTRIBUTED_QUERY_THREADS_BY_PID("DistributedQueryThreadsByPid"), + DISTRIBUTED_GET_FUN_DATA_BY_TID("DistributedGetFunDataByTid"), + DISTRIBUTED_SET_TRACE_RANGE_START_TIME("DistributedSetTraceRangeStartTime"), + DISTRIBUTED_CPU_VIEWS("DistributedCpuViews"), + DISTRIBUTED_TRACE_CPU("DistributedTraceCpu"), + DISTRIBUTED_TRACE_MEM("DistributedTraceMem"), + DISTRIBUTED_TRACE_MEM_UNAGG("DistributedTraceMemUnagg"), + DISTRIBUTED_TRACE_METADATA("DistributedTraceMetadata"), + DISTRIBUTED_TRACE_STATS("DistributedTraceStats"), + DISTRIBUTED_TRACE_TASK_NAMES("DistributedTraceTaskNames"); + private final String name; + + Sql(String name) { + this.name = name; + } + + /** + * get name + * + * @return name name + */ + public String getName() { + return name; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TimeShaft.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TimeShaft.java new file mode 100644 index 000000000..017da984e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TimeShaft.java @@ -0,0 +1,491 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.util.Consumer; +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.AlphaComposite; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.text.DecimalFormat; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static java.awt.event.KeyEvent.VK_A; +import static java.awt.event.KeyEvent.VK_D; +import static java.awt.event.KeyEvent.VK_S; +import static java.awt.event.KeyEvent.VK_W; +import static ohos.devtools.views.trace.TracePanel.DURATION; +import static ohos.devtools.views.trace.TracePanel.endNS; +import static ohos.devtools.views.trace.TracePanel.startNS; + +/** + * The timescale + * + * @version 1.0 + * @date: 2021/5/12 16:39 + */ +public class TimeShaft extends JBPanel implements KeyListener, MouseListener, MouseMotionListener { + private static final int SELECT_BORDER_WIDTH = 3; + private final ITimeRange rangeListener; + private final Consumer keyReleaseHandler; + private final Consumer mouseReleaseHandler; + private final AlphaComposite alpha20 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .2f); + private final AlphaComposite alpha40 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .4f); + private final AlphaComposite alpha100 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); + private final long[] scales = + new long[] {50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 50_000, 100_000, 200_000, 500_000, + 1_000_000, 2_000_000, 5_000_000, 10_000_000, 20_000_000, 50_000_000, 100_000_000, 200_000_000, 500_000_000, + 1_000_000_000, 2_000_000_000, 5_000_000_000L, 10_000_000_000L, 20_000_000_000L, 50_000_000_000L, + 100_000_000_000L, 200_000_000_000L, 500_000_000_000L}; + private int startX; + private int endX; + private Rectangle selectRect = new Rectangle(); + private Rectangle selectLeftRect = new Rectangle(); + private Rectangle selectRightRect = new Rectangle(); + private Rectangle selectTopRect = new Rectangle(); + private Cursor wCursor = new Cursor(Cursor.W_RESIZE_CURSOR); + private Cursor eCursor = new Cursor(Cursor.E_RESIZE_CURSOR); + private Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); + private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); + private Status status = Status.DRAG; + private int offset; + private int length; + private double ratio1; + private double ratio2; + private double wheelNS; + private long scale; + private boolean isInit; + private Consumer timeShaftConsumer; + private DecimalFormat formatter = new DecimalFormat("#.##%"); + private Map rateMap = new HashMap<>(); + + /** + * structure function + * + * @param range range + */ + public TimeShaft(ITimeRange range, Consumer keyReleaseHandler, Consumer mouseReleaseHandler) { + this.rangeListener = range; + this.keyReleaseHandler = keyReleaseHandler; + this.mouseReleaseHandler = mouseReleaseHandler; + this.setOpaque(true); + this.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + super.componentResized(event); + startX = (int) (getWidth() * ratio1); + endX = (int) (getWidth() * ratio2); + Utils.setX(selectRect, Math.min(startX, endX)); + selectRect.width = Math.abs(endX - startX); + setAllRect(); + } + }); + addMouseListener(this); + addKeyListener(this); + addMouseMotionListener(this); + } + + /** + * mouseClicked function + * + * @param event event + */ + public void mouseClicked(MouseEvent event) { + } + + /** + * set TimeShaft Consumer function + * + * @param consumer consumer + */ + public void setTimeShaftConsumer(Consumer consumer) { + this.timeShaftConsumer = consumer; + } + + /** + * set TimeShaft Consumer function + * + * @param event event + */ + public void mousePressed(MouseEvent event) { + if (getVisibleRect().contains(event.getPoint())) { + if (status == Status.DRAG) { + startX = event.getX(); + endX = event.getX() + SELECT_BORDER_WIDTH * 3; + Utils.setX(selectRect, event.getX()); + Utils.setY(selectRect, 0); + selectRect.height = getHeight(); + selectRect.width = SELECT_BORDER_WIDTH * 3; + setAllRect(); + notifyRangeChange(startX, endX); + } else if (status == Status.MOVE) { + offset = Math.abs(event.getX() - Math.min(startX, endX)); + length = Math.abs(endX - startX); + notifyRangeChange(startX, endX); + } else { + notifyRangeChange(startX, endX); + } + } + } + + /** + * when the mouse released event + * + * @param event event + */ + public void mouseReleased(MouseEvent event) { + if (startX > endX) { + int tmp = startX; + startX = endX; + endX = tmp; + } + mouseReleaseHandler.consume(event); + } + + /** + * when the mouse Entered event + * + * @param event event + */ + public void mouseEntered(MouseEvent event) { + requestFocusInWindow(); + } + + /** + * when the mouse Entered event + * + * @param event event + */ + public void mouseExited(MouseEvent event) { + Tip.getInstance().hidden(); + } + + /** + * when the mouse Entered event + * + * @param event event + */ + public void mouseDragged(MouseEvent event) { + Tip.getInstance().hidden(); + if (status == Status.DRAG) { + endX = event.getX(); + } else if (status == Status.LEFT) { + startX = event.getX(); + } else if (status == Status.RIGHT) { + endX = event.getX(); + } else if (status == Status.MOVE) { + if (event.getX() - offset < 0) { + startX = 0; + endX = startX + length + event.getX() - offset; + } else { + startX = event.getX() - offset; + if (startX + length > getWidth()) { + endX = getWidth(); + } else { + endX = startX + length; + } + } + } else { + endX = endX; + } + if (startX < 0) { + startX = 0; + } + if (endX < 0) { + endX = 0; + } + if (startX > getWidth()) { + startX = getWidth(); + } + if (endX > getWidth()) { + endX = getWidth(); + } + Utils.setX(selectRect, Math.min(startX, endX)); + selectRect.width = Math.abs(endX - startX); + setAllRect(); + notifyRangeChange(Math.min(startX, endX), Math.max(startX, endX)); + } + + /** + * when the mouse move event + * + * @param event event + */ + public void mouseMoved(MouseEvent event) { + if (this.getVisibleRect().contains(event.getPoint())) { + if (selectLeftRect.contains(event.getPoint())) { + setCursor(wCursor); + status = Status.LEFT; + } else if (selectRightRect.contains(event.getPoint())) { + setCursor(eCursor); + status = Status.RIGHT; + } else if (selectTopRect.contains(event.getPoint())) { + setCursor(handCursor); + status = Status.MOVE; + } else { + status = Status.DRAG; + setCursor(defaultCursor); + tip(event); + } + } + } + + private void tip(MouseEvent event) { + String timeString = TimeUtils.getTimeFormatString(Common.x2ns(event.getX(), this.getBounds())); + Double rate = rateMap.get(event.getX()); + if (rate == null) { + rate = 0.0d; + } + List strings = Arrays.asList(timeString, "CPU Usage ", formatter.format(rate), "Select to inspect"); + Tip.getInstance().display(this, event.getPoint(), strings); + } + + /** + * when the key Typed event + * + * @param event event + */ + public void keyTyped(KeyEvent event) { + } + + /** + * when the mouse press event + * + * @param event event + */ + public void keyPressed(KeyEvent event) { + switch (event.getExtendedKeyCode()) { + case VK_A: + wheelNS = (endNS - startNS) * -0.2; + translation(); + break; + case VK_D: + wheelNS = (endNS - startNS) * 0.2; + translation(); + break; + case VK_W: + wheelNS = (endNS - startNS) * 0.2; + if (wheelNS == 0) { + wheelNS = 50L; + } + scale(); + break; + case VK_S: + wheelNS = (endNS - startNS) * -0.2; + if (wheelNS == 0) { + wheelNS = -50L; + } + scale(); + break; + default: + break; + } + } + + /** + * on the key released + * + * @param event event + */ + public void keyReleased(KeyEvent event) { + if (event.getExtendedKeyCode() == VK_A || event.getExtendedKeyCode() == VK_S + || event.getExtendedKeyCode() == VK_D || event.getExtendedKeyCode() == VK_W) { + keyReleaseHandler.consume(event); + } + } + + /** + * put Rate Map + * + * @param xPoint xPoint + * @param rate rate + */ + public void putRateMap(int xPoint, double rate) { + rateMap.put(xPoint, rate); + } + + /** + * set the current range + * + * @param mStartNS mStartNS + * @param mEndNS mEndNS + */ + public void setRange(long mStartNS, long mEndNS) { + startX = (int) (mStartNS * getWidth() * 1.0 / DURATION); + endX = (int) (mEndNS * getWidth() * 1.0 / DURATION); + double l20 = (mEndNS - mStartNS) * 1.0 / 20; + long min; + long max; + for (int index = 0; index < scales.length; index++) { + if (scales[index] > l20) { + if (index > 0) { + min = scales[index - 1]; + } else { + min = 0; + } + max = scales[index]; + double weight = (l20 - min) * 1.0 / (max - min); + if (weight > 0.243) { + scale = max; + } else { + scale = min; + } + break; + } + } + if (scale == 0) { + scale = scales[0]; + } + if (startX == 0 && endX == 0) { + endX = 1; + } + Utils.setX(selectRect, Math.min(startX, endX)); + selectRect.width = Math.abs(endX - startX); + setAllRect(); + } + + @Override + public void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + if (graphics instanceof Graphics2D) { + Graphics2D g2 = (Graphics2D) graphics; + Optional.ofNullable(timeShaftConsumer).ifPresent(it -> it.consume(g2)); + g2.setColor(JBColor.background().darker()); + g2.setComposite(alpha40); + g2.fillRect(0, 0, getWidth(), getHeight()); + g2.setComposite(alpha100); + g2.setColor(JBColor.foreground()); + g2.drawString("CPU Usage", 3, 13); + g2.setComposite(alpha100); + if (startX == 0 && endX == 0) { + startX = 0; + endX = getWidth(); + Utils.setX(selectRect, 0); + Utils.setY(selectRect, 0); + selectRect.width = getWidth(); + selectRect.height = getHeight(); + setAllRect(); + } + g2.setColor(JBUI.CurrentTheme.Link.linkColor()); + g2.setComposite(alpha20); + g2.fillRect(Utils.getX(selectRect), Utils.getY(selectRect), selectRect.width, selectRect.height); + g2.setComposite(alpha40); + g2.fillRect(Utils.getX(selectTopRect), Utils.getY(selectTopRect), selectTopRect.width, + selectTopRect.height); + g2.setComposite(alpha100); + g2.fillRect(Utils.getX(selectLeftRect), Utils.getY(selectLeftRect), selectLeftRect.width, + selectLeftRect.height); + g2.fillRect(Utils.getX(selectRightRect), Utils.getY(selectRightRect), selectRightRect.width, + selectRightRect.height); + if (!isInit) { + isInit = true; + setRange(0L, DURATION); + notifyRangeChange(0L, DURATION); + } + } + } + + private void setAllRect() { + ratio1 = startX * 1.0 / getWidth(); + if (ratio1 < 0) { + ratio1 = 0; + } + ratio2 = endX * 1.0 / getWidth(); + if (ratio2 > 1) { + ratio2 = 1; + } + Utils.setX(selectTopRect, Utils.getX(selectRect)); + Utils.setY(selectTopRect, Utils.getY(selectRect)); + selectTopRect.width = selectRect.width; + selectTopRect.height = SELECT_BORDER_WIDTH * 5; + Utils.setX(selectLeftRect, Utils.getX(selectRect)); + Utils.setY(selectLeftRect, Utils.getY(selectRect)); + selectLeftRect.width = SELECT_BORDER_WIDTH; + selectLeftRect.height = selectRect.height; + Utils.setX(selectRightRect, Utils.getX(selectRect) + selectRect.width - SELECT_BORDER_WIDTH); + Utils.setY(selectRightRect, Utils.getY(selectRect)); + selectRightRect.width = selectLeftRect.width; + selectRightRect.height = selectRect.height; + } + + private void translation() { + if (startNS + wheelNS <= 0) { + startNS = 0; + endNS = endNS - startNS; + setRange(startNS, endNS); + } else if (endNS + wheelNS >= DURATION) { + startNS = DURATION - (endNS - startNS); + endNS = DURATION; + setRange(startNS, endNS); + } else { + startNS = (long) (startNS + wheelNS); + endNS = (long) (endNS + wheelNS); + setRange(startNS, endNS); + } + notifyRangeChange(startNS, endNS); + } + + private void scale() { + startNS = (long) (startNS + wheelNS); + endNS = (long) (endNS - wheelNS); + if (startNS <= 0) { + startNS = 0L; + } + if (endNS >= DURATION) { + endNS = DURATION; + } + setRange(startNS, endNS); + notifyRangeChange(startNS, endNS); + } + + private void notifyRangeChange(int xPoint, int yPoint) { + long ns1 = Common.x2ns(xPoint, getVisibleRect()); + long ns2 = Common.x2ns(yPoint, getVisibleRect()); + startNS = Math.min(ns1, ns2); + endNS = Math.max(ns1, ns2); + repaint(); + Optional.ofNullable(rangeListener).ifPresent(range -> range.change(startNS, endNS, scale)); + } + + private void notifyRangeChange(long ns1, long ns2) { + startNS = Math.min(ns1, ns2); + endNS = Math.max(ns1, ns2); + repaint(); + Optional.ofNullable(rangeListener).ifPresent(range -> range.change(startNS, endNS, scale)); + } + + enum Status { + DRAG, LEFT, RIGHT, MOVE + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Tip.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Tip.java new file mode 100644 index 000000000..10ad8ae4c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/Tip.java @@ -0,0 +1,153 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JLayeredPane; +import javax.swing.SwingUtilities; +import javax.swing.border.LineBorder; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.event.MouseEvent; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +/** + * Tip Panel + * + * @date: 2021/5/28 19:32 + */ +public class Tip extends JBPanel { + private static final int LEFT_PADDING = 10; + private static final int RIGHT_PADDING = 10; + private static final int BOTTOM_PADDING = 20; + private static final int TOP_PADDING = 20; + private static final int ROW_HEIGHT = 20; + private static final int MEGA_BYTES = 10241024; + private static Tip tip = new Tip(); + private JLayeredPane layeredPane; + private List stringList; + + private Tip() { + setLayout(new MigLayout("")); + setBorder(new LineBorder(JBColor.background().darker())); + setBackground(JBColor.background().brighter()); + } + + /** + * get tip Instance + * + * @return Tip + */ + public static Tip getInstance() { + return tip; + } + + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + if (graphics instanceof Graphics2D) { + Graphics2D g2 = (Graphics2D) graphics; + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // Set anti-aliasing + if (Objects.nonNull(stringList)) { + int startY = TOP_PADDING; + for (String str : stringList) { + g2.setPaint(JBColor.foreground()); + g2.drawString(str, LEFT_PADDING, startY); + g2.setPaint(JBColor.foreground()); + g2.drawString(str, LEFT_PADDING, startY); + startY += ROW_HEIGHT; + } + } + } + } + + /** + * setJLayeredPane + * + * @param layeredPane layeredPane + */ + public void setJLayeredPane(JLayeredPane layeredPane) { + this.layeredPane = layeredPane; + if (Arrays.stream(layeredPane.getComponents()).allMatch(component -> component.getClass() != Tip.class)) { + layeredPane.add(this); + } + } + + /** + * setJLayeredPane + * + * @param source source + * @param point point + * @return Point + */ + public Point getPoint(Component source, Point point) { + return SwingUtilities.convertPoint(source, point, layeredPane); + } + + /** + * display current tip + * + * @param source source + * @param point point + * @param stringList List + */ + public void display(Component source, Point point, List stringList) { + if (Objects.isNull(stringList)) { + return; + } + if (Objects.nonNull(layeredPane)) { + this.stringList = stringList; + this.setVisible(true); + Point point1 = SwingUtilities.convertPoint(source, point, layeredPane); + String maxString = stringList.stream().max(Comparator.comparingInt(String::length)).orElse(""); + int maxWidth = SwingUtilities.computeStringWidth(getFontMetrics(getFont()), maxString); + setBounds(Utils.getX(point1), Utils.getY(point1), maxWidth + LEFT_PADDING + RIGHT_PADDING, + stringList.size() * ROW_HEIGHT + BOTTOM_PADDING); + layeredPane.setLayer(this, 1000); + } + } + + /** + * display current tip + * + * @param event event + * @param stringList List + */ + public void display(MouseEvent event, List stringList) { + display(event.getComponent(), event.getPoint(), stringList); + } + + /** + * display current tip + */ + public void hidden() { + if (Objects.nonNull(layeredPane)) { + this.setVisible(false); + layeredPane.setLayer(this, -1); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TracePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TracePanel.java new file mode 100644 index 000000000..08ccfbbd3 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TracePanel.java @@ -0,0 +1,362 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.util.Consumer; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +/** + * TracePanel + * + * @date: 2021/5/13 13:06 + */ +public class TracePanel extends JBPanel { + /** + * DURATION + */ + public static long DURATION = 10_000_000_000L; + + /** + * currentSelectThreadIds + */ + public static List currentSelectThreadIds = new ArrayList<>(); + + /** + * time shaft start time + */ + public static long START_TS; + + /** + * time shaft end time + */ + public static long END_TS; + + /** + * root TracePanel + */ + public static TracePanel root; + + /** + * current start time + */ + public static long startNS; + + /** + * current end time + */ + public static long endNS; + + /** + * range start time + */ + public static Long rangeStartNS; + + /** + * range end time + */ + public static Long rangeEndNS; + private TimeShaft timeShaft; + private Ruler ruler; + private JBScrollPane scrollPane; + private JBPanel contentPanel; + private List componentList; + private Point startPoint; + private Point endPoint; + private List allComponent; + + /** + * structure function + */ + public TracePanel() { + this(true); + } + + /** + * TracePanel constructor + * + * @param showTimeShaft showTimeShaft + */ + public TracePanel(boolean showTimeShaft) { + timeShaft = new TimeShaft((startNS, endNS, scale) -> { + EventDispatcher.dispatcherRange(startNS, endNS, scale); + Component[] components = contentPanel.getComponents(); + for (Component component : components) { + if (component instanceof ExpandPanel) { + ((ExpandPanel) component).refresh(startNS, endNS); + } + } + }, keyEvent -> timeShaftComplete(), mouseEvent -> timeShaftComplete()); + contentPanel = new JBPanel(); + contentPanel.setLayout(new MigLayout("inset 0,wrap 1", "[grow,fill]", "0[]0")); + contentPanel.setFocusable(true); + contentPanel.setBorder(null); + setLayout(new MigLayout("inset 0", "", "0[]0")); + scrollPane = new JBScrollPane(contentPanel); + scrollPane.setBorder(null); + ruler = new Ruler(TracePanel.DURATION); + if (showTimeShaft) { + add(ruler, "wrap,pushx,growx,h 20!"); + add(timeShaft, "wrap,pushx,growx,h 50!"); + } + add(scrollPane, "push,grow"); + setBorder(null); + scrollPane.getVerticalScrollBar().addAdjustmentListener(event -> { + Component[] components = contentPanel.getComponents(); + for (Component component : components) { + if (scrollPane.getViewport().getViewRect().intersects(component.getBounds())) { + if (component instanceof ExpandPanel) { + ((ExpandPanel) component).refresh(startNS, endNS); + } + } + } + }); + root = this; + contentPanel.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent event) { + super.mousePressed(event); + mousePressedThreadRow(event); + } + + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + mouseClickThreadRow(event); + } + + @Override + public void mouseExited(MouseEvent event) { + super.mouseExited(event); + Tip.getInstance().hidden(); + } + + @Override + public void mouseReleased(MouseEvent event) { + super.mouseReleased(event); + } + }); + contentPanel.addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent event) { + super.mouseDragged(event); + mouseDraggedThreadRow(event); + } + + @Override + public void mouseMoved(MouseEvent event) { + super.mouseMoved(event); + tip(event); + } + }); + } + + /** + * range end time + * + * @return get current contentPanel + */ + public JBPanel getContentPanel() { + return contentPanel; + } + + private void timeShaftComplete() { + Arrays.stream(contentPanel.getComponents()) + .filter(it -> it instanceof ExpandPanel) + .map(it -> ((ExpandPanel) it)) + .filter(it -> !it.isCollapsed()) + .forEach(it -> Arrays.stream(it.getContent().getComponents()) + .filter(row -> row instanceof TraceSimpleRow) + .map(row -> ((TraceSimpleRow) row)) + .filter(row -> row.getRowName().toLowerCase().startsWith("cpu")) + .forEach(row -> row.reload())); + } + + private void tip(MouseEvent event) { + if (Objects.isNull(allComponent)) { + allComponent = Arrays.stream(contentPanel.getComponents()).filter(ExpandPanel.class::isInstance) + .flatMap(component -> Arrays.stream(((ExpandPanel) component).getContent().getComponents())) + .collect(Collectors.toList()); + } + boolean flag = allComponent.stream().anyMatch(it -> { + if (it instanceof AbstractRow) { + AbstractRow row = (AbstractRow) it; + Rectangle rectangle = SwingUtilities.convertRectangle(row, row.getContentBounds(), contentPanel); + if (rectangle.contains(event.getPoint())) { + return true; + } + } + return false; + }); + if (flag) { + allComponent.forEach(component -> { + if (component instanceof AbstractRow) { + AbstractRow row = (AbstractRow) component; + Rectangle rectangle = SwingUtilities.convertRectangle(row, row.getContentBounds(), contentPanel); + if (rectangle.contains(event.getPoint())) { + Point point = SwingUtilities.convertPoint(contentPanel, event.getPoint(), row.content); + row.mouseMoveHandler(point); + } + } + }); + } else { + Tip.getInstance().hidden(); + } + } + + /** + * structure function + * + * @param startNS startNS + * @param endNS endNS + */ + public void setRange(long startNS, long endNS) { + Optional.ofNullable(timeShaft).ifPresent(tf -> tf.setRange(startNS, endNS)); + } + + private void mouseDraggedThreadRow(MouseEvent event) { + endPoint = SwingUtilities.convertPoint(contentPanel, event.getPoint(), componentList.get(0).getParent()); + int xPoint = Math.min(Utils.getX(startPoint), Utils.getX(endPoint)); + int yPoint = Math.min(Utils.getY(startPoint), Utils.getY(endPoint)); + int width = Math.abs(Utils.getX(startPoint) - Utils.getX(endPoint)) == 0 ? 1 : + Math.abs(Utils.getX(startPoint) - Utils.getX(endPoint)); + int height = Math.abs(Utils.getY(startPoint) - Utils.getY(endPoint)); + Rectangle range = new Rectangle(xPoint, yPoint, width, height); + + for (Component component : componentList) { + if (component instanceof TraceThreadRow) { + TraceThreadRow cp = (TraceThreadRow) component; + if (range.intersects(component.getBounds())) { + if (!currentSelectThreadIds.contains(cp.getTid())) { + currentSelectThreadIds.add(cp.getTid()); + } + cp.setSelect(true, xPoint - Utils.getX(cp.getContentBounds()), + xPoint + width - Utils.getX(cp.getContentBounds())); + } else { + if (currentSelectThreadIds.contains(cp.getTid())) { + currentSelectThreadIds.remove(cp.getTid()); + } + cp.setSelect(false, null, null); + } + } + } + notifySelectRangeChange(); + Tip.getInstance().hidden(); + } + + private void mouseClickThreadRow(MouseEvent event) { + TracePanel.rangeStartNS = null; + TracePanel.rangeEndNS = null; + AtomicBoolean flag = new AtomicBoolean(false); + componentList.forEach(component -> { + if (component instanceof TraceThreadRow) { + TraceThreadRow thread = (TraceThreadRow) component; + if (thread.getBounds().contains(startPoint) && Utils.getX(startPoint) < Utils.getX( + thread.getContentBounds())) { + if (!currentSelectThreadIds.contains(thread.getTid())) { + currentSelectThreadIds.add(thread.getTid()); + } + thread.setSelect(true, null, null); + } else { + Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), thread.content); + if ((thread.getData() != null && thread.getData().stream() + .anyMatch(it -> it.getRect().contains(point))) || (thread.getData2() != null && thread + .getData2().stream().anyMatch(it -> it.getRect().contains(point)))) { + if (Objects.nonNull(thread.getData())) { + thread.getData().stream().filter(it -> it.getRect().contains(point)) + .forEach(it -> it.onClick(event)); + } + if (Objects.nonNull(thread.getData2())) { + thread.getData2().stream().filter(it -> it.getRect().contains(point)) + .forEach(it -> it.onClick(event)); + } + flag.set(true); + } + currentSelectThreadIds.remove(thread.getTid()); + thread.setSelect(false, null, null); + } + } + }); + if (!flag.get()) { + notifySelectRangeChange(); + } + } + + private void notifySelectRangeChange() { + if (Objects.isNull(TracePanel.rangeStartNS) && Objects.isNull(TracePanel.rangeEndNS)) { + EventDispatcher.dispatcherThreadRange(TracePanel.startNS, TracePanel.endNS, currentSelectThreadIds); + } else { + long st = TracePanel.rangeStartNS < TracePanel.startNS ? TracePanel.startNS : TracePanel.rangeStartNS; + long et = TracePanel.rangeEndNS > TracePanel.endNS ? TracePanel.endNS : TracePanel.rangeEndNS; + EventDispatcher.dispatcherThreadRange(st, et, currentSelectThreadIds); + } + } + + private void mousePressedThreadRow(MouseEvent event) { + if (Objects.isNull(componentList)) { + componentList = Arrays.stream(contentPanel.getComponents()).filter(component -> { + if (component instanceof ExpandPanel) { + ExpandPanel ep = (ExpandPanel) component; + if (!ep.getTitle().startsWith("Display") && !ep.getTitle().startsWith("CPU")) { + return true; + } + } + return false; + }).flatMap(component -> Arrays.stream(((ExpandPanel) component).getContent().getComponents())) + .collect(Collectors.toList()); + } + if (componentList.size() > 0) { + startPoint = SwingUtilities.convertPoint(contentPanel, event.getPoint(), componentList.get(0).getParent()); + } + } + + /** + * paint the TimeShaft + * + * @param consumer consumer + */ + public void paintTimeShaft(Consumer consumer) { + timeShaft.setTimeShaftConsumer(consumer); + timeShaft.repaint(); + } + + /** + * get the TimeShaft + * + * @return timeShaft timeShaft + */ + public TimeShaft getTimeShaft() { + return timeShaft; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceSimpleRow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceSimpleRow.java new file mode 100644 index 000000000..a71680695 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceSimpleRow.java @@ -0,0 +1,150 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * TraceSimpleRow + * + * @date: 2021/5/18 13:56 + */ +public class TraceSimpleRow extends AbstractRow { + private IRender render; + private List data; + private T currentData; + private Supplier> supplier; + + /** + * structure + * + * @param name name + */ + public TraceSimpleRow(String name) { + super(name, false, true); + loadData(); + } + + /** + * setRender + * + * @param render set current render + */ + public void setRender(IRender render) { + this.render = render; + } + + /** + * setSupplier + * + * @param supplier set current supplier + */ + public void setSupplier(Supplier> supplier) { + this.supplier = supplier; + } + + @Override + public void contentPaint(Graphics graphics) { + if (render != null) { + if (Objects.isNull(data)) { + graphics.setColor(JBColor.foreground()); + graphics.drawString("Loading...", 10, 10 + 12); + loadData(); + } else { + if (graphics instanceof Graphics2D) { + render.paint((Graphics2D) graphics, data); + } + } + } + } + + @Override + public void mouseMoveHandler(Point point) { + super.mouseMoveHandler(point); + if (Objects.nonNull(data)) { + if (data.stream().filter(it -> contains(it)).anyMatch(it -> it.getRect().contains(point))) { + data.stream().filter(it -> contains(it) && it.getRect().contains(point)).forEach(it -> { + List stringList = it.getStringList(getTimeByX(Utils.getX(point))); + Tip.getInstance().display(content, point, stringList); + if (Objects.nonNull(currentData)) { + currentData.moveOut(point, content); + } + it.moveIn(point, content); + currentData = it; + }); + } else { + if (Objects.nonNull(currentData)) { + currentData.moveOut(point, content); + } + Tip.getInstance().display(content, point, Arrays.asList(getTimeByX(Utils.getX(point)))); + } + } + } + + @Override + public void loadData() { + if (!isLoading.get()) { + isLoading.set(true); + CompletableFuture.runAsync(() -> { + if (supplier != null) { + data = supplier.get(); + } + SwingUtilities.invokeLater(() -> { + isLoading.set(false); + content.repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + /** + * reload current row + */ + public void reload() { + data = null; + repaint(); + } + + /** + * interface IRender + * + * @param T + */ + public interface IRender { + /** + * paint + * + * @param g2 Graphics2D + * @param data data + */ + void paint(Graphics2D g2, List data); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceThreadRow.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceThreadRow.java new file mode 100644 index 000000000..9c9726453 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/TraceThreadRow.java @@ -0,0 +1,279 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace; + +import com.intellij.ui.JBColor; +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.border.LineBorder; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +import static java.util.Objects.nonNull; + +/** + * TraceThreadRow + * + * @date: 2021/5/18 13:56 + */ +public class TraceThreadRow extends AbstractRow { + private final Integer tid; + private IRender render; + private List data; + private List data2; + private T currentData; + private R currentData2; + private Supplier> supplier; + private Supplier> supplier2; + private Long rangeStartNS; + private Long rangeEndNS; + private Integer x1; + private Integer x2; + + /** + * structure + * + * @param name name + * @param tid tid + */ + public TraceThreadRow(String name, Integer tid) { + super(name, true, false); + this.tid = tid; + layout.setComponentConstraints(expandBtn, "split 2,gapleft 15,gaptop 3,gapbottom push"); + layout.setComponentConstraints(nameLabel, "gapleft 5,gaptop 3,gapbottom push,w 70!"); + loadData(); + nameLabelClickConsumer = (e) -> { + setSelect(true, null, null); + }; + } + + /** + * getTid + * + * @return Integer tid + */ + public Integer getTid() { + return tid; + } + + /** + * setRender + * + * @param render set current render + */ + public void setRender(IRender render) { + this.render = render; + } + + /** + * set thread Supplier + * + * @param supplier set thread supplier + */ + public void setSupplier(Supplier> supplier) { + this.supplier = supplier; + } + + /** + * set thread function Supplier + * + * @param supplier set thread function supplier + */ + public void setSupplier2(Supplier> supplier) { + this.supplier2 = supplier; + } + + @Override + public void contentPaint(Graphics graphics) { + if (render != null && graphics instanceof Graphics2D) { + Graphics2D g2 = (Graphics2D) graphics; + if (data != null || data2 != null) { + render.paint(g2, data, data2); + } else { + g2.setColor(JBColor.foreground()); + g2.drawString("Loading...", 10, 10 + 12); + loadData(); + } + if (nonNull(x1) && nonNull(x2)) { + int xMin = Math.min(x1, x2); + int xMax = Math.max(x1, x2); + int width = Math.abs(x2 - x1); + Common.setAlpha(g2, 0.5F); + g2.setColor(JBColor.foreground().darker()); + g2.fillRect(0, 0, xMin, getHeight()); + g2.fillRect(xMax, 0, getWidth() - xMax, getHeight()); + Common.setAlpha(g2, 1F); + } + } + } + + @Override + public void mouseMoveHandler(Point point) { + super.mouseMoveHandler(point); + if (nonNull(data)) { + if (data.stream().filter(it -> contains(it)).anyMatch(it -> it.getRect().contains(point))) { + data.stream().filter(it -> contains(it) && it.getRect().contains(point)).forEach(it -> { + List stringList = it.getStringList(getTimeByX(Utils.getX(point))); + Tip.getInstance().display(content, point, stringList); + if (Objects.nonNull(currentData)) { + currentData.moveOut(point, content); + } + it.moveIn(point, content); + currentData = it; + }); + return; + } else { + if (Objects.nonNull(currentData)) { + currentData.moveOut(point, content); + } + Tip.getInstance().display(content, point, Arrays.asList(getTimeByX(Utils.getX(point)))); + } + } + if (nonNull(data2)) { + if (data2.stream().filter(it -> contains(it)).anyMatch(it -> it.getRect().contains(point))) { + data2.stream().filter(it -> contains(it) && it.getRect().contains(point)).forEach(it -> { + List stringList = it.getStringList(getTimeByX(Utils.getX(point))); + Tip.getInstance().display(content, point, stringList); + if (Objects.nonNull(currentData2)) { + currentData2.moveOut(point, content); + } + it.moveIn(point, content); + currentData2 = it; + }); + return; + } else { + if (Objects.nonNull(currentData2)) { + currentData2.moveOut(point, content); + } + Tip.getInstance().display(content, point, Arrays.asList(getTimeByX(Utils.getX(point)))); + } + } + } + + @Override + public void loadData() { + if (!isLoading.get()) { + isLoading.set(true); + CompletableFuture.runAsync(() -> { + if (nonNull(supplier)) { + data = supplier.get(); + } + if (nonNull(supplier2)) { + data2 = supplier2.get(); + } + SwingUtilities.invokeLater(() -> { + isLoading.set(false); + content.repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + /** + * setSelect + * + * @param flag flag + * @param x1 x1 + * @param x2 x2 + */ + public void setSelect(boolean flag, Integer x1, Integer x2) { + this.x1 = x1; + this.x2 = x2; + if (flag) { + if (nonNull(x1) && nonNull(x2)) { + rangeStartNS = x2ns(Math.min(x1, x2)); + rangeEndNS = x2ns(Math.max(x1, x2)); + TracePanel.rangeStartNS = rangeStartNS; + TracePanel.rangeEndNS = rangeEndNS; + } + setBorder(new LineBorder(JBUI.CurrentTheme.Link.linkColor(), 1)); + setBackground(JBUI.CurrentTheme.Link.linkSecondaryColor()); + } else { + rangeStartNS = null; + rangeEndNS = null; + setBorder(null); + setBackground(JBColor.background()); + } + } + + @Override + public void refreshNotify() { + super.refreshNotify(); + if (nonNull(rangeStartNS) && nonNull(rangeEndNS)) { + x1 = (int) Common.ns2x(rangeStartNS, getContentBounds()); + x2 = (int) Common.ns2x(rangeEndNS, getContentBounds()); + } + } + + private long x2ns(int x1) { + long start = Math.min(startNS, endNS); + long end = Math.max(startNS, endNS); + long dur = Math.abs(endNS - startNS); + if (x1 >= getContentBounds().width) { + return end; + } + if (x1 <= 0) { + return start; + } + double ns = x1 * (dur) * 1.0 / getContentBounds().width; + return (long) ns + start; + } + + /** + * Gets the value of data . + * + * @return the value of java.util.List + */ + public List getData() { + return data; + } + + /** + * Gets the value of data2 . + * + * @return the value of java.util.List + */ + public List getData2() { + return data2; + } + + /** + * interface IRender + * @param T + * @param R + */ + public interface IRender { + /** + * paint + * @param g2 Graphics2D + * @param data data + * @param data2 data2 + */ + void paint(Graphics2D g2, List data, List data2); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/AsyncEvent.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/AsyncEvent.java new file mode 100644 index 000000000..4066aef0a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/AsyncEvent.java @@ -0,0 +1,199 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * AsyncEvent + * + * @date: 2021/6/29 10:55 + */ +public class AsyncEvent extends AbstractGraph { + @DField(name = "id") private Integer id; + @DField(name = "startTime") private Long startTime; + @DField(name = "dur") private Long duration; + @DField(name = "pid") private Integer pid; + @DField(name = "name") private String name; + @DField(name = "cookie") private Integer cookie; + @DField(name = "depth") private Integer depth; + + /** + * Gets the value of depth . + * + * @return the value of java.lang.Integer + */ + public Integer getDepth() { + return depth; + } + + /** + * Sets the depth . + *

You can use getDepth() to get the value of depth

+ * + * @param depth depth + */ + public void setDepth(Integer depth) { + this.depth = depth; + } + + /** + * Gets the value of cookie . + * + * @return the value of java.lang.Integer + */ + public Integer getCookie() { + return cookie; + } + + /** + * Sets the cookie . + *

You can use getCookie() to get the value of cookie

+ * + * @param cookie cookie + */ + public void setCookie(Integer cookie) { + this.cookie = cookie; + } + + /** + * Gets the value of id . + * + * @return the value of java.lang.Integer + */ + public Integer getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id

+ * + * @param id id + */ + public void setId(Integer id) { + this.id = id; + } + + /** + * Gets the value of startTime . + * + * @return the value of java.lang.Long + */ + public Long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param startTime startTime + */ + public void setStartTime(Long startTime) { + this.startTime = startTime; + } + + /** + * Gets the value of duration . + * + * @return the value of java.lang.Long + */ + public Long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param duration duration + */ + public void setDuration(Long duration) { + this.duration = duration; + } + + /** + * Gets the value of pid . + * + * @return the value of java.lang.Integer + */ + public Integer getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param pid pid + */ + public void setPid(Integer pid) { + this.pid = pid; + } + + /** + * Gets the value of name . + * + * @return the value of java.lang.String + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name

+ * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + @Override + public void draw(Graphics2D graphics) { + graphics.setColor(ColorUtils.colorForTid(cookie)); + Rectangle rectangle = new Rectangle(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.fillRect(Utils.getX(rectangle), Utils.getY(rectangle), rectangle.width, rectangle.height); + graphics.setColor(Color.WHITE); + drawString(graphics, rectangle, name, Placement.CENTER_LINE); + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUProcessBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUProcessBean.java index b0e6d8b2d..bc66fe0a4 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUProcessBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUProcessBean.java @@ -1,147 +1,147 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -/** - * cpu process data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CPUProcessBean { - private long avgDuration; - - private long wallDuration; - - private String pid; - - private String occurrences; - - private String process; - - /** - * Construction method with parameters - * - * @param mAvgDuration mAvgDuration - * @param mWallDuration mWallDuration - * @param mPid mPid - * @param mOccurrences mOccurrences - * @param mProcess mProcess - */ - public CPUProcessBean(final long mAvgDuration, final long mWallDuration, final String mPid, - final String mOccurrences, final String mProcess) { - this.avgDuration = mAvgDuration; - this.wallDuration = mWallDuration; - this.pid = mPid; - this.occurrences = mOccurrences; - this.process = mProcess; - } - - /** - * Gets the value of avgDuration . - * - * @return the value of long - */ - public long getAvgDuration() { - return avgDuration; - } - - /** - * Sets the avgDuration . - *

You can use getAvgDuration() to get the value of avgDuration

- * - * @param avgDuration avgDuration - */ - public void setAvgDuration(final long avgDuration) { - this.avgDuration = avgDuration; - } - - /** - * Gets the value of wallDuration . - * - * @return the value of long - */ - public long getWallDuration() { - return wallDuration; - } - - /** - * Sets the wallDuration . - *

You can use getWallDuration() to get the value of wallDuration

- * - * @param wallDuration wallDuration - */ - public void setWallDuration(final long wallDuration) { - this.wallDuration = wallDuration; - } - - /** - * Gets the value of pid . - * - * @return the value of java.lang.String - */ - public String getPid() { - return pid; - } - - /** - * Sets the pid . - *

You can use getPid() to get the value of pid

- * - * @param pid pid - */ - public void setPid(final String pid) { - this.pid = pid; - } - - /** - * Gets the value of occurrences . - * - * @return the value of java.lang.String - */ - public String getOccurrences() { - return occurrences; - } - - /** - * Sets the occurrences . - *

You can use getOccurrences() to get the value of occurrences

- * - * @param occurrences occurrences - */ - public void setOccurrences(final String occurrences) { - this.occurrences = occurrences; - } - - /** - * Gets the value of process . - * - * @return the value of java.lang.String - */ - public String getProcess() { - return process; - } - - /** - * Sets the process . - *

You can use getProcess() to get the value of process

- * - * @param process process - */ - public void setProcess(final String process) { - this.process = process; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +/** + * cpu process data + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class CPUProcessBean { + private long avgDuration; + + private long wallDuration; + + private String pid; + + private String occurrences; + + private String process; + + /** + * Construction method with parameters + * + * @param mAvgDuration mAvgDuration + * @param mWallDuration mWallDuration + * @param mPid mPid + * @param mOccurrences mOccurrences + * @param mProcess mProcess + */ + public CPUProcessBean(final long mAvgDuration, final long mWallDuration, final String mPid, + final String mOccurrences, final String mProcess) { + this.avgDuration = mAvgDuration; + this.wallDuration = mWallDuration; + this.pid = mPid; + this.occurrences = mOccurrences; + this.process = mProcess; + } + + /** + * Gets the value of avgDuration . + * + * @return the value of long + */ + public long getAvgDuration() { + return avgDuration; + } + + /** + * Sets the avgDuration . + *

You can use getAvgDuration() to get the value of avgDuration

+ * + * @param avgDuration avgDuration + */ + public void setAvgDuration(final long avgDuration) { + this.avgDuration = avgDuration; + } + + /** + * Gets the value of wallDuration . + * + * @return the value of long + */ + public long getWallDuration() { + return wallDuration; + } + + /** + * Sets the wallDuration . + *

You can use getWallDuration() to get the value of wallDuration

+ * + * @param wallDuration wallDuration + */ + public void setWallDuration(final long wallDuration) { + this.wallDuration = wallDuration; + } + + /** + * Gets the value of pid . + * + * @return the value of java.lang.String + */ + public String getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param pid pid + */ + public void setPid(final String pid) { + this.pid = pid; + } + + /** + * Gets the value of occurrences . + * + * @return the value of java.lang.String + */ + public String getOccurrences() { + return occurrences; + } + + /** + * Sets the occurrences . + *

You can use getOccurrences() to get the value of occurrences

+ * + * @param occurrences occurrences + */ + public void setOccurrences(final String occurrences) { + this.occurrences = occurrences; + } + + /** + * Gets the value of process . + * + * @return the value of java.lang.String + */ + public String getProcess() { + return process; + } + + /** + * Sets the process . + *

You can use getProcess() to get the value of process

+ * + * @param process process + */ + public void setProcess(final String process) { + this.process = process; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUThreadBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUThreadBean.java index 98cb70091..867662820 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUThreadBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CPUThreadBean.java @@ -1,193 +1,193 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.bean; - -/** - * cup thread entity class - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CPUThreadBean { - private long avgDuration; - - private long wallDuration; - - private String pid; - - private String tid; - - private String occurrences; - - private String process; - - private String thread; - - /** - * Parametric structure - * - * @param mAvgDuration mAvgDuration - * @param mWallDuration mWallDuration - * @param mPid mPid - * @param mTid mTid - * @param mOccurrences mOccurrences - * @param mProcess mProcess - * @param mThread mThread - */ - public CPUThreadBean(final long mAvgDuration, final long mWallDuration, final String mPid, final String mTid, - final String mOccurrences, final String mProcess, final String mThread) { - this.avgDuration = mAvgDuration; - this.wallDuration = mWallDuration; - this.pid = mPid; - this.tid = mTid; - this.occurrences = mOccurrences; - this.process = mProcess; - this.thread = mThread; - } - - /** - * Gets the value of avgDuration . - * - * @return the value of long - */ - public long getAvgDuration() { - return avgDuration; - } - - /** - * Sets the avgDuration . - *

You can use getAvgDuration() to get the value of avgDuration

- * - * @param avgDuration avgDuration - */ - public void setAvgDuration(final long avgDuration) { - this.avgDuration = avgDuration; - } - - /** - * Gets the value of wallDuration . - * - * @return the value of long - */ - public long getWallDuration() { - return wallDuration; - } - - /** - * Sets the wallDuration . - *

You can use getWallDuration() to get the value of wallDuration

- * - * @param wallDuration wallDuration - */ - public void setWallDuration(final long wallDuration) { - this.wallDuration = wallDuration; - } - - /** - * Gets the value of pid . - * - * @return the value of java.lang.String - */ - public String getPid() { - return pid; - } - - /** - * Sets the pid . - *

You can use getPid() to get the value of pid

- * - * @param pid pid - */ - public void setPid(final String pid) { - this.pid = pid; - } - - /** - * Gets the value of tid . - * - * @return the value of java.lang.String - */ - public String getTid() { - return tid; - } - - /** - * Sets the tid . - *

You can use getTid() to get the value of tid

- * - * @param tid tid - */ - public void setTid(final String tid) { - this.tid = tid; - } - - /** - * Gets the value of occurrences . - * - * @return the value of java.lang.String - */ - public String getOccurrences() { - return occurrences; - } - - /** - * Sets the occurrences . - *

You can use getOccurrences() to get the value of occurrences

- * - * @param occurrences occurrences - */ - public void setOccurrences(final String occurrences) { - this.occurrences = occurrences; - } - - /** - * Gets the value of process . - * - * @return the value of java.lang.String - */ - public String getProcess() { - return process; - } - - /** - * Sets the process . - *

You can use getProcess() to get the value of process

- * - * @param process process - */ - public void setProcess(final String process) { - this.process = process; - } - - /** - * Gets the value of thread . - * - * @return the value of java.lang.String - */ - public String getThread() { - return thread; - } - - /** - * Sets the thread . - *

You can use getThread() to get the value of thread

- * - * @param thread thread - */ - public void setThread(final String thread) { - this.thread = thread; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +/** + * cup thread entity class + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class CPUThreadBean { + private long avgDuration; + + private long wallDuration; + + private String pid; + + private String tid; + + private String occurrences; + + private String process; + + private String thread; + + /** + * Parametric structure + * + * @param mAvgDuration mAvgDuration + * @param mWallDuration mWallDuration + * @param mPid mPid + * @param mTid mTid + * @param mOccurrences mOccurrences + * @param mProcess mProcess + * @param mThread mThread + */ + public CPUThreadBean(final long mAvgDuration, final long mWallDuration, final String mPid, final String mTid, + final String mOccurrences, final String mProcess, final String mThread) { + this.avgDuration = mAvgDuration; + this.wallDuration = mWallDuration; + this.pid = mPid; + this.tid = mTid; + this.occurrences = mOccurrences; + this.process = mProcess; + this.thread = mThread; + } + + /** + * Gets the value of avgDuration . + * + * @return the value of long + */ + public long getAvgDuration() { + return avgDuration; + } + + /** + * Sets the avgDuration . + *

You can use getAvgDuration() to get the value of avgDuration

+ * + * @param avgDuration avgDuration + */ + public void setAvgDuration(final long avgDuration) { + this.avgDuration = avgDuration; + } + + /** + * Gets the value of wallDuration . + * + * @return the value of long + */ + public long getWallDuration() { + return wallDuration; + } + + /** + * Sets the wallDuration . + *

You can use getWallDuration() to get the value of wallDuration

+ * + * @param wallDuration wallDuration + */ + public void setWallDuration(final long wallDuration) { + this.wallDuration = wallDuration; + } + + /** + * Gets the value of pid . + * + * @return the value of java.lang.String + */ + public String getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param pid pid + */ + public void setPid(final String pid) { + this.pid = pid; + } + + /** + * Gets the value of tid . + * + * @return the value of java.lang.String + */ + public String getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid

+ * + * @param tid tid + */ + public void setTid(final String tid) { + this.tid = tid; + } + + /** + * Gets the value of occurrences . + * + * @return the value of java.lang.String + */ + public String getOccurrences() { + return occurrences; + } + + /** + * Sets the occurrences . + *

You can use getOccurrences() to get the value of occurrences

+ * + * @param occurrences occurrences + */ + public void setOccurrences(final String occurrences) { + this.occurrences = occurrences; + } + + /** + * Gets the value of process . + * + * @return the value of java.lang.String + */ + public String getProcess() { + return process; + } + + /** + * Sets the process . + *

You can use getProcess() to get the value of process

+ * + * @param process process + */ + public void setProcess(final String process) { + this.process = process; + } + + /** + * Gets the value of thread . + * + * @return the value of java.lang.String + */ + public String getThread() { + return thread; + } + + /** + * Sets the thread . + *

You can use getThread() to get the value of thread

+ * + * @param thread thread + */ + public void setThread(final String thread) { + this.thread = thread; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Clock.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Clock.java new file mode 100644 index 000000000..169e0d742 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Clock.java @@ -0,0 +1,86 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Clock + * + * @date 2021/08/25 00:31 + */ +public class Clock { + @DField(name = "name") + private String name; + @DField(name = "srcname") + private String srcname; + @DField(name = "num") + private Integer num; + + /** + * get clock name + * + * @return name + */ + public String getName() { + return name; + } + + /** + * set clock name + * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + /** + * get source name + * + * @return source name + */ + public String getSrcname() { + return srcname; + } + + /** + * set source name + * + * @param srcname source name + */ + public void setSrcname(String srcname) { + this.srcname = srcname; + } + + /** + * get clock num + * + * @return num + */ + public Integer getNum() { + return num; + } + + /** + * set clock num + * + * @param num num + */ + public void setNum(Integer num) { + this.num = num; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ClockData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ClockData.java new file mode 100644 index 000000000..96dbc8490 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ClockData.java @@ -0,0 +1,399 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * clock data + * + * @date 2021/04/22 12:25 + */ +public class ClockData extends AbstractGraph { + private final int padding1 = 2; + private final int padding2 = 4; + private final float alpha90 = .9f; + private final int strOffsetY = 16; + private final int redOff = 40; + private final int greenOff = 60; + private final int blueOff = 75; + @DField(name = "filter_id") + private Integer filterId; + @DField(name = "ts") + private Long startTime; + @DField(name = "end_ts") + private Long endTime; + @DField(name = "dur") + private Long duration; + @DField(name = "type") + private String type; + @DField(name = "value") + private Long value; + private Long delta; + private Long minValue; // Save the smallest value in the entire row of data + private Long maxValue; // Save the largest value in the entire row of data + private javax.swing.JComponent root; + private boolean isSelected; // Whether to be selected + private IEventListener eventListener; + + /** + * ui control extension field. + */ + public ClockData() { + } + + /** + * get min value + * + * @return Long min value + */ + public Long getMinValue() { + return minValue; + } + + /** + * set min value + * + * @param minValue value + */ + public void setMinValue(Long minValue) { + this.minValue = minValue; + } + + /** + * get max value + * + * @return long max value + */ + public Long getMaxValue() { + return maxValue; + } + + public void setMaxValue(Long maxValue) { + this.maxValue = maxValue; + } + + /** + * get the number of cpu . + * + * @return int Returns the number of cpu + */ + public int getFilterId() { + return filterId; + } + + /** + * set the value of cpu . + * + * @param filterId Set the number of cpu + */ + public void setFilterId(final int filterId) { + this.filterId = filterId; + } + + /** + * get the startTime . + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * set the startTime . + * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * get the duration . + * + * @return long + */ + public Long getDuration() { + return duration; + } + + /** + * set the duration . + * + * @param duration duration + */ + public void setDuration(final Long duration) { + this.duration = duration; + } + + /** + * get the type . + * + * @return String + */ + public String getType() { + return type; + } + + /** + * set the type . + * + * @param type type + */ + public void setType(final String type) { + this.type = type; + } + + /** + * get value + * + * @return value + */ + public Long getValue() { + return value; + } + + /** + * set value + * + * @param value value + */ + public void setValue(Long value) { + this.value = value; + } + + /** + * get delta value + * + * @return delta value + */ + public Long getDelta() { + return delta; + } + + /** + * set delta value + * + * @param delta delta value + */ + public void setDelta(Long delta) { + this.delta = delta; + } + + /** + * Get rootcomponent + * + * @return javax.swing.JComponent + */ + public javax.swing.JComponent getRoot() { + return root; + } + + /** + * Set to get rootcomponent + * + * @param root root + */ + public void setRoot(final javax.swing.JComponent root) { + this.root = root; + } + + /** + * Draw graphics based on attributes + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isSelected) { + drawSelect(graphics); + } else { + drawNoSelect(graphics); + } + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + graphics.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + graphics.setFont(Final.SMALL_FONT); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha90)); + rectangle.setRect(rect.getX(), rect.getY() + strOffsetY, rect.getWidth(), rect.getHeight()); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); + graphics.setFont(Final.NORMAL_FONT); + } + + private void drawSelect(final Graphics2D graphics) { + Color color = ColorUtils.colorForTid(maxValue.intValue()); + graphics.setColor(color); + double tmpHeight = rect.height * value * 1.0 / maxValue; + if (tmpHeight <= 0) { + tmpHeight = 1; + } + int yAxis = (int) (rect.getY() + rect.height - tmpHeight); + int xAxis = (int) rect.getX(); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); + graphics.fillRect(xAxis, yAxis, rect.width, (int) tmpHeight); + graphics.drawRect(xAxis, yAxis, rect.width, (int) tmpHeight); + int red = color.getRed(); + int green = color.getGreen(); + int blue = color.getBlue(); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + Color borderColor = new Color(red <= redOff ? 0 : red - redOff, + green <= greenOff ? 0 : green - greenOff, blue <= blueOff ? 0 : blue - blueOff); + graphics.setColor(borderColor); + graphics.fillRect(xAxis, yAxis, rect.width, 3); + } + + private void drawNoSelect(final Graphics2D graphics) { + Color color = ColorUtils.colorForTid(maxValue.intValue()); + graphics.setColor(color); + // int offset = rect.height/5;//value 为max的话 y = offset + double tmpHeight = rect.height * value * 1.0 / maxValue; + if (tmpHeight <= 0) { + tmpHeight = 1; + } + int yAxis = (int) (rect.getY() + rect.height - tmpHeight); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); + graphics.fillRect((int) rect.getX(), yAxis, rect.width, (int) tmpHeight); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + graphics.drawRect((int) rect.getX(), yAxis, rect.width, (int) tmpHeight); + } + + /** + * Set selected state + * + * @param isSelected isSelected + */ + public void select(final boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Redraw the current page + */ + public void repaint() { + if (root != null) { + root.repaint(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + } + } + + /** + * Focus acquisition event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + if (eventListener != null) { + eventListener.focus(event, this); + } + } + + /** + * Focus loss event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + if (eventListener != null) { + eventListener.blur(event, this); + } + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (eventListener != null) { + AnalystPanel.clicked = true; + eventListener.click(event, this); + } + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + if (edgeInspect(event)) { + if (eventListener != null) { + eventListener.mouseMove(event, this); + } + } + } + + /** + * Set callback event listener + * + * @param eventListener eventListener + */ + public void setEventListener(final IEventListener eventListener) { + this.eventListener = eventListener; + } + + /** + * Listener + */ + public interface IEventListener { + /** + * Mouse click event + * + * @param event event + * @param data data + */ + void click(MouseEvent event, ClockData data); + + /** + * Mouse blur event + * + * @param event event + * @param data data + */ + void blur(MouseEvent event, ClockData data); + + /** + * Mouse focus event + * + * @param event event + * @param data data + */ + void focus(MouseEvent event, ClockData data); + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + void mouseMove(MouseEvent event, ClockData data); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Counter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Counter.java new file mode 100644 index 000000000..346bdb03e --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Counter.java @@ -0,0 +1,150 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Counter + * + * @date 2021/04/20 12:24 + */ +public class Counter { + /** + * id + */ + @DField(name = "id") + private Integer id; + + /** + * track id + */ + @DField(name = "trackId") + private Integer trackId; + + /** + * track name + */ + @DField(name = "name") + private String name; + + /** + * value + */ + @DField(name = "value") + private Long value; + + /** + * start time + */ + @DField(name = "startTime") + private Long startTime; + + /** + * Gets the value of id . + * + * @return the value of id . + */ + public Integer getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id.

+ * + * @param param . + */ + public void setId(final Integer param) { + this.id = param; + } + + /** + * Gets the value of trackId . + * + * @return the value of trackId . + */ + public Integer getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId.

+ * + * @param param . + */ + public void setTrackId(final Integer param) { + this.trackId = param; + } + + /** + * Gets the value of value . + * + * @return the value of value . + */ + public Long getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value.

+ * + * @param param . + */ + public void setValue(final Long param) { + this.value = param; + } + + /** + * Gets the value of startTime . + * + * @return the value of startTime . + */ + public Long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime.

+ * + * @param param . + */ + public void setStartTime(final Long param) { + this.startTime = param; + } + + /** + * Gets the value of name . + * + * @return the value of name . + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name.

+ * + * @param param . + */ + public void setName(final String param) { + this.name = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Cpu.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Cpu.java new file mode 100644 index 000000000..f1a6ac51d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Cpu.java @@ -0,0 +1,338 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import com.intellij.ui.JBColor; +import ohos.devtools.views.applicationtrace.util.TimeUtils; +import ohos.devtools.views.trace.AbstractNode; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Graphics2D; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * cpu data + * + * @version 1.0 + * @date: 2021/5/14 15:52 + */ +public class Cpu extends AbstractNode { + private ArrayList stats = new ArrayList<>(); + @DField(name = "cpu") + private Integer cpu; + @DField(name = "name") + private String name; + @DField(name = "end_state") + private String endState; + @DField(name = "schedId") + private Integer schedId; + @DField(name = "type") + private String type; + @DField(name = "tid") + private Integer tid; + @DField(name = "processCmdLine") + private String processCmdLine; + @DField(name = "processName") + private String processName; + @DField(name = "processId") + private Integer processId; + @DField(name = "id") + private Integer id; + @DField(name = "priority") + private Integer priority; + @DField(name = "startTime") + private long startTime; + @DField(name = "dur") + private long duration; + + /** + * get the number of cpu . + * + * @return Integer Returns the number of cpu + */ + public Integer getCpu() { + return cpu; + } + + /** + * set the value of cpu . + * + * @param cpu Set the number of cpu + */ + public void setCpu(final Integer cpu) { + this.cpu = cpu; + } + + /** + * get the name . + * + * @return String Get the name + */ + public String getName() { + return name; + } + + /** + * set the name . + * + * @param name Set name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * get the stats . + * + * @return java.util.ArrayList + */ + public ArrayList getStats() { + return stats; + } + + /** + * set the stats . + * + * @param stats stats + */ + public void setStats(final ArrayList stats) { + this.stats = stats; + } + + /** + * get the endState . + * + * @return String endState + */ + public String getEndState() { + return endState; + } + + /** + * get the endState . + * + * @param endState endState + */ + public void setEndState(final String endState) { + this.endState = endState; + } + + /** + * get the priority . + * + * @return Integer priority + */ + public Integer getPriority() { + return priority; + } + + /** + * set the priority . + * + * @param priority priority + */ + public void setPriority(final Integer priority) { + this.priority = priority; + } + + /** + * get the schedId . + * + * @return Integer + */ + public Integer getSchedId() { + return schedId; + } + + /** + * set the schedId . + * + * @param schedId schedId + */ + public void setSchedId(final Integer schedId) { + this.schedId = schedId; + } + + /** + * get the startTime . + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * set the startTime . + * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * get the duration . + * + * @return long + */ + public long getDuration() { + return duration; + } + + /** + * set the duration . + * + * @param duration duration + */ + public void setDuration(final long duration) { + this.duration = duration; + } + + /** + * get the type . + * + * @return String + */ + public String getType() { + return type; + } + + /** + * set the type . + * + * @param type type + */ + public void setType(final String type) { + this.type = type; + } + + /** + * get the id . + * + * @return Integer + */ + public Integer getId() { + return id; + } + + /** + * set the id . + * + * @param id id + */ + public void setId(final Integer id) { + this.id = id; + } + + /** + * get the tid . + * + * @return Integer + */ + public Integer getTid() { + return tid; + } + + /** + * set the tid . + * + * @param tid tid + */ + public void setTid(final Integer tid) { + this.tid = tid; + } + + /** + * get the processCmdLine . + * + * @return String + */ + public String getProcessCmdLine() { + return processCmdLine; + } + + /** + * set the processCmdLine . + * + * @param processCmdLine processCmdLine + */ + public void setProcessCmdLine(final String processCmdLine) { + this.processCmdLine = processCmdLine; + } + + /** + * get the processName . + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * set the processName . + * + * @param processName processName + */ + public void setProcessName(final String processName) { + this.processName = processName; + } + + /** + * get the processId . + * + * @return Integer + */ + public Integer getProcessId() { + return processId; + } + + /** + * set the processId . + * + * @param processId processId + */ + public void setProcessId(final Integer processId) { + this.processId = processId; + } + + @Override + public void draw(Graphics2D paint) { + if (isMouseIn) { + Common.setAlpha(paint, 0.7F); + } else { + Common.setAlpha(paint, 1.0F); + } + paint.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + paint.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + Common.setAlpha(paint, 1.0F); + paint.setColor(JBColor.foreground().brighter()); + Common.drawStringCenter(paint, getName(), rect); + } + + @Override + public List getStringList(String time) { + return Arrays.asList(time, "Thread: " + name, + "Process: " + ((processName == null || processName.isBlank()) ? name : processName), + "Duration: " + TimeUtils.getTimeString(duration), "CPU: " + cpu); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuData.java index 253d3d6bc..a88dc9df1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuData.java @@ -1,553 +1,566 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.CpuDataFragment; -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.ColorUtils; -import ohos.devtools.views.trace.util.Final; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; - -/** - * cpu data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuData extends AbstractGraph { - private int cpu; - - /** - * get the number of cpu . - * - * @return int Returns the number of cpu - */ - public int getCpu() { - return cpu; - } - - /** - * set the value of cpu . - * - * @param cpu Set the number of cpu - */ - public void setCpu(final int cpu) { - this.cpu = cpu; - } - - private String name; - - /** - * get the name . - * - * @return String Get the name - */ - public String getName() { - return name; - } - - /** - * set the name . - * - * @param name Set name - */ - public void setName(final String name) { - this.name = name; - } - - private ArrayList stats = new ArrayList<>(); - - /** - * get the stats . - * - * @return java.util.ArrayList - */ - public java.util.ArrayList getStats() { - return stats; - } - - /** - * set the stats . - * - * @param stats stats - */ - public void setStats(final java.util.ArrayList stats) { - this.stats = stats; - } - - private String endState; - - /** - * get the endState . - * - * @return String endState - */ - public String getEndState() { - return endState; - } - - /** - * get the endState . - * - * @param endState endState - */ - public void setEndState(final String endState) { - this.endState = endState; - } - - private int priority; - - /** - * get the priority . - * - * @return int priority - */ - public int getPriority() { - return priority; - } - - /** - * set the priority . - * - * @param priority priority - */ - public void setPriority(final int priority) { - this.priority = priority; - } - - private int schedId; - - /** - * get the schedId . - * - * @return int - */ - public int getSchedId() { - return schedId; - } - - /** - * set the schedId . - * - * @param schedId schedId - */ - public void setSchedId(final int schedId) { - this.schedId = schedId; - } - - private long startTime; - - /** - * get the startTime . - * - * @return long - */ - public long getStartTime() { - return startTime; - } - - /** - * set the startTime . - * - * @param startTime startTime - */ - public void setStartTime(final long startTime) { - this.startTime = startTime; - } - - private long duration; - - /** - * get the duration . - * - * @return long - */ - public long getDuration() { - return duration; - } - - /** - * set the duration . - * - * @param duration duration - */ - public void setDuration(final long duration) { - this.duration = duration; - } - - private String type; - - /** - * get the type . - * - * @return String - */ - public String getType() { - return type; - } - - /** - * set the type . - * - * @param type type - */ - public void setType(final String type) { - this.type = type; - } - - private int id; - - /** - * get the id . - * - * @return int - */ - public int getId() { - return id; - } - - /** - * set the id . - * - * @param id id - */ - public void setId(final int id) { - this.id = id; - } - - private int tid; - - /** - * get the tid . - * - * @return int - */ - public int getTid() { - return tid; - } - - /** - * set the tid . - * - * @param tid tid - */ - public void setTid(final int tid) { - this.tid = tid; - } - - private String processCmdLine; - - /** - * get the processCmdLine . - * - * @return String - */ - public String getProcessCmdLine() { - return processCmdLine; - } - - /** - * set the processCmdLine . - * - * @param processCmdLine processCmdLine - */ - public void setProcessCmdLine(final String processCmdLine) { - this.processCmdLine = processCmdLine; - } - - private String processName; - - /** - * get the processName . - * - * @return String - */ - public String getProcessName() { - return processName; - } - - /** - * set the processName . - * - * @param processName processName - */ - public void setProcessName(final String processName) { - this.processName = processName; - } - - private int processId; - - /** - * get the processId . - * - * @return int - */ - public int getProcessId() { - return processId; - } - - /** - * set the processId . - * - * @param processId processId - */ - public void setProcessId(final int processId) { - this.processId = processId; - } - - /** - * ui control extension field. - */ - public CpuData() { - } - - private double chartWidth; - - private double chartNum; - - private String str; - - private Rectangle2D bounds; - - private javax.swing.JComponent root; - - /** - * Get rootcomponent - * - * @return javax.swing.JComponent - */ - public javax.swing.JComponent getRoot() { - return root; - } - - /** - * Set to get rootcomponent - * - * @param root root - */ - public void setRoot(final javax.swing.JComponent root) { - this.root = root; - } - - private final int padding1 = 2; - - private final int padding2 = 4; - - private final float alpha90 = .9f; - - private final float alpha60 = .6f; - - private final int strOffsetY = 16; - - private final int processNameControl = -2; - - /** - * Draw graphics based on attributes - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - if (isSelected) { - drawSelect(graphics); - } else { - drawNoSelect(graphics); - } - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); - graphics.setColor(Color.white); - int nameControl = processNameControl; - if (processName != null && !processName.isEmpty()) { - nameControl = processName.lastIndexOf("/"); - } - Rectangle rectangle = new Rectangle(); - if (nameControl >= 0) { - rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); - drawString(graphics, rectangle, processName.substring(nameControl + 1) + "[" + processId + "]", - Placement.CENTER); - } else if (nameControl == -1) { - rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); - drawString(graphics, rectangle, processName + "[" + processId + "]", Placement.CENTER); - } else { - rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); - drawString(graphics, rectangle, name + "[" + processId + "]", Placement.CENTER); - } - graphics.setFont(Final.SMALL_FONT); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha90)); - rectangle.setRect(rect.getX(), rect.getY() + strOffsetY, rect.getWidth(), rect.getHeight()); - drawString(graphics, rectangle, name + "[" + tid + "]", Placement.CENTER); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); - graphics.setFont(Final.NORMAL_FONT); - } - - private void drawSelect(final Graphics2D graphics) { - graphics.setColor(Color.BLACK); - graphics.fillRect((int) rect.getX(), (int) (rect.getY() - padding1), rect.width, rect.height + padding2); - if (CpuDataFragment.focusCpuData != null) { - if (CpuDataFragment.focusCpuData.processId != processId) { - graphics.setColor(Color.GRAY); - } else { - if (CpuDataFragment.focusCpuData.hashCode() != this.hashCode()) { - graphics.setComposite(AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, alpha60)); - } - graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); - } - } else { - graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); - } - graphics.fillRect((int) (rect.getX() + padding1), (int) rect.getY(), rect.width - padding2, rect.height); - } - - private void drawNoSelect(final Graphics2D graphics) { - if (CpuDataFragment.focusCpuData != null) { - if (CpuDataFragment.focusCpuData.processId != processId) { - graphics.setColor(Color.GRAY); - } else { - if (CpuDataFragment.focusCpuData.hashCode() != this.hashCode()) { - graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); - } - graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); - } - } else { - graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); - } - graphics.fillRect((int) rect.getX(), (int) rect.getY(), rect.width, rect.height); - } - - private boolean isSelected; // Whether to be selected - - /** - * Set selected state - * - * @param isSelected isSelected - */ - public void select(final boolean isSelected) { - this.isSelected = isSelected; - } - - /** - * Redraw the current page - */ - public void repaint() { - if (root != null) { - root.repaint(rect.x, rect.y - padding1, rect.width, rect.height + padding2); - } - } - - /** - * Focus acquisition event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - if (eventListener != null) { - eventListener.focus(event, this); - } - } - - /** - * Focus loss event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - if (eventListener != null) { - eventListener.blur(event, this); - } - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - if (eventListener != null) { - eventListener.click(event, this); - } - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - if (edgeInspect(event)) { - if (eventListener != null) { - eventListener.mouseMove(event, this); - } - } - } - - private IEventListener eventListener; - - /** - * Set callback event listener - * - * @param eventListener eventListener - */ - public void setEventListener(final IEventListener eventListener) { - this.eventListener = eventListener; - } - - /** - * Listener - */ - public interface IEventListener { - /** - * Mouse click event - * - * @param event event - * @param data data - */ - void click(MouseEvent event, CpuData data); - - /** - * Mouse blur event - * - * @param event event - * @param data data - */ - void blur(MouseEvent event, CpuData data); - - /** - * Mouse focus event - * - * @param event event - * @param data data - */ - void focus(MouseEvent event, CpuData data); - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - void mouseMove(MouseEvent event, CpuData data); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.fragment.CpuDataFragment; +import ohos.devtools.views.trace.fragment.ProcessDataFragment; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; + +/** + * cpu data + * + * @date 2021/04/22 12:25 + */ +public class CpuData extends AbstractGraph { + private final int padding1 = 2; + private final int padding2 = 4; + private final float alpha90 = .9f; + private final float alpha60 = .6f; + private final int strOffsetY = 16; + private final int processNameControl = -2; + @DField(name = "cpu") + private int cpu; + @DField(name = "name") + private String name; + private ArrayList stats = new ArrayList<>(); + @DField(name = "end_state") + private String endState; + @DField(name = "priority") + private int priority; + @DField(name = "schedId") + private int schedId; + @DField(name = "startTime") + private long startTime; + @DField(name = "dur") + private long duration; + @DField(name = "type") + private String type; + @DField(name = "id") + private int id; + @DField(name = "tid") + private int tid; + @DField(name = "processCmdLine") + private String processCmdLine; + @DField(name = "processName") + private String processName; + @DField(name = "processId") + private int processId; + private double chartWidth; + private double chartNum; + private String str; + private Rectangle2D bounds; + private javax.swing.JComponent root; + private boolean isSelected; // Whether to be selected + private IEventListener eventListener; + + /** + * ui control extension field. + */ + public CpuData() { + } + + /** + * get the number of cpu . + * + * @return int Returns the number of cpu + */ + public int getCpu() { + return cpu; + } + + /** + * set the value of cpu . + * + * @param cpu Set the number of cpu + */ + public void setCpu(final int cpu) { + this.cpu = cpu; + } + + /** + * get the name . + * + * @return String Get the name + */ + public String getName() { + return name; + } + + /** + * set the name . + * + * @param name Set name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * get the stats . + * + * @return java.util.ArrayList + */ + public java.util.ArrayList getStats() { + return stats; + } + + /** + * set the stats . + * + * @param stats stats + */ + public void setStats(final java.util.ArrayList stats) { + this.stats = stats; + } + + /** + * get the endState . + * + * @return String endState + */ + public String getEndState() { + return endState; + } + + /** + * get the endState . + * + * @param endState endState + */ + public void setEndState(final String endState) { + this.endState = endState; + } + + /** + * get the priority . + * + * @return int priority + */ + public int getPriority() { + return priority; + } + + /** + * set the priority . + * + * @param priority priority + */ + public void setPriority(final int priority) { + this.priority = priority; + } + + /** + * get the schedId . + * + * @return int + */ + public int getSchedId() { + return schedId; + } + + /** + * set the schedId . + * + * @param schedId schedId + */ + public void setSchedId(final int schedId) { + this.schedId = schedId; + } + + /** + * get the startTime . + * + * @return long + */ + public long getStartTime() { + return startTime; + } + + /** + * set the startTime . + * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * get the duration . + * + * @return long + */ + public long getDuration() { + return duration; + } + + /** + * set the duration . + * + * @param duration duration + */ + public void setDuration(final long duration) { + this.duration = duration; + } + + /** + * get the type . + * + * @return String + */ + public String getType() { + return type; + } + + /** + * set the type . + * + * @param type type + */ + public void setType(final String type) { + this.type = type; + } + + /** + * get the id . + * + * @return int + */ + public int getId() { + return id; + } + + /** + * set the id . + * + * @param id id + */ + public void setId(final int id) { + this.id = id; + } + + /** + * get the tid . + * + * @return int + */ + public int getTid() { + return tid; + } + + /** + * set the tid . + * + * @param tid tid + */ + public void setTid(final int tid) { + this.tid = tid; + } + + /** + * get the processCmdLine . + * + * @return String + */ + public String getProcessCmdLine() { + return processCmdLine; + } + + /** + * set the processCmdLine . + * + * @param processCmdLine processCmdLine + */ + public void setProcessCmdLine(final String processCmdLine) { + this.processCmdLine = processCmdLine; + } + + /** + * get the processName . + * + * @return String + */ + public String getProcessName() { + return processName; + } + + /** + * set the processName . + * + * @param processName processName + */ + public void setProcessName(final String processName) { + this.processName = processName; + } + + /** + * get the processId . + * + * @return int + */ + public int getProcessId() { + return processId; + } + + /** + * set the processId . + * + * @param processId processId + */ + public void setProcessId(final int processId) { + this.processId = processId; + } + + /** + * Get rootcomponent + * + * @return javax.swing.JComponent + */ + public javax.swing.JComponent getRoot() { + return root; + } + + /** + * Set to get rootcomponent + * + * @param root root + */ + public void setRoot(final javax.swing.JComponent root) { + this.root = root; + } + + /** + * Draw graphics based on attributes + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isSelected) { + drawSelect(graphics); + } else { + drawNoSelect(graphics); + } + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + graphics.setColor(Color.white); + int nameControl = processNameControl; + if (processName != null && !processName.isEmpty()) { + nameControl = processName.lastIndexOf("/"); + } + Rectangle rectangle = new Rectangle(); + if (nameControl >= 0) { + rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); + drawString(graphics, rectangle, processName.substring(nameControl + 1) + "[" + processId + "]", + Placement.CENTER); + } else if (nameControl == -1) { + rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); + drawString(graphics, rectangle, processName + "[" + processId + "]", Placement.CENTER); + } else { + rectangle.setRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); + drawString(graphics, rectangle, name + "[" + processId + "]", Placement.CENTER); + } + graphics.setFont(Final.SMALL_FONT); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha90)); + rectangle.setRect(rect.getX(), rect.getY() + strOffsetY, rect.getWidth(), rect.getHeight()); + drawString(graphics, rectangle, name + "[" + tid + "]", Placement.CENTER); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); + graphics.setFont(Final.NORMAL_FONT); + } + + private void drawSelect(final Graphics2D graphics) { + graphics.setColor(Color.BLACK); + graphics.fillRect((int) rect.getX(), (int) (rect.getY() - padding1), rect.width, rect.height + padding2); + if (CpuDataFragment.focusCpuData != null || ProcessDataFragment.focusProcessData != null) { + if (CpuDataFragment.focusCpuData != null) { + if (CpuDataFragment.focusCpuData.processId != processId) { + graphics.setColor(Color.GRAY); + } else if (CpuDataFragment.focusCpuData.getTid() != this.tid) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + } else { + if (ProcessDataFragment.focusProcessData.getPid() != processId) { + graphics.setColor(Color.GRAY); + } else if (ProcessDataFragment.focusProcessData.getTid() != this.tid) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + } + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + graphics.fillRect((int) (rect.getX() + padding1), (int) rect.getY(), rect.width - padding2, rect.height); + } + + private void drawNoSelect(final Graphics2D graphics) { + if (CpuDataFragment.focusCpuData != null || ProcessDataFragment.focusProcessData != null) { + if (CpuDataFragment.focusCpuData != null) { + if (CpuDataFragment.focusCpuData.processId != processId) { + graphics.setColor(Color.GRAY); + } else if (CpuDataFragment.focusCpuData.getTid() != this.tid) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + } else { + if (ProcessDataFragment.focusProcessData.getPid() != processId) { + graphics.setColor(Color.GRAY); + } else if (ProcessDataFragment.focusProcessData.getTid() != this.tid) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + } + } else { + graphics.setColor(ColorUtils.colorForTid(processId > 0 ? processId : tid)); + } + graphics.fillRect((int) rect.getX(), (int) rect.getY(), rect.width, rect.height); + } + + /** + * Set selected state + * + * @param isSelected isSelected + */ + public void select(final boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Redraw the current page + */ + public void repaint() { + if (root != null) { + root.repaint(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + } + } + + /** + * Focus acquisition event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + if (eventListener != null) { + eventListener.focus(event, this); + } + } + + /** + * Focus loss event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + if (eventListener != null) { + eventListener.blur(event, this); + } + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (eventListener != null) { + AnalystPanel.clicked = true; + eventListener.click(event, this); + } + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + if (edgeInspect(event)) { + if (eventListener != null) { + eventListener.mouseMove(event, this); + } + } + } + + /** + * Set callback event listener + * + * @param eventListener eventListener + */ + public void setEventListener(final IEventListener eventListener) { + this.eventListener = eventListener; + } + + /** + * Listener + */ + public interface IEventListener { + /** + * Mouse click event + * + * @param event event + * @param data data + */ + void click(MouseEvent event, CpuData data); + + /** + * Mouse blur event + * + * @param event event + * @param data data + */ + void blur(MouseEvent event, CpuData data); + + /** + * Mouse focus event + * + * @param event event + * @param data data + */ + void focus(MouseEvent event, CpuData data); + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + void mouseMove(MouseEvent event, CpuData data); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqData.java index 88d6a806a..f714efcaa 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqData.java @@ -1,213 +1,218 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.ColorUtils; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; - -/** - * cpu frequency data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuFreqData extends AbstractGraph { - private int cpu; - - private long value; - - private long startTime; - - private long duration; - - private JComponent root; - - private boolean flagFocus; - - private double max; - - /** - * Empty parameter construction method - */ - public CpuFreqData() { - } - - /** - * Gets the value of cpu . - * - * @return the value of int - */ - public int getCpu() { - return cpu; - } - - /** - * Sets the cpu . - *

You can use getCpu() to get the value of cpu

- * - * @param cpu cpu - */ - public void setCpu(final int cpu) { - this.cpu = cpu; - } - - /** - * Gets the value of value . - * - * @return the value of long - */ - public long getValue() { - return value; - } - - /** - * Sets the value . - *

You can use getValue() to get the value of value

- * - * @param value value - */ - public void setValue(final long value) { - this.value = value; - } - - /** - * Gets the value of startTime . - * - * @return the value of long - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the startTime . - *

You can use getStartTime() to get the value of startTime

- * - * @param startTime startTime - */ - public void setStartTime(final long startTime) { - this.startTime = startTime; - } - - /** - * Gets the value of duration . - * - * @return the value of long - */ - public long getDuration() { - return duration; - } - - /** - * Sets the duration . - *

You can use getDuration() to get the value of duration

- * - * @param duration duration - */ - public void setDuration(final long duration) { - this.duration = duration; - } - - /** - * Gets the value of root . - * - * @return the value of javax.swing.JComponent - */ - public JComponent getRoot() { - return root; - } - - /** - * Sets the root . - *

You can use getRoot() to get the value of root

- * - * @param root root - */ - public void setRoot(final JComponent root) { - this.root = root; - } - - /** - * Gets the value of flagFocus . - * - * @return the value of boolean - */ - public boolean isFlagFocus() { - return flagFocus; - } - - /** - * Sets the flagFocus . - *

You can use getFlagFocus() to get the value of flagFocus

- * - * @param flagFocus flagFocus - */ - public void setFlagFocus(final boolean flagFocus) { - this.flagFocus = flagFocus; - } - - /** - * Gets the value of max . - * - * @return the value of double - */ - public double getMax() { - return max; - } - - /** - * Sets the max . - *

You can use getMax() to get the value of max

- * - * @param max max - */ - public void setMax(double max) { - this.max = max; - } - - /** - * Rewrite drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - double drawHeight = (value * (rect.height - 5) * 1.0) / max; - graphics.setColor(ColorUtils.MD_PALETTE[cpu]); - graphics.fillRect(rect.x, rect.y + rect.height - (int) drawHeight, rect.width, (int) drawHeight); - } - - @Override - public void onFocus(final MouseEvent event) { - } - - @Override - public void onBlur(final MouseEvent event) { - } - - @Override - public void onClick(final MouseEvent event) { - } - - @Override - public void onMouseMove(final MouseEvent event) { - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; + +/** + * cpu frequency data + * + * @date 2021/04/22 12:25 + */ +public class CpuFreqData extends AbstractGraph { + @DField(name = "cpu") + private int cpu; + + @DField(name = "value") + private long value; + + @DField(name = "startNS") + private long startTime; + + private long duration; + + private JComponent root; + + private boolean flagFocus; + + private double max; + + /** + * Empty parameter construction method + */ + public CpuFreqData() { + } + + /** + * Gets the value of cpu . + * + * @return the value of int + */ + public int getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(final int cpu) { + this.cpu = cpu; + } + + /** + * Gets the value of value . + * + * @return the value of long + */ + public long getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param value value + */ + public void setValue(final long value) { + this.value = value; + } + + /** + * Gets the value of startTime . + * + * @return the value of long + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param startTime startTime + */ + public void setStartTime(final long startTime) { + this.startTime = startTime; + } + + /** + * Gets the value of duration . + * + * @return the value of long + */ + public long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param duration duration + */ + public void setDuration(final long duration) { + this.duration = duration; + } + + /** + * Gets the value of root . + * + * @return the value of javax.swing.JComponent + */ + public JComponent getRoot() { + return root; + } + + /** + * Sets the root . + *

You can use getRoot() to get the value of root

+ * + * @param root root + */ + public void setRoot(final JComponent root) { + this.root = root; + } + + /** + * Gets the value of flagFocus . + * + * @return the value of boolean + */ + public boolean isFlagFocus() { + return flagFocus; + } + + /** + * Sets the flagFocus . + *

You can use getFlagFocus() to get the value of flagFocus

+ * + * @param flagFocus flagFocus + */ + public void setFlagFocus(final boolean flagFocus) { + this.flagFocus = flagFocus; + } + + /** + * Gets the value of max . + * + * @return the value of double + */ + public double getMax() { + return max; + } + + /** + * Sets the max . + *

You can use getMax() to get the value of max

+ * + * @param max max + */ + public void setMax(double max) { + this.max = max; + } + + /** + * Rewrite drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + double drawHeight = (value * (rect.height - 5) * 1.0) / max; + graphics.setColor(ColorUtils.MD_PALETTE[cpu]); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect) + rect.height - (int) drawHeight, rect.width, + (int) drawHeight); + } + + @Override + public void onFocus(final MouseEvent event) { + } + + @Override + public void onBlur(final MouseEvent event) { + } + + @Override + public void onClick(final MouseEvent event) { + } + + @Override + public void onMouseMove(final MouseEvent event) { + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqMax.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqMax.java new file mode 100644 index 000000000..d2b1412bc --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuFreqMax.java @@ -0,0 +1,109 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Cpu FreqMax + * + * @date: 2021/5/27 12:29 + */ +public class CpuFreqMax { + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + @DField(name = "maxFreq") private Integer maxFreq; + private String name = "0 Ghz"; + private Double value = 0D; + + /** + * Gets the value of name . + * + * @return String + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name

+ * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the value of value . + * + * @return Double + */ + public Double getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param value value + */ + public void setValue(Double value) { + this.value = value; + } + + /** + * Gets the value of maxFreq . + * + * @return Integer + */ + public Integer getMaxFreq() { + return maxFreq; + } + + /** + * Sets the maxFreq . + *

You can use getMaxFreq() to get the value of maxFreq

+ * + * @param maxFreq maxFreq + */ + public void setMaxFreq(Integer maxFreq) { + this.maxFreq = maxFreq; + } + + /** + * get the math maxFreq . + * + * @return CpuFreqMax CpuFreqMax + */ + public CpuFreqMax math() { + StringBuilder sb = new StringBuilder(" "); + setName(" "); + if (maxFreq > 0) { + double log10 = Math.ceil(Math.log10(maxFreq)); + double pow10 = Math.pow(10, log10); + double afterCeil = Math.ceil(maxFreq / (pow10 / 4)) * (pow10 / 4); + setValue(afterCeil); + double unitIndex = Math.floor(log10 / 3); + sb.append(afterCeil / Math.pow(10, unitIndex * 3)); + sb.append(units[(int) unitIndex + 1]); + sb.append("hz"); + } + setName(sb.toString()); + return this; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuMax.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuMax.java new file mode 100644 index 000000000..1634d9901 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuMax.java @@ -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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * CpuMax + * + * @version 1.0 + * @date: 2021/5/27 12:22 + */ +public class CpuMax { + @DField(name = "cpu") + private Integer cpu; + + /** + * Gets the value of cpu . + * + * @return the value of java.lang.Integer + */ + public Integer getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(Integer cpu) { + this.cpu = cpu; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuRateBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuRateBean.java index 3618fa37f..1ddbd055f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuRateBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/CpuRateBean.java @@ -1,87 +1,91 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -/** - * cup usage rate entity class - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuRateBean { - private int cpu; - - private int index; - - private double rate; - - /** - * Gets the value of cpu . - * - * @return the value of int - */ - public int getCpu() { - return cpu; - } - - /** - * Sets the cpu . - *

You can use getCpu() to get the value of cpu

- * - * @param cpu cpu - */ - public void setCpu(final int cpu) { - this.cpu = cpu; - } - - /** - * Gets the value of index . - * - * @return the value of int - */ - public int getIndex() { - return index; - } - - /** - * Sets the index . - *

You can use getIndex() to get the value of index

- * - * @param index index - */ - public void setIndex(final int index) { - this.index = index; - } - - /** - * Gets the value of rate . - * - * @return the value of double - */ - public double getRate() { - return rate; - } - - /** - * Sets the rate . - *

You can use getRate() to get the value of rate

- * - * @param rate rate - */ - public void setRate(final double rate) { - this.rate = rate; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * cup usage rate entity class + * + * @date 2021/04/22 12:25 + */ +public class CpuRateBean { + @DField(name = "cpu") + private int cpu; + + @DField(name = "ro") + private int index; + + @DField(name = "rate") + private double rate; + + /** + * Gets the value of cpu . + * + * @return the value of int + */ + public int getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(final int cpu) { + this.cpu = cpu; + } + + /** + * Gets the value of index . + * + * @return the value of int + */ + public int getIndex() { + return index; + } + + /** + * Sets the index . + *

You can use getIndex() to get the value of index

+ * + * @param index index + */ + public void setIndex(final int index) { + this.index = index; + } + + /** + * Gets the value of rate . + * + * @return the value of double + */ + public double getRate() { + return rate; + } + + /** + * Sets the rate . + *

You can use getRate() to get the value of rate

+ * + * @param rate rate + */ + public void setRate(final double rate) { + this.rate = rate; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Duration.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Duration.java new file mode 100644 index 000000000..39cde3284 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Duration.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Duration class + * + * @version 1.0 + * @date: 2021/5/27 12:01 + */ +public class Duration { + @DField(name = "total") + private Long total; + @DField(name = "start_ts") + private Long startTs; + @DField(name = "end_ts") + private Long endTs; + + /** + * Gets the value of total . + * + * @return the value of java.lang.Long + */ + public Long getTotal() { + return total; + } + + /** + * Sets the total . + *

You can use getTotal() to get the value of total

+ * + * @param total total + */ + public void setTotal(Long total) { + this.total = total; + } + + /** + * Gets the value of startTs . + * + * @return the value of java.lang.Long + */ + public Long getStartTs() { + return startTs; + } + + /** + * Sets the startTs . + *

You can use getStartTs() to get the value of startTs

+ * + * @param startTs startTs + */ + public void setStartTs(Long startTs) { + this.startTs = startTs; + } + + /** + * Gets the value of endTs . + * + * @return the value of java.lang.Long + */ + public Long getEndTs() { + return endTs; + } + + /** + * Sets the endTs . + *

You can use getEndTs() to get the value of endTs

+ * + * @param endTs endTs + */ + public void setEndTs(Long endTs) { + this.endTs = endTs; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FlagBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FlagBean.java index 8963d45ce..87f3d9fc8 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FlagBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FlagBean.java @@ -1,265 +1,259 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.ColorUtils; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; - -/** - * Little Red Flag Data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class FlagBean extends AbstractGraph { - private long ns; - - private boolean visible; - - private String name; - - private long time; - - private Color color; - - /** - * Gets the value of ns . - * - * @return the value of long - */ - public long getNs() { - return ns; - } - - /** - * Sets the ns . - *

You can use getNs() to get the value of ns

- * - * @param ns Nanoseconds - */ - public void setNs(final long ns) { - this.ns = ns; - } - - /** - * Gets the value of visible . - * - * @return the value of boolean - */ - public boolean isVisible() { - return visible; - } - - /** - * Sets the visible . - *

You can use getVisible() to get the value of visible

- * - * @param visible Whether to show - */ - public void setVisible(final boolean visible) { - this.visible = visible; - } - - /** - * Gets the value of name . - * - * @return the value of java.lang.String - */ - public String getName() { - return name; - } - - /** - * Sets the name . - *

You can use getName() to get the value of name

- * - * @param name name - */ - public void setName(final String name) { - this.name = name; - } - - /** - * Gets the value of time . - * - * @return the value of long - */ - public long getTime() { - return time; - } - - /** - * Sets the time . - *

You can use getTime() to get the value of time

- * - * @param time time - */ - public void setTime(final long time) { - this.time = time; - } - - /** - * Gets the value of color . - * - * @return the value of java.awt.Color - */ - public Color getColor() { - return color; - } - - /** - * Sets the color . - *

You can use getColor() to get the value of color

- * - * @param color color - */ - public void setColor(final Color color) { - this.color = color; - } - - /** - * remove listener - */ - public void remove() { - if (eventListener != null) { - eventListener.delete(this); - } - } - - private final int defaultFuncColorIndex = 6; - - /** - * no parameter structure - */ - public FlagBean() { - visible = false; - color = ColorUtils.FUNC_COLOR[defaultFuncColorIndex]; - } - - /** - * Draw the corresponding shape according to the brush - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - if (name != null && !name.isEmpty()) { - graphics.setColor(color); - final int sx = 202; - final int xy = 4; - graphics.drawString(name, sx + rect.x + rect.width, rect.y + rect.height - xy); - } - } - - /** - * Focus acquisition - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - } - - /** - * lose focus - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - if (eventListener != null) { - eventListener.click(event, this); - } - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } - - private IEventListener eventListener; - - /** - * Set up the event listener - * - * @param eventListener eventListener - */ - public void setEventListener(final IEventListener eventListener) { - this.eventListener = eventListener; - } - - /** - * Event listener - */ - public interface IEventListener { - /** - * Click event - * - * @param event event - * @param data data - */ - void click(MouseEvent event, FlagBean data); - - /** - * Focus cancel event - * - * @param event event - * @param data data - */ - void blur(MouseEvent event, FlagBean data); - - /** - * Focus acquisition event - * - * @param event event - * @param data data - */ - void focus(MouseEvent event, FlagBean data); - - /** - * Mouse movement event - * - * @param event event - * @param data data - */ - void mouseMove(MouseEvent event, FlagBean data); - - /** - * Delete event - * - * @param data data - */ - void delete(FlagBean data); - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; + +/** + * Little Red Flag Data + * + * @date 2021/04/22 12:25 + */ +public class FlagBean extends AbstractGraph { + private final int defaultFuncColorIndex = 6; + private long ns; + private boolean visible; + private String name; + private long time; + private Color color; + private IEventListener eventListener; + + /** + * no parameter structure + */ + public FlagBean() { + visible = false; + color = ColorUtils.FUNC_COLOR[defaultFuncColorIndex]; + } + + /** + * Gets the value of ns . + * + * @return the value of long + */ + public long getNs() { + return ns; + } + + /** + * Sets the ns . + *

You can use getNs() to get the value of ns

+ * + * @param ns Nanoseconds + */ + public void setNs(final long ns) { + this.ns = ns; + } + + /** + * Gets the value of visible . + * + * @return the value of boolean + */ + public boolean isVisible() { + return visible; + } + + /** + * Sets the visible . + *

You can use getVisible() to get the value of visible

+ * + * @param visible Whether to show + */ + public void setVisible(final boolean visible) { + this.visible = visible; + } + + /** + * Gets the value of name . + * + * @return the value of java.lang.String + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name

+ * + * @param name name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Gets the value of time . + * + * @return the value of long + */ + public long getTime() { + return time; + } + + /** + * Sets the time . + *

You can use getTime() to get the value of time

+ * + * @param time time + */ + public void setTime(final long time) { + this.time = time; + } + + /** + * Gets the value of color . + * + * @return the value of java.awt.Color + */ + public Color getColor() { + return color; + } + + /** + * Sets the color . + *

You can use getColor() to get the value of color

+ * + * @param color color + */ + public void setColor(final Color color) { + this.color = color; + } + + /** + * remove listener + */ + public void remove() { + if (eventListener != null) { + eventListener.delete(this); + } + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (name != null && !name.isEmpty()) { + graphics.setColor(color); + final int sx = 202; + final int xy = 4; + graphics.drawString(name, sx + Utils.getX(rect) + rect.width, Utils.getY(rect) + rect.height - xy); + } + } + + /** + * Focus acquisition + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + } + + /** + * lose focus + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (eventListener != null) { + eventListener.click(event, this); + } + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } + + /** + * Set up the event listener + * + * @param eventListener eventListener + */ + public void setEventListener(final IEventListener eventListener) { + this.eventListener = eventListener; + } + + /** + * Event listener + */ + public interface IEventListener { + /** + * Click event + * + * @param event event + * @param data data + */ + void click(MouseEvent event, FlagBean data); + + /** + * Focus cancel event + * + * @param event event + * @param data data + */ + void blur(MouseEvent event, FlagBean data); + + /** + * Focus acquisition event + * + * @param event event + * @param data data + */ + void focus(MouseEvent event, FlagBean data); + + /** + * Mouse movement event + * + * @param event event + * @param data data + */ + void mouseMove(MouseEvent event, FlagBean data); + + /** + * Delete event + * + * @param data data + */ + void delete(FlagBean data); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FunctionBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FunctionBean.java index 04077ffeb..1c2f3295d 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FunctionBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/FunctionBean.java @@ -1,365 +1,375 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.ColorUtils; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; - -/** - * Method entity class - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class FunctionBean extends AbstractGraph { - private int tid; - - private String threadName; - - private int isMainThread; - - private int trackId; - - private long startTime; - - private long duration; - - private String funName; - - private int depth; - - private String category; - - private boolean isSelected; // Whether to be selected - - /** - * Gets the value of tid . - * - * @return the value of int - */ - public int getTid() { - return tid; - } - - /** - * Sets the tid . - *

You can use getTid() to get the value of tid

- * - * @param pTid pTid - */ - public void setTid(final int pTid) { - this.tid = pTid; - } - - /** - * Gets the value of threadName . - * - * @return the value of java.lang.String - */ - public String getThreadName() { - return threadName; - } - - /** - * Sets the threadName . - *

You can use getThreadName() to get the value of threadName

- * - * @param name name - */ - public void setThreadName(final String name) { - this.threadName = name; - } - - /** - * Gets the value of isMainThread . - * - * @return the value of int - */ - public int getIsMainThread() { - return isMainThread; - } - - /** - * Sets the isMainThread . - *

You can use getIsMainThread() to get the value of isMainThread

- * - * @param mainThread mainThread - */ - public void setIsMainThread(final int mainThread) { - this.isMainThread = mainThread; - } - - /** - * Gets the value of trackId . - * - * @return the value of int - */ - public int getTrackId() { - return trackId; - } - - /** - * Sets the trackId . - *

You can use getTrackId() to get the value of trackId

- * - * @param id id - */ - public void setTrackId(final int id) { - this.trackId = id; - } - - /** - * Gets the value of startTime . - * - * @return the value of long - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the startTime . - *

You can use getStartTime() to get the value of startTime

- * - * @param time time - */ - public void setStartTime(final long time) { - this.startTime = time; - } - - /** - * Gets the value of duration . - * - * @return the value of long - */ - public long getDuration() { - return duration; - } - - /** - * Sets the duration . - *

You can use getDuration() to get the value of duration

- * - * @param dur dur - */ - public void setDuration(final long dur) { - this.duration = dur; - } - - /** - * Gets the value of funName . - * - * @return the value of java.lang.String - */ - public String getFunName() { - return funName; - } - - /** - * Sets the funName . - *

You can use getFunName() to get the value of funName

- * - * @param name name - */ - public void setFunName(final String name) { - this.funName = name; - } - - /** - * Gets the value of depth . - * - * @return the value of int - */ - public int getDepth() { - return depth; - } - - /** - * Sets the depth . - *

You can use getDepth() to get the value of depth

- * - * @param dep dep - */ - public void setDepth(final int dep) { - this.depth = dep; - } - - /** - * Gets the value of category . - * - * @return the value of java.lang.String - */ - public String getCategory() { - return category; - } - - /** - * Sets the category . - *

You can use getCategory() to get the value of category

- * - * @param cate cate - */ - public void setCategory(final String cate) { - this.category = cate; - } - - /** - * Gets the value of isSelected . - * - * @return the value of boolean - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets the isSelected . - *

You can use getSelected() to get the value of isSelected

- * - * @param selected selected - */ - public void setSelected(final boolean selected) { - this.isSelected = selected; - } - - /** - * Draw the corresponding shape according to the brush - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - if (isSelected) { - graphics.setColor(Color.black); - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); - graphics.fillRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); - graphics.setColor(Color.white); - Rectangle rectangle = new Rectangle(); - rectangle.setRect(rect.getX() + 1, rect.getY() + 1, rect.getWidth() - 2, rect.getHeight() - 2); - drawString(graphics, rectangle, funName, Placement.CENTER_LINE); - } else { - graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, funName, Placement.CENTER_LINE); - } - } - - /** - * Focus acquisition event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - if (eventListener != null) { - eventListener.focus(event, this); - } - } - - /** - * Focus cancel event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - if (eventListener != null) { - eventListener.blur(event, this); - } - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - if (eventListener != null) { - eventListener.click(event, this); - } - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - if (edgeInspect(event)) { - if (eventListener != null) { - eventListener.mouseMove(event, this); - } - } - } - - private IEventListener eventListener; - - /** - * Set up the event listener - * - * @param listener listener - */ - public void setEventListener(final IEventListener listener) { - this.eventListener = listener; - } - - /** - * listener - */ - public interface IEventListener { - /** - * Click event - * - * @param event event - * @param data data - */ - void click(MouseEvent event, FunctionBean data); - - /** - * Focus cancel event - * - * @param event event - * @param data data - */ - void blur(MouseEvent event, FunctionBean data); - - /** - * Focus acquisition event - * - * @param event event - * @param data data - */ - void focus(MouseEvent event, FunctionBean data); - - /** - * Mouse movement event - * - * @param event event - * @param data data - */ - void mouseMove(MouseEvent event, FunctionBean data); - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * Method entity class + * + * @date 2021/04/22 12:25 + */ +public class FunctionBean extends AbstractGraph { + @DField(name = "tid") + private Integer tid; + + @DField(name = "threadName") + private String threadName; + + @DField(name = "is_main_thread") + private Integer isMainThread; + + @DField(name = "track_id") + private Integer trackId; + + @DField(name = "startTs") + private Long startTime; + + @DField(name = "dur") + private Long duration; + + @DField(name = "funName") + private String funName; + + @DField(name = "depth") + private Integer depth; + + private String category; + + private boolean isSelected; // Whether to be selected + private IEventListener eventListener; + + /** + * Gets the value of tid . + * + * @return the value of int + */ + public Integer getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid

+ * + * @param pTid pTid + */ + public void setTid(final Integer pTid) { + this.tid = pTid; + } + + /** + * Gets the value of threadName . + * + * @return the value of java.lang.String + */ + public String getThreadName() { + return threadName; + } + + /** + * Sets the threadName . + *

You can use getThreadName() to get the value of threadName

+ * + * @param name name + */ + public void setThreadName(final String name) { + this.threadName = name; + } + + /** + * Gets the value of isMainThread . + * + * @return the value of int + */ + public Integer getIsMainThread() { + return isMainThread; + } + + /** + * Sets the isMainThread . + *

You can use getIsMainThread() to get the value of isMainThread

+ * + * @param mainThread mainThread + */ + public void setIsMainThread(final Integer mainThread) { + this.isMainThread = mainThread; + } + + /** + * Gets the value of trackId . + * + * @return the value of int + */ + public Integer getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId

+ * + * @param id id + */ + public void setTrackId(final Integer id) { + this.trackId = id; + } + + /** + * Gets the value of startTime . + * + * @return the value of long + */ + public Long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param time time + */ + public void setStartTime(final Long time) { + this.startTime = time; + } + + /** + * Gets the value of duration . + * + * @return the value of long + */ + public Long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param dur dur + */ + public void setDuration(final Long dur) { + this.duration = dur; + } + + /** + * Gets the value of funName . + * + * @return the value of java.lang.String + */ + public String getFunName() { + return funName; + } + + /** + * Sets the funName . + *

You can use getFunName() to get the value of funName

+ * + * @param name name + */ + public void setFunName(final String name) { + this.funName = name; + } + + /** + * Gets the value of depth . + * + * @return the value of int + */ + public Integer getDepth() { + return depth; + } + + /** + * Sets the depth . + *

You can use getDepth() to get the value of depth

+ * + * @param dep dep + */ + public void setDepth(final Integer dep) { + this.depth = dep; + } + + /** + * Gets the value of category . + * + * @return the value of java.lang.String + */ + public String getCategory() { + return category; + } + + /** + * Sets the category . + *

You can use getCategory() to get the value of category

+ * + * @param cate cate + */ + public void setCategory(final String cate) { + this.category = cate; + } + + /** + * Gets the value of isSelected . + * + * @return the value of boolean + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the isSelected . + *

You can use getSelected() to get the value of isSelected

+ * + * @param selected selected + */ + public void setSelected(final boolean selected) { + this.isSelected = selected; + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isSelected) { + graphics.setColor(Color.black); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); + graphics.fillRect(Utils.getX(rect) + 1, Utils.getY(rect) + 1, rect.width - 2, rect.height - 2); + graphics.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + 1, rect.getY() + 1, rect.getWidth() - 2, rect.getHeight() - 2); + drawString(graphics, rectangle, funName, Placement.CENTER_LINE); + } else { + graphics.setColor(ColorUtils.FUNC_COLOR[depth % ColorUtils.FUNC_COLOR.length]); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, funName, Placement.CENTER_LINE); + } + } + + /** + * Focus acquisition event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + if (eventListener != null) { + eventListener.focus(event, this); + } + } + + /** + * Focus cancel event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + if (eventListener != null) { + eventListener.blur(event, this); + } + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (eventListener != null) { + AnalystPanel.clicked = true; + eventListener.click(event, this); + } + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + if (edgeInspect(event)) { + if (eventListener != null) { + eventListener.mouseMove(event, this); + } + } + } + + /** + * Set up the event listener + * + * @param listener listener + */ + public void setEventListener(final IEventListener listener) { + this.eventListener = listener; + } + + /** + * listener + */ + public interface IEventListener { + /** + * Click event + * + * @param event event + * @param data data + */ + void click(MouseEvent event, FunctionBean data); + + /** + * Focus cancel event + * + * @param event event + * @param data data + */ + void blur(MouseEvent event, FunctionBean data); + + /** + * Focus acquisition event + * + * @param event event + * @param data data + */ + void focus(MouseEvent event, FunctionBean data); + + /** + * Mouse movement event + * + * @param event event + * @param data data + */ + void mouseMove(MouseEvent event, FunctionBean data); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Process.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Process.java index 1d46b71d6..da6239c68 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Process.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/Process.java @@ -1,66 +1,74 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.bean; - -/** - * Process entity class - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class Process { - private int pid; - - private String name; - - /** - * Gets the value of pid . - * - * @return the value of int - */ - public int getPid() { - return pid; - } - - /** - * Sets the pid . - *

You can use getPid() to get the value of pid

- * - * @param id id - */ - public void setPid(final int id) { - this.pid = id; - } - - /** - * Gets the value of name . - * - * @return the value of java.lang.String - */ - public String getName() { - return name; - } - - /** - * Sets the name . - *

You can use getName() to get the value of name

- * - * @param name name - */ - public void setName(final String name) { - this.name = name; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Process entity class + * + * @date 2021/04/22 12:25 + */ +public class Process { + @DField(name = "pid") + private Integer pid; + + @DField(name = "processName") + private String name; + + /** + * Gets the value of pid . + * + * @return the value of int + */ + public Integer getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param id id + */ + public void setPid(final Integer id) { + this.pid = id; + } + + /** + * Gets the value of name . + * + * @return the value of java.lang.String + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name

+ * + * @param name name + */ + public void setName(final String name) { + this.name = name; + } + + @Override + public String toString() { + return pid + "-" + name; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessData.java index f818e2987..897676415 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessData.java @@ -1,200 +1,294 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; - -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; - -/** - * Process data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ProcessData extends AbstractGraph { - private int id; - - private int utid; - - private int cpu; - - private long startTime; - - private long duration; - - private String state; - - /** - * Gets the value of id . - * - * @return the value of int - */ - public int getId() { - return id; - } - - /** - * Sets the id . - *

You can use getId() to get the value of id

- * - * @param id id - */ - public void setId(final int id) { - this.id = id; - } - - /** - * Gets the value of utid . - * - * @return the value of int - */ - public int getUtid() { - return utid; - } - - /** - * Sets the utid . - *

You can use getUtid() to get the value of utid

- * - * @param id id - */ - public void setUtid(final int id) { - this.utid = id; - } - - /** - * Gets the value of cpu . - * - * @return the value of int - */ - public int getCpu() { - return cpu; - } - - /** - * Sets the cpu . - *

You can use getCpu() to get the value of cpu

- * - * @param cpu cpu - */ - public void setCpu(final int cpu) { - this.cpu = cpu; - } - - /** - * Gets the value of startTime . - * - * @return the value of long - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the startTime . - *

You can use getStartTime() to get the value of startTime

- * - * @param time time - */ - public void setStartTime(final long time) { - this.startTime = time; - } - - /** - * Gets the value of duration . - * - * @return the value of long - */ - public long getDuration() { - return duration; - } - - /** - * Sets the duration . - *

You can use getDuration() to get the value of duration

- * - * @param dur dur - */ - public void setDuration(final long dur) { - this.duration = dur; - } - - /** - * Gets the value of state . - * - * @return the value of java.lang.String - */ - public String getState() { - return state; - } - - /** - * Sets the state . - *

You can use getState() to get the value of state

- * - * @param state state - */ - public void setState(final String state) { - this.state = state; - } - - /** - * Draw the corresponding shape according to the brush - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - } - - /** - * Get focus event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - } - - /** - * Focus cancel callback event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; + +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; + +/** + * Process data + * + * @date 2021/04/22 12:25 + */ +public class ProcessData extends AbstractGraph { + @DField(name = "id") + private int id; + + @DField(name = "utid") + private int utid; + + @DField(name = "cpu") + private int cpu; + + @DField(name = "startTime") + private long startTime; + + @DField(name = "dur") + private long duration; + + @DField(name = "state") + private String state; + + @DField(name = "tid") + private int tid; + + @DField(name = "pid") + private int pid; + + @DField(name = "process") + private String process; + + @DField(name = "thread") + private String thread; + + /** + * Gets the value of id . + * + * @return the value of int + */ + public int getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id

+ * + * @param id id + */ + public void setId(final int id) { + this.id = id; + } + + /** + * Gets the value of utid . + * + * @return the value of int + */ + public int getUtid() { + return utid; + } + + /** + * Sets the utid . + *

You can use getUtid() to get the value of utid

+ * + * @param id id + */ + public void setUtid(final int id) { + this.utid = id; + } + + /** + * Gets the value of cpu . + * + * @return the value of int + */ + public int getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu

+ * + * @param cpu cpu + */ + public void setCpu(final int cpu) { + this.cpu = cpu; + } + + /** + * Gets the value of startTime . + * + * @return the value of long + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param time time + */ + public void setStartTime(final long time) { + this.startTime = time; + } + + /** + * Gets the value of duration . + * + * @return the value of long + */ + public long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param dur dur + */ + public void setDuration(final long dur) { + this.duration = dur; + } + + /** + * Gets the value of state . + * + * @return the value of java.lang.String + */ + public String getState() { + return state; + } + + /** + * Sets the state . + *

You can use getState() to get the value of state

+ * + * @param state state + */ + public void setState(final String state) { + this.state = state; + } + + /** + * Gets the value of tid . + * + * @return the value of tid . + */ + public int getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid.

+ * + * @param param . + */ + public void setTid(final int param) { + this.tid = param; + } + + /** + * Gets the value of pid . + * + * @return the value of pid . + */ + public int getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid.

+ * + * @param param . + */ + public void setPid(final int param) { + this.pid = param; + } + + /** + * Gets the value of process . + * + * @return the value of process . + */ + public String getProcess() { + return process; + } + + /** + * Sets the process . + *

You can use getProcess() to get the value of process.

+ * + * @param param . + */ + public void setProcess(final String param) { + this.process = param; + } + + /** + * Gets the value of thread . + * + * @return the value of thread . + */ + public String getThread() { + return thread; + } + + /** + * Sets the thread . + *

You can use getThread() to get the value of thread.

+ * + * @param param . + */ + public void setThread(final String param) { + this.thread = param; + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + } + + /** + * Get focus event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + } + + /** + * Focus cancel callback event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMem.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMem.java index dafd2444c..7e8ac2557 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMem.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMem.java @@ -1,129 +1,135 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -/** - * Process memory directory - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ProcessMem { - private int trackId; - - private String processName; - - private int pid; - - private int upid; - - private String trackName; - - /** - * Gets the value of trackId . - * - * @return the value of int - */ - public int getTrackId() { - return trackId; - } - - /** - * Sets the trackId . - *

You can use getTrackId() to get the value of trackId

- * - * @param track track - */ - public void setTrackId(final int track) { - this.trackId = track; - } - - /** - * Gets the value of processName . - * - * @return the value of java.lang.String - */ - public String getProcessName() { - return processName; - } - - /** - * Sets the processName . - *

You can use getProcessName() to get the value of processName

- * - * @param name name - */ - public void setProcessName(final String name) { - this.processName = name; - } - - /** - * Gets the value of pid . - * - * @return the value of int - */ - public int getPid() { - return pid; - } - - /** - * Sets the pid . - *

You can use getPid() to get the value of pid

- * - * @param id id - */ - public void setPid(final int id) { - this.pid = id; - } - - /** - * Gets the value of upid . - * - * @return the value of int - */ - public int getUpid() { - return upid; - } - - /** - * Sets the upid . - *

You can use getUpid() to get the value of upid

- * - * @param id id - */ - public void setUpid(final int id) { - this.upid = id; - } - - /** - * Gets the value of trackName . - * - * @return the value of java.lang.String - */ - public String getTrackName() { - return trackName; - } - - /** - * Sets the trackName . - *

You can use getTrackName() to get the value of trackName

- * - * @param name name - */ - public void setTrackName(final String name) { - this.trackName = name; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Process memory directory + * + * @date 2021/04/22 12:25 + */ +public class ProcessMem { + @DField(name = "trackId") + private int trackId; + + @DField(name = "processName") + private String processName; + + @DField(name = "pid") + private int pid; + + @DField(name = "upid") + private int upid; + + @DField(name = "trackName") + private String trackName; + + /** + * Gets the value of trackId . + * + * @return the value of int + */ + public int getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId

+ * + * @param track track + */ + public void setTrackId(final int track) { + this.trackId = track; + } + + /** + * Gets the value of processName . + * + * @return the value of java.lang.String + */ + public String getProcessName() { + return processName; + } + + /** + * Sets the processName . + *

You can use getProcessName() to get the value of processName

+ * + * @param name name + */ + public void setProcessName(final String name) { + this.processName = name; + } + + /** + * Gets the value of pid . + * + * @return the value of int + */ + public int getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param id id + */ + public void setPid(final int id) { + this.pid = id; + } + + /** + * Gets the value of upid . + * + * @return the value of int + */ + public int getUpid() { + return upid; + } + + /** + * Sets the upid . + *

You can use getUpid() to get the value of upid

+ * + * @param id id + */ + public void setUpid(final int id) { + this.upid = id; + } + + /** + * Gets the value of trackName . + * + * @return the value of java.lang.String + */ + public String getTrackName() { + return trackName; + } + + /** + * Sets the trackName . + *

You can use getTrackName() to get the value of trackName

+ * + * @param name name + */ + public void setTrackName(final String name) { + this.trackName = name; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMemData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMemData.java index 92d189bb2..227536e71 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMemData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ProcessMemData.java @@ -1,230 +1,229 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.ColorUtils; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; - -/** - * Process memory data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ProcessMemData extends AbstractGraph { - private int maxValue; - - /** - * Gets the value of maxValue . - * - * @return the value of int - */ - public int getMaxValue() { - return maxValue; - } - - /** - * Sets the maxValue . - *

You can use getMaxValue() to get the value of maxValue

- * - * @param max max - */ - public void setMaxValue(final int max) { - this.maxValue = max; - } - - private int id; - - private String type; - - private int trackId; - - private int value; - - private long startTime; - - private long duration; - - /** - * Gets the value of id . - * - * @return the value of int - */ - public int getId() { - return id; - } - - /** - * Sets the id . - *

You can use getId() to get the value of id

- * - * @param id id - */ - public void setId(final int id) { - this.id = id; - } - - /** - * Gets the value of type . - * - * @return the value of java.lang.String - */ - public String getType() { - return type; - } - - /** - * Sets the type . - *

You can use getType() to get the value of type

- * - * @param type type - */ - public void setType(final String type) { - this.type = type; - } - - /** - * Gets the value of trackId . - * - * @return the value of int - */ - public int getTrackId() { - return trackId; - } - - /** - * Sets the trackId . - *

You can use getTrackId() to get the value of trackId

- * - * @param id id - */ - public void setTrackId(final int id) { - this.trackId = id; - } - - /** - * Gets the value of value . - * - * @return the value of int - */ - public int getValue() { - return value; - } - - /** - * Sets the value . - *

You can use getValue() to get the value of value

- * - * @param value value - */ - public void setValue(final int value) { - this.value = value; - } - - /** - * Gets the value of startTime . - * - * @return the value of long - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the startTime . - *

You can use getStartTime() to get the value of startTime

- * - * @param time time - */ - public void setStartTime(final long time) { - this.startTime = time; - } - - /** - * Gets the value of duration . - * - * @return the value of long - */ - public long getDuration() { - return duration; - } - - /** - * Sets the duration . - *

You can use getDuration() to get the value of duration

- * - * @param dur dur - */ - public void setDuration(final long dur) { - this.duration = dur; - } - - /** - * Draw the corresponding shape according to the brush - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - Color color = ColorUtils.MD_PALETTE[trackId % ColorUtils.MD_PALETTE.length]; - int height = 0; - if (maxValue > 0) { - height = ((rect.height - 5) * value) / maxValue; - graphics.setColor(color); - graphics.fillRect(rect.x, rect.y + rect.height - height, rect.width, height); - } - } - - /** - * Focus acquisition event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - } - - /** - * Focus cancel event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; + +/** + * Process memory data + * + * @date 2021/04/22 12:25 + */ +public class ProcessMemData extends AbstractGraph { + private int maxValue; + private int id; + @DField(name = "type") + private String type; + @DField(name = "track_id") + private int trackId; + @DField(name = "value") + private int value; + @DField(name = "startTime") + private long startTime; + private long duration; + + /** + * Gets the value of maxValue . + * + * @return the value of int + */ + public int getMaxValue() { + return maxValue; + } + + /** + * Sets the maxValue . + *

You can use getMaxValue() to get the value of maxValue

+ * + * @param max max + */ + public void setMaxValue(final int max) { + this.maxValue = max; + } + + /** + * Gets the value of id . + * + * @return the value of int + */ + public int getId() { + return id; + } + + /** + * Sets the id . + *

You can use getId() to get the value of id

+ * + * @param id id + */ + public void setId(final int id) { + this.id = id; + } + + /** + * Gets the value of type . + * + * @return the value of java.lang.String + */ + public String getType() { + return type; + } + + /** + * Sets the type . + *

You can use getType() to get the value of type

+ * + * @param type type + */ + public void setType(final String type) { + this.type = type; + } + + /** + * Gets the value of trackId . + * + * @return the value of int + */ + public int getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId

+ * + * @param id id + */ + public void setTrackId(final int id) { + this.trackId = id; + } + + /** + * Gets the value of value . + * + * @return the value of int + */ + public int getValue() { + return value; + } + + /** + * Sets the value . + *

You can use getValue() to get the value of value

+ * + * @param value value + */ + public void setValue(final int value) { + this.value = value; + } + + /** + * Gets the value of startTime . + * + * @return the value of long + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime

+ * + * @param time time + */ + public void setStartTime(final long time) { + this.startTime = time; + } + + /** + * Gets the value of duration . + * + * @return the value of long + */ + public long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration

+ * + * @param dur dur + */ + public void setDuration(final long dur) { + this.duration = dur; + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + Color color = ColorUtils.MD_PALETTE[trackId % ColorUtils.MD_PALETTE.length]; + int height = 0; + if (maxValue > 0) { + height = ((rect.height - 5) * value) / maxValue; + graphics.setColor(color); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect) + rect.height - height, rect.width, height); + } + } + + /** + * Focus acquisition event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + } + + /** + * Focus cancel event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabCounterBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabCounterBean.java new file mode 100644 index 000000000..3f56ccc3a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabCounterBean.java @@ -0,0 +1,226 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +/** + * TabCounterBean + * + * @date: 2021/5/12 16:34 + */ +public class TabCounterBean { + private Integer trackId; + private String name; + private Long deltaValue; // Calculate the rule. box selection range last value - first value + private Double rate; // Calculate the rule .box selection range time delta value / range time(单位换算成 s ) + private Double weightAvgValue; + + // The calculation rule calculates the weighted average by value as a weight of time in the selected time area + private Integer count; // Calculate the rules Statistics the number of counters in the selected range + private Long firstValue; // Box within the selection room first value + private Long lastValue; // Box within the selection room last value + private Long minValue; // Box within the selection room min value + private Long maxValue; // Box within the selection room max value + + /** + * Gets the value of trackId . + * + * @return the value of trackId . + */ + public Integer getTrackId() { + return trackId; + } + + /** + * Sets the trackId . + *

You can use getTrackId() to get the value of trackId.

+ * + * @param param . + */ + public void setTrackId(final Integer param) { + this.trackId = param; + } + + /** + * Gets the value of name . + * + * @return the value of name . + */ + public String getName() { + return name; + } + + /** + * Sets the name . + *

You can use getName() to get the value of name.

+ * + * @param param . + */ + public void setName(final String param) { + this.name = param; + } + + /** + * Gets the value of deltaValue . + * + * @return the value of deltaValue . + */ + public Long getDeltaValue() { + return deltaValue; + } + + /** + * Sets the deltaValue . + *

You can use getDeltaValue() to get the value of deltaValue.

+ * + * @param param . + */ + public void setDeltaValue(final Long param) { + this.deltaValue = param; + } + + /** + * Gets the value of rate . + * + * @return the value of rate . + */ + public Double getRate() { + return rate; + } + + /** + * Sets the rate . + *

You can use getRate() to get the value of rate.

+ * + * @param param . + */ + public void setRate(final Double param) { + this.rate = param; + } + + /** + * Gets the value of weightAvgValue . + * + * @return the value of weightAvgValue . + */ + public Double getWeightAvgValue() { + return weightAvgValue; + } + + /** + * Sets the weightAvgValue . + *

You can use getWeightAvgValue() to get the value of weightAvgValue.

+ * + * @param param . + */ + public void setWeightAvgValue(final Double param) { + this.weightAvgValue = param; + } + + /** + * Gets the value of count . + * + * @return the value of count . + */ + public Integer getCount() { + return count; + } + + /** + * Sets the count . + *

You can use getCount() to get the value of count.

+ * + * @param param . + */ + public void setCount(final Integer param) { + this.count = param; + } + + /** + * Gets the value of firstValue . + * + * @return the value of firstValue . + */ + public Long getFirstValue() { + return firstValue; + } + + /** + * Sets the firstValue . + *

You can use getFirstValue() to get the value of firstValue.

+ * + * @param param . + */ + public void setFirstValue(final Long param) { + this.firstValue = param; + } + + /** + * Gets the value of lastValue . + * + * @return the value of lastValue . + */ + public Long getLastValue() { + return lastValue; + } + + /** + * Sets the lastValue . + *

You can use getLastValue() to get the value of lastValue.

+ * + * @param param . + */ + public void setLastValue(final Long param) { + this.lastValue = param; + } + + /** + * Gets the value of minValue . + * + * @return the value of minValue . + */ + public Long getMinValue() { + return minValue; + } + + /** + * Sets the minValue . + *

You can use getMinValue() to get the value of minValue.

+ * + * @param param . + */ + public void setMinValue(final Long param) { + this.minValue = param; + } + + /** + * Gets the value of maxValue . + * + * @return the value of maxValue . + */ + public Long getMaxValue() { + return maxValue; + } + + /** + * Sets the maxValue . + *

You can use getMaxValue() to get the value of maxValue.

+ * + * @param param . + */ + public void setMaxValue(final Long param) { + this.maxValue = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabSlicesBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabSlicesBean.java new file mode 100644 index 000000000..9b8095f9b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabSlicesBean.java @@ -0,0 +1,126 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * TabSlicesBean + * + * @version 1.0.1 + * @date 2021/04/20 12:12 + */ +public class TabSlicesBean { + /** + * function name + */ + @DField(name = "funName") + private String funName; + + /** + * total wall duration + */ + @DField(name = "wallDuration") + private Long wallDuration; + + /** + * avg wall duration + */ + @DField(name = "avgDuration") + private Double avgDuration; + + /** + * count + */ + @DField(name = "occurrences") + private Integer occurrences; + + /** + * Gets the value of funName . + * + * @return the value of funName . + */ + public String getFunName() { + return funName; + } + + /** + * Sets the threadName . + *

You can use getThreadName() to get the value of threadName.

+ * + * @param param . + */ + public void setFunName(final String param) { + this.funName = param; + } + + /** + * Gets the value of allDuration . + * + * @return the value of allDuration . + */ + public Long getWallDuration() { + return wallDuration; + } + + /** + * Sets the allDuration . + *

You can use getAllDuration() to get the value of allDuration.

+ * + * @param param . + */ + public void setWallDuration(final long param) { + this.wallDuration = param; + } + + /** + * Gets the value of avgDuration . + * + * @return the value of avgDuration . + */ + public Double getAvgDuration() { + return avgDuration; + } + + /** + * Sets the avgDuration . + *

You can use getAvgDuration() to get the value of avgDuration.

+ * + * @param param . + */ + public void setAvgDuration(final double param) { + this.avgDuration = param; + } + + /** + * Gets the value of occurrences . + * + * @return the value of occurrences . + */ + public Integer getOccurrences() { + return occurrences; + } + + /** + * Sets the occurrences . + *

You can use getOccurrences() to get the value of occurrences.

+ * + * @param param . + */ + public void setOccurrences(final int param) { + this.occurrences = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabThreadStatesBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabThreadStatesBean.java new file mode 100644 index 000000000..4e5e890df --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/TabThreadStatesBean.java @@ -0,0 +1,225 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * TabThreadStatesBean + * + * @date: 2021/5/13 13:06 + */ +public class TabThreadStatesBean { + /** + * process name + */ + @DField(name = "process") + private String process; + + /** + * process id + */ + @DField(name = "pid") + private Integer pid; + + /** + * thread name + */ + @DField(name = "thread") + private String thread; + + /** + * thread id + */ + @DField(name = "tid") + private Integer tid; + + /** + * thread state + */ + @DField(name = "state") + private String state; + + /** + * total wall duration + */ + @DField(name = "wallDuration") + private Long wallDuration; + + /** + * avg wall duration + */ + @DField(name = "avgDuration") + private Double avgDuration; + + /** + * count + */ + @DField(name = "occurrences") + private Integer occurrences; + + /** + * Gets the value of process . + * + * @return the value of process . + */ + public String getProcess() { + return process; + } + + /** + * Sets the process . + *

You can use getProcess() to get the value of process.

+ * + * @param param . + */ + public void setProcess(final String param) { + this.process = param; + } + + /** + * Gets the value of pid . + * + * @return the value of pid . + */ + public Integer getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid.

+ * + * @param param . + */ + public void setPid(final Integer param) { + this.pid = param; + } + + /** + * Gets the value of thread . + * + * @return the value of thread . + */ + public String getThread() { + return thread; + } + + /** + * Sets the thread . + *

You can use getThread() to get the value of thread.

+ * + * @param param . + */ + public void setThread(final String param) { + this.thread = param; + } + + /** + * Gets the value of tid . + * + * @return the value of tid . + */ + public Integer getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid.

+ * + * @param param . + */ + public void setTid(final Integer param) { + this.tid = param; + } + + /** + * Gets the value of state . + * + * @return the value of state . + */ + public String getState() { + return state; + } + + /** + * Sets the state . + *

You can use getState() to get the value of state.

+ * + * @param param . + */ + public void setState(final String param) { + this.state = param; + } + + /** + * Gets the value of allDuration . + * + * @return the value of allDuration . + */ + public Long getWallDuration() { + return wallDuration; + } + + /** + * Sets the allDuration . + *

You can use getAllDuration() to get the value of allDuration.

+ * + * @param param . + */ + public void setWallDuration(final long param) { + this.wallDuration = param; + } + + /** + * Gets the value of avgDuration . + * + * @return the value of avgDuration . + */ + public Double getAvgDuration() { + return avgDuration; + } + + /** + * Sets the avgDuration . + *

You can use getAvgDuration() to get the value of avgDuration.

+ * + * @param param . + */ + public void setAvgDuration(final double param) { + this.avgDuration = param; + } + + /** + * Gets the value of occurrences . + * + * @return the value of occurrences . + */ + public Integer getOccurrences() { + return occurrences; + } + + /** + * Sets the occurrences . + *

You can use getOccurrences() to get the value of occurrences.

+ * + * @param param . + */ + public void setOccurrences(final int param) { + this.occurrences = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ThreadData.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ThreadData.java index 2e91ee17b..a4e6df6d0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ThreadData.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/ThreadData.java @@ -1,456 +1,451 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.Utils; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; - -/** - * Thread data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ThreadData extends AbstractGraph { - private static Color runningColor = new Color(Final.RUNNING_COLOR); - - private static Color rColor = new Color(Final.R_COLOR); - - private static Color uninterruptibleSleepColor = new Color(Final.UNINTERRUPTIBLE_SLEEP_COLOR); - - private static Color sColor = new Color(Final.S_COLOR); - - private int uPid; - - private int uTid; - - private int pid; // Process id - - private int tid; // Thread id - - private String processName; - - private String threadName; - - private String state; - - private long startTime; - - private long duration; - - private boolean isSelected; // Whether to be selected - - private int cpu; - - /** - * Gets the value of uPid . - * - * @return the value of uPid . - */ - public int getuPid() { - return uPid; - } - - /** - * Sets the uPid . - *

You can use getuPid() to get the value of uPid.

- * - * @param param param. - */ - public void setuPid(final int param) { - this.uPid = param; - } - - /** - * Gets the value of uTid . - * - * @return the value of uTid . - */ - public int getuTid() { - return uTid; - } - - /** - * Sets the uTid . - *

You can use getuTid() to get the value of uTid.

- * - * @param param . - */ - public void setuTid(final int param) { - this.uTid = param; - } - - /** - * Gets the value of pid . - * - * @return the value of pid . - */ - public int getPid() { - return pid; - } - - /** - * Sets the pid . - *

You can use getPid() to get the value of pid.

- * - * @param param . - */ - public void setPid(final int param) { - this.pid = param; - } - - /** - * Gets the value of tid . - * - * @return the value of tid . - */ - public int getTid() { - return tid; - } - - /** - * Sets the tid . - *

You can use getTid() to get the value of tid.

- * - * @param param . - */ - public void setTid(final int param) { - this.tid = param; - } - - /** - * Gets the value of processName . - * - * @return the value of processName . - */ - public String getProcessName() { - return processName; - } - - /** - * Sets the processName . - *

You can use getProcessName() to get the value of processName.

- * - * @param param . - */ - public void setProcessName(final String param) { - this.processName = param; - } - - /** - * Gets the value of threadName . - * - * @return the value of threadName . - */ - public String getThreadName() { - return threadName; - } - - /** - * Sets the threadName . - *

You can use getThreadName() to get the value of threadName.

- * - * @param param param - */ - public void setThreadName(final String param) { - this.threadName = param; - } - - /** - * Gets the value of state . - * - * @return the value of state . - */ - public String getState() { - return state; - } - - /** - * Sets the state . - *

You can use getState() to get the value of state.

- * - * @param param param - */ - public void setState(final String param) { - this.state = param; - } - - /** - * Gets the value of startTime . - * - * @return the value of startTime . - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the startTime . - *

You can use getStartTime() to get the value of startTime.

- * - * @param param param - */ - public void setStartTime(final long param) { - this.startTime = param; - } - - /** - * Gets the value of duration . - * - * @return the value of duration . - */ - public long getDuration() { - return duration; - } - - /** - * Sets the duration . - *

You can use getDuration() to get the value of duration.

- * - * @param param param - */ - public void setDuration(final long param) { - this.duration = param; - } - - /** - * Gets the value of cpu . - * - * @return the value of cpu . - */ - public int getCpu() { - return cpu; - } - - /** - * Sets the cpu . - *

You can use getCpu() to get the value of cpu.

- * - * @param param param - */ - public void setCpu(final int param) { - this.cpu = param; - } - - /** - * Sets the isSelected . - *

You can use getSelected() to get the value of isSelected.

- * - * @param param param - */ - public void select(final boolean param) { - isSelected = param; - } - - private final int padding1 = 5; - - private final int padding2 = 10; - - private final float alpha2 = 0.02f; - - /** - * repaint. - **/ - public void repaint() { - if (root != null) { - root.repaint(rect.x, rect.y - padding1, rect.width, rect.height + padding2); - } - } - - /** - * Draw the corresponding shape according to the brush - * - * @param graphics graphics - **/ - @Override - public void draw(final Graphics2D graphics) { - if (isSelected && !"S".equals(state)) { - graphics.setColor(Color.BLACK); - graphics.fillRect(rect.x, rect.y - padding1, rect.width, rect.height + padding2); - drawSelected(graphics); - } else { - drawUnSelected(graphics); - } - } - - private void drawSelected(final Graphics2D graphics) { - if ("S".equals(state)) { - graphics.setColor(sColor); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha2)); // transparency - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency - } else if ("R".equals(state)) { - graphics.setColor(rColor); - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } else if ("D".equals(state)) { - graphics.setColor(uninterruptibleSleepColor); - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } else if ("Running".equals(state)) { - graphics.setColor(runningColor); - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setColor(Color.white); - Rectangle rectangle = new Rectangle(); - rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); - drawString(graphics, rectangle, Utils.getEndState(state), Placement.CENTER_LINE); - } else { - graphics.setColor(rColor); - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setColor(Color.white); - Rectangle rectangle = new Rectangle(); - rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); - drawString(graphics, rectangle, Utils.getEndState(state), Placement.CENTER_LINE); - } - } - - private void drawUnSelected(final Graphics2D graphics) { - if ("S".equals(state)) { - graphics.setColor(sColor); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha2)); // transparency - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency - } else if ("R".equals(state)) { - graphics.setColor(rColor); - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } else if ("D".equals(state)) { - graphics.setColor(uninterruptibleSleepColor); - graphics.fillRect(rect.x + padding1, rect.y, rect.width - padding2, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } else if ("Running".equals(state)) { - graphics.setColor(runningColor); - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } else { - graphics.setColor(rColor); - graphics.fillRect(rect.x, rect.y, rect.width, rect.height); - graphics.setColor(Color.white); - drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); - } - } - - /** - * Focus acquisition callback event - * - * @param event event - **/ - @Override - public void onFocus(final MouseEvent event) { - if (eventListener != null) { - eventListener.focus(event, this); - } - } - - /** - * Focus cancel callback event - * - * @param event event - **/ - @Override - public void onBlur(final MouseEvent event) { - if (eventListener != null) { - eventListener.blur(event, this); - } - } - - /** - * Click event callback - * - * @param event event - **/ - @Override - public void onClick(final MouseEvent event) { - if (eventListener != null) { - eventListener.click(event, this); - } - } - - /** - * Mouse movement event callback - * - * @param event event - **/ - @Override - public void onMouseMove(final MouseEvent event) { - if (edgeInspect(event)) { - if (eventListener != null) { - eventListener.mouseMove(event, this); - } - } - } - - private IEventListener eventListener; - - /** - * Set callback event listener - * - * @param listener listener - **/ - public void setEventListener(final IEventListener listener) { - this.eventListener = listener; - } - - /** - * listener - */ - public interface IEventListener { - /** - * Mouse click event - * - * @param event event - * @param data data - **/ - void click(MouseEvent event, ThreadData data); - - /** - * Mouse blur event - * - * @param event event - * @param data data - **/ - void blur(MouseEvent event, ThreadData data); - - /** - * Mouse focus event - * - * @param event event - * @param data data - **/ - void focus(MouseEvent event, ThreadData data); - - /** - * Mouse move event - * - * @param event event - * @param data data - **/ - void mouseMove(MouseEvent event, ThreadData data); - } -} - +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * Thread data + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class ThreadData extends AbstractGraph { + private static Color runningColor = new Color(Final.RUNNING_COLOR); + private static Color rColor = new Color(Final.R_COLOR); + private static Color uninterruptibleSleepColor = new Color(Final.UNINTERRUPTIBLE_SLEEP_COLOR); + private static Color sColor = new Color(Final.S_COLOR); + private final int padding1 = 5; + private final int padding2 = 10; + private final float alpha2 = 0.02f; + @DField(name = "upid") + private int uPid; + @DField(name = "utid") + private int uTid; + @DField(name = "pid") + private int pid; // Process id + @DField(name = "tid") + private int tid; // Thread id + @DField(name = "processName") + private String processName; + @DField(name = "threadName") + private String threadName; + @DField(name = "state") + private String state; + @DField(name = "startTime") + private long startTime; + @DField(name = "dur") + private long duration; + private boolean isSelected; // Whether to be selected + @DField(name = "cpu") + private int cpu; + private IEventListener eventListener; + + /** + * Gets the value of uPid . + * + * @return the value of uPid . + */ + public int getuPid() { + return uPid; + } + + /** + * Sets the uPid . + *

You can use getuPid() to get the value of uPid.

+ * + * @param param param. + */ + public void setuPid(final int param) { + this.uPid = param; + } + + /** + * Gets the value of uTid . + * + * @return the value of uTid . + */ + public int getuTid() { + return uTid; + } + + /** + * Sets the uTid . + *

You can use getuTid() to get the value of uTid.

+ * + * @param param . + */ + public void setuTid(final int param) { + this.uTid = param; + } + + /** + * Gets the value of pid . + * + * @return the value of pid . + */ + public int getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid.

+ * + * @param param . + */ + public void setPid(final int param) { + this.pid = param; + } + + /** + * Gets the value of tid . + * + * @return the value of tid . + */ + public int getTid() { + return tid; + } + + /** + * Sets the tid . + *

You can use getTid() to get the value of tid.

+ * + * @param param . + */ + public void setTid(final int param) { + this.tid = param; + } + + /** + * Gets the value of processName . + * + * @return the value of processName . + */ + public String getProcessName() { + return processName; + } + + /** + * Sets the processName . + *

You can use getProcessName() to get the value of processName.

+ * + * @param param . + */ + public void setProcessName(final String param) { + this.processName = param; + } + + /** + * Gets the value of threadName . + * + * @return the value of threadName . + */ + public String getThreadName() { + return threadName; + } + + /** + * Sets the threadName . + *

You can use getThreadName() to get the value of threadName.

+ * + * @param param param + */ + public void setThreadName(final String param) { + this.threadName = param; + } + + /** + * Gets the value of state . + * + * @return the value of state . + */ + public String getState() { + return state; + } + + /** + * Sets the state . + *

You can use getState() to get the value of state.

+ * + * @param param param + */ + public void setState(final String param) { + this.state = param; + } + + /** + * Gets the value of startTime . + * + * @return the value of startTime . + */ + public long getStartTime() { + return startTime; + } + + /** + * Sets the startTime . + *

You can use getStartTime() to get the value of startTime.

+ * + * @param param param + */ + public void setStartTime(final long param) { + this.startTime = param; + } + + /** + * Gets the value of duration . + * + * @return the value of duration . + */ + public long getDuration() { + return duration; + } + + /** + * Sets the duration . + *

You can use getDuration() to get the value of duration.

+ * + * @param param param + */ + public void setDuration(final long param) { + this.duration = param; + } + + /** + * Gets the value of cpu . + * + * @return the value of cpu . + */ + public int getCpu() { + return cpu; + } + + /** + * Sets the cpu . + *

You can use getCpu() to get the value of cpu.

+ * + * @param param param + */ + public void setCpu(final int param) { + this.cpu = param; + } + + /** + * Sets the isSelected . + *

You can use getSelected() to get the value of isSelected.

+ * + * @param param param + */ + public void select(final boolean param) { + isSelected = param; + } + + /** + * repaint. + */ + public void repaint() { + if (root != null) { + root.repaint(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + } + } + + /** + * Draw the corresponding shape according to the brush + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isSelected && !"S".equals(state)) { + graphics.setColor(Color.BLACK); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect) - padding1, rect.width, rect.height + padding2); + drawSelected(graphics); + } else { + drawUnSelected(graphics); + } + } + + private void drawSelected(final Graphics2D graphics) { + if ("S".equals(state)) { + graphics.setColor(sColor); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha2)); // transparency + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency + } else if ("R".equals(state)) { + graphics.setColor(rColor); + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } else if ("D".equals(state)) { + graphics.setColor(uninterruptibleSleepColor); + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } else if ("Running".equals(state)) { + graphics.setColor(runningColor); + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); + drawString(graphics, rectangle, Utils.getEndState(state), Placement.CENTER_LINE); + } else { + graphics.setColor(rColor); + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setColor(Color.white); + Rectangle rectangle = new Rectangle(); + rectangle.setRect(rect.getX() + padding1, rect.getY(), rect.getWidth() - padding2, rect.getHeight()); + drawString(graphics, rectangle, Utils.getEndState(state), Placement.CENTER_LINE); + } + } + + private void drawUnSelected(final Graphics2D graphics) { + if ("S".equals(state)) { + graphics.setColor(sColor); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha2)); // transparency + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency + } else if ("R".equals(state)) { + graphics.setColor(rColor); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } else if ("D".equals(state)) { + graphics.setColor(uninterruptibleSleepColor); + graphics.fillRect(Utils.getX(rect) + padding1, Utils.getY(rect), rect.width - padding2, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } else if ("Running".equals(state)) { + graphics.setColor(runningColor); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } else { + graphics.setColor(rColor); + graphics.fillRect(Utils.getX(rect), Utils.getY(rect), rect.width, rect.height); + graphics.setColor(Color.white); + drawString(graphics, rect, Utils.getEndState(state), Placement.CENTER_LINE); + } + } + + /** + * Focus acquisition callback event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + if (eventListener != null) { + eventListener.focus(event, this); + } + } + + /** + * Focus cancel callback event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + if (eventListener != null) { + eventListener.blur(event, this); + } + } + + /** + * Click event callback + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (eventListener != null) { + AnalystPanel.clicked = true; + eventListener.click(event, this); + } + } + + /** + * Mouse movement event callback + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + if (edgeInspect(event)) { + if (eventListener != null) { + eventListener.mouseMove(event, this); + } + } + } + + /** + * Set callback event listener + * + * @param listener listener + */ + public void setEventListener(final IEventListener listener) { + this.eventListener = listener; + } + + /** + * listener + */ + public interface IEventListener { + /** + * Mouse click event + * + * @param event event + * @param data data + */ + void click(MouseEvent event, ThreadData data); + + /** + * Mouse blur event + * + * @param event event + * @param data data + */ + void blur(MouseEvent event, ThreadData data); + + /** + * Mouse focus event + * + * @param event event + * @param data data + */ + void focus(MouseEvent event, ThreadData data); + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + void mouseMove(MouseEvent event, ThreadData data); + } +} + diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupBean.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupBean.java index 49d6ce67b..1b50867f6 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupBean.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupBean.java @@ -1,184 +1,187 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -/** - * Wake up data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class WakeupBean { - private long wakeupTime; - - private int wakeupCpu; - - private String wakeupProcess; - - private String wakeupPid; - - private String wakeupThread; - - private String wakeupTid; - - private long schedulingLatency; - - private String schedulingDesc; - - /** - * get wakeup time. - * - * @return wakeup time - */ - public long getWakeupTime() { - return wakeupTime; - } - - /** - * set wakeup time. - * - * @param wt wt - */ - public void setWakeupTime(final long wt) { - this.wakeupTime = wt; - } - - /** - * get wakeup cpu. - * - * @return wakeup cpu - */ - public int getWakeupCpu() { - return wakeupCpu; - } - - /** - * set wakeup cpu. - * - * @param cpu cpu - */ - public void setWakeupCpu(final int cpu) { - this.wakeupCpu = cpu; - } - - /** - * get wakeup process. - * - * @return wakeup process - */ - public String getWakeupProcess() { - return wakeupProcess; - } - - /** - * set wakeup process. - * - * @param process process - */ - public void setWakeupProcess(final String process) { - this.wakeupProcess = process; - } - - /** - * get wakeup pId. - * - * @return wakeup pId - */ - public String getWakeupPid() { - return wakeupPid; - } - - /** - * set wakeup pId. - * - * @param pid pid - */ - public void setWakeupPid(final String pid) { - this.wakeupPid = pid; - } - - /** - * get wakeup thread. - * - * @return wakeup thread - */ - public String getWakeupThread() { - return wakeupThread; - } - - /** - * set wakeup thread. - * - * @param thread thread - */ - public void setWakeupThread(final String thread) { - this.wakeupThread = thread; - } - - /** - * get wakeup tId. - * - * @return wakeup thread id - */ - public String getWakeupTid() { - return wakeupTid; - } - - /** - * set wakeup tId. - * - * @param tid tid - */ - public void setWakeupTid(final String tid) { - this.wakeupTid = tid; - } - - /** - * get scheduling Latency. - * - * @return scheduling Latency - */ - public long getSchedulingLatency() { - return schedulingLatency; - } - - /** - * set scheduling Latency. - * - * @param latency latency - */ - public void setSchedulingLatency(final long latency) { - this.schedulingLatency = latency; - } - - /** - * get scheduling Desc. - * - * @return scheduling Desc - */ - public String getSchedulingDesc() { - return schedulingDesc; - } - - /** - * set scheduling Desc. - * - * @param desc desc - */ - public void setSchedulingDesc(final String desc) { - this.schedulingDesc = desc; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Wake up data + * + * @date 2021/04/22 12:25 + */ +public class WakeupBean { + private long wakeupTime; + @DField(name = "cpu") + private int wakeupCpu; + @DField(name = "process") + private String wakeupProcess; + @DField(name = "pid") + private Integer wakeupPid; + @DField(name = "thread") + private String wakeupThread; + @DField(name = "tid") + private Integer wakeupTid; + private long schedulingLatency; + private String schedulingDesc; + + /** + * get wakeup time. + * + * @return wakeup time + */ + public long getWakeupTime() { + return wakeupTime; + } + + /** + * set wakeup time. + * + * @param wt wt + */ + public void setWakeupTime(final long wt) { + this.wakeupTime = wt; + } + + /** + * get wakeup cpu. + * + * @return wakeup cpu + */ + public int getWakeupCpu() { + return wakeupCpu; + } + + /** + * set wakeup cpu. + * + * @param cpu cpu + */ + public void setWakeupCpu(final int cpu) { + this.wakeupCpu = cpu; + } + + /** + * get wakeup process. + * + * @return wakeup process + */ + public String getWakeupProcess() { + if (wakeupProcess == null || wakeupProcess.isBlank()) { + return wakeupThread; + } else { + return wakeupProcess; + } + } + + /** + * set wakeup process. + * + * @param process process + */ + public void setWakeupProcess(final String process) { + this.wakeupProcess = process; + } + + /** + * get wakeup pId. + * + * @return wakeup pId + */ + public Integer getWakeupPid() { + return wakeupPid; + } + + /** + * set wakeup pId. + * + * @param pid pid + */ + public void setWakeupPid(final Integer pid) { + this.wakeupPid = pid; + } + + /** + * get wakeup thread. + * + * @return wakeup thread + */ + public String getWakeupThread() { + return wakeupThread; + } + + /** + * set wakeup thread. + * + * @param thread thread + */ + public void setWakeupThread(final String thread) { + this.wakeupThread = thread; + } + + /** + * get wakeup tId. + * + * @return wakeup thread id + */ + public Integer getWakeupTid() { + return wakeupTid; + } + + /** + * set wakeup tId. + * + * @param tid tid + */ + public void setWakeupTid(final Integer tid) { + this.wakeupTid = tid; + } + + /** + * get scheduling Latency. + * + * @return scheduling Latency + */ + public long getSchedulingLatency() { + return schedulingLatency; + } + + /** + * set scheduling Latency. + * + * @param latency latency + */ + public void setSchedulingLatency(final long latency) { + this.schedulingLatency = latency; + } + + /** + * get scheduling Desc. + * + * @return scheduling Desc + */ + public String getSchedulingDesc() { + return schedulingDesc; + } + + /** + * set scheduling Desc. + * + * @param desc desc + */ + public void setSchedulingDesc(final String desc) { + this.schedulingDesc = desc; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupTime.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupTime.java new file mode 100644 index 000000000..15077ccb4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/bean/WakeupTime.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Wakeup Time data + * + * @date: 2021/5/14 15:52 + */ +public class WakeupTime { + @DField(name = "wakeTs") + private Long wakeTs; + @DField(name = "start_ts") + private Long startTs; + @DField(name = "preRow") + private Long preRow; + + /** + * Gets the value of wakeTs . + * + * @return the value of wakeTs . + */ + public Long getWakeTs() { + return wakeTs; + } + + /** + * Sets the wakeTs . + *

You can use getWakeTs() to get the value of wakeTs.

+ * + * @param param . + */ + public void setWakeTs(final Long param) { + this.wakeTs = param; + } + + /** + * Gets the value of startTs . + * + * @return the value of startTs . + */ + public Long getStartTs() { + return startTs; + } + + /** + * Sets the startTs . + *

You can use getStartTs() to get the value of startTs.

+ * + * @param param . + */ + public void setStartTs(final Long param) { + this.startTs = param; + } + + /** + * Gets the value of preRow . + * + * @return the value of preRow . + */ + public Long getPreRow() { + return preRow; + } + + /** + * Sets the preRow . + *

You can use getPreRow() to get the value of preRow.

+ * + * @param param . + */ + public void setPreRow(final Long param) { + this.preRow = param; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/AnalystPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/AnalystPanel.java index 625d102c4..d3816f606 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/AnalystPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/AnalystPanel.java @@ -1,718 +1,1248 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBLayeredPane; -import com.intellij.ui.components.JBScrollPane; -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.bean.FlagBean; -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.Process; -import ohos.devtools.views.trace.bean.ProcessMem; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.bean.WakeupBean; -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.fragment.CpuDataFragment; -import ohos.devtools.views.trace.fragment.CpuFreqDataFragment; -import ohos.devtools.views.trace.fragment.MemDataFragment; -import ohos.devtools.views.trace.fragment.ProcessDataFragment; -import ohos.devtools.views.trace.fragment.ThreadDataFragment; -import ohos.devtools.views.trace.listener.IFlagListener; -import ohos.devtools.views.trace.util.Db; -import ohos.devtools.views.trace.util.TimeUtils; -import ohos.devtools.views.trace.util.Utils; - -import javax.swing.JLayeredPane; -import javax.swing.SwingUtilities; -import java.awt.Rectangle; -import java.awt.event.AdjustmentEvent; -import java.awt.event.AdjustmentListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ForkJoinPool; -import java.util.stream.Collectors; - -import static java.awt.event.KeyEvent.VK_A; -import static java.awt.event.KeyEvent.VK_CONTROL; -import static java.awt.event.KeyEvent.VK_D; -import static java.awt.event.KeyEvent.VK_S; -import static java.awt.event.KeyEvent.VK_SHIFT; -import static java.awt.event.KeyEvent.VK_W; - -/** - * Analysis component - * - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ -public final class AnalystPanel extends JBLayeredPane - implements MouseWheelListener, KeyListener, MouseListener, MouseMotionListener { - /** - * cpu click listener - */ - public static ICpuDataClick iCpuDataClick; - - /** - * thread click listener - */ - public static IThreadDataClick iThreadDataClick; - - /** - * function click listener - */ - public static IFunctionDataClick iFunctionDataClick; - - /** - * flag click listener - */ - public static IFlagClick iFlagClick; - - /** - * cpu data list - */ - public static List> cpuList; - - /** - * cpu freg data list - */ - public static List> cpuFreqList; - - /** - * thread data list - */ - public static List threadsList; - - /** - * duration - */ - public static long DURATION = 10_000_000_000L; - - /** - * cpu count - */ - public static int cpuNum; - - /** - * bottom tab - */ - public TabPanel tab; - - private final javax.swing.JScrollPane scrollPane = new JBScrollPane(); - private ContentPanel contentPanel; - private TimeViewPort viewport; - private final int defaultFragmentHeight = 40; - private double wheelSize; - private double rangeNs; - private double lefPercent; - private double rightPercent; - private long startNS; - private final double defaultScale = 0.1; - private boolean isUserInteraction; - - /** - * Constructor - */ - public AnalystPanel() { - viewport = new TimeViewPort(height -> viewport.setBorder(null), (sn, en) -> { - // When the time axis range changes, - // the contentPanel is notified that all data is refreshed according to the time axis - contentPanel.rangeChange(sn, en); - }); - setBorder(null); - contentPanel = new ContentPanel(this); - contentPanel.setBorder(null); - viewport.setView(contentPanel); - scrollPane.setViewport(viewport); - scrollPane.setBorder(null); - viewport.addChangeListener(event -> { - if (TabPanel.getMyHeight() != 0) { - moveToFront(tab); - } - }); - tab = new TabPanel(); - this.add(scrollPane); - this.add(tab); - tab.setFocusable(true); - // tab Set invisible first - this.setLayer(scrollPane, DEFAULT_LAYER); - this.setPosition(scrollPane, 0); - this.setLayer(tab, FRAME_CONTENT_LAYER); - this.setPosition(tab, 1); - this.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(final ComponentEvent event) { - super.componentResized(event); - Rectangle rootBounds = AnalystPanel.this.getBounds(); - scrollPane.setBounds(rootBounds); - tab.setBounds(rootBounds.x, rootBounds.height - tab.getMHeight(), rootBounds.width, tab.getMHeight()); - viewport.setRootHeight(getHeight()); - contentPanel.repaint(); - } - }); - contentPanel.setFocusable(true); - contentPanel.addMouseMotionListener(this); - contentPanel.addMouseListener(this); - contentPanel.addKeyListener(this); - iCpuDataClick = cpu -> clickCpuData(cpu); - iThreadDataClick = thread -> clickThreadData(thread); - iFunctionDataClick = fun -> clickFunctionData(fun); - iFlagClick = flag -> clickTimeFlag(flag); - scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { - @Override - public void adjustmentValueChanged(final AdjustmentEvent e) { - tab.hide(); - } - }); - } - - /** - * add cpu data list - * - * @param list source - */ - public void addCpuList(final List> list) { - cpuList = list; - cpuNum = list.size(); - for (int index = 0; index < list.size(); index++) { - List dataList = list.get(index); - contentPanel.addDataFragment(new CpuDataFragment(contentPanel, index, dataList)); - } - } - - /** - * add cpu freg data list - * - * @param list source - * @param cpuMaxFreq cpu size - */ - public void addCpuFreqList(final List> list, final Map cpuMaxFreq) { - cpuFreqList = list; - for (int index = 0; index < list.size(); index++) { - List dataList = list.get(index); - - // Fill in the duration field in FreqData and calculate based on the start time of the next node - for (int idx = 0, len = dataList.size(); idx < len; idx++) { - CpuFreqData cpuGraph = dataList.get(idx); - if (idx == len - 1) { - cpuGraph.setDuration(AnalystPanel.DURATION - cpuGraph.getStartTime()); - } else { - cpuGraph.setDuration(dataList.get(idx + 1).getStartTime() - cpuGraph.getStartTime()); - } - } - contentPanel.addDataFragment( - new CpuFreqDataFragment(contentPanel, "Cpu " + index + " Frequency", cpuMaxFreq, dataList)); - } - } - - /** - * add thread data list - * - * @param list thread list - * @param processMem process list - */ - public void addThreadsList(final List list, final List processMem) { - threadsList = list; - List processes = Db.getInstance().queryProcess(); - for (Process process : processes) { - if (process.getPid() == 0) { - continue; - } - ProcessDataFragment processDataFragment = new ProcessDataFragment(contentPanel, process); - contentPanel.addDataFragment(processDataFragment); - processMem.stream().filter(mem -> mem.getPid() == process.getPid()).forEach(mem -> { - MemDataFragment fgr = new MemDataFragment(contentPanel, mem); - fgr.defaultHeight = defaultFragmentHeight; - fgr.parentUuid = processDataFragment.uuid; - fgr.visible = false; - contentPanel.addDataFragment(fgr); - }); - List collect = list.stream().filter( - threadData -> threadData.getPid() == process.getPid() && threadData.getTid() != 0 - && threadData.getThreadName() != null).collect(Collectors.toList()); - for (ThreadData data : collect) { - ThreadDataFragment fgr = new ThreadDataFragment(contentPanel, data); - fgr.defaultHeight = defaultFragmentHeight; - fgr.parentUuid = processDataFragment.uuid; - fgr.visible = false; - contentPanel.addDataFragment(fgr); - } - } - list.stream().filter(data -> data.getProcessName() == null || data.getProcessName().isEmpty()) - .forEach(threadData -> { - Process process = new Process(); - process.setPid(threadData.getTid()); - process.setName(threadData.getThreadName()); - ProcessDataFragment processDataFragment = new ProcessDataFragment(contentPanel, process); - contentPanel.addDataFragment(processDataFragment); - if (!process.getName().startsWith("swapper") && process.getPid() != 0) { - ThreadDataFragment fgr = new ThreadDataFragment(contentPanel, threadData); - fgr.defaultHeight = defaultFragmentHeight; - fgr.parentUuid = processDataFragment.uuid; - fgr.visible = false; - contentPanel.addDataFragment(fgr); - } - }); - } - - /** - * load database - * - * @param name db name - * @param isLocal is local db - */ - public void load(final String name, final boolean isLocal) { - Db.setDbName(name); - Db.load(isLocal); - ForkJoinPool.commonPool().submit(() -> { - DURATION = Db.getInstance().queryTotalTime(); - - // Add cpu time slice information - int cpuMax = Db.getInstance().queryCpuMax(); - List> list = new ArrayList<>(); - for (int index = 0; index <= cpuMax; index++) { - List cpuData = Db.getInstance().queryCpuData(index); - list.add(cpuData); - } - - // Add cpu frequency information - List> freqList = - Db.getInstance().queryCpuFreq().stream().map(Db.getInstance()::queryCpuFreqData) - .collect(Collectors.toList()); - - // Add the memory information of the process - List processMem = Db.getInstance().getProcessMem(); - - // Add thread information - List processThreads = Db.getInstance().queryProcessThreads(); - Map cpuMaxFreq = Db.getInstance().queryCpuMaxFreq(); - javax.swing.SwingUtilities.invokeLater(() -> { - viewport.rulerFragment.setRange(0, AnalystPanel.DURATION, 0); - tab.hide(); - addCpuList(list); - addCpuFreqList(freqList, cpuMaxFreq); - addThreadsList(processThreads, processMem); // The memory information of the process and - - // The thread information of the process is displayed together - contentPanel.refresh(); - }); - }); - } - - /** - * cpu data click callback - */ - public interface ICpuDataClick { - /** - * cpu data click callback - * - * @param cpu cpu - */ - void click(CpuData cpu); - } - - /** - * thread data click callback - */ - public interface IThreadDataClick { - /** - * thread data click callback - * - * @param data thread - */ - void click(ThreadData data); - } - - /** - * function data click callback - */ - public interface IFunctionDataClick { - /** - * function data click callback - * - * @param data function - */ - void click(FunctionBean data); - } - - /** - * flag click callback - */ - public interface IFlagClick { - /** - * flag click callback - * - * @param data flag - */ - void click(FlagBean data); - } - - /** - * The bottom tab is displayed when the method event is clicked. - * - * @param bean function - */ - public void clickFunctionData(final FunctionBean bean) { - setLayer(tab, JLayeredPane.DRAG_LAYER); - ArrayList dataSource = new ArrayList<>(); - dataSource.add(ScrollSlicePanel.createSliceData("Name", bean.getFunName(), false)); - dataSource.add(ScrollSlicePanel.createSliceData("Category", bean.getCategory(), false)); - dataSource.add( - ScrollSlicePanel.createSliceData("StartTime", TimeUtils.getTimeString(bean.getStartTime()) + "", false)); - dataSource - .add(ScrollSlicePanel.createSliceData("Duration", TimeUtils.getTimeString(bean.getDuration()) + "", false)); - SwingUtilities.invokeLater(() -> { - tab.recovery(); - tab.removeAll(); - ScrollSlicePanel ssp = new ScrollSlicePanel(); - ssp.setData("Slice Details", dataSource, null); - tab.add("Current Selection", ssp); - }); - } - - /** - * When you click the CPU event, the bottom tab is displayed. - * - * @param threadData thread - */ - public void clickThreadData(final ThreadData threadData) { - setLayer(tab, javax.swing.JLayeredPane.DRAG_LAYER); - ArrayList dataSource = new ArrayList<>(); - dataSource.add(ScrollSlicePanel - .createSliceData("StartTime", TimeUtils.getTimeString(threadData.getStartTime()) + "", false)); - dataSource.add(ScrollSlicePanel - .createSliceData("Duration", TimeUtils.getTimeString(threadData.getDuration()) + "", false)); - String state = Utils.getEndState(threadData.getState()); - if ("Running".equals(Utils.getEndState(threadData.getState()))) { - state = state + " on CPU " + threadData.getCpu(); - } - dataSource.add(ScrollSlicePanel.createSliceData("State", state, false)); - String processName = threadData.getProcessName(); - if (processName == null || processName.isEmpty()) { - processName = threadData.getThreadName(); - } - dataSource - .add(ScrollSlicePanel.createSliceData("Process", processName + " [" + threadData.getPid() + "]", false)); - javax.swing.SwingUtilities.invokeLater(() -> { - tab.recovery(); - tab.removeAll(); - ScrollSlicePanel ssp = new ScrollSlicePanel(); - ssp.setData("Thread State", dataSource, null); - tab.add("Current Selection", ssp); - }); - } - - /** - * The bottom tab is displayed when you click the CPU event. - * - * @param cpu cpu - */ - public void clickCpuData(final CpuData cpu) { - setLayer(tab, javax.swing.JLayeredPane.DRAG_LAYER); - ArrayList dataSource = new ArrayList<>(); - String process = cpu.getProcessName(); - int processId = cpu.getProcessId(); - if (cpu.getProcessName() == null || cpu.getProcessName().isEmpty()) { - process = cpu.getName(); - processId = cpu.getTid(); - } - dataSource.add(ScrollSlicePanel.createSliceData("Process", process + " [" + processId + "]", false)); - dataSource.add(ScrollSlicePanel.createSliceData("Thread", cpu.getName() + " [" + cpu.getTid() + "]", true)); - dataSource.add(ScrollSlicePanel.createSliceData("CmdLine", cpu.getProcessCmdLine() + "", false)); - dataSource.add( - ScrollSlicePanel.createSliceData("StartTime", TimeUtils.getTimeString(cpu.getStartTime()) + "", false)); - dataSource - .add(ScrollSlicePanel.createSliceData("Duration", TimeUtils.getTimeString(cpu.getDuration()) + "", false)); - dataSource.add(ScrollSlicePanel.createSliceData("Prio", cpu.getPriority() + "", false)); - dataSource.add(ScrollSlicePanel.createSliceData("End State", Utils.getEndState(cpu.getEndState()), false)); - - // wakeup description - ForkJoinPool.commonPool().submit(() -> { - Optional wb = Db.getInstance().queryWakeupThread(cpu); - SwingUtilities.invokeLater(() -> { - contentPanel.setWakeupBean(wb.orElse(null)); - tab.recovery(); - tab.removeAll(); - ScrollSlicePanel ssp = new ScrollSlicePanel(); - ssp.setData("Slice Details", dataSource, wb.orElse(null)); - tab.add("Current Selection", ssp); - repaint(); - }); - }); - } - - /** - * Evoking the red flag corresponds to the tabPanel at the bottom. - * - * @param flagBean flag - */ - public void clickTimeFlag(final FlagBean flagBean) { - setLayer(tab, javax.swing.JLayeredPane.DRAG_LAYER); - tab.recovery(); - tab.removeAll(); - ScrollFlagPanel flagPanel = new ScrollFlagPanel(flagBean); - flagPanel.setFlagListener(new IFlagListener() { - @Override - public void flagRemove(final FlagBean flag) { - flag.remove(); - viewport.rulerFragment.repaint(); - tab.recovery(); - tab.removeAll(); - tab.hide(); - } - - @Override - public void flagChange(final FlagBean flag) { - if (flag.getName() != null && !flag.getName().isEmpty()) { - flagBean.setName(flag.getName()); - } - flagBean.setColor(flag.getColor()); - viewport.rulerFragment.repaint(); - } - }); - tab.add("Current Selection", flagPanel); - } - - @Override - public void keyTyped(final KeyEvent event) { - } - - @Override - public void keyPressed(final KeyEvent event) { - switch (event.getExtendedKeyCode()) { - case VK_A: - wheelSize = viewport.rulerFragment.getScale() * -0.2; - translation(); - break; - case VK_D: - wheelSize = viewport.rulerFragment.getScale() * 0.2; - translation(); - break; - case VK_W: - wheelSize = viewport.rulerFragment.getScale() * -0.2; - lefPercent = 0.5; - scale(); - break; - case VK_S: - wheelSize = viewport.rulerFragment.getScale() * 0.2; - lefPercent = 0.5; - scale(); - break; - case VK_SHIFT: - case VK_CONTROL: - if (!isUserInteraction) { - isUserInteraction = true; - contentPanel.addMouseWheelListener(this); - } - break; - default: - break; - } - } - - @Override - public void keyReleased(final KeyEvent event) { - switch (event.getExtendedKeyCode()) { - case VK_SHIFT: - case VK_CONTROL: - if (isUserInteraction) { - isUserInteraction = false; - contentPanel.removeMouseWheelListener(this); - } - break; - default: - break; - } - } - - @Override - public void mouseClicked(final MouseEvent event) { - contentPanel.fragmentList.forEach(fragment -> fragment.mouseClicked(event)); - } - - @Override - public void mousePressed(final MouseEvent event) { - viewport.mousePressed(event); - contentPanel.fragmentList.forEach(fragment -> fragment.mouseReleased(event)); - } - - @Override - public void mouseReleased(final MouseEvent event) { - contentPanel.fragmentList.forEach(fragment -> fragment.mouseReleased(event)); - } - - @Override - public void mouseEntered(final MouseEvent event) { - contentPanel.fragmentList.forEach(fragment -> fragment.mouseEntered(event)); - } - - @Override - public void mouseExited(final MouseEvent event) { - contentPanel.fragmentList.forEach(fragment -> fragment.mouseExited(event)); - } - - @Override - public void mouseDragged(final MouseEvent event) { - viewport.mouseDragged(event); - } - - @Override - public void mouseMoved(final MouseEvent event) { - viewport.mouseMoved(event); - if (event.getY() < tab.getBounds().y) { - contentPanel.requestFocusInWindow(); - } - contentPanel.fragmentList.forEach(fragment -> fragment.mouseMoved(event)); - } - - @Override - public void mouseWheelMoved(final MouseWheelEvent event) { - tab.hide(); - if (event.isShiftDown() && !event.isControlDown()) { // Pan - long scale = viewport.rulerFragment.getScale(); - if (Math.abs(event.getPreciseWheelRotation()) >= 1) { - wheelSize = scale * event.getPreciseWheelRotation() * defaultScale; - } else { - wheelSize = scale * event.getPreciseWheelRotation(); - } - translation(); - } - if (event.isControlDown() && !event.isShiftDown()) { // Zoom - if (Math.abs(event.getPreciseWheelRotation()) >= 1) { - wheelSize = viewport.rulerFragment.getScale() * event.getPreciseWheelRotation() * defaultScale; - } else { - wheelSize = viewport.rulerFragment.getScale() * event.getPreciseWheelRotation(); - } - int rulerFragmentWidth = viewport.rulerFragment.getRect().width; - lefPercent = (event.getX() - viewport.rulerFragment.getRect().x) * 1.0 / rulerFragmentWidth; - if (scaleMin(event)) { - scale(); - } - } - } - - private boolean scaleMin(MouseWheelEvent event) { - if (event.getPreciseWheelRotation() < 0) { // Zoom out - long rightNS = viewport.rulerFragment.getRightNS(); - long leftNS = viewport.rulerFragment.getLeftNS(); - long centerNS = viewport.rulerFragment.getCenterNS(); - final int minRul = 1000; - if (rightNS - leftNS <= minRul) { - rightNS = leftNS + minRul; - centerNS = leftNS; - viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); - viewport.cpuFragment.setRange(leftNS, rightNS); - for (AbstractDataFragment fragment : viewport.favoriteFragments) { - fragment.range(leftNS, rightNS); - } - repaint(); - return false; - } - } - return true; - } - - private void scale() { - if (lefPercent < 0) { - lefPercent = 0; - } - if (lefPercent > 1) { - lefPercent = 1; - } - rightPercent = 1 - lefPercent; - if (lefPercent > 0) { - double leftNs = viewport.rulerFragment.getLeftNS() - this.wheelSize * lefPercent; - viewport.rulerFragment.setLeftNS((long) leftNs); - } - if (rightPercent > 0) { - double rightNs = viewport.rulerFragment.getRightNS() + this.wheelSize * rightPercent; - viewport.rulerFragment.setRightNS((long) rightNs); - } - if (viewport.rulerFragment.getLeftNS() <= 0) { - viewport.rulerFragment.setLeftNS(0); - } - if (viewport.rulerFragment.getRightNS() >= DURATION) { - viewport.rulerFragment.setRightNS(DURATION); - } - viewport.rulerFragment.setCenterNS(viewport.rulerFragment.getLeftNS()); - viewport.rulerFragment.setRange(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS(), - viewport.rulerFragment.getCenterNS()); - viewport.cpuFragment.setRange(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); - if (lefPercent > 0) { - startNS = viewport.leftFragment.getStartNS(); - startNS -= wheelSize * lefPercent; - if (startNS > 0) { - viewport.leftFragment.setStartTime(startNS); - } else { - viewport.leftFragment.setStartTime(0); - } - } - for (AbstractDataFragment fragment : viewport.favoriteFragments) { - fragment.range(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); - } - repaint(); - } - - private void translation() { - long leftNS = viewport.rulerFragment.getLeftNS(); - long rightNS = viewport.rulerFragment.getRightNS(); - long centerNS; - - if (leftNS + wheelSize <= 0) { - rangeNs = rightNS - leftNS; - leftNS = 0; - rightNS = (long) rangeNs; - centerNS = leftNS; - viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); - viewport.cpuFragment.setRange(leftNS, rightNS); - viewport.leftFragment.setStartTime(0); - } else if (rightNS + wheelSize >= DURATION) { - rangeNs = rightNS - leftNS; - rightNS = DURATION; - leftNS = (long) (DURATION - rangeNs); - centerNS = leftNS; - viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); - viewport.cpuFragment.setRange(leftNS, rightNS); - viewport.leftFragment.setStartTime(leftNS); - } else { - leftNS += wheelSize; - rightNS += wheelSize; - centerNS = leftNS; - viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); - viewport.cpuFragment.setRange(leftNS, rightNS); - startNS = viewport.leftFragment.getStartNS(); - startNS += wheelSize; - viewport.leftFragment.setStartTime(startNS); - } - // Slide the icons that need to be viewed in the timeShaft collection - for (AbstractDataFragment fragment : viewport.favoriteFragments) { - fragment.range(leftNS, rightNS); - } - repaint(); - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.AncestorListenerAdapter; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.AsyncEvent; +import ohos.devtools.views.trace.bean.Clock; +import ohos.devtools.views.trace.bean.ClockData; +import ohos.devtools.views.trace.bean.Cpu; +import ohos.devtools.views.trace.bean.CpuData; +import ohos.devtools.views.trace.bean.CpuFreqData; +import ohos.devtools.views.trace.bean.CpuFreqMax; +import ohos.devtools.views.trace.bean.CpuMax; +import ohos.devtools.views.trace.bean.Duration; +import ohos.devtools.views.trace.bean.FlagBean; +import ohos.devtools.views.trace.bean.FunctionBean; +import ohos.devtools.views.trace.bean.Process; +import ohos.devtools.views.trace.bean.ProcessMem; +import ohos.devtools.views.trace.bean.ThreadData; +import ohos.devtools.views.trace.bean.WakeupBean; +import ohos.devtools.views.trace.bean.WakeupTime; +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.fragment.AsyncEventDataFragment; +import ohos.devtools.views.trace.fragment.ClockDataFragment; +import ohos.devtools.views.trace.fragment.CpuDataFragment; +import ohos.devtools.views.trace.fragment.CpuFreqDataFragment; +import ohos.devtools.views.trace.fragment.FunctionDataFragment; +import ohos.devtools.views.trace.fragment.MemDataFragment; +import ohos.devtools.views.trace.fragment.ProcessDataFragment; +import ohos.devtools.views.trace.fragment.ThreadDataFragment; +import ohos.devtools.views.trace.listener.IFlagListener; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JLayeredPane; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.event.AncestorEvent; +import java.awt.Cursor; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static java.awt.event.KeyEvent.VK_A; +import static java.awt.event.KeyEvent.VK_CONTROL; +import static java.awt.event.KeyEvent.VK_D; +import static java.awt.event.KeyEvent.VK_F; +import static java.awt.event.KeyEvent.VK_S; +import static java.awt.event.KeyEvent.VK_SHIFT; +import static java.awt.event.KeyEvent.VK_W; + +/** + * Analysis component + * + * @date 2021/04/20 12:24 + */ +public final class AnalystPanel extends JBPanel + implements MouseWheelListener, KeyListener, MouseListener, MouseMotionListener { + /** + * rect clicked + */ + public static boolean clicked = false; + + /** + * cpu click listener + */ + public static ICpuDataClick iCpuDataClick; + + /** + * thread click listener + */ + public static IThreadDataClick iThreadDataClick; + + /** + * function click listener + */ + public static IFunctionDataClick iFunctionDataClick; + + /** + * clock data click listener + */ + public static IClockDataClick iClockDataClick; + + /** + * flag click listener + */ + public static IFlagClick iFlagClick; + + /** + * cpu data list + */ + public static List> cpuList; + + /** + * cpu freg data list + */ + public static List> cpuFreqList; + + /** + * thread data list + */ + public static List threadsList; + + /** + * duration + */ + public static long DURATION = 10_000_000_000L; + + /** + * cpu count + */ + public static int cpuNum; + + /** + * layered pane + */ + public static JLayeredPane layeredPane; + + /** + * bottom tab + */ + public TabPanel tab; + private final JBScrollPane scrollPane = new JBScrollPane(); + private final int defaultFragmentHeight = 40; + private final double defaultScale = 0.1; + private ContentPanel contentPanel; + private TimeViewPort viewport; + private double wheelSize; + private double rangeNs; + private double lefPercent; + private double rightPercent; + private long startNS; + private boolean isUserInteraction; + private Cursor wCursor = new Cursor(Cursor.W_RESIZE_CURSOR); + private Cursor eCursor = new Cursor(Cursor.E_RESIZE_CURSOR); + private Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); + private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); + + /** + * Constructor + */ + public AnalystPanel() { + setLayout(new MigLayout("insets 0")); + viewport = new TimeViewPort(height -> viewport.setBorder(null), (sn, en) -> { + /** + * When the time axis range changes, + * the contentPanel is notified that all data is refreshed according to the time axis + */ + contentPanel.rangeChange(sn, en); + }); + setBorder(null); + contentPanel = new ContentPanel(this); + contentPanel.setBorder(null); + viewport.setView(contentPanel); + scrollPane.setViewport(viewport); + scrollPane.setBorder(null); + tab = new TabPanel(); + tab.setFocusable(true); + tab.setVisible(false); + addAncestorListener(new AncestorListenerAdapter() { + @Override + public void ancestorAdded(AncestorEvent event) { + super.ancestorAdded(event); + layeredPane = AnalystPanel.this.getRootPane().getLayeredPane(); + layeredPane.add(tab); + layeredPane.setLayer(tab, JLayeredPane.UNDEFINED_CONDITION); + layeredPane.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + super.componentResized(event); + tab.setBounds(0, 0, 0, 0); + } + }); + contentPanel.requestFocusInWindow(); + } + + @Override + public void ancestorRemoved(AncestorEvent event) { + super.ancestorRemoved(event); + if (Objects.nonNull(tab)) { + tab.hidden(); + } + } + }); + this.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + super.componentResized(event); + viewport.setRootHeight(getHeight()); + contentPanel.repaint(); + } + }); + add(scrollPane, "push,grow"); + contentPanel.setFocusable(true); + contentPanel.addMouseMotionListener(this); + contentPanel.addMouseListener(this); + contentPanel.addKeyListener(this); + iCpuDataClick = cpu -> clickCpuData(cpu); + iThreadDataClick = thread -> clickThreadData(thread); + iFunctionDataClick = fun -> clickFunctionData(fun); + iClockDataClick = clock -> clickClockData(clock); + iFlagClick = flag -> clickTimeFlag(flag); + } + + static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return obj -> seen.putIfAbsent(keyExtractor.apply(obj), Boolean.TRUE) == null; + } + + /** + * add cpu data list + * + * @param list source + */ + public void addCpuList(final List> list) { + if (list == null) { + return; + } + cpuList = list; + cpuNum = list.size(); + for (int index = 0; index < list.size(); index++) { + List dataList = list.get(index); + contentPanel.addDataFragment(new CpuDataFragment(contentPanel, index, dataList)); + } + } + + /** + * add cpu freg data list + * + * @param list source + * @param cpuMaxFreq cpu size + */ + public void addCpuFreqList(final List> list, final CpuFreqMax cpuMaxFreq) { + cpuFreqList = list; + for (int index = 0; index < list.size(); index++) { + List dataList = list.get(index); + + // Fill in the duration field in FreqData and calculate based on the start time of the next node + for (int idx = 0, len = dataList.size(); idx < len; idx++) { + CpuFreqData cpuGraph = dataList.get(idx); + if (idx == len - 1) { + cpuGraph.setDuration(AnalystPanel.DURATION - cpuGraph.getStartTime()); + } else { + cpuGraph.setDuration(dataList.get(idx + 1).getStartTime() - cpuGraph.getStartTime()); + } + } + contentPanel.addDataFragment( + new CpuFreqDataFragment(contentPanel, "Cpu " + index + " Frequency", cpuMaxFreq, dataList)); + } + } + + /** + * add thread data list + * + * @param list thread list + * @param processMem process list + * @param asyncEvents asyncEvents + */ + public void addThreadsList(final List list, final List processMem, + List asyncEvents) { + /* + * If the list has no data (obtained by memory sorting), + * then directly query the process and thread tables to find the data + */ + if (list.isEmpty()) { + Db.getInstance().query(Sql.SYS_QUERY_PROCESS_THREADS_NORDER, list); + } + threadsList = list; + List processes = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_PROCESS, processes); + if (processes.isEmpty()) { + Db.getInstance().query(Sql.SYS_QUERY_PROCESS_NORDER, processes); + } + for (Process process : processes) { + if (process.getPid() == 0) { + continue; + } + ProcessDataFragment processDataFragment = new ProcessDataFragment(contentPanel, process); + contentPanel.addDataFragment(processDataFragment); + processMem.stream().filter(mem -> mem.getPid() == process.getPid()).forEach(mem -> { + MemDataFragment fgr = new MemDataFragment(contentPanel, mem); + fgr.defaultHeight = defaultFragmentHeight; + fgr.parentUuid = processDataFragment.uuid; + fgr.visible = false; + contentPanel.addDataFragment(fgr); + }); + asyncEvents.stream().filter(it -> it.getPid().equals(process.getPid())) + .filter(distinctByKey(it -> it.getName())).forEach(it -> { + List collect = asyncEvents.stream() + .filter(wt -> wt.getPid().equals(it.getPid()) && wt.getName().equals(it.getName())) + .collect(Collectors.toList()); + AsyncEventDataFragment fgr = new AsyncEventDataFragment(contentPanel, it, collect); + int maxHeight = (collect.stream().mapToInt(bean -> bean.getDepth()).max().getAsInt() + 1) * 20; + fgr.defaultHeight = maxHeight + 20; + fgr.parentUuid = processDataFragment.uuid; + fgr.visible = false; + contentPanel.addDataFragment(fgr); + }); + List collect = list.stream().filter( + threadData -> threadData.getPid() == process.getPid() && threadData.getTid() != 0 + && threadData.getThreadName() != null).collect(Collectors.toList()); + for (ThreadData data : collect) { + ThreadDataFragment fgr = new ThreadDataFragment(contentPanel, data); + fgr.defaultHeight = defaultFragmentHeight; + fgr.parentUuid = processDataFragment.uuid; + fgr.visible = false; + contentPanel.addDataFragment(fgr); + } + } + // If you use the memory method to find the data, you need to execute the following code + if (!list.isEmpty()) { + addThreadsList2(list); + } + } + + private void addThreadsList2(List list) { + list.stream().filter(data -> data.getProcessName() == null || data.getProcessName().isEmpty()) + .forEach(threadData -> { + Process process = new Process(); + process.setPid(threadData.getTid()); + process.setName(threadData.getThreadName()); + ProcessDataFragment processDataFragment = new ProcessDataFragment(contentPanel, process); + contentPanel.addDataFragment(processDataFragment); + if (!process.getName().startsWith("swapper") && process.getPid() != 0) { + ThreadDataFragment fgr = new ThreadDataFragment(contentPanel, threadData); + fgr.defaultHeight = defaultFragmentHeight; + fgr.parentUuid = processDataFragment.uuid; + fgr.visible = false; + contentPanel.addDataFragment(fgr); + } + }); + } + + private void recycle() { + Utils.resetPool(); + if (cpuList != null) { + cpuList.forEach(List::clear); + cpuList.clear(); + } + if (cpuFreqList != null) { + cpuFreqList.forEach(List::clear); + cpuFreqList.clear(); + } + if (threadsList != null) { + threadsList.clear(); + } + } + + /** + * load database + * + * @param name db name + * @param isLocal is local db + */ + public void load(final String name, final boolean isLocal) { + recycle(); + Db.setDbName(name); + Db.load(isLocal); + tab.hidden(); + CompletableFuture.runAsync(() -> { + loadDur(); + List> list = loadCpuData(); + List> freqList = loadCpuFreqData(); + // Add the memory information of the process + List processMem = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_PROCESS_MEM, processMem); + List asyncEvents = new ArrayList<>() { + }; + // Add thread information + List processThreads = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_PROCESS_THREADS, processThreads); + List cpuFreqMaxList = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_CPU_MAX_FREQ, cpuFreqMaxList); + SwingUtilities.invokeLater(() -> { + viewport.recycle(); + viewport.rulerFragment.setRange(0, AnalystPanel.DURATION, 0); + viewport.rulerFragment.recycle(); + viewport.cpuFragment.reloadData(); + contentPanel.recycle(); + addCpuList(list); + if (cpuFreqMaxList.size() > 0) { + addCpuFreqList(freqList, cpuFreqMaxList.get(0).math()); + } + ArrayList clocks = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_CLOCK_LIST, clocks); + addClock(clocks); + addThreadsList(processThreads, processMem, asyncEvents); // The memory information of the process and + // The thread information of the process is displayed together + contentPanel.refresh(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + + private void addClock(ArrayList clocks) { + if (!clocks.isEmpty()) { + Clock screenState = new Clock(); + screenState.setName("ScreenState"); + screenState.setSrcname("ScreenState"); + contentPanel.addDataFragment(new ClockDataFragment(contentPanel, screenState)); + clocks.forEach(it -> { + contentPanel.addDataFragment(new ClockDataFragment(contentPanel, it)); + }); + } + } + + private void loadDur() { + List dur = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_TOTAL_TIME, dur); + if (dur != null && dur.size() > 0) { + DURATION = dur.get(0).getTotal(); + } + } + + private List> loadCpuData() { + List cpuMaxes = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_CPU_MAX, cpuMaxes); + if (cpuMaxes.isEmpty()) { + return null; + } + int cpuMax = cpuMaxes.get(0).getCpu(); + List> list = new ArrayList<>(); + for (int index = 0; index <= cpuMax; index++) { + List cpuData = new ArrayList<>() { + }; + list.add(cpuData); + } + return list; + } + + private List> loadCpuFreqData() { + List cpus = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_CPU_FREQ, cpus); + List> freqList = cpus.stream().map(it -> { + List cpuFreqData = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_CPU_FREQ_DATA, cpuFreqData, it.getCpu()); + return cpuFreqData; + }).collect(Collectors.toList()); + return freqList; + } + + /** + * The bottom tab is displayed when the select event is clicked. + * + * @param cpus select cpu list() + * @param threadIds select thread id list + * @param trackIds select mem track id list + * @param ns select start time ns and end time ns + * @param funTids funTids + */ + public void boxSelection(final List cpus, final List threadIds, final List trackIds, + final List funTids, final LeftRightNS ns) { + if (cpus.isEmpty() && threadIds.isEmpty() && trackIds.isEmpty() && funTids.isEmpty()) { + tab.hidden(); + return; + } + SwingUtilities.invokeLater(() -> { + Rectangle b3 = + SwingUtilities.convertRectangle(scrollPane, scrollPane.getBounds(), layeredPane); + tab.display(b3); + tab.removeAll(); + if (cpus != null && !cpus.isEmpty()) { + TabCpuByThread cpuThread = new TabCpuByThread(); + TabCpuByProcess cpuProcess = new TabCpuByProcess(); + cpuThread.loadTabData(cpus, ns.getLeftNs(), ns.getRightNs()); + cpuProcess.loadTabData(cpus, ns.getLeftNs(), ns.getRightNs()); + tab.add("CPU by thread", cpuThread); + tab.add("CPU by process", cpuProcess); + } + if (threadIds != null && !threadIds.isEmpty()) { + TabThreadStates threadStatesTab = new TabThreadStates(); + threadStatesTab.loadTabData(threadIds, ns.getLeftNs(), ns.getRightNs()); + tab.add("Thread States", threadStatesTab); + } + if (funTids != null && !funTids.isEmpty()) { + TabSlices slicesTab = new TabSlices(); + slicesTab.loadTabData(funTids, ns.getLeftNs(), ns.getRightNs()); + tab.add("Slices", slicesTab); + } + if (trackIds != null && !trackIds.isEmpty()) { + TabCounter counterTab = new TabCounter(); + counterTab.loadTabData(trackIds, ns.getLeftNs(), ns.getRightNs()); + tab.add("Counters", counterTab); + } + }); + } + + /** + * The bottom tab is displayed when the method event is clicked. + * + * @param bean function + */ + public void clickFunctionData(final FunctionBean bean) { + cancelRangeSelect(); + ArrayList dataSource = new ArrayList<>(); + dataSource.add(ScrollSlicePanel.createSliceData("Name", bean.getFunName(), false)); + dataSource.add(ScrollSlicePanel.createSliceData("Category", bean.getCategory(), false)); + dataSource.add(ScrollSlicePanel.createSliceData("StartTime", + TimeUtils.getTimeString(bean.getStartTime()) + "", false)); + dataSource.add(ScrollSlicePanel.createSliceData("Duration", + TimeUtils.getTimeString(bean.getDuration()) + "", false)); + SwingUtilities.invokeLater(() -> { + Rectangle b3 = + SwingUtilities.convertRectangle(scrollPane, scrollPane.getBounds(), layeredPane); + tab.display(b3); + tab.removeAll(); + ScrollSlicePanel ssp = new ScrollSlicePanel(); + ssp.setData("Slice Details", dataSource, null); + tab.add("Current Selection", ssp); + }); + } + + /** + * The bottom tab is displayed when the clock data event is clicked. + * + * @param clock clock data + */ + public void clickClockData(final ClockData clock) { + cancelRangeSelect(); + ArrayList dataSource = new ArrayList<>(); + dataSource.add(ScrollSlicePanel.createSliceData("Start time", + TimeUtils.getTimeString(clock.getStartTime()), false)); + dataSource.add(ScrollSlicePanel.createSliceData("Value", + String.valueOf(clock.getValue()), false)); + dataSource.add(ScrollSlicePanel.createSliceData("Delta", + String.valueOf(clock.getDelta()), false)); + dataSource.add(ScrollSlicePanel.createSliceData("Duration", + TimeUtils.getTimeString(clock.getDuration()) + "", false)); + SwingUtilities.invokeLater(() -> { + Rectangle b3 = + SwingUtilities.convertRectangle(scrollPane, scrollPane.getBounds(), layeredPane); + tab.display(b3); + tab.removeAll(); + ScrollSlicePanel ssp = new ScrollSlicePanel(); + ssp.setData("Counter Details", dataSource, null); + tab.add("Current Selection", ssp); + }); + } + + /** + * When you click the CPU event, the bottom tab is displayed. + * + * @param threadData thread + */ + public void clickThreadData(final ThreadData threadData) { + cancelRangeSelect(); + ArrayList dataSource = new ArrayList<>(); + dataSource.add(ScrollSlicePanel + .createSliceData("StartTime", TimeUtils.getTimeString(threadData.getStartTime()) + "", false)); + dataSource.add(ScrollSlicePanel + .createSliceData("Duration", TimeUtils.getTimeString(threadData.getDuration()) + "", false)); + String state = Utils.getEndState(threadData.getState()); + if ("Running".equals(Utils.getEndState(threadData.getState()))) { + state = state + " on CPU " + threadData.getCpu(); + } + dataSource.add(ScrollSlicePanel.createSliceData("State", state, true)); + String processName = threadData.getProcessName(); + if (processName == null || processName.isEmpty()) { + processName = threadData.getThreadName(); + } + dataSource + .add(ScrollSlicePanel.createSliceData("Process", processName + " [" + threadData.getPid() + "]", false)); + SwingUtilities.invokeLater(() -> { + Rectangle b3 = + SwingUtilities.convertRectangle(scrollPane, scrollPane.getBounds(), layeredPane); + tab.setRootRect(b3); + tab.display(b3); + tab.removeAll(); + ScrollSlicePanel ssp = new ScrollSlicePanel(); + ssp.setData("Thread State", dataSource, null); + ssp.setScrollSliceLinkListener(bean -> { + contentPanel.scrollToCpu(threadData.getCpu(), threadData.getStartTime()); + }); + tab.add("Current Selection", ssp); + }); + } + + /** + * The bottom tab is displayed when you click the CPU event. + * + * @param cpu cpu + */ + public void clickCpuData(final CpuData cpu) { + cancelRangeSelect(); + ArrayList dataSource = new ArrayList<>(); + String process = cpu.getProcessName(); + int processId = cpu.getProcessId(); + if (cpu.getProcessName() == null || cpu.getProcessName().isEmpty()) { + process = cpu.getName(); + processId = cpu.getTid(); + } + dataSource.add(ScrollSlicePanel.createSliceData("Process", process + " [" + processId + "]", false)); + dataSource.add(ScrollSlicePanel.createSliceData("Thread", cpu.getName() + " [" + cpu.getTid() + "]", true)); + dataSource.add(ScrollSlicePanel.createSliceData("CmdLine", cpu.getProcessCmdLine() + "", false)); + dataSource.add( + ScrollSlicePanel.createSliceData("StartTime", TimeUtils.getTimeString(cpu.getStartTime()) + "", false)); + dataSource + .add(ScrollSlicePanel.createSliceData("Duration", TimeUtils.getTimeString(cpu.getDuration()) + "", false)); + dataSource.add(ScrollSlicePanel.createSliceData("Prio", cpu.getPriority() + "", false)); + dataSource.add(ScrollSlicePanel.createSliceData("End State", Utils.getEndState(cpu.getEndState()), false)); + // wakeup description + CompletableFuture.runAsync(() -> { + Optional wb = queryWakeUpThread(cpu); + SwingUtilities.invokeLater(() -> { + contentPanel.setWakeupBean(wb.orElse(null)); + Rectangle b3 = + SwingUtilities.convertRectangle(scrollPane, scrollPane.getBounds(), layeredPane); + tab.display(b3); + tab.removeAll(); + ScrollSlicePanel ssp = new ScrollSlicePanel(); + ssp.setData("Slice Details", dataSource, wb.orElse(null)); + ssp.setScrollSliceLinkListener(bean -> { + contentPanel.scrollToThread(cpu.getProcessId(), cpu.getTid(), cpu.getStartTime(), tab.getHeight()); + }); + tab.add("Current Selection", ssp); + repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + + private Optional queryWakeUpThread(final CpuData cpuData) { + WakeupBean wb = null; + List result = new ArrayList<>() { + }; + Db.getInstance() + .query(Sql.SYS_GET_WAKEUP_TIME, result, cpuData.getId(), cpuData.getStartTime(), cpuData.getId(), + cpuData.getStartTime()); + if (result != null && result.size() > 0) { + WakeupTime wakeupTime = result.get(0); + if (wakeupTime.getWakeTs() < wakeupTime.getPreRow()) { + return Optional.ofNullable(wb); + } + List beans = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_WAKEUP_THREAD, beans, wakeupTime.getWakeTs(), wakeupTime.getWakeTs(), + wakeupTime.getWakeTs()); + if (beans != null && beans.size() > 0) { + wb = beans.get(0); + wb.setWakeupTime(wakeupTime.getWakeTs() - wakeupTime.getStartTs()); + wb.setSchedulingLatency(cpuData.getStartTime() - wb.getWakeupTime()); + if (wb.getWakeupProcess() == null) { + wb.setWakeupProcess(wb.getWakeupThread()); + } + if (wb.getWakeupPid() == null) { + wb.setWakeupPid(wb.getWakeupTid()); + } + wb.setSchedulingDesc(Db.getSql("QueryWakeUpThread_Desc")); + } + } + return Optional.ofNullable(wb); + } + + /** + * Evoking the red flag corresponds to the tabPanel at the bottom. + * + * @param flagBean flag + */ + public void clickTimeFlag(final FlagBean flagBean) { + cancelRangeSelect(); + clicked = true; + layeredPane.setLayer(tab, javax.swing.JLayeredPane.DRAG_LAYER); + ScrollFlagPanel flagPanel = new ScrollFlagPanel(flagBean); + flagPanel.setFlagListener(new IFlagListener() { + @Override + public void flagRemove(final FlagBean flag) { + flag.remove(); + viewport.rulerFragment.repaint(); + tab.removeAll(); + tab.hidden(); + } + + @Override + public void flagChange(final FlagBean flag) { + if (flag.getName() != null && !flag.getName().isEmpty()) { + flagBean.setName(flag.getName()); + } + flagBean.setColor(flag.getColor()); + viewport.rulerFragment.repaint(); + } + }); + SwingUtilities.invokeLater(() -> { + Rectangle b3 = + SwingUtilities.convertRectangle(AnalystPanel.this, AnalystPanel.this.getBounds(), layeredPane); + tab.display(b3); + tab.removeAll(); + tab.add("Current Selection", flagPanel); + repaint(); + }); + } + + @Override + public void keyTyped(final KeyEvent event) { + } + + @Override + public void keyPressed(final KeyEvent event) { + switch (event.getExtendedKeyCode()) { + case VK_A: + wheelSize = viewport.rulerFragment.getScale() * -0.2; + translation(); + break; + case VK_D: + wheelSize = viewport.rulerFragment.getScale() * 0.2; + translation(); + break; + case VK_W: + wheelSize = viewport.rulerFragment.getScale() * -0.2; + lefPercent = 0.5; + scale(); + break; + case VK_S: + wheelSize = viewport.rulerFragment.getScale() * 0.2; + lefPercent = 0.5; + scale(); + break; + case VK_F: + keyPressedVKF(event); + break; + case VK_SHIFT: + case VK_CONTROL: + if (!isUserInteraction) { + isUserInteraction = true; + contentPanel.addMouseWheelListener(this); + } + break; + default: + break; + } + } + + private void keyPressedVKF(KeyEvent event) { + if (event.isControlDown() || event.isMetaDown()) { + for (AbstractDataFragment frg : viewport.favoriteFragments) { + viewport.cancel(frg); + } + String keyword = Optional.ofNullable(JOptionPane + .showInputDialog(null, "Search for pid uid name", + "Search", JOptionPane.PLAIN_MESSAGE, null, null, + "")) + .map(it -> it.toString().trim()).orElse(""); + if (keyword == null || keyword.isEmpty()) { + keyPressedVKFEmptyKeyword(); + } else { + contentPanel.fragmentList.stream().forEach(it -> { + if (it instanceof ThreadDataFragment) { + ThreadDataFragment fr1 = (ThreadDataFragment) it; + if (String.valueOf(fr1.thread.getTid()).equals(keyword)) { + it.setVisible(true); + } else if (fr1.thread.getThreadName() != null + && fr1.thread.getThreadName().indexOf(keyword) != -1) { + it.setVisible(true); + } else { + it.setVisible(false); + } + } + if (it instanceof ProcessDataFragment) { + ProcessDataFragment it1 = (ProcessDataFragment) it; + if (it1.getProcess().getName() != null && it1.getProcess().getName().indexOf(keyword) != -1) { + it1.getExpandGraph().setExpand(true); + it.setVisible(true); + } else if (it1.getProcess().getPid().toString().equals(keyword)) { + it1.getExpandGraph().setExpand(true); + it.setVisible(true); + } else { + it.setVisible(false); + } + } + }); + } + contentPanel.refresh(); + } + } + + private void keyPressedVKFEmptyKeyword() { + contentPanel.fragmentList.stream().forEach(it -> { + if (it instanceof ThreadDataFragment || it instanceof MemDataFragment + || it instanceof AsyncEventDataFragment || it instanceof FunctionDataFragment) { + it.setVisible(false); + } else { + if (it instanceof ProcessDataFragment) { + ProcessDataFragment it1 = (ProcessDataFragment) it; + it1.getExpandGraph().setExpand(false); + } + it.setVisible(true); + } + }); + } + + @Override + public void keyReleased(final KeyEvent event) { + switch (event.getExtendedKeyCode()) { + case VK_SHIFT: + case VK_CONTROL: + if (isUserInteraction) { + isUserInteraction = false; + contentPanel.removeMouseWheelListener(this); + contentPanel.fragmentList.forEach(it -> it.keyReleased(event)); + } + break; + default: + break; + } + } + + @Override + public void mouseClicked(final MouseEvent event) { + clicked = false; + viewport.mouseClicked(event); + // Select the area, judge to click on the tab in the area to restore the display + Rectangle rectangle = new Rectangle(contentPanel.x1, contentPanel.y1, contentPanel.x2 - contentPanel.x1, + contentPanel.y2 - contentPanel.y1); + if (rectangle.contains(event.getPoint())) { + tab.display(); + } else { + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + contentPanel.fragmentList.stream().filter(it -> it.getRect().contains(event.getPoint())) + .forEach(fragment -> fragment.mouseClicked(event)); + } + if (!clicked) { + tab.hidden(); + contentPanel.fragmentList.stream().findFirst().ifPresent(it -> { + it.clearSelected(); + }); + contentPanel.clearWakeupAndBoxSelect(); + } + } + } + + @Override + public void mousePressed(final MouseEvent event) { + viewport.mousePressed(event); + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + Rectangle rect = new Rectangle(0, 0, viewport.getWidth(), TimeViewPort.height); + if (!rect.contains(event.getPoint()) && Utils.getX(event.getPoint()) > 200) { + if (getCursor().getType() == Cursor.DEFAULT_CURSOR) { + contentPanel.startPoint = event.getPoint(); + } + contentPanel.drawRangeSelect = true; + contentPanel.fragmentList.forEach(fragment -> fragment.mousePressed(event)); + } + } + } + + @Override + public void mouseReleased(final MouseEvent event) { + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + contentPanel.drawRangeSelect = false; + contentPanel.fragmentList.stream().filter(it -> !(it instanceof CpuDataFragment)) + .forEach(fragment -> fragment.mouseReleased(event)); + } else { + contentPanel.fragmentList.forEach(it -> it.mouseReleased(event)); + } + if (Objects.nonNull(contentPanel.startPoint) && Objects.nonNull(contentPanel.endPoint)) { + if (contentPanel.startPoint.getX() > contentPanel.endPoint.getX()) { + Point tmp = contentPanel.startPoint; + contentPanel.startPoint = contentPanel.endPoint; + contentPanel.endPoint = tmp; + } + } + contentPanel.repaint(); + } + + @Override + public void mouseEntered(final MouseEvent event) { + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + contentPanel.fragmentList.forEach(fragment -> fragment.mouseEntered(event)); + } + } + + @Override + public void mouseExited(final MouseEvent event) { + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + contentPanel.fragmentList.forEach(fragment -> fragment.mouseExited(event)); + } + } + + @Override + public void mouseDragged(final MouseEvent event) { + viewport.mouseDragged(event); + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + Rectangle rect = new Rectangle(0, 0, viewport.getWidth(), TimeViewPort.height); + if (!rect.contains(event.getPoint()) && Utils.getX(event.getPoint()) > 200) { + long startNSTmp = Math.min(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); + long endNSTmp = Math.max(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); + long dur = endNSTmp - startNSTmp; + if (getCursor().getType() == Cursor.W_RESIZE_CURSOR) { + contentPanel.startPoint = event.getPoint(); + contentPanel.x1 = Math.min(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.x2 = Math.max(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.rangeStartNS = + (contentPanel.x1 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + contentPanel.rangeEndNS = + (contentPanel.x2 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + } else if (getCursor().getType() == Cursor.E_RESIZE_CURSOR) { + contentPanel.endPoint = event.getPoint(); + contentPanel.x1 = Math.min(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.x2 = Math.max(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.rangeStartNS = + (contentPanel.x1 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + contentPanel.rangeEndNS = + (contentPanel.x2 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + } else { + contentPanel.endPoint = event.getPoint(); + if (Objects.nonNull(contentPanel.startPoint)) { + contentPanel.x1 = + Math.min(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.y1 = + Math.min(Utils.getY(contentPanel.startPoint), Utils.getY(contentPanel.endPoint)); + contentPanel.x2 = + Math.max(Utils.getX(contentPanel.startPoint), Utils.getX(contentPanel.endPoint)); + contentPanel.y2 = + Math.max(Utils.getY(contentPanel.startPoint), Utils.getY(contentPanel.endPoint)); + contentPanel.rangeStartNS = + (contentPanel.x1 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + contentPanel.rangeEndNS = + (contentPanel.x2 - 200) * dur / (viewport.rulerFragment.getRect().width) + startNSTmp; + } + } + contentPanel.drawRangeSelectData = true; + contentPanel.repaint(); + } + } + } + + @Override + public void mouseMoved(final MouseEvent event) { + viewport.mouseMoved(event); + if (SwingUtilities.convertMouseEvent(contentPanel, event, AnalystPanel.this).getY() > TimeViewPort.height) { + if (event.getY() < Utils.getY(tab.getBounds())) { + contentPanel.requestFocusInWindow(); + } + contentPanel.fragmentList.forEach(fragment -> fragment.mouseMoved(event)); + } + Rectangle rect1 = new Rectangle(contentPanel.x1 - 2, contentPanel.y1, 4, contentPanel.y2 - contentPanel.y1); + Rectangle rect2 = new Rectangle(contentPanel.x2 - 2, contentPanel.y1, 4, contentPanel.y2 - contentPanel.y1); + if (rect1.contains(event.getPoint())) { + setCursor(wCursor); + } else if (rect2.contains(event.getPoint())) { + setCursor(eCursor); + } else { + setCursor(defaultCursor); + } + } + + @Override + public void mouseWheelMoved(final MouseWheelEvent event) { + if (event.isShiftDown() && !event.isControlDown()) { // Pan + long scale = viewport.rulerFragment.getScale(); + if (Math.abs(event.getPreciseWheelRotation()) >= 1) { + wheelSize = scale * event.getPreciseWheelRotation() * defaultScale; + } else { + wheelSize = scale * event.getPreciseWheelRotation(); + } + translation(); + } + if (event.isControlDown() && !event.isShiftDown()) { // Zoom + if (Math.abs(event.getPreciseWheelRotation()) >= 1) { + wheelSize = viewport.rulerFragment.getScale() * event.getPreciseWheelRotation() * defaultScale; + } else { + wheelSize = viewport.rulerFragment.getScale() * event.getPreciseWheelRotation(); + } + int rulerFragmentWidth = viewport.rulerFragment.getRect().width; + lefPercent = (event.getX() - Utils.getX(viewport.rulerFragment.getRect())) * 1.0 / rulerFragmentWidth; + if (scaleMin(event)) { + scale(); + } + } + } + + private boolean scaleMin(MouseWheelEvent event) { + if (event.getPreciseWheelRotation() < 0) { // Zoom out + long rightNS = viewport.rulerFragment.getRightNS(); + long leftNS = viewport.rulerFragment.getLeftNS(); + long centerNS; + final int minrul = 1000; + if (rightNS - leftNS <= minrul) { + rightNS = leftNS + minrul; + centerNS = leftNS; + viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); + viewport.cpuFragment.setRange(leftNS, rightNS); + for (AbstractDataFragment fragment : viewport.favoriteFragments) { + fragment.range(leftNS, rightNS); + } + repaint(); + return false; + } + } + return true; + } + + private void scale() { + if (lefPercent < 0) { + lefPercent = 0; + } + if (lefPercent > 1) { + lefPercent = 1; + } + rightPercent = 1 - lefPercent; + if (lefPercent > 0) { + double leftNs = viewport.rulerFragment.getLeftNS() - this.wheelSize * lefPercent; + viewport.rulerFragment.setLeftNS((long) leftNs); + } + if (rightPercent > 0) { + double rightNs = viewport.rulerFragment.getRightNS() + this.wheelSize * rightPercent; + viewport.rulerFragment.setRightNS((long) rightNs); + } + if (viewport.rulerFragment.getLeftNS() <= 0) { + viewport.rulerFragment.setLeftNS(0); + } + if (viewport.rulerFragment.getRightNS() >= DURATION) { + viewport.rulerFragment.setRightNS(DURATION); + } + viewport.rulerFragment.setCenterNS(viewport.rulerFragment.getLeftNS()); + viewport.rulerFragment.setRange(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS(), + viewport.rulerFragment.getCenterNS()); + viewport.cpuFragment.setRange(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); + if (lefPercent > 0) { + startNS = viewport.leftFragment.getStartNS(); + startNS -= wheelSize * lefPercent; + if (startNS > 0) { + viewport.leftFragment.setStartTime(startNS); + } else { + viewport.leftFragment.setStartTime(0); + } + } + for (AbstractDataFragment fragment : viewport.favoriteFragments) { + fragment.range(viewport.rulerFragment.getLeftNS(), viewport.rulerFragment.getRightNS()); + } + resetRangePoint(); + contentPanel.repaint(); + } + + private void translation() { + long leftNS = viewport.rulerFragment.getLeftNS(); + long rightNS = viewport.rulerFragment.getRightNS(); + long centerNS; + + if (leftNS + wheelSize <= 0) { + rangeNs = rightNS - leftNS; + leftNS = 0; + rightNS = (long) rangeNs; + centerNS = leftNS; + viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); + viewport.cpuFragment.setRange(leftNS, rightNS); + viewport.leftFragment.setStartTime(0); + } else if (rightNS + wheelSize >= DURATION) { + rangeNs = rightNS - leftNS; + rightNS = DURATION; + leftNS = (long) (DURATION - rangeNs); + centerNS = leftNS; + viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); + viewport.cpuFragment.setRange(leftNS, rightNS); + viewport.leftFragment.setStartTime(leftNS); + } else { + leftNS += wheelSize; + rightNS += wheelSize; + centerNS = leftNS; + viewport.rulerFragment.setRange(leftNS, rightNS, centerNS); + viewport.cpuFragment.setRange(leftNS, rightNS); + startNS = viewport.leftFragment.getStartNS(); + startNS += wheelSize; + viewport.leftFragment.setStartTime(startNS); + } + + // Slide the icons that need to be viewed in the timeShaft collection + for (AbstractDataFragment fragment : viewport.favoriteFragments) { + fragment.range(leftNS, rightNS); + } + resetRangePoint(); + contentPanel.repaint(); + } + + private void resetRangePoint() { + contentPanel.fragmentList.stream().findFirst().ifPresent(it -> { + if (Objects.nonNull(contentPanel.startPoint)) { + Utils.setX(contentPanel.startPoint, it.getX(contentPanel.rangeStartNS) + 200); + contentPanel.x1 = Utils.getX(contentPanel.startPoint); + } + if (Objects.nonNull(contentPanel.endPoint)) { + Utils.setX(contentPanel.endPoint, it.getX(contentPanel.rangeEndNS) + 200); + contentPanel.x2 = Utils.getX(contentPanel.endPoint); + } + }); + } + + private void cancelRangeSelect() { + contentPanel.startPoint = null; + contentPanel.endPoint = null; + } + + /** + * cpu data click callback + */ + public interface ICpuDataClick { + /** + * cpu data click callback + * + * @param cpu cpu + */ + void click(CpuData cpu); + } + + /** + * thread data click callback + */ + public interface IThreadDataClick { + /** + * thread data click callback + * + * @param data thread + */ + void click(ThreadData data); + } + + /** + * function data click callback + */ + public interface IFunctionDataClick { + /** + * function data click callback + * + * @param data function + */ + void click(FunctionBean data); + } + + /** + * function data click callback + */ + public interface IClockDataClick { + /** + * function data click callback + * + * @param data function + */ + void click(ClockData data); + } + + /** + * flag click callback + */ + public interface IFlagClick { + /** + * flag click callback + * + * @param data flag + */ + void click(FlagBean data); + } + + /** + * wrap left ns and right ns + */ + public static class LeftRightNS { + private long leftNs; + private long rightNs; + + /** + * Gets the value of leftNs . + * + * @return the value of long + */ + public long getLeftNs() { + return leftNs; + } + + /** + * Sets the leftNs . + *

You can use getLeftNs() to get the value of leftNs

+ * + * @param leftNs leftNs + */ + public void setLeftNs(long leftNs) { + this.leftNs = leftNs; + } + + /** + * Gets the value of rightNs . + * + * @return the value of long + */ + public long getRightNs() { + return rightNs; + } + + /** + * Sets the rightNs . + *

You can use getRightNs() to get the value of rightNs

+ * + * @param rightNs rightNs + */ + public void setRightNs(long rightNs) { + this.rightNs = rightNs; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/BottomScrollPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/BottomScrollPanel.java index d303a74b3..618ba6df1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/BottomScrollPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/BottomScrollPanel.java @@ -1,171 +1,174 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBBox; -import com.intellij.ui.components.JBPanel; -import com.intellij.ui.components.JBScrollPane; - -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * Bottom scroll component - * - * @date 2021/04/20 12:24 - * @version 1.0.1 - */ -public class BottomScrollPanel extends JBScrollPane { - /** - * box container - */ - protected JBBox box = JBBox.createHorizontalBox(); - - /** - * Constructor - */ - public BottomScrollPanel() { - setViewportView(box); - addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(final MouseEvent event) { - super.mouseEntered(event); - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - }); - } - - /** - * @date 2021/04/20 12:24 - * @version 1.0.1 - */ - public static class ChildPanel extends JBPanel { - /** - * line height - */ - public int lineHeight; - /** - * line width - */ - public int lineWidth; - - /** - * construct with line width and line height - * - * @param lineWidth line width - * @param lineHeight line height - */ - public ChildPanel(final int lineWidth, final int lineHeight) { - this.lineHeight = lineHeight; - this.lineWidth = lineWidth; - } - - @Override - public Dimension getMinimumSize() { - Dimension dimension = super.getMinimumSize(); - if (this.lineWidth != 0) { - dimension.width = lineWidth; - } - dimension.height = lineHeight; - return dimension; - } - - @Override - public Dimension getPreferredSize() { - Dimension dimension = super.getPreferredSize(); - if (this.lineWidth != 0) { - dimension.width = lineWidth; - } - dimension.height = lineHeight; - return dimension; - } - - @Override - public Dimension getMaximumSize() { - Dimension dimension = super.getMaximumSize(); - if (this.lineWidth != 0) { - dimension.width = lineWidth; - } - dimension.height = lineHeight; - return dimension; - } - } - - /** - * @date 2021/04/20 12:24 - * @version 1.0.1 - */ - public static class ChildLineComponent extends ChildPanel { - private static final int DEFAULT_LINE_HEIGHT = 27; - /** - * Monitor whether the mouse is moved into the component - */ - public boolean mouseIn; - - /** - * Constructor - */ - public ChildLineComponent() { - super(0, DEFAULT_LINE_HEIGHT); - addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(final MouseEvent event) { - childMouseEntered(event); - } - - @Override - public void mouseExited(final MouseEvent event) { - childMouseExited(event); - } - - @Override - public void mouseClicked(final MouseEvent event) { - childMouseClicked(event); - } - }); - } - - /** - * Custom mouse events - * - * @param event mouse event - */ - public void childMouseEntered(final MouseEvent event) { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - mouseIn = true; - repaint(); - } - - /** - * Custom mouse events - * - * @param event mouse event - */ - public void childMouseExited(final MouseEvent event) { - mouseIn = false; - repaint(); - } - - /** - * Custom mouse events - * - * @param event mouse event - */ - public void childMouseClicked(final MouseEvent event) { } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBBox; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; + +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * Bottom scroll component + * + * @date 2021/04/20 12:24 + */ +public class BottomScrollPanel extends JBScrollPane { + /** + * box container + */ + protected JBBox box = JBBox.createHorizontalBox(); + + /** + * Constructor + */ + public BottomScrollPanel() { + setBorder(null); + setViewportView(box); + addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(final MouseEvent event) { + super.mouseEntered(event); + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + }); + } + + /** + * ChildPanel + * + * @date 2021/04/20 12:24 + */ + public static class ChildPanel extends JBPanel { + /** + * line height + */ + public int lineHeight; + /** + * line width + */ + public int lineWidth; + + /** + * construct with line width and line height + * + * @param lineWidth line width + * @param lineHeight line height + */ + public ChildPanel(final int lineWidth, final int lineHeight) { + this.lineHeight = lineHeight; + this.lineWidth = lineWidth; + } + + @Override + public Dimension getMinimumSize() { + Dimension dimension = super.getMinimumSize(); + if (this.lineWidth != 0) { + dimension.width = lineWidth; + } + dimension.height = lineHeight; + return dimension; + } + + @Override + public Dimension getPreferredSize() { + Dimension dimension = super.getPreferredSize(); + if (this.lineWidth != 0) { + dimension.width = lineWidth; + } + dimension.height = lineHeight; + return dimension; + } + + @Override + public Dimension getMaximumSize() { + Dimension dimension = super.getMaximumSize(); + if (this.lineWidth != 0) { + dimension.width = lineWidth; + } + dimension.height = lineHeight; + return dimension; + } + } + + /** + * ChildLineComponent + * + * @date 2021/04/20 12:24 + */ + public static class ChildLineComponent extends ChildPanel { + private static final int DEFAULT_LINE_HEIGHT = 27; + /** + * Monitor whether the mouse is moved into the component + */ + public boolean mouseIn; + + /** + * Constructor + */ + public ChildLineComponent() { + super(0, DEFAULT_LINE_HEIGHT); + addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(final MouseEvent event) { + childMouseEntered(event); + } + + @Override + public void mouseExited(final MouseEvent event) { + childMouseExited(event); + } + + @Override + public void mouseClicked(final MouseEvent event) { + childMouseClicked(event); + } + }); + } + + /** + * Custom mouse events + * + * @param event mouse event + */ + public void childMouseEntered(final MouseEvent event) { + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + mouseIn = true; + repaint(); + } + + /** + * Custom mouse events + * + * @param event mouse event + */ + public void childMouseExited(final MouseEvent event) { + mouseIn = false; + repaint(); + } + + /** + * Custom mouse events + * + * @param event mouse event + */ + public void childMouseClicked(final MouseEvent event) { + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ContentPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ContentPanel.java index c14a3536a..8bb9a76b4 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ContentPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ContentPanel.java @@ -1,173 +1,515 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBPanel; -import ohos.devtools.views.trace.bean.WakeupBean; -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.util.Final; - -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Rolling container - * - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ -public final class ContentPanel extends JBPanel { - /** - * FragmentList to be rendered - */ - public List fragmentList = new ArrayList<>(); - - /** - * Analysis component - */ - public AnalystPanel analystPanel; - private WakeupBean wakeupBean; - - /** - * Constructor - * - * @param analystPanel component - */ - public ContentPanel(AnalystPanel analystPanel) { - this.analystPanel = analystPanel; - this.setOpaque(false); - setFont(Final.NORMAL_FONT); - } - - /** - * Sets the wakeupBean . - *

You can use getWakeupBean() to get the value of wakeupBean

- * - * @param wakeup wakeup - */ - public void setWakeupBean(WakeupBean wakeup) { - this.wakeupBean = wakeup; - } - - /** - * Gets the value of wakeupBean . - * - * @return the value of ohos.devtools.views.trace.bean.WakeupBean - */ - public WakeupBean getWakeupBean() { - return wakeupBean; - } - - /** - * refresh bottom tab - */ - public void refreshTab() { - if (analystPanel != null) { - if (TabPanel.getMyHeight() != 0) { - analystPanel.moveToFront(analystPanel.tab); - } - } - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - if (graphics instanceof Graphics2D) { - Graphics2D g2 = (Graphics2D) graphics; - g2.setFont(Final.NORMAL_FONT); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - if (getParent() instanceof TimeViewPort) { - TimeViewPort parent = (TimeViewPort) getParent(); - Rectangle viewRect = parent.getViewRect(); - // Render the line in the viewport display area, and the line beyond the range will not be rendered - fragmentList.stream().filter(fragment -> fragment.visible).filter(fragment -> { - if (fragment != null && fragment.getRect() != null && viewRect != null) { - return fragment.getRect().y + fragment.getRect().height >= viewRect.y + TimeViewPort.height - && fragment.getRect().y <= viewRect.y + viewRect.height - TabPanel.getMyHeight(); - } else { - return false; - } - }).forEach(fragment -> { - if (fragment != null) { - fragment.draw(g2); - } - }); - } - } - } - - /** - * add data line - * - * @param fragment data fragment - */ - public void addDataFragment(AbstractDataFragment fragment) { - fragmentList.add(fragment); - } - - /** - * add data line - * - * @param index line index - * @param fragment data fragment - */ - public void addDataFragment(int index, AbstractDataFragment fragment) { - fragmentList.add(index, fragment); - } - - /** - * refresh content data - */ - public void refresh() { - List fs = - fragmentList.stream().filter(fragment -> fragment.visible).collect(Collectors.toList()); - int timeViewHeight = TimeViewPort.height; - for (int index = 0, len = fs.size(); index < len; index++) { - AbstractDataFragment dataFragment = fs.get(index); - timeViewHeight += dataFragment.defaultHeight; - dataFragment.getRect().height = dataFragment.defaultHeight; - dataFragment.getDescRect().height = dataFragment.defaultHeight; - dataFragment.getDataRect().height = dataFragment.defaultHeight; - dataFragment.getRect().y = timeViewHeight - dataFragment.defaultHeight; - dataFragment.getDescRect().y = timeViewHeight - dataFragment.defaultHeight; - dataFragment.getDataRect().y = timeViewHeight - dataFragment.defaultHeight; - dataFragment.getRect().x = 0; - dataFragment.getDescRect().x = 0; - dataFragment.getDataRect().x = 200; - } - Dimension dim = new Dimension(0, timeViewHeight); - this.setPreferredSize(dim); - this.setSize(dim); - this.setMaximumSize(dim); - repaint(); - } - - /** - * time range change will call this - * - * @param startNS range start ns - * @param endNS range end ns - */ - public void rangeChange(long startNS, long endNS) { - fragmentList.forEach(fragment -> fragment.range(startNS, endNS)); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import ohos.devtools.views.trace.Common; +import ohos.devtools.views.trace.bean.CpuData; +import ohos.devtools.views.trace.bean.WakeupBean; +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.fragment.CpuDataFragment; +import ohos.devtools.views.trace.fragment.FunctionDataFragment; +import ohos.devtools.views.trace.fragment.MemDataFragment; +import ohos.devtools.views.trace.fragment.ProcessDataFragment; +import ohos.devtools.views.trace.fragment.ThreadDataFragment; +import ohos.devtools.views.trace.fragment.ruler.AbstractNode; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Rolling container + * + * @date 2021/04/20 12:24 + */ +public final class ContentPanel extends JBPanel implements AbstractDataFragment.IDataFragment { + /** + * clint fragment + */ + public static AbstractDataFragment clickFragment; + + /** + * FragmentList to be rendered + */ + public List fragmentList = new ArrayList<>(); + + /** + * start point object + */ + public Point startPoint; + + /** + * end point object + */ + public Point endPoint; + + /** + * Analysis component + */ + public AnalystPanel analystPanel; + + /** + * draw range select flag + */ + public boolean drawRangeSelect; + + /** + * draw range select data flag + */ + public boolean drawRangeSelectData; + + /** + * range select x1 + */ + public int x1; + + /** + * range select y1 + */ + public int y1; + + /** + * range select x2 + */ + public int x2; + + /** + * range select y2 + */ + public int y2; + + /** + * range start time + */ + public long rangeStartNS; + + /** + * range end time + */ + public long rangeEndNS; + + private WakeupBean wakeupBean; + private long startNS; + private long endNS; + private final BasicStroke boldStoke = new BasicStroke(2); + private final BasicStroke normalStoke = new BasicStroke(1); + + /** + * Constructor + * + * @param analystPanel component + */ + public ContentPanel(AnalystPanel analystPanel) { + this.analystPanel = analystPanel; + this.setOpaque(false); + setFont(Final.NORMAL_FONT); + } + + /** + * Gets the value of wakeupBean . + * + * @return the value of ohos.devtools.views.trace.bean.WakeupBean + */ + public WakeupBean getWakeupBean() { + return wakeupBean; + } + + /** + * Sets the wakeupBean . + *

You can use getWakeupBean() to get the value of wakeupBean

+ * + * @param wakeup wakeup + */ + public void setWakeupBean(WakeupBean wakeup) { + this.wakeupBean = wakeup; + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + if (graphics instanceof Graphics2D) { + Graphics2D g2 = (Graphics2D) graphics; + g2.setFont(Final.NORMAL_FONT); + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + if (getParent() instanceof TimeViewPort) { + TimeViewPort parent = (TimeViewPort) getParent(); + Rectangle viewRect = parent.getViewRect(); + // Render the line in the viewport display area, and the line beyond the range will not be rendered + fragmentList.stream().filter(fragment -> fragment.visible).filter(fragment -> { + if (fragment != null && fragment.getRect() != null && viewRect != null) { + return Utils.getY(fragment.getRect()) + fragment.getRect().height + >= Utils.getY(viewRect) + TimeViewPort.height + && Utils.getY(fragment.getRect()) <= Utils.getY(viewRect) + viewRect.height; + } else { + return false; + } + }).forEach(fragment -> { + if (fragment != null) { + fragment.draw(g2); + } + }); + } + drawRangeSelect(g2); + drawWakeup(g2); + } + } + + private void drawRangeSelect(Graphics2D g2) { + if (Objects.nonNull(startPoint) && Objects.nonNull(endPoint)) { + var ref = new Object() { + int realY1; + int realY2; + }; + fragmentList.stream().filter(it -> it.visible).filter(it -> it.getDataRect().contains(x1, y1)) + .forEach(it -> ref.realY1 = Utils.getY(it.getRect())); + fragmentList.stream().filter(it -> it.visible).filter(it -> it.getDataRect().contains(x2 - 1, y2 - 1)) + .forEach(it -> ref.realY2 = Utils.getY(it.getRect()) + it.getRect().height); + int tmpWidth = Math.abs(x2 - x1); + int tmpHeight = Math.abs(ref.realY2 - ref.realY1); + Rectangle range = new Rectangle(x1, ref.realY1, tmpWidth, tmpHeight); + if (drawRangeSelect) { + g2.setStroke(new BasicStroke(2)); + g2.setColor(JBColor.foreground().brighter()); + g2.drawRect(Utils.getX(range), Utils.getY(range), range.width, range.height); + } else { + Common.setAlpha(g2, 0.5F); + g2.setColor(JBColor.foreground().brighter()); + g2.fillRect(Utils.getX(range), Utils.getY(range), range.width, range.height); + if (drawRangeSelectData) { + drawRangeSelectData = false; + List rangeFragments = + fragmentList.stream().filter(it -> range.intersects(it.getDataRect())) + .collect(Collectors.toList()); + List process = new ArrayList<>(); + rangeFragments.stream().filter(it -> it instanceof ProcessDataFragment) + .map(it -> (ProcessDataFragment) it).forEach(it -> { + process.addAll(fragmentList.stream().filter(that -> that.parentUuid.equals(it.uuid)) + .collect(Collectors.toList())); + }); + rangeFragments.addAll(process); + List cpu = rangeFragments.stream().filter(it -> it instanceof CpuDataFragment) + .map(it -> ((CpuDataFragment) it).getIndex()).collect(Collectors.toList()); + List threads = rangeFragments.stream().filter(it -> it instanceof ThreadDataFragment) + .map(it -> ((ThreadDataFragment) it).thread.getTid()).collect(Collectors.toList()); + List tracks = rangeFragments.stream().filter(it -> it instanceof MemDataFragment) + .map(it -> ((MemDataFragment) it).mem.getTrackId()).collect(Collectors.toList()); + List functions = rangeFragments.stream().filter(it -> it instanceof FunctionDataFragment) + .map(it -> ((FunctionDataFragment) it).thread.getTid()).collect(Collectors.toList()); + AnalystPanel.LeftRightNS ns = new AnalystPanel.LeftRightNS(); + ns.setLeftNs(rangeStartNS); + ns.setRightNs(rangeEndNS); + this.analystPanel.boxSelection(cpu, threads, tracks, functions, ns); + } + } + Common.setAlpha(g2, 1.0F); + } + } + + /** + * add data line + * + * @param fragment data fragment + */ + public void addDataFragment(AbstractDataFragment fragment) { + fragment.setDataFragmentListener(this); + fragmentList.add(fragment); + } + + /** + * add data line + * + * @param index line index + * @param fragment data fragment + */ + public void addDataFragment(int index, AbstractDataFragment fragment) { + fragment.setDataFragmentListener(this); + fragmentList.add(index, fragment); + } + + /** + * refresh content data + */ + public void refresh() { + List fs = + fragmentList.stream().filter(fragment -> fragment.visible).collect(Collectors.toList()); + int timeViewHeight = TimeViewPort.height; + for (int index = 0, len = fs.size(); index < len; index++) { + AbstractDataFragment dataFragment = fs.get(index); + timeViewHeight += dataFragment.defaultHeight; + dataFragment.getRect().height = dataFragment.defaultHeight; + dataFragment.getDescRect().height = dataFragment.defaultHeight; + dataFragment.getDataRect().height = dataFragment.defaultHeight; + Utils.setY(dataFragment.getRect(), timeViewHeight - dataFragment.defaultHeight); + Utils.setY(dataFragment.getDescRect(), timeViewHeight - dataFragment.defaultHeight); + Utils.setY(dataFragment.getDataRect(), timeViewHeight - dataFragment.defaultHeight); + Utils.setX(dataFragment.getRect(), 0); + Utils.setX(dataFragment.getDescRect(), 0); + Utils.setX(dataFragment.getDataRect(), 200); + } + Dimension dim = new Dimension(0, timeViewHeight); + this.setPreferredSize(dim); + this.setSize(dim); + this.setMaximumSize(dim); + repaint(); + } + + /** + * recycle content data + */ + public void recycle() { + clickFragment = null; + if (fragmentList != null) { + fragmentList.forEach(AbstractDataFragment::recycle); + fragmentList.clear(); + } + } + + /** + * time range change will call this + * + * @param startNS range start ns + * @param endNS range end ns + */ + public void rangeChange(long startNS, long endNS) { + this.startNS = startNS; + this.endNS = endNS; + x1 = (int) getRangeX(rangeStartNS) + 200; + x2 = (int) getRangeX(rangeEndNS) + 200; + fragmentList.forEach(fragment -> fragment.range(startNS, endNS)); + } + + private double getRangeX(long range) { + double xSize = (range - startNS) * (getWidth() - 200) / (endNS - startNS); + if (xSize < 0) { + xSize = 0; + } + if (xSize > getWidth() - 200) { + xSize = getWidth() - 200; + } + return xSize; + } + + @Override + public void collect(AbstractDataFragment fgr) { + if (getParent() instanceof TimeViewPort) { + TimeViewPort viewPort = (TimeViewPort) getParent(); + if (fgr.visible) { + viewPort.favorite(fgr); + } else { + viewPort.cancel(fgr); + } + refresh(); + } + } + + @Override + public void check(AbstractDataFragment fgr) { + } + + private void drawWakeup(Graphics2D graphics) { + if (clickFragment == null || CpuDataFragment.currentSelectedCpuData == null || !AnalystPanel.clicked) { + return; + } + Optional.ofNullable(wakeupBean).ifPresent(wakeup -> { + graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics.setColor(Color.BLACK); + graphics.setStroke(boldStoke); + Rectangle visibleRect = getVisibleRect(); + Rectangle dataRect = clickFragment.getDataRect(); + int wakeupX = clickFragment.getX(wakeup.getWakeupTime()); + if (wakeup.getWakeupTime() > startNS && wakeup.getWakeupTime() < endNS) { + /** + * Draw the vertical line + */ + graphics.drawLine(wakeupX + Utils.getX(dataRect), Utils.getY(visibleRect), + wakeupX + Utils.getX(dataRect), + Utils.getY(visibleRect) + visibleRect.height); + /** + * Draw a diamond First filter out which cpu fragment the wake-up thread is in, + * get the rect of the cpu fragment, and then calculate the coordinates of the drawing diamond + */ + for (AbstractDataFragment dataFragment : fragmentList) { + if (dataFragment instanceof CpuDataFragment) { + if (((CpuDataFragment) dataFragment).getIndex() == wakeup.getWakeupCpu()) { + Rectangle wakeCPURect = dataFragment.getRect(); + final int[] xs = {Utils.getX(dataRect) + wakeupX, Utils.getX(dataRect) + wakeupX + 6, + Utils.getX(dataRect) + wakeupX, + Utils.getX(dataRect) + wakeupX - 6}; + final int[] ys = + {Utils.getY(wakeCPURect) + wakeCPURect.height / 2 - 10, + Utils.getY(wakeCPURect) + wakeCPURect.height / 2, + Utils.getY(wakeCPURect) + wakeCPURect.height / 2 + 10, + Utils.getY(wakeCPURect) + wakeCPURect.height / 2}; + graphics.fillPolygon(xs, ys, xs.length); + break; + } + } + } + } + drawArrayAndText(graphics, dataRect, wakeupX, wakeup); + }); + } + + private void drawArrayAndText(Graphics2D graphics, Rectangle dataRect, int wakeupX, WakeupBean wakeup) { + /** + * Draw arrows and text + */ + CpuData selectCpu = CpuDataFragment.currentSelectedCpuData; + if (selectCpu != null) { + Rectangle rectangle = + new Rectangle(wakeupX + Utils.getX(dataRect), Utils.getY(selectCpu.rect) + selectCpu.rect.height / 2, + Utils.getX(selectCpu.rect) - wakeupX - Utils.getX(dataRect), 30); + if (selectCpu.getStartTime() > startNS && wakeup.getWakeupTime() < endNS) { + graphics.drawLine(Utils.getX(dataRect) + wakeupX, + Utils.getY(selectCpu.rect) + selectCpu.rect.height - 2, + Utils.getX(selectCpu.rect), + Utils.getY(selectCpu.rect) + selectCpu.rect.height - 2); + } + if (rectangle.width > 10) { + if (wakeup.getWakeupTime() > startNS && wakeup.getWakeupTime() < endNS) { + drawArrow(graphics, Utils.getX(dataRect) + wakeupX, + Utils.getY(selectCpu.rect) + selectCpu.rect.height - 2, + -1); + } + if (selectCpu.getStartTime() < endNS && selectCpu.getStartTime() > startNS) { + drawArrow(graphics, Utils.getX(selectCpu.rect), + Utils.getY(selectCpu.rect) + selectCpu.rect.height - 2, 1); + } + } + if (wakeup.getWakeupTime() < endNS && selectCpu.getStartTime() > startNS) { + long offsetTime = selectCpu.getStartTime() - wakeup.getWakeupTime(); + String timeString = TimeUtils.getTimeString(offsetTime); + Utils.setY(rectangle, Utils.getY(rectangle) - 5); + selectCpu.drawString(graphics, rectangle, timeString, AbstractNode.Placement.CENTER); + } + } + graphics.setStroke(normalStoke); + } + + /** + * repaint panel + */ + public void clearWakeupAndBoxSelect() { + if (Objects.nonNull(startPoint) || Objects.nonNull(endPoint) || Objects.nonNull(wakeupBean)) { + drawRangeSelect = false; + drawRangeSelectData = false; + startPoint = null; + endPoint = null; + repaint(); + } + } + + private void drawArrow(Graphics2D graphics, int xVal, int yVal, int align) { + if (align == -1) { + final int[] xArray = {xVal, xVal + 5, xVal + 5}; + final int[] yArray = {yVal, yVal - 5, yVal + 5}; + graphics.fillPolygon(xArray, yArray, xArray.length); + } + if (align == 1) { + final int[] xArray = {xVal, xVal - 5, xVal - 5}; + final int[] yArray = {yVal, yVal - 5, yVal + 5}; + graphics.fillPolygon(xArray, yArray, xArray.length); + } + } + + /** + * Jump to the cpu line and select the node where startTime starts + * + * @param cpu cpu + * @param startTime startTime + */ + public void scrollToCpu(int cpu, long startTime) { + fragmentList.stream().filter(CpuDataFragment.class::isInstance).map(it -> ((CpuDataFragment) it)) + .filter(it -> it.getIndex() == cpu).findFirst().ifPresent(it -> { + if (getParent() instanceof JViewport) { + JViewport parent = (JViewport) getParent(); + if (it.getData() != null) { + it.getData().stream().filter(cpuData -> cpuData.getStartTime() == startTime).findFirst() + .ifPresent(cpuData -> it.click(null, cpuData)); + } else { + it.delayClickStartTime = startTime; + } + JBScrollPane scrollPane = (JBScrollPane) parent.getParent(); + scrollPane.getVerticalScrollBar().setValue(0); + } + }); + } + + /** + * Jump to the specified location + * + * @param processId processId + * @param tid tid + * @param startTime startTime + * @param offsetHeight tab height + */ + public void scrollToThread(int processId, int tid, long startTime, int offsetHeight) { + fragmentList.stream().filter(ProcessDataFragment.class::isInstance).map(it -> ((ProcessDataFragment) it)) + .filter(it -> it.getProcess().getPid() == processId).findFirst().ifPresent(it -> { + if (getParent() instanceof JViewport) { + JViewport parent = (JViewport) getParent(); + it.expandThreads(); + + SwingUtilities.invokeLater(() -> { + fragmentList.stream().filter(ThreadDataFragment.class::isInstance) + .map(th -> ((ThreadDataFragment) th)) + .filter(th -> th.thread.getTid() == tid && th.parentUuid.equals(it.uuid)).findFirst() + .ifPresent(th -> { + // If the thread data has been loaded, data is not empty, + // find the node whose start time is startTime, and select it + if (th.getData() != null) { + th.getData().stream() + .filter(threadData -> threadData.getStartTime() == startTime) + .findFirst().ifPresent(threadData -> { + th.click(null, threadData); + }); + } else { + // If the thread data has not been loaded yet, + // save the start time of the node to be selected, + // the load Data() method in the component will process this field, + // select it directly after loading, + // and then set the delay Click Start Time to null + th.delayClickStartTime = startTime; + } + parent.scrollRectToVisible( + new Rectangle(Utils.getX(th.getRect()), Utils.getY(th.getRect()) + offsetHeight, + th.getRect().width, + th.getRect().height)); + }); + }); + } + }); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/FTableModel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/FTableModel.java new file mode 100644 index 000000000..1f4fde3c4 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/FTableModel.java @@ -0,0 +1,104 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import javax.swing.table.AbstractTableModel; +import java.util.ArrayList; +import java.util.List; + +/** + * FTableModel + * + * @param obj + * @date: 2021/5/24 11:57 + */ +public class FTableModel extends AbstractTableModel { + private List> columnNames; + private List dataSource = new ArrayList<>(); + + /** + * set columns + * + * @param columns columns + */ + public void setColumns(List> columns) { + this.columnNames = columns; + } + + public void setDataSource(final List param) { + this.dataSource = param; + } + + @Override + public int getRowCount() { + return dataSource.size(); + } + + @Override + public int getColumnCount() { + return columnNames == null ? 0 : columnNames.size(); + } + + @Override + public String getColumnName(int column) { + return columnNames.get(column).name; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + return columnNames.get(columnIndex).callable.map(dataSource.get(rowIndex)); + } + + /** + * Process map + * + * @param Data + */ + public interface Process { + /** + * map + * + * @param obj obj + * @return Object object + */ + Object map(T obj); + } + + /** + * Column + * + * @param obj + * @date: 2021/5/24 11:57 + */ + public static class Column { + /** + * name + */ + public String name; + private Process callable; + + /** + * construct + * + * @param name name + * @param callable callable + */ + public Column(String name, Process callable) { + this.name = name; + this.callable = callable; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollFlagPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollFlagPanel.java index ec257a74b..722cebf9a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollFlagPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollFlagPanel.java @@ -22,6 +22,7 @@ import ohos.devtools.views.trace.bean.FlagBean; import ohos.devtools.views.trace.listener.IFlagListener; import ohos.devtools.views.trace.util.Final; import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; import javax.swing.JButton; import javax.swing.JColorChooser; @@ -83,8 +84,8 @@ public class ScrollFlagPanel extends BottomScrollPanel { public void componentResized(ComponentEvent componentEvent) { super.componentResized(componentEvent); Rectangle rootBounds = layer.getBounds(); - box.setBounds(rootBounds.x + 10, rootBounds.y + 10, - rootBounds.width - 20, 40); + box.setBounds(Utils.getX(rootBounds) + 10, Utils.getY(rootBounds) + 10, + rootBounds.width - 20, 40); } }); input.addKeyListener(new KeyAdapter() { @@ -182,7 +183,7 @@ public class ScrollFlagPanel extends BottomScrollPanel { */ public void selectColor() { JDialog dialog = JColorChooser.createDialog(getRootPane(), "Choose Color", true, colorChooser, - actionEvent -> setCurrentColor(colorChooser.getColor()), null); + actionEvent -> setCurrentColor(colorChooser.getColor()), null); dialog.setVisible(true); } diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollSlicePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollSlicePanel.java index 7045aa4e2..a40944652 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollSlicePanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollSlicePanel.java @@ -1,355 +1,355 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBBox; -import ohos.devtools.views.trace.bean.WakeupBean; -import ohos.devtools.views.trace.listener.IScrollSliceLinkListener; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.TimeUtils; -import ohos.devtools.views.trace.util.Utils; - -import javax.imageio.ImageIO; -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Cursor; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * bottom Slice panel - * - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ -public class ScrollSlicePanel extends BottomScrollPanel { - private Font font = getFont(); - private List comps = new ArrayList<>(); - private List dataSource; - private WakeupBean wakeupBean; - private IScrollSliceLinkListener listener; - - /** - * set component data source - * - * @param title table title - * @param dataSource table data source - * @param wakeupBean wakeup data information - */ - public void setData(String title, List dataSource, WakeupBean wakeupBean) { - this.dataSource = dataSource; - this.wakeupBean = wakeupBean; - box.removeAll(); - JBBox b1 = JBBox.createVerticalBox(); - b1.add(new TitlePanel(title)); - comps.clear(); - if (dataSource != null) { - for (SliceData sliceData : dataSource) { - LineComponent lc = new LineComponent(sliceData.key, sliceData.value == null ? "" : sliceData.value, - sliceData.linkable); - lc.setListener(listener); - comps.add(lc); - b1.add(lc); - } - } - b1.add(JBBox.createVerticalGlue()); - JBBox b2 = JBBox.createVerticalBox(); - b2.add(new RightPanel()); - b2.add(JBBox.createVerticalGlue()); - box.add(b1); - box.add(b2); - revalidate(); - } - - /** - * set link click listener - * - * @param listener listener - */ - public void setScrollSliceLinkListener(IScrollSliceLinkListener listener) { - this.listener = listener; - for (LineComponent comp : comps) { - if (comp.linkable) { - comp.setListener(listener); - } - } - } - - /** - * create table line data - * - * @param key key - * @param value value - * @param linkable link - * @return SliceData data - */ - public static SliceData createSliceData(String key, String value, boolean linkable) { - SliceData data = new SliceData(); - data.key = key; - data.value = value; - data.linkable = linkable; - return data; - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - public static class SliceData { - /** - * parameter key - */ - public String key; - - /** - * parameter value - */ - public String value; - - /** - * parameter linkable - */ - public boolean linkable; - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - class RightPanel extends ChildPanel { - private final int[][] pointX = {{11, 2, 11, 20}, {13, 13, 18, 20, 15, 20, 18}, {103, 103, 98, 96, 101, 96, 98}}; - private final int[][] pointY = {{50, 58, 66, 58}, {120, 124, 129, 127, 122, 117, 115}}; - private final int strStartX = 30; - private final int lineCharSize = 60; - - /** - * RightPanel constructor - */ - public RightPanel() { - super(0, 222); - } - - /** - * paint - * - * @param graphics graphics - */ - @Override - public void paint(Graphics graphics) { - super.paint(graphics); - setFont(Final.NORMAL_FONT); - if (wakeupBean == null || wakeupBean.getWakeupProcess() == null) { - return; - } - graphics.setFont(font.deriveFont(13f)); - if (graphics instanceof Graphics2D) { - ((Graphics2D) graphics) - .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - ((Graphics2D) graphics) - .setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - } - graphics.drawString("Scheduling Latency", 10, 20); - graphics.fillRect(10, 30, 3, 130); - graphics.fillPolygon(pointX[0], pointY[0], pointX[0].length); - graphics.fillPolygon(pointX[1], pointY[1], pointX[1].length); - graphics.fillPolygon(pointX[2], pointY[1], pointX[2].length); - graphics.fillRect(13, 121, 90, 3); - graphics.setFont(font.deriveFont(11f)); - graphics.drawString( - "Wakeup @" + TimeUtils.getTimeString(wakeupBean.getWakeupTime()) + " on CPU " + wakeupBean - .getWakeupCpu() + " by", strStartX, 55); - graphics - .drawString("P:" + wakeupBean.getWakeupProcess() + " [ " + wakeupBean.getWakeupPid() + " ]", strStartX, - 75); - graphics - .drawString("T:" + wakeupBean.getWakeupThread() + " [ " + wakeupBean.getWakeupTid() + " ]", strStartX, - 95); - graphics.drawString("Scheduling latency:" + TimeUtils.getTimeString(wakeupBean.getSchedulingLatency()), 115, - 125); - graphics.setFont(font.deriveFont(9f)); - graphics.setColor(new Color(0x88, 0x88, 0x88)); - int lines = wakeupBean.getSchedulingDesc().length() % lineCharSize == 0 ? - wakeupBean.getSchedulingDesc().length() / lineCharSize : - wakeupBean.getSchedulingDesc().length() / lineCharSize + 1; - for (int index = 0; index < lines; index++) { - String str = ""; - if (index == lines - 1) { - str = wakeupBean.getSchedulingDesc().substring(index * lineCharSize); - } else { - str = wakeupBean.getSchedulingDesc().substring(index * lineCharSize, (index + 1) * lineCharSize); - } - graphics.drawString(str, 115, 142 + index * 14); - } - setFont(Final.NORMAL_FONT); - } - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - class TitlePanel extends ChildLineComponent { - private String title; - - /** - * set title - */ - public TitlePanel(String title) { - this.title = title; - setFont(Final.NORMAL_FONT); - } - - /** - * paint - * - * @param graphics graphics - */ - @Override - public void paint(Graphics graphics) { - super.paint(graphics); - graphics.setFont(font.deriveFont(13f)); - graphics.drawString(title, 10, 20); - } - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - class LineComponent extends ChildLineComponent { - /** - * linkable - */ - public boolean linkable; - - private String key; - - private String value; - - private IScrollSliceLinkListener listener; - - private Rectangle linkRect; - - private final int leftW = 200; - - /** - * LineComponent constructor - * - * @param key key - * @param value value - * @param linkable linkable - */ - public LineComponent(String key, String value, boolean linkable) { - super(); - this.key = key; - this.value = value; - this.linkable = linkable; - addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseMoved(final MouseEvent event) { - if (Utils.pointInRect(linkRect, event.getX(), event.getY())) { - setCursor(new Cursor(Cursor.HAND_CURSOR)); - } else { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - } - }); - } - - /** - * set link listener - * - * @param listener listener - */ - public void setListener(IScrollSliceLinkListener listener) { - this.listener = listener; - } - - /** - * child mouse clicked - * - * @param event event - */ - @Override - public void childMouseClicked(final MouseEvent event) { - if (Utils.pointInRect(linkRect, event.getX(), event.getY())) { - if (listener != null) { - listener.linkClick(value); - } - } - } - - /** - * paint - * - * @param graphics graphics - */ - @Override - public void paint(Graphics graphics) { - super.paint(graphics); - graphics.setFont(font.deriveFont(11f)); - if (graphics instanceof Graphics2D) { - ((Graphics2D) graphics) - .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - } - if (mouseIn) { - if (graphics instanceof Graphics2D) { - graphics.setColor(getForeground()); - Composite originalComposite = ((Graphics2D) graphics).getComposite(); - ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); - graphics.fillRect(0, 0, leftW - 2, lineHeight); - graphics.fillRect(leftW, 0, getWidth() - leftW, lineHeight); - ((Graphics2D) graphics).setComposite(originalComposite); - } - } - graphics.setColor(getForeground()); - graphics.drawString(key, 10, lineHeight / 2 + 4); - int sw = getWidth() - (leftW + 2); - int chars = sw / 7; - if (value.length() > chars && chars > 0) { - String vs1 = value.substring(0, chars); - String vs2 = value.substring(chars, value.length() - 1); - graphics.drawString(vs1, leftW + 2, lineHeight / 3); - graphics.drawString(vs2, leftW + 2, (lineHeight * 2) / 3); - } else { - graphics.drawString(value, leftW, lineHeight / 2 + 4); - } - if (linkable) { - try { - if (value != null && value.length() > 0) { - Rectangle2D bounds = graphics.getFontMetrics(font).getStringBounds(value, graphics); - linkRect = new Rectangle((int) (202 + bounds.getWidth() + 5), (lineHeight - 20) / 2, 20, 20); - Image link = ImageIO.read(getClass().getResourceAsStream("/assets/link.png")); - graphics.drawImage(link, linkRect.x + 2, linkRect.y + 3, 15, 15, null); - } - } catch (IOException ioException) { - ioException.printStackTrace(); - } - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBBox; +import ohos.devtools.views.trace.bean.WakeupBean; +import ohos.devtools.views.trace.listener.IScrollSliceLinkListener; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.imageio.ImageIO; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Composite; +import java.awt.Cursor; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.awt.geom.Rectangle2D; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * bottom Slice panel + * + * @date 2021/04/20 12:24 + */ +public class ScrollSlicePanel extends BottomScrollPanel { + private Font font = getFont(); + private List comps = new ArrayList<>(); + private List dataSource; + private WakeupBean wakeupBean; + private IScrollSliceLinkListener listener; + + /** + * create table line data + * + * @param key key + * @param value value + * @param linkable link + * @return SliceData data + */ + public static SliceData createSliceData(String key, String value, boolean linkable) { + SliceData data = new SliceData(); + data.key = key; + data.value = value; + data.linkable = linkable; + return data; + } + + /** + * set component data source + * + * @param title table title + * @param dataSource table data source + * @param wakeupBean wakeup data information + */ + public void setData(String title, List dataSource, WakeupBean wakeupBean) { + this.dataSource = dataSource; + this.wakeupBean = wakeupBean; + box.removeAll(); + JBBox b1 = JBBox.createVerticalBox(); + b1.add(new TitlePanel(title)); + comps.clear(); + if (dataSource != null) { + for (SliceData sliceData : dataSource) { + LineComponent lc = new LineComponent(sliceData.key, sliceData.value == null ? "" : sliceData.value, + sliceData.linkable); + lc.setListener(listener); + comps.add(lc); + b1.add(lc); + } + } + b1.add(JBBox.createVerticalGlue()); + JBBox b2 = JBBox.createVerticalBox(); + b2.add(new RightPanel()); + b2.add(JBBox.createVerticalGlue()); + box.add(b1); + box.add(b2); + revalidate(); + } + + /** + * set link click listener + * + * @param listener listener + */ + public void setScrollSliceLinkListener(IScrollSliceLinkListener listener) { + this.listener = listener; + for (LineComponent comp : comps) { + if (comp.linkable) { + comp.setListener(listener); + } + } + } + + /** + * SliceData + * + * @date 2021/04/20 12:24 + */ + public static class SliceData { + /** + * parameter key + */ + public String key; + + /** + * parameter value + */ + public String value; + + /** + * parameter linkable + */ + public boolean linkable; + } + + /** + * RightPanel + * + * @date 2021/04/20 12:24 + */ + class RightPanel extends ChildPanel { + private final int[][] pointX = {{11, 2, 11, 20}, {13, 13, 18, 20, 15, 20, 18}, {103, 103, 98, 96, 101, 96, 98}}; + private final int[][] pointY = {{50, 58, 66, 58}, {120, 124, 129, 127, 122, 117, 115}}; + private final int strStartX = 30; + private final int lineCharSize = 60; + + /** + * RightPanel constructor + */ + public RightPanel() { + super(0, 222); + } + + /** + * paint + * + * @param graphics graphics + */ + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + setFont(Final.NORMAL_FONT); + if (wakeupBean == null || wakeupBean.getWakeupProcess() == null) { + return; + } + graphics.setFont(font.deriveFont(13f)); + if (graphics instanceof Graphics2D) { + ((Graphics2D) graphics) + .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + ((Graphics2D) graphics) + .setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + } + graphics.drawString("Scheduling Latency", 10, 20); + graphics.fillRect(10, 30, 3, 130); + graphics.fillPolygon(pointX[0], pointY[0], pointX[0].length); + graphics.fillPolygon(pointX[1], pointY[1], pointX[1].length); + graphics.fillPolygon(pointX[2], pointY[1], pointX[2].length); + graphics.fillRect(13, 121, 90, 3); + graphics.setFont(font.deriveFont(11f)); + graphics.drawString( + "Wakeup @" + TimeUtils.getTimeString(wakeupBean.getWakeupTime()) + " on CPU " + wakeupBean + .getWakeupCpu() + " by", strStartX, 55); + graphics + .drawString("P:" + wakeupBean.getWakeupProcess() + " [ " + wakeupBean.getWakeupPid() + " ]", strStartX, + 75); + graphics + .drawString("T:" + wakeupBean.getWakeupThread() + " [ " + wakeupBean.getWakeupTid() + " ]", strStartX, + 95); + graphics.drawString("Scheduling latency:" + TimeUtils.getTimeString(wakeupBean.getSchedulingLatency()), 115, + 125); + graphics.setFont(font.deriveFont(9f)); + graphics.setColor(new Color(0x88, 0x88, 0x88)); + int lines = wakeupBean.getSchedulingDesc().length() % lineCharSize == 0 ? + wakeupBean.getSchedulingDesc().length() / lineCharSize : + wakeupBean.getSchedulingDesc().length() / lineCharSize + 1; + for (int index = 0; index < lines; index++) { + String str = ""; + if (index == lines - 1) { + str = wakeupBean.getSchedulingDesc().substring(index * lineCharSize); + } else { + str = wakeupBean.getSchedulingDesc().substring(index * lineCharSize, (index + 1) * lineCharSize); + } + graphics.drawString(str, 115, 142 + index * 14); + } + setFont(Final.NORMAL_FONT); + } + } + + /** + * TitlePanel + * + * @date 2021/04/20 12:24 + */ + class TitlePanel extends ChildLineComponent { + private String title; + + /** + * set title + */ + public TitlePanel(String title) { + this.title = title; + setFont(Final.NORMAL_FONT); + } + + /** + * paint + * + * @param graphics graphics + */ + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + graphics.setFont(font.deriveFont(13f)); + graphics.drawString(title, 10, 20); + } + } + + /** + * LineComponent + * + * @date 2021/04/20 12:24 + */ + class LineComponent extends ChildLineComponent { + private final int leftW = 200; + + /** + * linkable + */ + public boolean linkable; + + private String key; + private String value; + private IScrollSliceLinkListener listener; + private Rectangle linkRect; + + /** + * LineComponent constructor + * + * @param key key + * @param value value + * @param linkable linkable + */ + public LineComponent(String key, String value, boolean linkable) { + super(); + this.key = key; + this.value = value; + this.linkable = linkable; + addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseMoved(final MouseEvent event) { + if (Utils.pointInRect(linkRect, event.getX(), event.getY())) { + setCursor(new Cursor(Cursor.HAND_CURSOR)); + } else { + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + } + }); + } + + /** + * set link listener + * + * @param listener listener + */ + public void setListener(IScrollSliceLinkListener listener) { + this.listener = listener; + } + + /** + * child mouse clicked + * + * @param event event + */ + @Override + public void childMouseClicked(final MouseEvent event) { + if (Utils.pointInRect(linkRect, event.getX(), event.getY())) { + if (listener != null) { + listener.linkClick(value); + } + } + } + + /** + * paint + * + * @param graphics graphics + */ + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + graphics.setFont(font.deriveFont(11f)); + if (graphics instanceof Graphics2D) { + ((Graphics2D) graphics) + .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + } + if (mouseIn) { + if (graphics instanceof Graphics2D) { + graphics.setColor(getForeground()); + Composite originalComposite = ((Graphics2D) graphics).getComposite(); + ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); + graphics.fillRect(0, 0, leftW - 2, lineHeight); + graphics.fillRect(leftW, 0, getWidth() - leftW, lineHeight); + ((Graphics2D) graphics).setComposite(originalComposite); + } + } + graphics.setColor(getForeground()); + graphics.drawString(key, 10, lineHeight / 2 + 4); + int sw = getWidth() - (leftW + 2); + int chars = sw / 7; + if (value.length() > chars && chars > 0) { + String vs1 = value.substring(0, chars); + String vs2 = value.substring(chars, value.length() - 1); + graphics.drawString(vs1, leftW + 2, lineHeight / 3); + graphics.drawString(vs2, leftW + 2, (lineHeight * 2) / 3); + } else { + graphics.drawString(value, leftW, lineHeight / 2 + 4); + } + if (linkable) { + try { + if (value != null && value.length() > 0) { + Rectangle2D bounds = graphics.getFontMetrics(font).getStringBounds(value, graphics); + linkRect = new Rectangle((int) (202 + bounds.getWidth() + 5), (lineHeight - 20) / 2, 20, 20); + Image link = ImageIO.read(getClass().getResourceAsStream("/assets/link.png")); + graphics.drawImage(link, Utils.getX(linkRect) + 2, Utils.getY(linkRect) + 3, 15, 15, null); + } + } catch (IOException ioException) { + ioException.printStackTrace(); + } + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollTablePanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollTablePanel.java index e36fb07a6..2cc029d85 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollTablePanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/ScrollTablePanel.java @@ -1,224 +1,232 @@ -/* - * 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. - */ -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBBox; -import ohos.devtools.views.trace.bean.CPUProcessBean; -import ohos.devtools.views.trace.bean.CPUThreadBean; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.Utils; - -import javax.imageio.ImageIO; -import java.awt.AlphaComposite; -import java.awt.Composite; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Scroll table component - * - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ -public class ScrollTablePanel extends BottomScrollPanel { - private String[] columns; - private List dataSource = new ArrayList<>(); - - /** - * Constructor - * - * @param columns columns - * @param dataSource dataSource - */ - public ScrollTablePanel(String[] columns, ArrayList dataSource) { - super(); - setFont(Final.NORMAL_FONT); - box = JBBox.createVerticalBox(); - setViewportView(box); - setColumnsAndData(columns, dataSource); - } - - /** - * Set up columns and data sources - * - * @param columns columns - * @param dataSource dataSource - */ - public void setColumnsAndData(String[] columns, ArrayList dataSource) { - this.columns = columns; - this.dataSource = dataSource; - box.removeAll(); - if (columns != null) { - box.add(new TitleComponent()); - } - if (dataSource != null) { - for (Object obj : dataSource) { - box.add(new LineComponent(obj, columns.length)); - } - } - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - class TitleComponent extends ChildLineComponent { - private Rectangle[] rects = new Rectangle[columns.length]; - private int[] filters = {-1, -1}; - - @Override - public void childMouseClicked(final MouseEvent event) { - for (int index = 0; index < rects.length; index++) { - if (Utils.pointInRect(rects[index], event.getX(), event.getY())) { - if (filters[0] == index) { - filters[1] = filters[1] == 0 ? 1 : 0; - } else { - filters[0] = index; - filters[1] = 0; - } - repaint(); - return; - } - } - } - - @Override - public void paint(Graphics graphics) { - if (columns.length == 0) { - return; - } - graphics.setColor(getForeground()); - graphics.clearRect(0, 0, getWidth(), lineHeight); - graphics.setFont(getFont().deriveFont(Font.BOLD, 12f)); - int width = (getWidth() - 20) / columns.length; - if (mouseIn) { - if (graphics instanceof Graphics2D) { - Composite originalComposite = ((Graphics2D) graphics).getComposite(); - ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); - graphics.setColor(getForeground()); - graphics.fillRect(0, 0, getWidth(), lineHeight); - ((Graphics2D) graphics).setComposite(originalComposite); - } - graphics.setColor(getBackground()); - for (int index = 0; index < columns.length; index++) { - if (rects[index] == null) { - rects[index] = new Rectangle(10 + index * width - 4, 0, width - 2, lineHeight); - } - if (index > 0) { - graphics.fillRect(rects[index].x, rects[index].y, 2, rects[index].height); - } - } - } - graphics.setColor(getForeground()); - for (int index = 0; index < columns.length; index++) { - Rectangle2D bounds = graphics.getFontMetrics().getStringBounds(columns[index], graphics); - graphics.drawString(columns[index], 10 + index * width, lineHeight / 2 + 4); - if (index == filters[0]) { - try { - int xVal = (int) (10 + index * width + bounds.getWidth() + 10); - Image img = ImageIO.read( - getClass().getResourceAsStream(filters[1] == 0 ? "/assets/down.png" : "/assets/up.png")); - graphics.drawImage(img, xVal, (lineHeight - 20) / 2, 20, 20, null); - } catch (IOException ioException) { - ioException.printStackTrace(); - } - } - } - } - } - - /** - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ - class LineComponent extends ChildLineComponent { - private Object data; - private int columnSize = 7; - private final int xAxis = 10; - - public LineComponent(Object data, int columnSize) { - super(); - this.data = data; - this.columnSize = columnSize; - } - - @Override - public void paint(Graphics graphics) { - graphics.setColor(getForeground()); - graphics.clearRect(0, 0, getWidth(), lineHeight); - graphics.setFont(getFont().deriveFont(11f)); - int width = (getWidth() - 20) / columnSize; - if (mouseIn) { - graphics.setColor(getForeground()); - Composite originalComposite = ((Graphics2D) graphics).getComposite(); - ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); - graphics.fillRect(0, 0, getWidth(), lineHeight); - ((Graphics2D) graphics).setComposite(originalComposite); - graphics.setColor(getBackground()); - for (int index = 0; index < columns.length; index++) { - if (index > 0) { - graphics.fillRect(xAxis + index * width - 4, 0, 2, lineHeight); - } - } - } - graphics.setColor(getForeground()); - int yNum = lineHeight / 2 + 4; - if (data instanceof CPUThreadBean) { - drawString(graphics, xAxis, yNum, width - 2, ((CPUThreadBean) data).getProcess()); - drawString(graphics, xAxis + 1 * width, yNum, width - 2, ((CPUThreadBean) data).getPid()); - drawString(graphics, xAxis + 2 * width, yNum, width - 2, ((CPUThreadBean) data).getThread()); - drawString(graphics, xAxis + 3 * width, yNum, width - 2, ((CPUThreadBean) data).getTid()); - drawString(graphics, xAxis + 4 * width, yNum, width - 2, ((CPUThreadBean) data).getWallDuration() + ""); - drawString(graphics, xAxis + 5 * width, yNum, width - 2, ((CPUThreadBean) data).getAvgDuration() + ""); - drawString(graphics, xAxis + 6 * width, yNum, width - 2, ((CPUThreadBean) data).getOccurrences()); - } - if (data instanceof CPUProcessBean) { - drawString(graphics, xAxis, yNum, width - 2, ((CPUProcessBean) data).getProcess()); - drawString(graphics, xAxis + 1 * width, yNum, width - 2, ((CPUProcessBean) data).getPid()); - drawString(graphics, xAxis + 2 * width, yNum, width - 2, - ((CPUProcessBean) data).getWallDuration() + ""); - drawString(graphics, xAxis + 3 * width, yNum, width - 2, ((CPUProcessBean) data).getAvgDuration() + ""); - drawString(graphics, xAxis + 4 * width, yNum, width - 2, ((CPUProcessBean) data).getOccurrences()); - } - } - - /** - * draw String - * - * @param graphics graphics - * @param xAxis xAxis - * @param yAxis yAxis - * @param width width - * @param str string - */ - private void drawString(Graphics graphics, int xAxis, int yAxis, int width, String str) { - int size = width / 7; - if (str.length() > size) { - graphics.drawString(str.substring(0, size) + "...", xAxis, yAxis); - } else { - graphics.drawString(str, xAxis, yAxis); - } - } - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBBox; +import ohos.devtools.views.trace.bean.CPUProcessBean; +import ohos.devtools.views.trace.bean.CPUThreadBean; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.imageio.ImageIO; +import java.awt.AlphaComposite; +import java.awt.Composite; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Scroll table component + * + * @date 2021/04/20 12:24 + */ +@Deprecated +public class ScrollTablePanel extends BottomScrollPanel { + private String[] columns; + private List dataSource = new ArrayList<>(); + + /** + * Constructor + * + * @param columns columns + * @param dataSource dataSource + */ + public ScrollTablePanel(String[] columns, ArrayList dataSource) { + super(); + setFont(Final.NORMAL_FONT); + box = JBBox.createVerticalBox(); + setViewportView(box); + setColumnsAndData(columns, dataSource); + } + + /** + * Set up columns and data sources + * + * @param columns columns + * @param dataSource dataSource + */ + public void setColumnsAndData(String[] columns, ArrayList dataSource) { + this.columns = columns; + this.dataSource = dataSource; + box.removeAll(); + if (columns != null) { + box.add(new TitleComponent()); + } + if (dataSource != null) { + for (Object obj : dataSource) { + box.add(new LineComponent(obj, columns.length)); + } + } + } + + /** + * TitleComponent + * + * @date 2021/04/20 12:24 + */ + class TitleComponent extends ChildLineComponent { + private Rectangle[] rects = new Rectangle[columns.length]; + private int[] filters = {-1, -1}; + + @Override + public void childMouseClicked(final MouseEvent event) { + for (int index = 0; index < rects.length; index++) { + if (Utils.pointInRect(rects[index], event.getX(), event.getY())) { + if (filters[0] == index) { + filters[1] = filters[1] == 0 ? 1 : 0; + } else { + filters[0] = index; + filters[1] = 0; + } + repaint(); + return; + } + } + } + + @Override + public void paint(Graphics graphics) { + if (columns.length == 0) { + return; + } + graphics.setColor(getForeground()); + graphics.clearRect(0, 0, getWidth(), lineHeight); + graphics.setFont(getFont().deriveFont(Font.BOLD, 12f)); + int width = (getWidth() - 20) / columns.length; + if (mouseIn) { + if (graphics instanceof Graphics2D) { + Composite originalComposite = ((Graphics2D) graphics).getComposite(); + ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); + graphics.setColor(getForeground()); + graphics.fillRect(0, 0, getWidth(), lineHeight); + ((Graphics2D) graphics).setComposite(originalComposite); + } + graphics.setColor(getBackground()); + for (int index = 0; index < columns.length; index++) { + if (rects[index] == null) { + rects[index] = new Rectangle(10 + index * width - 4, 0, width - 2, lineHeight); + } + if (index > 0) { + graphics.fillRect(Utils.getX(rects[index]), Utils.getY(rects[index]), 2, rects[index].height); + } + } + } + graphics.setColor(getForeground()); + for (int index = 0; index < columns.length; index++) { + Rectangle2D bounds = graphics.getFontMetrics().getStringBounds(columns[index], graphics); + graphics.drawString(columns[index], 10 + index * width, lineHeight / 2 + 4); + if (index == filters[0]) { + try { + int xVal = (int) (10 + index * width + bounds.getWidth() + 10); + Image img = ImageIO.read( + getClass().getResourceAsStream(filters[1] == 0 ? "/assets/down.png" : "/assets/up.png")); + graphics.drawImage(img, xVal, (lineHeight - 20) / 2, 20, 20, null); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + } + } + } + } + + /** + * LineComponent + * + * @date 2021/04/20 12:24 + */ + class LineComponent extends ChildLineComponent { + private final int xAxis = 10; + private Object data; + private int columnSize = 7; + + /** + * Construction + * + * @param data Bean of Cpu + * @param columnSize size of column size + */ + public LineComponent(Object data, int columnSize) { + super(); + this.data = data; + this.columnSize = columnSize; + } + + @Override + public void paint(Graphics graphics) { + graphics.setColor(getForeground()); + graphics.clearRect(0, 0, getWidth(), lineHeight); + graphics.setFont(getFont().deriveFont(11f)); + int width = (getWidth() - 20) / columnSize; + if (mouseIn) { + graphics.setColor(getForeground()); + Composite originalComposite = ((Graphics2D) graphics).getComposite(); + ((Graphics2D) graphics).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f)); + graphics.fillRect(0, 0, getWidth(), lineHeight); + ((Graphics2D) graphics).setComposite(originalComposite); + graphics.setColor(getBackground()); + for (int index = 0; index < columns.length; index++) { + if (index > 0) { + graphics.fillRect(xAxis + index * width - 4, 0, 2, lineHeight); + } + } + } + graphics.setColor(getForeground()); + int yNum = lineHeight / 2 + 4; + if (data instanceof CPUThreadBean) { + drawString(graphics, xAxis, yNum, width - 2, ((CPUThreadBean) data).getProcess()); + drawString(graphics, xAxis + 1 * width, yNum, width - 2, ((CPUThreadBean) data).getPid()); + drawString(graphics, xAxis + 2 * width, yNum, width - 2, ((CPUThreadBean) data).getThread()); + drawString(graphics, xAxis + 3 * width, yNum, width - 2, ((CPUThreadBean) data).getTid()); + drawString(graphics, xAxis + 4 * width, yNum, width - 2, ((CPUThreadBean) data).getWallDuration() + ""); + drawString(graphics, xAxis + 5 * width, yNum, width - 2, ((CPUThreadBean) data).getAvgDuration() + ""); + drawString(graphics, xAxis + 6 * width, yNum, width - 2, ((CPUThreadBean) data).getOccurrences()); + } + if (data instanceof CPUProcessBean) { + drawString(graphics, xAxis, yNum, width - 2, ((CPUProcessBean) data).getProcess()); + drawString(graphics, xAxis + 1 * width, yNum, width - 2, ((CPUProcessBean) data).getPid()); + drawString(graphics, xAxis + 2 * width, yNum, width - 2, + ((CPUProcessBean) data).getWallDuration() + ""); + drawString(graphics, xAxis + 3 * width, yNum, width - 2, ((CPUProcessBean) data).getAvgDuration() + ""); + drawString(graphics, xAxis + 4 * width, yNum, width - 2, ((CPUProcessBean) data).getOccurrences()); + } + } + + /** + * draw String + * + * @param graphics graphics + * @param xAxis xAxis + * @param yAxis yAxis + * @param width width + * @param str string + */ + private void drawString(Graphics graphics, int xAxis, int yAxis, int width, String str) { + int size = width / 7; + if (str.length() > size) { + graphics.drawString(str.substring(0, size) + "...", xAxis, yAxis); + } else { + graphics.drawString(str, xAxis, yAxis); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/StackBar.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/StackBar.java new file mode 100644 index 000000000..debd5d3e8 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/StackBar.java @@ -0,0 +1,177 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import ohos.devtools.views.trace.bean.TabThreadStatesBean; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JPanel; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionListener; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * StackBar + * + * @date: 2021/5/27 12:03 + */ +public class StackBar extends JPanel { + private List source = new ArrayList<>(); + private long totalWallDuration; + private StateValue current; + private BigDecimal charW = BigDecimal.valueOf(getFontMetrics(getFont().deriveFont(11.0f)).charWidth('a') ) + .subtract(new BigDecimal( 0.2)); + private int drawX = 0; + + /** + * structure function + */ + public StackBar() { + addMouseMotionListener(new MouseMotionListener() { + @Override + public void mouseDragged(final MouseEvent event) { + } + + @Override + public void mouseMoved(final MouseEvent event) { + for (int index = 0, size = source.size(); index < size; index++) { + if (Utils.pointInRect(source.get(index).drawRect, event.getX(), event.getY())) { + if (current != source.get(index)) { + current = source.get(index); + repaint(); + } + break; + } + } + } + }); + addMouseListener(new MouseAdapter() { + @Override + public void mouseExited(final MouseEvent event) { + super.mouseMoved(event); + current = null; + } + }); + } + + /** + * set data source + * + * @param data data + */ + public void setSource(final List data) { + source.clear(); + if (data != null) { + Map> collect = + data.stream().collect(Collectors.groupingBy(TabThreadStatesBean::getState)); + for (String state : collect.keySet()) { + long sum = 0; + for (TabThreadStatesBean bean : collect.get(state)) { + sum += bean.getWallDuration(); + } + if ("".equals(state)) { + totalWallDuration = sum; + } else { + StateValue sv = new StateValue(); + sv.color = getStateColor(state); + sv.state = Utils.getEndState(state) + " : " + Utils.transformTimeToMs(sum) + "ms"; + sv.value = sum; + source.add(sv); + } + } + source = source.stream().sorted(Comparator.comparing(StateValue::getValue)).collect(Collectors.toList()); + } + repaint(); + } + + @Override + public void paint(final Graphics graphics) { + drawX = 0; + if (graphics instanceof Graphics2D) { + ((Graphics2D) graphics) + .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + } + for (StateValue sv : source) { + graphics.setFont(getFont().deriveFont(11.0f)); + graphics.setColor(sv.color); + int trueW; + if (sv == current && sv.drawRect.width < charW.doubleValue() * sv.state.length()) { + trueW = (int) (charW.doubleValue() * sv.state.length() + 1); + } else { + trueW = (int) ((sv.value * 1.0 / totalWallDuration) * getWidth() + 1); + } + if (trueW + drawX > getWidth()) { + trueW = getWidth() - drawX - 5; + } + graphics.fillRect(drawX, 0, trueW, getHeight()); + sv.drawRect = new Rectangle(drawX, 0, trueW, getHeight()); + + // 计算单个字符所占宽度 + if (sv.drawRect.width > charW.doubleValue()) { + if (sv.state.startsWith("Sleeping")) { + graphics.setColor(Color.gray); + } else { + graphics.setColor(Color.white); + } + int chars = (int) (sv.drawRect.width / charW.doubleValue()); + if (chars < sv.state.length()) { + graphics.drawString(sv.state.substring(0, chars), drawX + 1, 13); + } else { + graphics.drawString(sv.state, drawX + 1, 13); + } + } + drawX = drawX + trueW + 1; + } + } + + private Color getStateColor(String state) { + switch (state) { + case "Running": + return new Color(Final.RUNNING_COLOR); + case "D": + return new Color(Final.UNINTERRUPTIBLE_SLEEP_COLOR); + case "S": + return new Color(Final.S_COLOR); + case "R": + case "R+": + default: + return new Color(Final.R_COLOR); + } + } + + private class StateValue { + private String state; + private long value; + private Color color; + private Rectangle drawRect; + + private long getValue() { + return value; + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCounter.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCounter.java new file mode 100644 index 000000000..c0077a958 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCounter.java @@ -0,0 +1,201 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.Counter; +import ohos.devtools.views.trace.bean.TabCounterBean; +import ohos.devtools.views.trace.util.ComparatorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.table.TableRowSorter; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +/** + * TabCounter + * + * @date: 2021/5/12 16:34 + */ +public class TabCounter extends JBPanel { + private JBTable table = new JBTable(); + private FTableModel model = new FTableModel(); + private List> columns; + private JBLabel selectRangeLabel = new JBLabel("selected range:"); + private TableRowSorter tableRowSorter; + private long leftNs; + private long rightNs; + + /** + * structure function + */ + public TabCounter() { + setLayout(new MigLayout("insets 0", "[grow,fill][]", "[15!,fill][grow,fill]")); + setFocusable(true); + add(selectRangeLabel, "skip 1,wrap"); + initColumns(); + model.setColumns(columns); + table.setModel(model); + JBScrollPane jsp = new JBScrollPane(); + jsp.setViewportView(table); + add(jsp, "span"); + tableRowSorter = new TableRowSorter(model); + table.setRowSorter(tableRowSorter); + } + + /** + * set TabData + * + * @param trackIds trackIds + * @param leftNs leftNs + * @param rightNs rightNs + */ + public void loadTabData(final List trackIds, long leftNs, long rightNs) { + this.leftNs = leftNs; + this.rightNs = rightNs; + selectRangeLabel.setText("Selected range:" + (rightNs - leftNs) / 1000000.0 + "ms"); + if (trackIds != null && !trackIds.isEmpty()) { + StringBuffer buffer = new StringBuffer(); + for (int index = 0, size = trackIds.size(); index < size; index++) { + buffer.append(trackIds.get(index)); + if (index < size - 1) { + buffer.append(","); + } + } + loadTabData2(buffer); + } + } + + private void loadTabData2(StringBuffer buffer) { + CompletableFuture.runAsync(() -> { + List result = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_TAB_COUNTERS, result, buffer.toString(), rightNs); + Map> collect = + result.stream().collect(Collectors.groupingBy(Counter::getTrackId)); + Set keys = collect.keySet(); + List source = new ArrayList<>(); + double range = (rightNs - leftNs) * 1.0 / 1000000000; + int count = 0; + for (Integer key : keys) { + List counters = collect.get(key); + List list = counters.stream().filter(counter -> counter.getStartTime() > leftNs) + .collect(Collectors.toList()); + if (list.size() > 0) { + int index = counters.indexOf(list.get(0)); + if (index > 0) { + list.add(0, counters.get(index - 1)); + } + } else { + list.add(counters.get(counters.size() - 1)); + } + TabCounterBean tabCounter = getTabCounter(list, range); + count += tabCounter.getCount(); + source.add(tabCounter); + } + TabCounterBean tcb = new TabCounterBean(); + tcb.setCount(count); + source.add(0, tcb); + SwingUtilities.invokeLater(() -> { + if (result != null && result.size() > 0) { + // set row sorter + TabCounterBean cb = source.get(0); + for (int index = 0; index < 9; index++) { + if (index == 4) { + tableRowSorter + .setComparator(index, ComparatorUtils.generateComparator(cb.getCount() + "")); + } else { + tableRowSorter.setComparator(index, ComparatorUtils.generateComparator("")); + } + } + } + model.setDataSource(source); + model.fireTableDataChanged(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + + private TabCounterBean getTabCounter(List list, double range) { + TabCounterBean bean = new TabCounterBean(); + if (list.size() > 0) { + Counter first = list.get(0); + bean.setTrackId(first.getTrackId()); + bean.setName(first.getName()); + bean.setFirstValue(first.getValue()); + bean.setCount(list.size()); + bean.setLastValue(list.get(list.size() - 1).getValue()); + // delta value = (last value - first value) + bean.setDeltaValue(bean.getLastValue() - bean.getFirstValue()); + // rate = (last value - first value) / time range + bean.setRate(bean.getDeltaValue() / range); + List collect = + list.stream().sorted(Comparator.comparing(Counter::getValue)).collect(Collectors.toList()); + bean.setMinValue(collect.get(0).getValue()); + bean.setMaxValue(collect.get(collect.size() - 1).getValue()); + // Calculate the weighted average value + double weightAvg = 0.0; + long timeRange = rightNs - leftNs; + for (int index = 0, size = list.size(); index < size; index++) { + long start = index == 0 ? leftNs : list.get(index).getStartTime(); + long end = index == size - 1 ? rightNs : list.get(index + 1).getStartTime(); + weightAvg += list.get(index).getValue() * ((end - start) * 1.0 / timeRange); + } + BigDecimal decimal = new BigDecimal(weightAvg); + weightAvg = decimal.setScale(2, RoundingMode.HALF_UP).doubleValue(); + bean.setWeightAvgValue(weightAvg); + } + return bean; + } + + private void initColumns() { + columns = new ArrayList<>(); + columns.add(new FTableModel.Column<>("Name", item -> item.getName() == null ? "" : item.getName())); + columns.add( + new FTableModel.Column<>("Delta value", item -> item.getDeltaValue() == null ? "" : item.getDeltaValue())); + columns.add(new FTableModel.Column<>("Rate /s", item -> item.getRate() == null ? "" : item.getRate())); + columns.add(new FTableModel.Column<>("Weight avg value", + item -> item.getWeightAvgValue() == null ? "" : item.getWeightAvgValue())); + columns.add(new FTableModel.Column<>("Count", item -> item.getCount() == null ? "" : item.getCount())); + columns.add( + new FTableModel.Column<>("First value", item -> item.getFirstValue() == null ? "" : item.getFirstValue())); + columns.add( + new FTableModel.Column<>("Last value", item -> item.getLastValue() == null ? "" : item.getLastValue())); + columns + .add(new FTableModel.Column<>("Min value", item -> item.getMinValue() == null ? "" : item.getMinValue())); + columns + .add(new FTableModel.Column<>("Max value", item -> item.getMaxValue() == null ? "" : item.getMaxValue())); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByProcess.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByProcess.java new file mode 100644 index 000000000..6f9f7848b --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByProcess.java @@ -0,0 +1,133 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.TabThreadStatesBean; +import ohos.devtools.views.trace.util.ComparatorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.table.TableRowSorter; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * TabCounterBean + * + * @date: 2021/5/12 16:34 + */ +public class TabCpuByProcess extends JBPanel { + private JBTable table = new JBTable(); + private FTableModel model = new FTableModel(); + private List> columns; + private JBLabel selectRangeLabel = new JBLabel("selected range:"); + private TableRowSorter tableRowSorter; + + /** + * structure function + */ + public TabCpuByProcess() { + setLayout(new MigLayout("insets 0", "[grow,fill][]", "[15!,fill][grow,fill]")); + setFocusable(true); + add(selectRangeLabel, "skip 1,wrap"); + initColumns(); + model.setColumns(columns); + table.setModel(model); + JBScrollPane jsp = new JBScrollPane(); + jsp.setViewportView(table); + add(jsp, "span"); + tableRowSorter = new TableRowSorter(model); + table.setRowSorter(tableRowSorter); + } + + /** + * loadTabData + * + * @param cpus cpus + * @param leftNs leftNs + * @param rightNs rightNs + */ + public void loadTabData(final List cpus, long leftNs, long rightNs) { + selectRangeLabel.setText("Selected range:" + (rightNs - leftNs) / 1000000.0 + "ms"); + if (cpus != null && !cpus.isEmpty()) { + StringBuffer buffer = new StringBuffer(); + for (int index = 0, size = cpus.size(); index < size; index++) { + buffer.append(cpus.get(index)); + if (index < size - 1) { + buffer.append(","); + } + } + CompletableFuture.runAsync(() -> { + List result = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_TAB_PROCESS_BY_CPU, result, buffer.toString(), leftNs, rightNs); + SwingUtilities.invokeLater(() -> { + if (result != null && result.size() > 0) { + long sumWall = 0; + int sumOcc = 0; + for (TabThreadStatesBean bean : result) { + sumWall += bean.getWallDuration(); + sumOcc += bean.getOccurrences(); + } + TabThreadStatesBean sumBean = new TabThreadStatesBean(); + sumBean.setProcess(" "); + sumBean.setWallDuration(sumWall); + sumBean.setOccurrences(sumOcc); + result.add(0, sumBean); + TabThreadStatesBean count = result.get(0); + tableRowSorter.setComparator(0, ComparatorUtils.generateComparator(" ")); + tableRowSorter.setComparator(1, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(2, + ComparatorUtils.generateComparator(Utils.transformTimeToMs(count.getWallDuration()))); + tableRowSorter.setComparator(3, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(4, + ComparatorUtils.generateComparator(String.valueOf(count.getOccurrences()))); + } + model.setDataSource(result); + model.fireTableDataChanged(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + private void initColumns() { + columns = new ArrayList<>(); + columns.add(new FTableModel.Column<>("Process", + item -> item.getProcess() == null || item.getProcess().isEmpty() ? "[NULL]" : item.getProcess())); + columns.add(new FTableModel.Column<>("PID", item -> item.getPid() == null ? "" : item.getPid())); + columns.add(new FTableModel.Column<>("Wall Duration(ms)", + item -> item.getWallDuration() == null ? "" : Utils.transformTimeToMs(item.getWallDuration()))); + columns.add(new FTableModel.Column<>("Avg Wall Duration(ms)", + item -> item.getAvgDuration() == null ? "" : Utils.transformTimeToMs(item.getAvgDuration()))); + // Occurrences : time range the same thread state count + columns.add(new FTableModel.Column<>("Occurrences", + item -> item.getOccurrences() == null ? "" : item.getOccurrences())); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByThread.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByThread.java new file mode 100644 index 000000000..1081fbd1c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabCpuByThread.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.TabThreadStatesBean; +import ohos.devtools.views.trace.util.ComparatorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.table.TableRowSorter; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * TabCounterBean + * + * @date: 2021/5/12 16:34 + */ +public class TabCpuByThread extends JBPanel { + private JBTable table = new JBTable(); + private FTableModel model = new FTableModel(); + private List> columns; + private JBLabel selectRangeLabel = new JBLabel("selected range:"); + private TableRowSorter tableRowSorter; + + /** + * structure function + */ + public TabCpuByThread() { + setLayout(new MigLayout("insets 0", "[grow,fill][]", "[15!,fill][grow,fill]")); + setFocusable(true); + add(selectRangeLabel, "skip 1,wrap"); + initColumns(); + model.setColumns(columns); + table.setModel(model); + JBScrollPane jsp = new JBScrollPane(); + jsp.setViewportView(table); + add(jsp, "span"); + tableRowSorter = new TableRowSorter(model); + table.setRowSorter(tableRowSorter); + } + + /** + * loadTabData + * + * @param cpus cpus + * @param leftNs leftNs + * @param rightNs rightNs + */ + public void loadTabData(final List cpus, long leftNs, long rightNs) { + selectRangeLabel.setText("Selected range:" + (rightNs - leftNs) / 1000000.0 + "ms"); + if (cpus != null && !cpus.isEmpty()) { + StringBuffer buffer = new StringBuffer(); + for (int index = 0, size = cpus.size(); index < size; index++) { + buffer.append(cpus.get(index)); + if (index < size - 1) { + buffer.append(","); + } + } + CompletableFuture.runAsync(() -> { + List result = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_TAB_THREAD_BY_CPU, result, buffer.toString(), leftNs, rightNs); + SwingUtilities.invokeLater(() -> { + if (result != null && result.size() > 0) { + long sumWall = 0; + int sumOcc = 0; + for (TabThreadStatesBean bean : result) { + sumWall += bean.getWallDuration(); + sumOcc += bean.getOccurrences(); + } + TabThreadStatesBean sumBean = new TabThreadStatesBean(); + sumBean.setProcess(" "); + sumBean.setThread(" "); + sumBean.setWallDuration(sumWall); + sumBean.setOccurrences(sumOcc); + result.add(0, sumBean); + TabThreadStatesBean count = result.get(0); + tableRowSorter.setComparator(0, ComparatorUtils.generateComparator(" ")); + tableRowSorter.setComparator(1, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(2, ComparatorUtils.generateComparator(" ")); + tableRowSorter.setComparator(3, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(4, + ComparatorUtils.generateComparator(Utils.transformTimeToMs(count.getWallDuration()))); + tableRowSorter.setComparator(5, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(6, + ComparatorUtils.generateComparator(String.valueOf(count.getOccurrences()))); + } + model.setDataSource(result); + model.fireTableDataChanged(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + private void initColumns() { + columns = new ArrayList<>(); + columns.add(new FTableModel.Column<>("Process", + item -> item.getProcess() == null || item.getProcess().isEmpty() ? "[NULL]" : item.getProcess())); + columns.add(new FTableModel.Column<>("PID", item -> item.getPid() == null ? "" : item.getPid())); + columns.add(new FTableModel.Column<>("Thread", item -> item.getThread() == null ? "[NULL]" : item.getThread())); + columns.add(new FTableModel.Column<>("TID", item -> item.getTid() == null ? "" : item.getTid())); + columns.add(new FTableModel.Column<>("Wall Duration(ms)", + item -> item.getWallDuration() == null ? "" : Utils.transformTimeToMs(item.getWallDuration()))); + columns.add(new FTableModel.Column<>("Avg Wall Duration(ms)", + item -> item.getAvgDuration() == null ? "" : Utils.transformTimeToMs(item.getAvgDuration()))); + columns.add(new FTableModel.Column<>("Occurrences", + item -> item.getOccurrences() == null ? "" : item.getOccurrences())); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabPanel.java index 2a921663c..e2d59789d 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabPanel.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabPanel.java @@ -1,211 +1,246 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBTabbedPane; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.Utils; - -import javax.imageio.ImageIO; -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.io.IOException; - -/** - * tab component - * - * @version 1.0.1 - * @date 2021/04/20 12:12 - */ -public class TabPanel extends JBTabbedPane implements MouseMotionListener { - private static int mHeight = 300; - private static int barHeight; - - private final int iconWH = 20; - private Rectangle topRect; - private Rectangle bottomRect; - private int pressedY; - private Image top = null; - private Image bottom = null; - - /** - * construct - */ - public TabPanel() { - setFont(Final.NORMAL_FONT); - this.addMouseMotionListener(this); - try { - top = ImageIO.read(getClass().getResourceAsStream("/assets/top.png")); - bottom = ImageIO.read(getClass().getResourceAsStream("/assets/bottom.png")); - } catch (IOException ioException) { - ioException.printStackTrace(); - } - addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(final MouseEvent event) { - clickTop(event); - clickBottom(event); - } - - @Override - public void mousePressed(final MouseEvent event) { - pressedY = event.getYOnScreen(); - } - - @Override - public void mouseReleased(final MouseEvent event) { - super.mouseReleased(event); - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - }); - } - - @Override - public void paint(Graphics graphics) { - super.paint(graphics); - if (getTabCount() > 0) { - Rectangle tabBounds = getUI().getTabBounds(this, 0); - barHeight = tabBounds.height; - } - topRect = new Rectangle(getWidth() - 65, (barHeight - iconWH) / 2, iconWH, iconWH); - bottomRect = new Rectangle(getWidth() - 35, (barHeight - iconWH) / 2, iconWH, iconWH); - if (top != null) { - graphics.drawImage(top, topRect.x + 2, topRect.y + 2, iconWH - 5, iconWH - 5, null); - } - if (bottom != null) { - graphics.drawImage(bottom, bottomRect.x + 2, bottomRect.y + 2, iconWH - 5, iconWH - 5, null); - } - } - - @Override - public void mouseDragged(final MouseEvent event) { - if (getCursor().getType() == Cursor.N_RESIZE_CURSOR) { - Rectangle rect = getBounds(); - int drag = event.getYOnScreen() - pressedY; - pressedY = event.getYOnScreen(); - rect.y = rect.y + drag; - int ph = getParent().getHeight(); - int heightTmp = ph - rect.y; - if (heightTmp < barHeight) { - heightTmp = barHeight; - rect.y = ph - barHeight; - } - if (heightTmp > ph) { - rect.y = 0; - heightTmp = ph; - } - rect.height = heightTmp; - mHeight = rect.height; - setBounds(rect); - } - } - - @Override - public void mouseMoved(final MouseEvent event) { - int xAxis = event.getX(); - int yAxis = event.getY(); - int xNum = 0; - if (getTabCount() > 0) { - Rectangle rect = getUI().getTabBounds(this, getTabCount() - 1); - xNum = rect.width + rect.x + 10; - } - if (yAxis > 0 && yAxis < barHeight && xAxis > xNum) { - if (Utils.pointInRect(topRect, xAxis, yAxis) || Utils.pointInRect(bottomRect, xAxis, yAxis)) { - setCursor(new Cursor(Cursor.HAND_CURSOR)); - } else { - setCursor(new Cursor(Cursor.N_RESIZE_CURSOR)); - } - } else { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - } - - /** - * Click to top - * - * @param event Mouse event - */ - private void clickTop(final MouseEvent event) { - if (Utils.pointInRect(topRect, event.getX(), event.getY())) { - mHeight = getParent().getHeight(); - setBounds(0, 0, getWidth(), mHeight); - } - } - - /** - * Click to bottom - * - * @param event Mouse event - */ - private void clickBottom(final MouseEvent event) { - if (Utils.pointInRect(bottomRect, event.getX(), event.getY())) { - hideInBottom(); - } - } - - /** - * Restore the default height of the bottom tab - */ - public void recovery() { - if (getMyHeight() == 0) { - mHeight = 300; - setBounds(0, getParent().getHeight() - mHeight, getWidth(), mHeight); - } - } - - /** - * Minimize the bottom tab - */ - public void hideInBottom() { - if (mHeight != barHeight && barHeight > 0) { - mHeight = barHeight; - setBounds(0, getParent().getHeight() - barHeight, getWidth(), mHeight); - } - } - - /** - * hide bottom tab - */ - public void hide() { - if (mHeight != 0) { - mHeight = 0; - setBounds(0, getParent().getHeight(), getWidth(), mHeight); - } - } - - /** - * Get the height of the current tab - * - * @return height - */ - public int getMHeight() { - return mHeight; - } - - /** - * Get the height of the current tab - * - * @return height - */ - public static int getMyHeight() { - return mHeight == barHeight || barHeight == 0 ? 0 : mHeight; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBTabbedPane; +import com.intellij.util.Consumer; +import com.intellij.util.ui.JBUI; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.imageio.ImageIO; +import javax.swing.JLayeredPane; +import javax.swing.SwingUtilities; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionListener; +import java.io.IOException; +import java.util.Objects; + +/** + * tab component + * + * @date 2021/04/20 12:12 + */ +public class TabPanel extends JBTabbedPane implements MouseMotionListener { + private static int mHeight = 300; + private static int barHeight; + private final int iconWH = 20; + private Rectangle topRect; + private Rectangle bottomRect; + private Image topImage = null; + private Image bottomImage = null; + private Rectangle rootRect; + + private Point startPoint; + private Point endPoint; + private Rectangle srcBounds; + private Consumer boundsChangeListener; + + /** + * structure function + */ + public TabPanel() { + setFont(Final.NORMAL_FONT); + setBorder(JBUI.Borders.customLine(JBColor.background().darker(), 1, 0, 0, 0)); + this.addMouseMotionListener(this); + try { + topImage = ImageIO.read(getClass().getResourceAsStream("/assets/top.png")); + bottomImage = ImageIO.read(getClass().getResourceAsStream("/assets/bottom.png")); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(final MouseEvent event) { + clickTop(event); + clickBottom(event); + } + + @Override + public void mousePressed(final MouseEvent event) { + srcBounds = TabPanel.this.getBounds(); + startPoint = SwingUtilities + .convertPoint(TabPanel.this, event.getPoint(), TabPanel.this.getRootPane().getLayeredPane()); + } + + @Override + public void mouseReleased(final MouseEvent event) { + super.mouseReleased(event); + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + }); + } + + // /** + // * Sets the layerRect . + // *

You can use getLayerRect() to get the value of layerRect

+ // * + // * @param rect LayerRect + // */ + // public void setLayerRect(Rectangle rect) { + // this.layerRect = rect; + // } + + /** + * Sets the rootRect . + *

You can use getRootRect() to get the value of rootRect

+ * + * @param rect RootRect + */ + public void setRootRect(Rectangle rect) { + this.rootRect = rect; + } + + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + if (getTabCount() > 0) { + Rectangle tabBounds = getUI().getTabBounds(this, 0); + barHeight = tabBounds.height; + } + topRect = new Rectangle(getWidth() - 65, (barHeight - iconWH) / 2, iconWH, iconWH); + bottomRect = new Rectangle(getWidth() - 35, (barHeight - iconWH) / 2, iconWH, iconWH); + if (topImage != null) { + graphics.drawImage(topImage, Utils.getX(topRect) + 2, Utils.getY(topRect) + 2, iconWH - 5, iconWH - 5, + null); + } + if (bottomImage != null) { + graphics.drawImage(bottomImage, Utils.getX(bottomRect) + 2, Utils.getY(bottomRect) + 2, iconWH - 5, + iconWH - 5, null); + } + } + + @Override + public void mouseDragged(final MouseEvent event) { + if (getCursor().getType() == Cursor.N_RESIZE_CURSOR) { + endPoint = SwingUtilities.convertPoint(TabPanel.this, event.getPoint(), + TabPanel.this.getRootPane().getLayeredPane()); + int yPosition = Utils.getY(endPoint) - Utils.getY(startPoint); + if (srcBounds.height - yPosition < barHeight) { + return; + } else if (srcBounds.height - yPosition + > TabPanel.this.getRootPane().getLayeredPane().getHeight() - barHeight) { + return; + } else { + TabPanel.this.setBounds(Utils.getX(srcBounds), Utils.getY(srcBounds) + yPosition, srcBounds.width, + srcBounds.height - yPosition); + TabPanel.this.revalidate(); + if (boundsChangeListener != null) { + boundsChangeListener.consume(TabPanel.this.getBounds()); + } + } + } + } + + @Override + public void mouseMoved(final MouseEvent event) { + int xNum = 0; + if (getTabCount() > 0) { + Rectangle rect = getUI().getTabBounds(this, getTabCount() - 1); + xNum = rect.width + Utils.getX(rect) + 10; + } + if (event.getY() > 0 && event.getY() < barHeight && event.getX() > xNum) { + if (topRect.contains(event.getPoint()) || bottomRect.contains(event.getPoint())) { + setCursor(new Cursor(Cursor.HAND_CURSOR)); + } else { + setCursor(new Cursor(Cursor.N_RESIZE_CURSOR)); + } + } else { + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + } + + /** + * Click to top + * + * @param event Mouse event + */ + private void clickTop(final MouseEvent event) { + if (topRect.contains(event.getPoint())) { + int bottomHeight = + getRootPane().getLayeredPane().getBounds().height - Utils.getY(rootRect) - rootRect.height; + mHeight = getRootPane().getLayeredPane().getBounds().height - bottomHeight; + setBounds(Utils.getX(rootRect), 0, rootRect.width, mHeight); + } + } + + /** + * Click to bottom + * + * @param event Mouse event + */ + private void clickBottom(final MouseEvent event) { + if (bottomRect.contains(event.getPoint())) { + hideInBottom(); + } + } + + /** + * Minimize the bottom tab + */ + public void hideInBottom() { + mHeight = barHeight; + int bottomHeight = getRootPane().getLayeredPane().getBounds().height - Utils.getY(rootRect) - rootRect.height; + setBounds(Utils.getX(rootRect), getRootPane().getLayeredPane().getBounds().height - bottomHeight - mHeight, + getWidth(), + mHeight); + } + + /** + * hide bottom tab + */ + public void hidden() { + if (Objects.nonNull(getRootPane()) && Objects.nonNull(getRootPane().getLayeredPane())) { + getRootPane().getLayeredPane().setLayer(this, JLayeredPane.UNDEFINED_CONDITION); + this.setVisible(false); + } + } + + /** + * display current panel + */ + public void display() { + mHeight = rootRect.height / 5 * 3; + setVisible(true); + getRootPane().getLayeredPane().setLayer(this, JLayeredPane.DRAG_LAYER); + setBounds(new Rectangle(Utils.getX(rootRect), Utils.getY(rootRect) + mHeight, rootRect.width, + rootRect.height - mHeight)); + } + + /** + * display current panel + * + * @param rectangle rectangle + */ + public void display(Rectangle rectangle) { + setRootRect(rectangle); + mHeight = rootRect.height / 5 * 3; + setVisible(true); + if (getRootPane() != null) { + getRootPane().getLayeredPane().setLayer(this, JLayeredPane.DRAG_LAYER); + setBounds(new Rectangle(Utils.getX(rectangle), Utils.getY(rectangle) + mHeight, rectangle.width, + rectangle.height - mHeight)); + } + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabSlices.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabSlices.java new file mode 100644 index 000000000..6eba3184d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabSlices.java @@ -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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.TabSlicesBean; +import ohos.devtools.views.trace.util.ComparatorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.table.TableRowSorter; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * TabSlices + * + * @date 2021/04/20 12:12 + */ +public class TabSlices extends JBPanel { + private JBTable table = new JBTable(); + private FTableModel model = new FTableModel(); + private List> columns; + private JBLabel selectRangeLabel = new JBLabel("selected range:"); + private TableRowSorter tableRowSorter; + + /** + * structure function + */ + public TabSlices() { + setLayout(new MigLayout("insets 0", "[grow,fill][]", "[][grow,fill]")); + add(selectRangeLabel, "skip 1,wrap"); + initColumns(); + model.setColumns(columns); + table.setModel(model); + JBScrollPane jsp = new JBScrollPane(); + jsp.setViewportView(table); + add(jsp, "span"); + tableRowSorter = new TableRowSorter(model); + table.setRowSorter(tableRowSorter); + } + + /** + * loadTabData + * + * @param ids ids + * @param leftNs leftNs + * @param rightNs rightNs + */ + public void loadTabData(final List ids, long leftNs, long rightNs) { + selectRangeLabel.setText("Selected range:" + (rightNs - leftNs) / 1000000.0 + "ms"); + if (ids != null && !ids.isEmpty()) { + StringBuffer buffer = new StringBuffer(); + for (int index = 0, size = ids.size(); index < size; index++) { + buffer.append(ids.get(index)); + if (index < size - 1) { + buffer.append(","); + } + } + CompletableFuture.runAsync(() -> { + List result = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_TAB_SLICES, result, buffer.toString(), leftNs, rightNs); + SwingUtilities.invokeLater(() -> { + if (result != null && result.size() > 0) { + long sumWall = 0; + int sumOcc = 0; + for (TabSlicesBean bean : result) { + sumWall += bean.getWallDuration(); + sumOcc += bean.getOccurrences(); + } + TabSlicesBean sumBean = new TabSlicesBean(); + sumBean.setWallDuration(sumWall); + sumBean.setOccurrences(sumOcc); + result.add(0, sumBean); + TabSlicesBean count = result.get(0); + tableRowSorter.setComparator(0, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(1, + ComparatorUtils.generateComparator(Utils.transformTimeToMs(count.getWallDuration()))); + tableRowSorter.setComparator(2, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(3, + ComparatorUtils.generateComparator(String.valueOf(count.getOccurrences()))); + } + model.setDataSource(result); + model.fireTableDataChanged(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + private void initColumns() { + columns = new ArrayList<>(); + columns.add(new FTableModel.Column<>("Name", item -> item.getFunName() == null ? "" : item.getFunName())); + columns.add(new FTableModel.Column<>("Wall Duration(ms)", + item -> item.getWallDuration() == null ? "" : Utils.transformTimeToMs(item.getWallDuration()))); + columns.add(new FTableModel.Column<>("Avg Wall Duration(ms)", + item -> item.getAvgDuration() == null ? "" : Utils.transformTimeToMs(item.getAvgDuration()))); + columns.add(new FTableModel.Column<>("Occurrences", + item -> item.getOccurrences() == null ? "" : item.getOccurrences())); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabThreadStates.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabThreadStates.java new file mode 100644 index 000000000..ecbef8f25 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TabThreadStates.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import com.intellij.ui.components.JBScrollPane; +import com.intellij.ui.table.JBTable; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.TabThreadStatesBean; +import ohos.devtools.views.trace.util.ComparatorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import javax.swing.table.TableRowSorter; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * TabThreadStates + * + * @date 2021/04/20 12:12 + */ +public class TabThreadStates extends JBPanel { + private JBTable table = new JBTable(); + private FTableModel model = new FTableModel(); + private List> columns; + private JBLabel selectRangeLabel = new JBLabel("selected range:"); + private TableRowSorter tableRowSorter; + private StackBar stackBar; + + /** + * structure function + */ + public TabThreadStates() { + setLayout(new MigLayout("insets 0", "[grow,fill][]", "[15!,fill][grow,fill]")); + stackBar = new StackBar(); + setFocusable(true); + add(stackBar); + add(selectRangeLabel, "wrap"); + initColumns(); + model.setColumns(columns); + table.setModel(model); + JBScrollPane jsp = new JBScrollPane(); + jsp.setViewportView(table); + add(jsp, "span"); + tableRowSorter = new TableRowSorter(model); + table.setRowSorter(tableRowSorter); + } + + /** + * loadTabData + * + * @param ids ids + * @param leftNs leftNs + * @param rightNs rightNs + */ + public void loadTabData(final List ids, long leftNs, long rightNs) { + selectRangeLabel.setText("Selected range:" + (rightNs - leftNs) / 1000000.0 + "ms"); + if (ids != null && !ids.isEmpty()) { + StringBuffer buffer = new StringBuffer(); + for (int index = 0, size = ids.size(); index < size; index++) { + buffer.append(ids.get(index)); + if (index < size - 1) { + buffer.append(","); + } + } + CompletableFuture.runAsync(() -> { + List result = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_TAB_THREAD_STATES, result, buffer.toString(), leftNs, rightNs); + SwingUtilities.invokeLater(() -> { + if (result != null && result.size() > 0) { + long sumWall = 0; + int sumOcc = 0; + for (TabThreadStatesBean bean : result) { + sumWall += bean.getWallDuration(); + sumOcc += bean.getOccurrences(); + } + TabThreadStatesBean sumBean = new TabThreadStatesBean(); + sumBean.setProcess(" "); + sumBean.setThread(""); + sumBean.setState(""); + sumBean.setWallDuration(sumWall); + sumBean.setOccurrences(sumOcc); + result.add(0, sumBean); + stackBar.setSource(result); + TabThreadStatesBean count = result.get(0); + for (int index = 1; index < 5; index++) { + tableRowSorter.setComparator(index, ComparatorUtils.generateComparator("")); + } + tableRowSorter.setComparator(0, ComparatorUtils.generateComparator(" ")); + tableRowSorter.setComparator(5, + ComparatorUtils.generateComparator(Utils.transformTimeToMs(count.getWallDuration()))); + tableRowSorter.setComparator(6, ComparatorUtils.generateComparator("")); + tableRowSorter.setComparator(7, + ComparatorUtils.generateComparator(String.valueOf(count.getOccurrences()))); + } + model.setDataSource(result); + model.fireTableDataChanged(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + private void initColumns() { + columns = new ArrayList<>(); + columns.add(new FTableModel.Column<>("Process", + item -> item.getProcess() == null || item.getProcess().isEmpty() ? "[NULL]" : item.getProcess())); + columns.add(new FTableModel.Column<>("PID", item -> item.getPid() == null ? "" : item.getPid())); + columns.add(new FTableModel.Column<>("Thread", item -> item.getThread() == null ? "[NULL]" : item.getThread())); + columns.add(new FTableModel.Column<>("TID", item -> item.getTid() == null ? "" : item.getTid())); + columns.add(new FTableModel.Column<>("State", item -> Utils.getEndState(item.getState()))); + columns.add(new FTableModel.Column<>("Wall Duration(ms)", + item -> item.getWallDuration() == null ? "" : Utils.transformTimeToMs(item.getWallDuration()))); + columns.add(new FTableModel.Column<>("Avg Wall Duration(ms)", + item -> item.getAvgDuration() == null ? "" : Utils.transformTimeToMs(item.getAvgDuration()))); + columns.add(new FTableModel.Column<>("Occurrences", + item -> item.getOccurrences() == null ? "" : item.getOccurrences())); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TimeViewPort.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TimeViewPort.java index 2d23ec71b..1159099d1 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TimeViewPort.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/component/TimeViewPort.java @@ -1,223 +1,280 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import com.intellij.ui.components.JBViewport; -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.fragment.CpuDataFragment; -import ohos.devtools.views.trace.fragment.ruler.CpuFragment; -import ohos.devtools.views.trace.fragment.ruler.LeftFragment; -import ohos.devtools.views.trace.fragment.ruler.RulerFragment; -import ohos.devtools.views.trace.fragment.ruler.TopFragment; -import ohos.devtools.views.trace.util.Final; - -import javax.swing.JComponent; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -/** - * Timeline component - * - * @version 1.0.1 - * @date 2021/04/20 12:24 - */ -public final class TimeViewPort extends JBViewport { - /** - * Initial height of the time axis - */ - public static int height = 140; - - /** - * Fragment above - */ - public TopFragment topFragment; - - /** - * Fragment on the left - */ - public LeftFragment leftFragment; - - /** - * Cpu fragment - */ - public CpuFragment cpuFragment; - - /** - * Rule fragment - */ - public RulerFragment rulerFragment; - - /** - * Favorite fragment list - */ - public List favoriteFragments = new ArrayList<>(); - - private final IRangeChangeListener rangeChangeListener; - private final IHeightChangeListener heightChangeListener; - - /** - * Timeline interval change listener - */ - @FunctionalInterface - public interface IRangeChangeListener { - void change(long startNS, long endNS); - } - - /** - * Height change listener - */ - @FunctionalInterface - public interface IHeightChangeListener { - void change(int height); - } - - /** - * Constructor。 - * - * @param heightChangeListener Altitude change monitoring - * @param rangeChangeListener Altitude change monitoring - */ - public TimeViewPort(IHeightChangeListener heightChangeListener, IRangeChangeListener rangeChangeListener) { - this.rangeChangeListener = rangeChangeListener; - this.heightChangeListener = heightChangeListener; - this.topFragment = new TopFragment(this); - this.leftFragment = new LeftFragment(this); - this.cpuFragment = new CpuFragment(this, (leftX, rightX, leftNS, rightNS, centerNS) -> { - leftFragment.setStartTime(leftNS); - rulerFragment.setRange(leftNS, rightNS, centerNS); - }); - this.rulerFragment = new RulerFragment(this, (startNS, endNS) -> { - if (rangeChangeListener != null) { - rangeChangeListener.change(startNS, endNS); - } - }); - this.setOpaque(true); - setFont(Final.NORMAL_FONT); - } - - /** - * set root height - * - * @param rootHeight root height - */ - public void setRootHeight(int rootHeight) { - rulerFragment.setExtendHeight(rootHeight - height); - leftFragment.setExtendHeight(rootHeight - height); - } - - /** - * collect fragment - * - * @param dataFragment fragment - */ - public void favorite(AbstractDataFragment dataFragment) { - dataFragment.getRect().y = height; - height += dataFragment.getRect().height; - favoriteFragments.add(dataFragment); - if (heightChangeListener != null) { - heightChangeListener.change(height); - repaint(); - } - } - - /** - * cancel collect fragment - * - * @param dataFragment fragment - */ - public void cancel(AbstractDataFragment dataFragment) { - if (favoriteFragments.contains(dataFragment)) { - height -= dataFragment.getRect().height; - favoriteFragments.remove(dataFragment); - if (heightChangeListener != null) { - heightChangeListener.change(height); - repaint(); - } - } - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - } - - @Override - public void paint(Graphics graphics) { - super.paint(graphics); - if (graphics instanceof Graphics2D) { - Graphics2D g2 = (Graphics2D) graphics; - graphics.setColor(getBackground()); - graphics.fillRect(0, 0, getWidth(), height); - leftFragment.draw(g2); - topFragment.draw(g2); - cpuFragment.draw(g2); - rulerFragment.draw(g2); - } - } - - /** - * custom mouse event pressed - * - * @param event mouse event - */ - public void mousePressed(final MouseEvent event) { - Object eventSource = event.getSource(); - if (eventSource instanceof JComponent) { - JComponent jComponent = ((JComponent) eventSource); - int scrollY = event.getY() + jComponent - .getY(); // subtract the scroll height of the parent node. After scrolling down, y is a negative number. - cpuFragment.setSelectX(event.getX() < cpuFragment.getRect().x ? cpuFragment.getRect().x : event.getX()); - cpuFragment.setSelectY(scrollY); - rulerFragment - .setSelectX(event.getX() < rulerFragment.getRect().x ? rulerFragment.getRect().x : event.getX()); - rulerFragment.setSelectY(scrollY); - rulerFragment.mousePressed(event); - } - } - - /** - * custom mouse event dragged - * - * @param event mouse event - */ - public void mouseDragged(final MouseEvent event) { - cpuFragment.mouseDragged(event); - } - - /** - * custom mouse event moved - * - * @param event mouse event - */ - public void mouseMoved(final MouseEvent event) { - Object eventSource = event.getSource(); - if (eventSource instanceof JComponent) { - JComponent jComponent = ((JComponent) eventSource); - int scrollY = event.getY() + jComponent - .getY(); // Subtract the scroll height of the parent node. After scrolling down, y is a negative number. - cpuFragment.setSelectX(event.getX() < cpuFragment.getRect().x ? cpuFragment.getRect().x : event.getX()); - cpuFragment.setSelectY(scrollY); - rulerFragment - .setSelectX(event.getX() < rulerFragment.getRect().x ? rulerFragment.getRect().x : event.getX()); - rulerFragment.setSelectY(scrollY); - CpuDataFragment.focusCpuData = null; - rulerFragment.mouseMoved(event); - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.ui.components.JBViewport; +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.fragment.CpuDataFragment; +import ohos.devtools.views.trace.fragment.ruler.CpuFragment; +import ohos.devtools.views.trace.fragment.ruler.LeftFragment; +import ohos.devtools.views.trace.fragment.ruler.RulerFragment; +import ohos.devtools.views.trace.fragment.ruler.TopFragment; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Timeline component + * + * @date 2021/04/20 12:24 + */ +public final class TimeViewPort extends JBViewport { + /** + * Initial height of the time axis + */ + public static int height = 140; + + /** + * Fragment above + */ + public TopFragment topFragment; + + /** + * Fragment on the left + */ + public LeftFragment leftFragment; + + /** + * Cpu fragment + */ + public CpuFragment cpuFragment; + + /** + * Rule fragment + */ + public RulerFragment rulerFragment; + + /** + * Favorite fragment list + */ + public List favoriteFragments = new CopyOnWriteArrayList<>(); + + private final IRangeChangeListener rangeChangeListener; + private final IHeightChangeListener heightChangeListener; + + /** + * Constructor。 + * + * @param heightChangeListener Altitude change monitoring + * @param rangeChangeListener Altitude change monitoring + */ + public TimeViewPort(IHeightChangeListener heightChangeListener, IRangeChangeListener rangeChangeListener) { + this.rangeChangeListener = rangeChangeListener; + this.heightChangeListener = heightChangeListener; + this.topFragment = new TopFragment(this); + this.leftFragment = new LeftFragment(this); + this.cpuFragment = new CpuFragment(this, (leftX, rightX, leftNS, rightNS, centerNS) -> { + leftFragment.setStartTime(leftNS); + rulerFragment.setRange(leftNS, rightNS, centerNS); + }); + this.rulerFragment = new RulerFragment(this, (startNS, endNS) -> { + if (rangeChangeListener != null) { + rangeChangeListener.change(startNS, endNS); + } + }); + this.setOpaque(true); + setFont(Final.NORMAL_FONT); + } + + /** + * mouse clicked handler + * + * @param event event + */ + public void mouseClicked(MouseEvent event) { + for (AbstractDataFragment favoriteFragment : favoriteFragments) { + favoriteFragment.mouseClicked(event); + } + rulerFragment.mouseClicked(event); + } + + /** + * set root height + * + * @param rootHeight root height + */ + public void setRootHeight(int rootHeight) { + rulerFragment.setExtendHeight(rootHeight - height); + leftFragment.setExtendHeight(rootHeight - height); + } + + /** + * collect fragment + * + * @param dataFragment fragment + */ + public void favorite(AbstractDataFragment dataFragment) { + dataFragment.setVisible(false); + dataFragment.favoriteGraph.favorite(true); + Utils.setY(dataFragment.getRect(), height); + height += dataFragment.getRect().height; + favoriteFragments.add(dataFragment); + if (heightChangeListener != null) { + heightChangeListener.change(height); + repaint(); + } + } + + /** + * cancel collect fragment + * + * @param dataFragment fragment + */ + public void cancel(AbstractDataFragment dataFragment) { + if (favoriteFragments.contains(dataFragment)) { + dataFragment.setVisible(true); + dataFragment.favoriteGraph.favorite(false); + height -= dataFragment.getRect().height; + favoriteFragments.remove(dataFragment); + if (heightChangeListener != null) { + heightChangeListener.change(height); + repaint(); + } + } + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + } + + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + if (graphics instanceof Graphics2D) { + Graphics2D g2 = (Graphics2D) graphics; + graphics.setColor(getBackground()); + graphics.fillRect(0, 0, getWidth(), height); + leftFragment.draw(g2); + topFragment.draw(g2); + cpuFragment.draw(g2); + rulerFragment.draw(g2); + for (int index = favoriteFragments.size() - 1; index >= 0; index--) { + AbstractDataFragment frg = favoriteFragments.get(index); + if (index == favoriteFragments.size() - 1) { + Utils.setY(frg.getRect(), height - frg.getRect().height); + Utils.setY(frg.getDescRect(), height - frg.getRect().height); + Utils.setY(frg.getDataRect(), height - frg.getRect().height); + } else { + Utils.setY(frg.getRect(), + Utils.getY(favoriteFragments.get(index + 1).getRect()) - frg.getRect().height); + Utils.setY(frg.getDescRect(), + Utils.getY(favoriteFragments.get(index + 1).getRect()) - frg.getRect().height); + Utils.setY(frg.getDataRect(), + Utils.getY(favoriteFragments.get(index + 1).getRect()) - frg.getRect().height); + } + frg.draw(g2); + } + } + } + + /** + * custom mouse event pressed + * + * @param event mouse event + */ + public void mousePressed(final MouseEvent event) { + Object eventSource = event.getSource(); + if (eventSource instanceof JComponent) { + JComponent jComponent = (JComponent) eventSource; + int scrollY = event.getY() + jComponent + .getY(); // subtract the scroll height of the parent node. After scrolling down, y is a negative number. + cpuFragment.setSelectX( + event.getX() < Utils.getX(cpuFragment.getRect()) ? Utils.getX(cpuFragment.getRect()) : event.getX()); + cpuFragment.setSelectY(scrollY); + rulerFragment.setSelectX( + event.getX() < Utils.getX(rulerFragment.getRect()) ? Utils.getX(rulerFragment.getRect()) : + event.getX()); + rulerFragment.setSelectY(scrollY); + } + } + + /** + * custom mouse event dragged + * + * @param event mouse event + */ + public void mouseDragged(final MouseEvent event) { + cpuFragment.mouseDragged(event); + } + + /** + * custom mouse event moved + * + * @param event mouse event + */ + public void mouseMoved(final MouseEvent event) { + Object eventSource = event.getSource(); + if (eventSource instanceof JComponent) { + JComponent jComponent = (JComponent) eventSource; + int scrollY = event.getY() + jComponent + .getY(); // Subtract the scroll height of the parent node. After scrolling down, y is a negative number. + cpuFragment.setSelectX( + event.getX() < Utils.getX(cpuFragment.getRect()) ? Utils.getX(cpuFragment.getRect()) : event.getX()); + cpuFragment.setSelectY(scrollY); + rulerFragment.setSelectX( + event.getX() < Utils.getX(rulerFragment.getRect()) ? Utils.getX(rulerFragment.getRect()) : + event.getX()); + rulerFragment.setSelectY(scrollY); + CpuDataFragment.focusCpuData = null; + rulerFragment.mouseMoved(event); + favoriteFragments.forEach(fragment -> fragment.mouseMoved(event)); + } + } + + /** + * recycle all fragments + */ + public void recycle() { + if (favoriteFragments != null) { + favoriteFragments.forEach(AbstractDataFragment::recycle); + favoriteFragments.clear(); + } + } + + /** + * Timeline interval change listener + */ + @FunctionalInterface + public interface IRangeChangeListener { + /** + * change callback + * + * @param startNS start time + * @param endNS end time + */ + void change(long startNS, long endNS); + } + + /** + * Height change listener + */ + @FunctionalInterface + public interface IHeightChangeListener { + /** + * change callback + * + * @param height height change + */ + void change(int height); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AbstractDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AbstractDataFragment.java index 6f79e5eae..8ce08ed2a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AbstractDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AbstractDataFragment.java @@ -1,242 +1,420 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.fragment.ruler.AbstractFragment; - -import java.awt.AlphaComposite; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.util.UUID; - -/** - * Draw data rows - * - * @param Plot data type - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public abstract class AbstractDataFragment extends AbstractFragment { - /** - * uuid - */ - public String uuid = UUID.randomUUID().toString(); - - /** - * Parent node uuid - */ - public String parentUuid = UUID.randomUUID().toString(); - - /** - * The default height can be modified. After hiding, the height of rect descRect dataRect is 0, - * no rendering, and the display restores the height according to defaultHeight - */ - public int defaultHeight = 40; - - /** - * Small font - */ - public Font smallFont = new Font("宋体", Font.ITALIC, 10); - - /** - * Start event - */ - public long startNS; - - /** - * End event - */ - public long endNS; - - /** - * ndicates whether the data row is selected. - * null does not display the selected state. true/false displays the sufficient selection box - */ - public Boolean isSelected = false; - - /** - * Whether to show - */ - public boolean visible = true; - - /** - * Set to show or hide - * - * @param visible visible - */ - public void setVisible(boolean visible) { - this.visible = visible; - } - - /** - * Time range interval change - * - * @param startNS Starting time - * @param endNS End Time - */ - public void range(long startNS, long endNS) { - this.startNS = startNS; - this.endNS = endNS; - } - - /** - * Data click event - * - * @param event event - */ - public abstract void mouseClicked(MouseEvent event); - - /** - * Mouse click event - * - * @param event event - */ - public abstract void mousePressed(MouseEvent event); - - /** - * Mouse exited event - * - * @param event event - */ - public abstract void mouseExited(MouseEvent event); - - /** - * Mouse entered event - * - * @param event event - */ - public abstract void mouseEntered(MouseEvent event); - - /** - * Mouse move event - * - * @param event event - */ - public abstract void mouseMoved(MouseEvent event); - - /** - * Mouse release event - * - * @param event event - */ - public abstract void mouseReleased(MouseEvent event); - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - if (endNS == 0) { - endNS = AnalystPanel.DURATION; - } - getRect().width = getRoot().getWidth(); - getDescRect().width = 200; - getDataRect().width = getRoot().getWidth() - 200; - graphics.setColor(getRoot().getForeground()); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f)); - graphics.drawLine(getRect().x, getRect().y + getRect().height, getRoot().getWidth(), - getRect().y + getRect().height); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); - } - - /** - * Calculate the x coordinate based on time - * - * @param ns time - * @return int x coordinate - */ - public int getX(long ns) { - if (endNS == 0) { - endNS = AnalystPanel.DURATION; - } - int xSize = (int) ((ns - startNS) * getDataRect().width / (endNS - startNS)); - if (xSize < 0) { - xSize = 0; - } - if (xSize > getDataRect().width) { - xSize = getDataRect().width; - } - return xSize; - } - - /** - * Calculate the x coordinate based on time - * - * @param ns time - * @return double Returns the x coordinate - */ - public double getXDouble(long ns) { - if (endNS == 0) { - endNS = AnalystPanel.DURATION; - } - double xSize = (ns - startNS) * getDataRect().width / (endNS - startNS); - if (xSize < 0) { - xSize = 0; - } - if (xSize > getDataRect().width) { - xSize = getDataRect().width; - } - return xSize; - } - - /** - * Clear focus - * - * @param event Mouse event - */ - public void clearFocus(MouseEvent event) { - if (edgeInspect(event)) { - CpuDataFragment.focusCpuData = null; - } - } - - /** - * Clear selection element - */ - public void clearSelected() { - if (CpuDataFragment.currentSelectedCpuData != null) { - CpuDataFragment.currentSelectedCpuData.select(false); - CpuDataFragment.currentSelectedCpuData.repaint(); - } - if (ThreadDataFragment.currentSelectedThreadData != null) { - ThreadDataFragment.currentSelectedThreadData.select(false); - ThreadDataFragment.currentSelectedThreadData.repaint(); - } - if (FunctionDataFragment.currentSelectedFunctionData != null) { - FunctionDataFragment.currentSelectedFunctionData.setSelected(false); - FunctionDataFragment.currentSelectedFunctionData.repaint(); - } - } - - /** - * Set rect object - * - * @param xSize x coordinate - * @param ySize y coordinate - * @param width width - * @param height height - */ - public void setRect(int xSize, int ySize, int width, int height) { - getRect().x = xSize; - getRect().y = ySize; - getRect().width = width; - getRect().height = height; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; +import ohos.devtools.views.trace.fragment.graph.CheckGraph; +import ohos.devtools.views.trace.fragment.graph.FavoriteGraph; +import ohos.devtools.views.trace.fragment.ruler.AbstractFragment; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.AlphaComposite; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +import static java.util.Objects.nonNull; + +/** + * Draw data rows + * + * @param Plot data type + * @date 2021/04/22 12:25 + */ +public abstract class AbstractDataFragment extends AbstractFragment { + /** + * uuid + */ + public String uuid = UUID.randomUUID().toString(); + + /** + * is alive + */ + public boolean isAlive; + + /** + * Parent node uuid + */ + public String parentUuid = UUID.randomUUID().toString(); + + /** + * The default height can be modified. After hiding, the height of rect descRect dataRect is 0, + * no rendering, and the display restores the height according to defaultHeight + */ + public int defaultHeight = 40; + + /** + * Small font + */ + public Font smallFont = new Font("宋体", Font.ITALIC, 10); + + /** + * ndicates whether the data row is selected. + * null does not display the selected state. true/false displays the sufficient selection box + */ + public Boolean isSelected = false; + + /** + * Whether to show + */ + public boolean visible = true; + + /** + * Favorite button + */ + public FavoriteGraph favoriteGraph; + + /** + * Select button + */ + public CheckGraph checkGraph; + + /** + * Start event + */ + public long startNS; + + /** + * End event + */ + public long endNS; + + /** + * data list + */ + protected List data; + + private IDataFragment dataFragmentListener; + private final boolean hasFavorite; + private final boolean hasCheck; + + /** + * The construction method + * + * @param component component + * @param hasFavorite hasFavorite + * @param hasCheck hasCheck + */ + public AbstractDataFragment(JComponent component, boolean hasFavorite, boolean hasCheck) { + this.hasFavorite = hasFavorite; + this.hasCheck = hasCheck; + favoriteGraph = new FavoriteGraph(this, component, event -> { + if (nonNull(dataFragmentListener)) { + dataFragmentListener.collect(this); + } + }); + checkGraph = new CheckGraph(this, component); + } + + /** + * Set to show or hide + * + * @param visible visible + */ + public void setVisible(boolean visible) { + this.visible = visible; + } + + /** + * Time range interval change + * + * @param startNS Starting time + * @param endNS End Time + */ + public void range(long startNS, long endNS) { + this.startNS = startNS; + this.endNS = endNS; + } + + /** + * Data click event + * + * @param event event + */ + public void mouseClicked(MouseEvent event) { + if (favoriteGraph.isFavorite()) { + MouseEvent me = SwingUtilities.convertMouseEvent(getRoot(), event, getRoot().getParent()); + if (favoriteGraph.edgeInspect(me)) { + favoriteGraph.onClick(me); + } + if (checkGraph.edgeInspect(me)) { + checkGraph.onClick(me); + } + } else { + if (favoriteGraph.edgeInspect(event)) { + favoriteGraph.onClick(event); + } + if (checkGraph.edgeInspect(event)) { + checkGraph.onClick(event); + } + } + } + + /** + * Mouse click event + * + * @param event event + */ + public abstract void mousePressed(MouseEvent event); + + /** + * Mouse exited event + * + * @param event event + */ + public abstract void mouseExited(MouseEvent event); + + /** + * Mouse entered event + * + * @param event event + */ + public abstract void mouseEntered(MouseEvent event); + + /** + * Mouse move event + * + * @param event event + */ + public void mouseMoved(MouseEvent event) { + favoriteGraph.display(edgeInspectRect(getDescRect(), event)); + if (hasFavorite && !visible) { + if (favoriteGraph.edgeInspect(event)) { + if (!favoriteGraph.flagFocus) { + favoriteGraph.flagFocus = true; + favoriteGraph.onFocus(event); + } + } else { + if (favoriteGraph.flagFocus) { + favoriteGraph.flagFocus = false; + favoriteGraph.onBlur(event); + } + } + } + } + + /** + * Mouse release event + * + * @param event event + */ + public abstract void mouseReleased(MouseEvent event); + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + if (endNS == 0) { + endNS = AnalystPanel.DURATION; + } + getRect().width = getRoot().getWidth(); + getDescRect().width = 200; + getDataRect().width = getRoot().getWidth() - 200; + graphics.setColor(getRoot().getForeground()); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f)); + graphics.drawLine(Utils.getX(getRect()), Utils.getY(getRect()) + getRect().height, getRoot().getWidth(), + Utils.getY(getRect()) + getRect().height); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); + if (hasCheck) { + checkGraph.setChecked(isSelected); + checkGraph.draw(graphics); + } + if (hasFavorite) { + if (hasCheck) { + favoriteGraph.setRightGraph(isSelected != null ? checkGraph : null); + } + favoriteGraph.draw(graphics); + } + } + + /** + * Calculate the x coordinate based on time + * + * @param ns time + * @return int x coordinate + */ + public int getX(long ns) { + if (endNS == 0) { + endNS = AnalystPanel.DURATION; + } + int xSize = (int) ((ns - startNS) * getDataRect().width / (endNS - startNS)); + if (xSize < 0) { + xSize = 0; + } + if (xSize > getDataRect().width) { + xSize = getDataRect().width; + } + return xSize; + } + + /** + * Calculate the x coordinate based on time + * + * @param ns time + * @return double Returns the x coordinate + */ + public double getXDouble(long ns) { + if (endNS == 0) { + endNS = AnalystPanel.DURATION; + } + double xSize = (ns - startNS) * getDataRect().width / (endNS - startNS); + if (xSize < 0) { + xSize = 0; + } + if (xSize > getDataRect().width) { + xSize = getDataRect().width; + } + return xSize; + } + + /** + * Clear focus + * + * @param event Mouse event + */ + public void clearFocus(MouseEvent event) { + if (edgeInspect(event)) { + CpuDataFragment.focusCpuData = null; + } + } + + /** + * Clear selection element + */ + public void clearSelected() { + if (nonNull(CpuDataFragment.currentSelectedCpuData)) { + CpuDataFragment.currentSelectedCpuData.select(false); + CpuDataFragment.currentSelectedCpuData.repaint(); + } + if (nonNull(ThreadDataFragment.currentSelectedThreadData)) { + ThreadDataFragment.currentSelectedThreadData.select(false); + ThreadDataFragment.currentSelectedThreadData.repaint(); + } + if (nonNull(FunctionDataFragment.currentSelectedFunctionData)) { + FunctionDataFragment.currentSelectedFunctionData.setSelected(false); + FunctionDataFragment.currentSelectedFunctionData.repaint(); + } + } + + /** + * Set rect object + * + * @param xSize x coordinate + * @param ySize y coordinate + * @param width width + * @param height height + */ + public void setRect(int xSize, int ySize, int width, int height) { + getRect().setLocation(xSize, ySize); + getRect().width = width; + getRect().height = height; + } + + /** + * Gets the value of dataFragmentListener . + * + * @return the value of ohos.devtools.views.trace.fragment.AbstractDataFragment.IDataFragment + */ + public IDataFragment getDataFragmentListener() { + return dataFragmentListener; + } + + /** + * Sets the dataFragmentListener . + *

You can use getDataFragmentListener() to get the value of dataFragmentListener

+ * + * @param listener listener + */ + public void setDataFragmentListener(IDataFragment listener) { + this.dataFragmentListener = listener; + } + + /** + * recycle the data + */ + public void recycle() { + if (data != null) { + data.clear(); + } + } + + /** + * get the real mouse event + * + * @param evt MouseEvent + * @return MouseEvent + */ + public MouseEvent getRealMouseEvent(MouseEvent evt) { + MouseEvent event; + if (favoriteGraph.isFavorite()) { + event = SwingUtilities.convertMouseEvent(getRoot(), evt, getRoot().getParent()); + } else { + event = evt; + } + return event; + } + + /** + * key released + * + * @param event event + */ + public abstract void keyReleased(KeyEvent event); + + /** + * get the click mouse event is empty + * + * @param event MouseEvent + * @return return the click point is in function or thread + */ + public boolean isEmptyClick(MouseEvent event) { + if (Objects.nonNull(data)) { + return data.stream().allMatch(it -> !it.rect.contains(event.getPoint())); + } + return true; + } + + /** + * IDataFragment + * + * @date 2021/04/22 12:25 + */ + public interface IDataFragment { + /** + * collect Callback + * + * @param fgr data + */ + void collect(AbstractDataFragment fgr); + + /** + * check Callback + * + * @param fgr data + */ + void check(AbstractDataFragment fgr); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AsyncEventDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AsyncEventDataFragment.java new file mode 100644 index 000000000..7eb5cbc6f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/AsyncEventDataFragment.java @@ -0,0 +1,186 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.bean.AsyncEvent; +import ohos.devtools.views.trace.bean.ThreadData; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Memory data line + * + * @date 2021/04/22 12:25 + */ +public class AsyncEventDataFragment extends AbstractDataFragment { + /** + * graph event callback + */ + public static ThreadData currentSelectedThreadData; + + /** + * Process memory + */ + public AsyncEvent obj; + private boolean isLoading; + private Rectangle2D bounds; + private int max; + + /** + * structure + * + * @param root root + * @param obj mem + * @param asyncEvents asyncEvents + */ + public AsyncEventDataFragment(JComponent root, AsyncEvent obj, List asyncEvents) { + super(root, true, false); + this.obj = obj; + this.setRoot(root); + this.data = asyncEvents; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + graphics.setFont(Final.NORMAL_FONT); + graphics.setColor(getRoot().getForeground()); + String name = obj.getName(); + bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + double wordWidth = bounds.getWidth() / name.length(); // Width per character + double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line + if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display + graphics.drawString(name, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 10)); + } else { + String substring = name.substring((int) wordNum); + if (substring.length() < wordNum) { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 8)); + graphics + .drawString(substring, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 8)); + } else { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 2)); + graphics.drawString(substring.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 2)); + } + } + drawData(graphics); + } + + private void drawData(Graphics2D graphics) { + if (data != null) { + List collect = data.stream().filter( + memData -> memData.getStartTime() + + memData.getDuration() > startNS && memData.getStartTime() < endNS) + .collect(Collectors.toList()); + int x1; + int x2; + for (int index = 0, len = collect.size(); index < len; index++) { + AsyncEvent asyncEvent = collect.get(index); + if (asyncEvent.getStartTime() < startNS) { + x1 = getX(startNS); + } else { + x1 = getX(asyncEvent.getStartTime()); + } + if (asyncEvent.getStartTime() + asyncEvent.getDuration() > endNS) { + x2 = getX(endNS); + } else { + x2 = getX(asyncEvent.getStartTime() + asyncEvent.getDuration()); + } + asyncEvent.root = getRoot(); + asyncEvent.setRect(x1 + Utils.getX(getDataRect()), + Utils.getY(getDataRect()) + asyncEvent.getDepth() * 20 + 10, + x2 - x1 <= 0 ? 1 : x2 - x1, 20); + asyncEvent.draw(graphics); + } + } else { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } + } + + /** + * Mouse clicked event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + private void loadData() { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ClockDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ClockDataFragment.java new file mode 100644 index 000000000..73b1d54ff --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ClockDataFragment.java @@ -0,0 +1,353 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.Clock; +import ohos.devtools.views.trace.bean.ClockData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.component.ContentPanel; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * cpu data + * + * @date 2021/04/22 12:25 + */ +public class ClockDataFragment extends AbstractDataFragment implements ClockData.IEventListener { + /** + * The node that currently has focus + */ + public static ClockData focusCpuData; + + /** + * Currently selected cpu graphics node + */ + public static ClockData currentSelectedCpuData; + + private final Clock clock; + + /** + * cpu data collection + */ + private double x1; + + private double x2; + + private Rectangle2D bounds; + + private ClockData showTipCpuData; // Prompt window + + private int tipX; // X position of the message + + private int tipWidth; // Prompt message width + + private boolean isLoading; + + private Long min; + private Long max; + + /** + * structure + * + * @param root root + * @param clock clock + */ + public ClockDataFragment(javax.swing.JComponent root, Clock clock) { + super(root, true, false); + this.clock = clock; + this.setRoot(root); + this.data = data; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + // Supplement the information on the left + graphics.setColor(getRoot().getForeground()); + bounds = graphics.getFontMetrics().getStringBounds(clock.getName(), graphics); + graphics.drawString(clock.getName(), (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + (getDescRect().getHeight()) / 2 + bounds.getHeight() / 3)); + if (Objects.isNull(data) || data.isEmpty()) { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } else { + data.stream() + .filter(it -> it.getStartTime() + it.getDuration() > startNS && it.getStartTime() < endNS) + .forEach(it -> { + if (it.getStartTime() < startNS) { + x1 = 0; + } else { + x1 = getXDouble(it.getStartTime()); + } + if (it.getStartTime() + it.getDuration() > endNS) { + x2 = getDataRect().width; + } else { + x2 = getXDouble(it.getStartTime() + it.getDuration()); + } + int index = data.indexOf(it); + if (index > 0) { + it.setDelta(it.getValue() - data.get(index - 1).getValue()); + } else { + it.setDelta(0L); + } + it.setRoot(getRoot()); + double getV = x2 - x1 <= 0 ? 1 : x2 - x1; + it.setRect(x1 + getDataRect().getX(), getDataRect().getY() + 5, getV, + getDataRect().getHeight() - 10); + it.setEventListener(ClockDataFragment.this); + it.setMinValue(min); + it.setMaxValue(max); + it.draw(graphics); + }); + } + drawTips(graphics); + } + + private void drawTips(Graphics2D graphics) { + if (showTipCpuData != null) { + graphics.setFont(Final.NORMAL_FONT); + String process = "value:" + showTipCpuData.getValue(); + String thread = ""; + Rectangle2D processBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(process, graphics); + Rectangle2D threadBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(thread, graphics); + tipWidth = (int) (Math.max(processBounds.getWidth(), threadBounds.getWidth()) + 20); + graphics.setColor(getRoot().getForeground()); + graphics.fillRect(tipX, Utils.getY(showTipCpuData.rect), tipWidth, showTipCpuData.rect.height); + graphics.setColor(getRoot().getBackground()); + graphics.drawString(process, tipX + 10, Utils.getY(showTipCpuData.rect) + 12); + graphics.drawString(thread, tipX + 10, Utils.getY(showTipCpuData.rect) + 24); + } + } + + /** + * Mouse click event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + ContentPanel.clickFragment = this; + data.stream().filter( + cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS && cpuData.getStartTime() < endNS) + .filter(cpuData -> cpuData.edgeInspect(event)).findFirst().ifPresent(cpuData -> cpuData.onClick(event)); + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * Mouse entered event + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * Mouse move event + * + * @param evt evt + */ + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + if (showTipCpuData != null) { + showTipCpuData.select(false); + } + showTipCpuData = null; + if (Objects.nonNull(data) && edgeInspect(event)) { + data.stream().filter( + it -> it.getStartTime() + it.getDuration() > startNS && it.getStartTime() < endNS) + .forEach(it -> { + it.onMouseMove(event); + if (it.edgeInspect(event)) { + if (!it.flagFocus) { + it.flagFocus = true; + it.onFocus(event); + } + } + }); + } + } + + /** + * Mouse released event + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + /** + * Click event + * + * @param evt event + * @param data data + */ + @Override + public void click(MouseEvent evt, ClockData data) { + MouseEvent event = getRealMouseEvent(evt); + clearSelected(); + if (showTipCpuData != null) { + showTipCpuData.select(true); + showTipCpuData.repaint(); + currentSelectedCpuData = ClockDataFragment.focusCpuData; + if (AnalystPanel.iClockDataClick != null) { + AnalystPanel.iClockDataClick.click(showTipCpuData); + } + } + } + + /** + * Loss of focus event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, ClockData data) { + if (showTipCpuData != null) { + showTipCpuData.select(false); + } + showTipCpuData = null; + ClockDataFragment.focusCpuData = null; + getRoot().repaint(); + } + + /** + * Get focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, ClockData data) { + showTipCpuData = data; + showTipCpuData.select(true); + ClockDataFragment.focusCpuData = data; + getRoot().repaint(); + } + + /** + * Mouse movement event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, ClockData data) { + showTipCpuData = data; + showTipCpuData.select(true); + ClockDataFragment.focusCpuData = data; + tipX = event.getX(); + getRoot().repaint(); + } + + private void loadData() { + if (!isLoading) { + isLoading = true; + CompletableFuture.runAsync(() -> { + ArrayList clockData = new ArrayList<>() { + }; + if (clock.getName().endsWith(" Frequency")) { + Db.getInstance().query(Sql.SYS_QUERY_CLOCK_FREQUENCY, clockData, clock.getSrcname()); + for (int idx = 0, len = clockData.size(); idx < len; idx++) { + ClockData it = clockData.get(idx); + if (idx == len - 1) { + it.setDuration(AnalystPanel.DURATION - it.getStartTime()); + } else { + it.setDuration(clockData.get(idx + 1).getStartTime() - it.getStartTime()); + } + } + } else if (clock.getName().endsWith(" State")) { + Db.getInstance().query(Sql.SYS_QUERY_CLOCK_STATE, clockData, clock.getSrcname()); + } else { + if (clock.getName().endsWith("ScreenState")) { + Db.getInstance().query(Sql.SYS_QUERY_SCREEN_STATE, clockData); + for (int idx = 0, len = clockData.size(); idx < len; idx++) { + ClockData it = clockData.get(idx); + if (idx == len - 1) { + it.setDuration(AnalystPanel.DURATION - it.getStartTime()); + } else { + it.setDuration(clockData.get(idx + 1).getStartTime() - it.getStartTime()); + } + } + } + } + min = clockData.stream().mapToLong(ClockData::getValue).min().orElseThrow(NoSuchElementException::new); + max = clockData.stream().mapToLong(ClockData::getValue).max().orElseThrow(NoSuchElementException::new); + data = clockData; + SwingUtilities.invokeLater(() -> { + isLoading = false; + repaint(); + }); + + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuDataFragment.java index 8cc05a38d..38ff3782f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuDataFragment.java @@ -1,371 +1,358 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.component.ContentPanel; -import ohos.devtools.views.trace.fragment.graph.CheckGraph; -import ohos.devtools.views.trace.fragment.graph.FavoriteGraph; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.TimeUtils; - -import javax.swing.JComponent; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.List; -import java.util.Optional; - -/** - * cpu data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuDataFragment extends AbstractDataFragment implements CpuData.IEventListener { - /** - * The node that currently has focus - */ - public static CpuData focusCpuData; - - /** - * Currently selected cpu graphics node - */ - public static CpuData currentSelectedCpuData; - - /** - * cpu data collection - */ - public List data; - - /** - * Favorite button - */ - public FavoriteGraph favoriteGraph; - - /** - * Select button - */ - public CheckGraph checkGraph; - - private double x1; - - private double x2; - - private Rectangle2D bounds; - - private CpuData showTipCpuData; // Prompt window - - private int tipX; // X position of the message - - private int tipWidth; // Prompt message width - - private int index; - - private final BasicStroke boldStoke = new BasicStroke(2); - private final BasicStroke normalStoke = new BasicStroke(1); - - /** - * structure - * - * @param root root - * @param index index - * @param data data - */ - public CpuDataFragment(javax.swing.JComponent root, int index, List data) { - this.index = index; - this.setRoot(root); - this.data = data; - favoriteGraph = new FavoriteGraph(this, root); - checkGraph = new CheckGraph(this, root); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - - // Supplement the information on the left - graphics.setColor(getRoot().getForeground()); - bounds = graphics.getFontMetrics().getStringBounds("Cpu " + index, graphics); - graphics.drawString("Cpu " + index, (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + (getDescRect().getHeight()) / 2 + bounds.getHeight() / 3)); - favoriteGraph.setRightGraph(isSelected != null ? checkGraph : null); - checkGraph.setChecked(isSelected); - checkGraph.draw(graphics); - favoriteGraph.draw(graphics); - data.stream().filter( - cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS && cpuData.getStartTime() < endNS) - .forEach(cpuGraph -> { - if (cpuGraph.getStartTime() < startNS) { - x1 = 0; - } else { - x1 = getXDouble(cpuGraph.getStartTime()); - } - if (cpuGraph.getStartTime() + cpuGraph.getDuration() > endNS) { - x2 = getDataRect().width; - } else { - x2 = getXDouble(cpuGraph.getStartTime() + cpuGraph.getDuration()); - } - cpuGraph.setRoot(getRoot()); - double getV = x2 - x1 <= 0 ? 1 : x2 - x1; - cpuGraph - .setRect(x1 + getDataRect().getX(), getDataRect().getY() + 5, getV, getDataRect().getHeight() - 10); - cpuGraph.setEventListener(CpuDataFragment.this); - cpuGraph.draw(graphics); - }); - drawTips(graphics); - drawWakeup(graphics); - } - - private void drawTips(Graphics2D graphics) { - if (showTipCpuData != null) { - graphics.setFont(Final.NORMAL_FONT); - if (showTipCpuData.getProcessName() == null || showTipCpuData.getProcessName().isEmpty()) { - showTipCpuData.setProcessName(showTipCpuData.getName()); - } - String process = "P:" + showTipCpuData.getProcessName() + " [" + showTipCpuData.getProcessId() + "]"; - String thread = "T:" + showTipCpuData.getName() + " [" + showTipCpuData.getTid() + "]"; - Rectangle2D processBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(process, graphics); - Rectangle2D threadBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(thread, graphics); - tipWidth = (int) (Math.max(processBounds.getWidth(), threadBounds.getWidth()) + 20); - graphics.setColor(getRoot().getForeground()); - graphics.fillRect(tipX, showTipCpuData.rect.y, tipWidth, showTipCpuData.rect.height); - graphics.setColor(getRoot().getBackground()); - graphics.drawString(process, tipX + 10, showTipCpuData.rect.y + 12); - graphics.drawString(thread, tipX + 10, showTipCpuData.rect.y + 24); - } - } - - private void drawWakeup(Graphics2D graphics) { - if (getRoot() instanceof ContentPanel) { - ContentPanel contentPanel = (ContentPanel) getRoot(); - Optional.ofNullable(contentPanel.getWakeupBean()).ifPresent(wakeup -> { - int wakeupX = getX(wakeup.getWakeupTime()); - graphics.setColor(Color.BLACK); - graphics.setStroke(boldStoke); - Rectangle visibleRect = contentPanel.getVisibleRect(); - graphics.drawLine(wakeupX + getDataRect().x, visibleRect.y, wakeupX + getDataRect().x, - visibleRect.y + visibleRect.height); - if (wakeup.getWakeupCpu() == index) { - final int[] xs = - {getDataRect().x + wakeupX, getDataRect().x + wakeupX + 6, getDataRect().x + wakeupX, - getDataRect().x + wakeupX - 6}; - final int[] ys = {getRect().y + getRect().height / 2 - 10, getRect().y + getRect().height / 2, - getRect().y + getRect().height / 2 + 10, getRect().y + getRect().height / 2}; - graphics.fillPolygon(xs, ys, xs.length); - if (currentSelectedCpuData != null) { - Rectangle rectangle = new Rectangle(wakeupX + getDataRect().x, - currentSelectedCpuData.rect.y + currentSelectedCpuData.rect.height / 2, - currentSelectedCpuData.rect.x - wakeupX - getDataRect().x, 30); - graphics.drawLine(getDataRect().x + wakeupX, - currentSelectedCpuData.rect.y + currentSelectedCpuData.rect.height - 2, - currentSelectedCpuData.rect.x, - currentSelectedCpuData.rect.y + currentSelectedCpuData.rect.height - 2); - if (rectangle.width > 10) { - drawArrow(graphics, getDataRect().x + wakeupX, - currentSelectedCpuData.rect.y + currentSelectedCpuData.rect.height - 2, -1); - drawArrow(graphics, currentSelectedCpuData.rect.x, - currentSelectedCpuData.rect.y + currentSelectedCpuData.rect.height - 2, 1); - } - long offsetTime = currentSelectedCpuData.getStartTime() - wakeup.getWakeupTime(); - String timeString = TimeUtils.getTimeString(offsetTime); - rectangle.y -= 5; - drawString(graphics, rectangle, timeString, Placement.CENTER); - } - } - graphics.setStroke(normalStoke); - }); - } - } - - private void drawArrow(Graphics2D graphics, int xVal, int yVal, int align) { - if (align == -1) { - final int[] xArray = {xVal, xVal + 5, xVal + 5}; - final int[] yArray = {yVal, yVal - 5, yVal + 5}; - graphics.fillPolygon(xArray, yArray, xArray.length); - } - if (align == 1) { - final int[] xArray = {xVal, xVal - 5, xVal - 5}; - final int[] yArray = {yVal, yVal - 5, yVal + 5}; - graphics.fillPolygon(xArray, yArray, xArray.length); - } - } - - /** - * Mouse click event - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - if (favoriteGraph.edgeInspect(event)) { - favoriteGraph.onClick(event); - } - if (checkGraph.edgeInspect(event)) { - checkGraph.onClick(event); - } - data.stream().filter( - cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS && cpuData.getStartTime() < endNS) - .filter(cpuData -> cpuData.edgeInspect(event)).findFirst().ifPresent(cpuData -> { - cpuData.onClick(event); - }); - } - - /** - * Mouse pressed event - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * Mouse exited event - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - /** - * Mouse entered event - * - * @param event event - */ - @Override - public void mouseEntered(MouseEvent event) { - } - - /** - * Mouse move event - * - * @param event event - */ - @Override - public void mouseMoved(MouseEvent event) { - favoriteGraph.display(edgeInspectRect(getDescRect(), event)); - if (favoriteGraph.edgeInspect(event)) { - if (!favoriteGraph.flagFocus) { - favoriteGraph.flagFocus = true; - favoriteGraph.onFocus(event); - } - } else { - if (favoriteGraph.flagFocus) { - favoriteGraph.flagFocus = false; - favoriteGraph.onBlur(event); - } - } - if (edgeInspect(event)) { - data.stream().filter( - cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS && cpuData.getStartTime() < endNS) - .forEach(cpuData -> { - cpuData.onMouseMove(event); - if (cpuData.edgeInspect(event)) { - if (!cpuData.flagFocus) { - cpuData.flagFocus = true; - cpuData.onFocus(event); - } - } - }); - } else { - showTipCpuData = null; - } - JComponent component = getRoot(); - if (component instanceof ContentPanel) { - ContentPanel root = ((ContentPanel) component); - root.refreshTab(); - } - } - - /** - * Mouse released event - * - * @param event event - */ - @Override - public void mouseReleased(MouseEvent event) { - } - - /** - * Click event - * - * @param event event - * @param data data - */ - @Override - public void click(MouseEvent event, CpuData data) { - if (showTipCpuData != null) { - clearSelected(); - showTipCpuData.select(true); - showTipCpuData.repaint(); - currentSelectedCpuData = data; - if (AnalystPanel.iCpuDataClick != null) { - AnalystPanel.iCpuDataClick.click(showTipCpuData); - } - } - } - - /** - * Loss of focus event - * - * @param event event - * @param data data - */ - @Override - public void blur(MouseEvent event, CpuData data) { - showTipCpuData = null; - CpuDataFragment.focusCpuData = null; - getRoot().repaint(); - } - - /** - * Get focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(MouseEvent event, CpuData data) { - showTipCpuData = data; - CpuDataFragment.focusCpuData = data; - getRoot().repaint(); - } - - /** - * Mouse movement event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(MouseEvent event, CpuData data) { - showTipCpuData = data; - CpuDataFragment.focusCpuData = data; - tipX = event.getX(); - getRoot().repaint(); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.CpuData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.component.ContentPanel; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.SwingUtilities; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * cpu data + * + * @date 2021/04/22 12:25 + */ +public class CpuDataFragment extends AbstractDataFragment implements CpuData.IEventListener { + /** + * The node that currently has focus + */ + public static CpuData focusCpuData; + + /** + * Currently selected cpu graphics node + */ + public static CpuData currentSelectedCpuData; + + /** + * If this value is not empty, select the node whose startTime is equal to this value after the data is loaded + */ + public Long delayClickStartTime; + + /** + * cpu data collection + */ + private double x1; + + private double x2; + + private Rectangle2D bounds; + + private CpuData showTipCpuData; // Prompt window + + private int tipX; // X position of the message + + private int tipWidth; // Prompt message width + + private int index; + private boolean isLoading; + + /** + * structure + * + * @param root root + * @param index index + * @param data data + */ + public CpuDataFragment(javax.swing.JComponent root, int index, List data) { + super(root, true, false); + this.index = index; + this.setRoot(root); + this.data = data; + } + + /** + * Gets the value of index . + * + * @return the value of int + */ + public int getIndex() { + return index; + } + + /** + * get cpu data list + * + * @return cpu data + */ + public List getData() { + return this.data; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + + // Supplement the information on the left + graphics.setColor(getRoot().getForeground()); + bounds = graphics.getFontMetrics().getStringBounds("Cpu " + index, graphics); + graphics.drawString("Cpu " + index, (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + (getDescRect().getHeight()) / 2 + bounds.getHeight() / 3)); + if (Objects.isNull(data) || data.isEmpty()) { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } else { + data.stream().filter( + cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS + && cpuData.getStartTime() < endNS) + .forEach(cpuGraph -> { + if (cpuGraph.getStartTime() < startNS) { + x1 = 0; + } else { + x1 = getXDouble(cpuGraph.getStartTime()); + } + if (cpuGraph.getStartTime() + cpuGraph.getDuration() > endNS) { + x2 = getDataRect().width; + } else { + x2 = getXDouble(cpuGraph.getStartTime() + cpuGraph.getDuration()); + } + cpuGraph.setRoot(getRoot()); + double getV = x2 - x1 <= 0 ? 1 : x2 - x1; + cpuGraph + .setRect(x1 + getDataRect().getX(), getDataRect().getY() + 5, getV, + getDataRect().getHeight() - 10); + cpuGraph.setEventListener(CpuDataFragment.this); + cpuGraph.draw(graphics); + }); + } + drawTips(graphics); + } + + private void drawTips(Graphics2D graphics) { + if (showTipCpuData != null) { + graphics.setFont(Final.NORMAL_FONT); + if (showTipCpuData.getProcessName() == null || showTipCpuData.getProcessName().isEmpty()) { + showTipCpuData.setProcessName(showTipCpuData.getName()); + } + String process = "P:" + showTipCpuData.getProcessName() + " [" + showTipCpuData.getProcessId() + "]"; + String thread = "T:" + showTipCpuData.getName() + " [" + showTipCpuData.getTid() + "]"; + Rectangle2D processBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(process, graphics); + Rectangle2D threadBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(thread, graphics); + tipWidth = (int) (Math.max(processBounds.getWidth(), threadBounds.getWidth()) + 20); + graphics.setColor(getRoot().getForeground()); + graphics.fillRect(tipX, Utils.getY(showTipCpuData.rect), tipWidth, showTipCpuData.rect.height); + graphics.setColor(getRoot().getBackground()); + graphics.drawString(process, tipX + 10, Utils.getY(showTipCpuData.rect) + 12); + graphics.drawString(thread, tipX + 10, Utils.getY(showTipCpuData.rect) + 24); + } + } + + /** + * Mouse click event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + ContentPanel.clickFragment = this; + data.stream().filter( + cpuData -> cpuData.getStartTime() + cpuData.getDuration() > startNS + && cpuData.getStartTime() < endNS) + .filter(cpuData -> cpuData.edgeInspect(event)).findFirst().ifPresent(cpuData -> cpuData.onClick(event)); + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * Mouse entered event + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * Mouse move event + * + * @param evt evt + */ + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + showTipCpuData = null; + if (edgeInspect(event)) { + data.stream().filter( + cpuData -> cpuData.getStartTime() + + cpuData.getDuration() > startNS && cpuData.getStartTime() < endNS) + .forEach(cpuData -> { + cpuData.onMouseMove(event); + if (cpuData.edgeInspect(event)) { + if (!cpuData.flagFocus) { + cpuData.flagFocus = true; + cpuData.onFocus(event); + } + } + }); + } + } + + /** + * Mouse released event + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + data.clear(); + repaint(); + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + data.clear(); + repaint(); + } + + /** + * Click event + * + * @param evt event + * @param data data + */ + @Override + public void click(MouseEvent evt, CpuData data) { + MouseEvent event = getRealMouseEvent(evt); + clearSelected(); + if (showTipCpuData != null) { + showTipCpuData.select(true); + showTipCpuData.repaint(); + currentSelectedCpuData = CpuDataFragment.focusCpuData; + if (AnalystPanel.iCpuDataClick != null) { + AnalystPanel.iCpuDataClick.click(showTipCpuData); + } + } else { + currentSelectedCpuData = data; + data.select(true); + data.repaint(); + if (AnalystPanel.iCpuDataClick != null) { + AnalystPanel.iCpuDataClick.click(data); + } + } + } + + /** + * Loss of focus event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, CpuData data) { + showTipCpuData = null; + CpuDataFragment.focusCpuData = null; + getRoot().repaint(); + } + + /** + * Get focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, CpuData data) { + showTipCpuData = data; + CpuDataFragment.focusCpuData = data; + getRoot().repaint(); + } + + /** + * Mouse movement event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, CpuData data) { + showTipCpuData = data; + CpuDataFragment.focusCpuData = data; + tipX = event.getX(); + getRoot().repaint(); + } + + private void loadData() { + if (!isLoading) { + isLoading = true; + CompletableFuture.runAsync(() -> { + List cpuData = new ArrayList<>() { + }; + int count = Db.getInstance().queryCount(Sql.SYS_QUERY_CPU_DATA_COUNT, index, startNS, endNS); + if (count > Final.CAPACITY) { + Db.getInstance() + .query(Sql.SYS_QUERY_CPU_DATA_LIMIT, cpuData, index, startNS, endNS, Final.CAPACITY); + } else { + Db.getInstance().query(Sql.SYS_QUERY_CPU_DATA, cpuData, index, startNS, endNS); + } + data = cpuData; + SwingUtilities.invokeLater(() -> { + isLoading = false; + repaint(); + if (delayClickStartTime != null) { + data.stream().filter(it -> it.getStartTime() == delayClickStartTime).findFirst() + .ifPresent(it -> click(null, it)); + delayClickStartTime = null; + } + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragment.java index a58fc2465..e066e8e58 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragment.java @@ -1,270 +1,245 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.fragment.graph.CheckGraph; -import ohos.devtools.views.trace.fragment.graph.FavoriteGraph; - -import javax.swing.JComponent; -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.List; -import java.util.Map; - -/** - * cpu frequency data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuFreqDataFragment extends AbstractDataFragment implements CpuData.IEventListener { - /** - * The currently selected cpu frequency data - */ - public static CpuData currentSelectedCpuData; - - /** - * cpu frequency data collection - */ - public List data; - - /** - * Favorite button - */ - public FavoriteGraph favoriteGraph; - - /** - * Select button - */ - public CheckGraph checkGraph; - - private double x1; - - private double x2; - - private Rectangle2D bounds; - - private String name; - - private Map cpuMaxFreq; - - /** - * Construction method - * - * @param root root - * @param name name - * @param cpuMaxFreq cpuMaxFreq - * @param data data - */ - public CpuFreqDataFragment(JComponent root, String name, Map cpuMaxFreq, List data) { - this.name = name; - this.setRoot(root); - this.data = data; - this.cpuMaxFreq = cpuMaxFreq; - favoriteGraph = new FavoriteGraph(this, root); - checkGraph = new CheckGraph(this, root); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - - // Supplement the information on the left - graphics.setColor(getRoot().getForeground()); - bounds = graphics.getFontMetrics().getStringBounds(name, graphics); - graphics.drawString(name, getDescRect().x + 10, - (int) (getDescRect().y + (getDescRect().height) / 2 + bounds.getHeight() / 3)); - favoriteGraph.setRightGraph(isSelected != null ? checkGraph : null); - checkGraph.setChecked(isSelected); - checkGraph.draw(graphics); - favoriteGraph.draw(graphics); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .7f)); // transparency - String cupFreqName = cpuMaxFreq.get("name").toString(); - Object value = cpuMaxFreq.get("value"); - data.stream().filter(cpuFreqData -> cpuFreqData.getStartTime() + cpuFreqData.getDuration() > startNS - && cpuFreqData.getStartTime() < endNS).forEach(cpuGraph -> { - if (cpuGraph.getStartTime() <= startNS) { - x1 = 0; - } else { - x1 = getXDouble(cpuGraph.getStartTime()); - } - if (cpuGraph.getStartTime() + cpuGraph.getDuration() >= endNS) { - x2 = getDataRect().width; - } else { - x2 = getXDouble(cpuGraph.getStartTime() + cpuGraph.getDuration()); - } - if (value instanceof Double) { - cpuGraph.setMax((Double) value); - } - cpuGraph.setRoot(getRoot()); - cpuGraph.setRect(x1 + getDataRect().x, getDataRect().y, x2 - x1 <= 0 ? 1 : x2 - x1, getDataRect().height); - cpuGraph.draw(graphics); - }); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency - bounds = graphics.getFontMetrics().getStringBounds(cupFreqName, graphics); - graphics.setColor(Color.lightGray); - graphics.drawString(cupFreqName, getDataRect().x + 2, (int) (getDataRect().y + 2 + bounds.getHeight())); - } - - /** - * Mouse click event - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - if (favoriteGraph.edgeInspect(event)) { - favoriteGraph.onClick(event); - } - if (checkGraph.edgeInspect(event)) { - checkGraph.onClick(event); - } - } - - /** - * Mouse pressed event - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * Mouse exited event - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - /** - * Mouse entered event - * - * @param event event - */ - @Override - public void mouseEntered(MouseEvent event) { - } - - /** - * Mouse move event - * - * @param event event - */ - @Override - public void mouseMoved(MouseEvent event) { - clearFocus(event); - favoriteGraph.display(edgeInspectRect(getDescRect(), event)); - if (favoriteGraph.edgeInspect(event)) { - if (!favoriteGraph.flagFocus) { - favoriteGraph.flagFocus = true; - favoriteGraph.onFocus(event); - } - } else { - if (favoriteGraph.flagFocus) { - favoriteGraph.flagFocus = false; - favoriteGraph.onBlur(event); - } - } - if (edgeInspect(event)) { - data.forEach(cpuFreqData -> { - if (cpuFreqData.edgeInspect(event)) { - if (!cpuFreqData.isFlagFocus()) { - cpuFreqData.setFlagFocus(true); - cpuFreqData.onFocus(event); - } - } else { - if (cpuFreqData.isFlagFocus()) { - cpuFreqData.setFlagFocus(false); - cpuFreqData.onBlur(event); - } - } - }); - } - } - - /** - * Mouse released event - * - * @param event event - */ - @Override - public void mouseReleased(MouseEvent event) { - } - - /** - * Click event - * - * @param event event - * @param cpuData cpuData - */ - @Override - public void click(MouseEvent event, CpuData cpuData) { - if (currentSelectedCpuData != null) { - currentSelectedCpuData.select(false); - currentSelectedCpuData.repaint(); - } - cpuData.select(true); - cpuData.repaint(); - currentSelectedCpuData = cpuData; - if (AnalystPanel.iCpuDataClick != null) { - AnalystPanel.iCpuDataClick.click(cpuData); - } - } - - /** - * Loss of focus event - * - * @param event event - * @param data data - */ - @Override - public void blur(MouseEvent event, CpuData data) { - } - - /** - * Get focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(MouseEvent event, CpuData data) { - } - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(MouseEvent event, CpuData data) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.bean.CpuData; +import ohos.devtools.views.trace.bean.CpuFreqData; +import ohos.devtools.views.trace.bean.CpuFreqMax; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.List; + +/** + * cpu frequency data + * + * @date 2021/04/22 12:25 + */ +public class CpuFreqDataFragment extends AbstractDataFragment implements CpuData.IEventListener { + /** + * The currently selected cpu frequency data + */ + public static CpuData currentSelectedCpuData; + + private double x1; + + private double x2; + + private Rectangle2D bounds; + + private String name; + + private CpuFreqMax cpuMaxFreq; + + /** + * Construction method + * + * @param root root + * @param name name + * @param cpuMaxFreq cpuMaxFreq + * @param data data + */ + public CpuFreqDataFragment(JComponent root, String name, CpuFreqMax cpuMaxFreq, List data) { + super(root, true, false); + this.name = name; + this.setRoot(root); + this.data = data; + this.cpuMaxFreq = cpuMaxFreq; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + + // Supplement the information on the left + graphics.setColor(getRoot().getForeground()); + bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + graphics.drawString(name, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + (getDescRect().height) / 2 + bounds.getHeight() / 3)); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .7f)); // transparency + String cupFreqName = cpuMaxFreq.getName(); + Object value = cpuMaxFreq.getValue(); + data.stream().filter(cpuFreqData -> cpuFreqData.getStartTime() + cpuFreqData.getDuration() > startNS + && cpuFreqData.getStartTime() < endNS).forEach(cpuGraph -> { + if (cpuGraph.getStartTime() <= startNS) { + x1 = 0; + } else { + x1 = getXDouble(cpuGraph.getStartTime()); + } + if (cpuGraph.getStartTime() + cpuGraph.getDuration() >= endNS) { + x2 = getDataRect().width; + } else { + x2 = getXDouble(cpuGraph.getStartTime() + cpuGraph.getDuration()); + } + if (value instanceof Double) { + cpuGraph.setMax((Double) value); + } + cpuGraph.setRoot(getRoot()); + cpuGraph.setRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()), x2 - x1 <= 0 ? 1 : x2 - x1, + getDataRect().height); + cpuGraph.draw(graphics); + }); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); // transparency + bounds = graphics.getFontMetrics().getStringBounds(cupFreqName, graphics); + graphics.setColor(Color.lightGray); + graphics.drawString(cupFreqName, Utils.getX(getDataRect()) + 2, + (int) (Utils.getY(getDataRect()) + 2 + bounds.getHeight())); + } + + /** + * Mouse click event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * Mouse entered event + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * Mouse move event + * + * @param evt event + */ + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + if (edgeInspect(event)) { + data.forEach(cpuFreqData -> { + if (cpuFreqData.edgeInspect(event)) { + if (!cpuFreqData.isFlagFocus()) { + cpuFreqData.setFlagFocus(true); + cpuFreqData.onFocus(event); + } + } else { + if (cpuFreqData.isFlagFocus()) { + cpuFreqData.setFlagFocus(false); + cpuFreqData.onBlur(event); + } + } + }); + } + } + + /** + * Mouse released event + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + /** + * Click event + * + * @param event event + * @param cpuData cpuData + */ + @Override + public void click(MouseEvent event, CpuData cpuData) { + if (currentSelectedCpuData != null) { + currentSelectedCpuData.select(false); + currentSelectedCpuData.repaint(); + } + cpuData.select(true); + cpuData.repaint(); + currentSelectedCpuData = cpuData; + if (AnalystPanel.iCpuDataClick != null) { + AnalystPanel.iCpuDataClick.click(cpuData); + } + } + + /** + * Loss of focus event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, CpuData data) { + } + + /** + * Get focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, CpuData data) { + } + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, CpuData data) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/FunctionDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/FunctionDataFragment.java index bd3363dab..26992a1bd 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/FunctionDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/FunctionDataFragment.java @@ -1,228 +1,234 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.component.ContentPanel; -import ohos.devtools.views.trace.util.Final; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; - -/** - * Method call data row - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class FunctionDataFragment extends AbstractDataFragment implements FunctionBean.IEventListener { - /** - * graph event callback - */ - public static FunctionBean currentSelectedFunctionData; - - /** - * Thread object - */ - public ThreadData thread; - - private final ArrayList data; - - /** - * structure - * - * @param contentPanel contentPanel - * @param functionBeans functionBeans - */ - public FunctionDataFragment(JComponent contentPanel, ArrayList functionBeans) { - super(); - this.setRoot(contentPanel); - this.data = functionBeans; - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - - // Supplement the information on the left - graphics.setColor(getRoot().getForeground()); - String name = thread.getThreadName() + " " + thread.getTid(); - Rectangle2D bounds = graphics.getFontMetrics().getStringBounds(name, graphics); - double wordWidth = bounds.getWidth() / name.length(); // Width per character - double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line - if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display - graphics.drawString(name, getDescRect().x + 10, (int) (getDescRect().y + bounds.getHeight() + 10)); - } else { - String substring = name.substring((int) wordNum); - if (substring.length() < wordNum) { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() + 8)); - graphics - .drawString(substring, getDescRect().x + 10, (int) (getDescRect().y + bounds.getHeight() * 2 + 8)); - } else { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() + 2)); - graphics.drawString(substring.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() * 2 + 2)); - graphics.drawString(substring.substring((int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() * 3 + 2)); - } - } - for (FunctionBean bean : data) { - int x1; - int x2; - if (bean.getStartTime() < startNS) { - x1 = getX(startNS); - } else { - x1 = getX(bean.getStartTime()); - } - if (bean.getStartTime() + bean.getDuration() > endNS) { - x2 = getX(endNS); - } else { - x2 = getX(bean.getStartTime() + bean.getDuration()); - } - bean.setRect(x1 + getDataRect().x, getDataRect().y + 10 + 20 * bean.getDepth(), x2 - x1 <= 0 ? 1 : x2 - x1, - 20); - bean.root = getRoot(); - bean.setEventListener(this); - bean.draw(graphics); - } - } - - /** - * Mouse click event - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - if (data != null) { - data.stream() - .filter(bean -> bean.getStartTime() + bean.getDuration() > startNS && bean.getStartTime() < endNS) - .filter(bean -> bean.edgeInspect(event)).findFirst().ifPresent(bean -> { - bean.onClick(event); - }); - } - } - - /** - * Mouse pressed event - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * Mouse exited event - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - /** - * Mouse entered event - * - * @param event event - */ - @Override - public void mouseEntered(MouseEvent event) { - } - - /** - * Mouse moved event - * - * @param event event - */ - @Override - public void mouseMoved(MouseEvent event) { - clearFocus(event); - JComponent component = getRoot(); - if (component instanceof ContentPanel) { - ContentPanel root = ((ContentPanel) component); - root.refreshTab(); - } - } - - /** - * Mouse released event - * - * @param event event - */ - @Override - public void mouseReleased(MouseEvent event) { - } - - /** - * Click event - * - * @param event event - * @param data data - */ - @Override - public void click(MouseEvent event, FunctionBean data) { - clearSelected(); - data.setSelected(true); - data.repaint(); - currentSelectedFunctionData = data; - if (AnalystPanel.iFunctionDataClick != null) { - AnalystPanel.iFunctionDataClick.click(data); - } - } - - /** - * Loss of focus event - * - * @param event event - * @param data data - */ - @Override - public void blur(MouseEvent event, FunctionBean data) { - } - - /** - * Get focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(MouseEvent event, FunctionBean data) { - } - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(MouseEvent event, FunctionBean data) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.bean.FunctionBean; +import ohos.devtools.views.trace.bean.ThreadData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; + +/** + * Method call data row + * + * @date 2021/04/22 12:25 + */ +public class FunctionDataFragment extends AbstractDataFragment implements FunctionBean.IEventListener { + /** + * graph event callback + */ + public static FunctionBean currentSelectedFunctionData; + + /** + * Thread object + */ + public ThreadData thread; + + /** + * structure + * + * @param contentPanel contentPanel + * @param functionBeans functionBeans + */ + public FunctionDataFragment(JComponent contentPanel, ArrayList functionBeans) { + super(contentPanel, true, false); + this.setRoot(contentPanel); + this.data = functionBeans; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + // Supplement the information on the left + graphics.setColor(getRoot().getForeground()); + String name = thread.getThreadName() + " " + thread.getTid(); + Rectangle2D bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + double wordWidth = bounds.getWidth() / name.length(); // Width per character + double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line + if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display + graphics.drawString(name, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 10)); + } else { + String substring = name.substring((int) wordNum); + if (substring.length() < wordNum) { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 8)); + graphics + .drawString(substring, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 8)); + } else { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 2)); + graphics.drawString(substring.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 2)); + graphics.drawString(substring.substring((int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 3 + 2)); + } + } + for (FunctionBean bean : data) { + int x1; + int x2; + if (bean.getStartTime() < startNS) { + x1 = getX(startNS); + } else { + x1 = getX(bean.getStartTime()); + } + if (bean.getStartTime() + bean.getDuration() > endNS) { + x2 = getX(endNS); + } else { + x2 = getX(bean.getStartTime() + bean.getDuration()); + } + bean.setRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 10 + 20 * bean.getDepth(), + x2 - x1 <= 0 ? 1 : x2 - x1, + 20); + bean.root = getRoot(); + bean.setEventListener(this); + bean.draw(graphics); + } + } + + /** + * Mouse click event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + if (data != null) { + data.stream() + .filter(bean -> bean.getStartTime() + bean.getDuration() > startNS && bean.getStartTime() < endNS) + .filter(bean -> bean.edgeInspect(event)).findFirst().ifPresent(bean -> { + bean.onClick(event); + }); + } + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * Mouse entered event + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * Mouse moved event + * + * @param evt event + */ + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + } + + /** + * Mouse released event + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + /** + * Click event + * + * @param event event + * @param data data + */ + @Override + public void click(MouseEvent event, FunctionBean data) { + clearSelected(); + data.setSelected(true); + data.repaint(); + currentSelectedFunctionData = data; + if (AnalystPanel.iFunctionDataClick != null) { + AnalystPanel.iFunctionDataClick.click(data); + } + } + + /** + * Loss of focus event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, FunctionBean data) { + } + + /** + * Get focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, FunctionBean data) { + } + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, FunctionBean data) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/MemDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/MemDataFragment.java index a0e72edc1..c905c2f48 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/MemDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/MemDataFragment.java @@ -1,249 +1,268 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.ProcessMem; -import ohos.devtools.views.trace.bean.ProcessMemData; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.component.ContentPanel; -import ohos.devtools.views.trace.util.Db; -import ohos.devtools.views.trace.util.Final; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.List; -import java.util.concurrent.ForkJoinPool; -import java.util.stream.Collectors; - -/** - * Memory data line - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class MemDataFragment extends AbstractDataFragment implements ThreadData.IEventListener { - /** - * graph event callback - */ - public static ThreadData currentSelectedThreadData; - - /** - * Process memory data - */ - public List data; - - /** - * Process memory - */ - public ProcessMem mem; - private boolean isLoading; - private Rectangle2D bounds; - private int max; - - /** - * structure - * - * @param root root - * @param mem mem - */ - public MemDataFragment(JComponent root, ProcessMem mem) { - this.mem = mem; - this.setRoot(root); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - graphics.setFont(Final.NORMAL_FONT); - graphics.setColor(getRoot().getForeground()); - String name = mem.getTrackName(); - bounds = graphics.getFontMetrics().getStringBounds(name, graphics); - double wordWidth = bounds.getWidth() / name.length(); // Width per character - double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line - if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display - graphics.drawString(name, getDescRect().x + 10, (int) (getDescRect().y + bounds.getHeight() + 10)); - } else { - String substring = name.substring((int) wordNum); - if (substring.length() < wordNum) { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() + 8)); - graphics - .drawString(substring, getDescRect().x + 10, (int) (getDescRect().y + bounds.getHeight() * 2 + 8)); - } else { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() + 2)); - graphics.drawString(substring.substring(0, (int) wordNum), getDescRect().x + 10, - (int) (getDescRect().y + bounds.getHeight() * 2 + 2)); - } - } - drawData(graphics); - } - - private void drawData(Graphics2D graphics) { - if (data != null) { - List collect = data.stream().filter( - memData -> memData.getStartTime() + memData.getDuration() > startNS && memData.getStartTime() < endNS) - .collect(Collectors.toList()); - int x1; - int x2; - for (int index = 0, len = collect.size(); index < len; index++) { - ProcessMemData memData = collect.get(index); - if (index == len - 1) { - memData.setDuration(AnalystPanel.DURATION); - } else { - memData.setDuration(collect.get(index + 1).getStartTime() - memData.getStartTime()); - } - if (memData.getStartTime() < startNS) { - x1 = getX(startNS); - } else { - x1 = getX(memData.getStartTime()); - } - if (memData.getStartTime() + memData.getDuration() > endNS) { - x2 = getX(endNS); - } else { - x2 = getX(memData.getStartTime() + memData.getDuration()); - } - memData.root = getRoot(); - memData - .setRect(x1 + getDataRect().x, getDataRect().y, x2 - x1 <= 0 ? 1 : x2 - x1, getDataRect().height); - memData.setMaxValue(max); - memData.draw(graphics); - } - } else { - graphics.setColor(getRoot().getForeground()); - graphics.drawString("Loading...", getDataRect().x, getDataRect().y + 12); - loadData(); - } - } - - /** - * Mouse clicked event - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - } - - /** - * Mouse pressed event - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * Mouse exited event - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - @Override - public void mouseEntered(MouseEvent event) { - } - - @Override - public void mouseMoved(MouseEvent event) { - clearFocus(event); - JComponent component = getRoot(); - if (component instanceof ContentPanel) { - ContentPanel root = ((ContentPanel) component); - root.refreshTab(); - } - } - - @Override - public void mouseReleased(MouseEvent event) { - } - - private void loadData() { - if (!isLoading) { - isLoading = true; - ForkJoinPool.commonPool().submit(() -> { - data = Db.getInstance().getProcessMemData(mem.getTrackId()); - SwingUtilities.invokeLater(() -> { - data.stream().mapToInt(memData -> memData.getValue()).max().ifPresent(maxData -> { - max = maxData; - }); - isLoading = false; - repaint(); - }); - }); - } - } - - /** - * Mouse click event - * - * @param event event - * @param data data - */ - @Override - public void click(MouseEvent event, ThreadData data) { - clearSelected(); - data.select(true); - data.repaint(); - currentSelectedThreadData = data; - if (AnalystPanel.iThreadDataClick != null) { - AnalystPanel.iThreadDataClick.click(data); - } - } - - /** - * Mouse blur event - * - * @param event event - * @param data data - */ - @Override - public void blur(MouseEvent event, ThreadData data) { - } - - /** - * Mouse focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(MouseEvent event, ThreadData data) { - } - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(MouseEvent event, ThreadData data) { - getRoot().repaint(); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.ProcessMem; +import ohos.devtools.views.trace.bean.ProcessMemData; +import ohos.devtools.views.trace.bean.ThreadData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +/** + * Memory data line + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class MemDataFragment extends AbstractDataFragment implements ThreadData.IEventListener { + /** + * graph event callback + */ + public static ThreadData currentSelectedThreadData; + + /** + * Process memory + */ + public ProcessMem mem; + + private boolean isLoading; + private Rectangle2D bounds; + private int max; + + /** + * structure + * + * @param root root + * @param mem mem + */ + public MemDataFragment(JComponent root, ProcessMem mem) { + super(root, true, false); + this.mem = mem; + this.setRoot(root); + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + graphics.setFont(Final.NORMAL_FONT); + graphics.setColor(getRoot().getForeground()); + String name = mem.getTrackName(); + bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + double wordWidth = bounds.getWidth() / name.length(); // Width per character + double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line + if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display + graphics.drawString(name, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 10)); + } else { + String substring = name.substring((int) wordNum); + if (substring.length() < wordNum) { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 8)); + graphics + .drawString(substring, Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 8)); + } else { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 2)); + graphics.drawString(substring.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 10, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 2)); + } + } + drawData(graphics); + } + + private void drawData(Graphics2D graphics) { + if (data != null) { + List collect = data.stream().filter( + memData -> memData.getStartTime() + + memData.getDuration() > startNS && memData.getStartTime() < endNS) + .collect(Collectors.toList()); + int x1; + int x2; + for (int index = 0, len = collect.size(); index < len; index++) { + ProcessMemData memData = collect.get(index); + if (index == len - 1) { + memData.setDuration(AnalystPanel.DURATION); + } else { + memData.setDuration(collect.get(index + 1).getStartTime() - memData.getStartTime()); + } + if (memData.getStartTime() < startNS) { + x1 = getX(startNS); + } else { + x1 = getX(memData.getStartTime()); + } + if (memData.getStartTime() + memData.getDuration() > endNS) { + x2 = getX(endNS); + } else { + x2 = getX(memData.getStartTime() + memData.getDuration()); + } + memData.root = getRoot(); + memData + .setRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()), x2 - x1 <= 0 ? 1 : x2 - x1, + getDataRect().height); + memData.setMaxValue(max); + memData.draw(graphics); + } + } else { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } + } + + /** + * Mouse clicked event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + private void loadData() { + if (!isLoading) { + isLoading = true; + CompletableFuture.runAsync(() -> { + List list = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_PROCESS_MEM_DATA, list, mem.getTrackId()); + data = list; + SwingUtilities.invokeLater(() -> { + data.stream().mapToInt(memData -> memData.getValue()).max().ifPresent(maxData -> { + max = maxData; + }); + isLoading = false; + repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + /** + * Mouse click event + * + * @param event event + * @param data data + */ + @Override + public void click(MouseEvent event, ThreadData data) { + clearSelected(); + data.select(true); + data.repaint(); + currentSelectedThreadData = data; + if (AnalystPanel.iThreadDataClick != null) { + AnalystPanel.iThreadDataClick.click(data); + } + } + + /** + * Mouse blur event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, ThreadData data) { + } + + /** + * Mouse focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, ThreadData data) { + } + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, ThreadData data) { + getRoot().repaint(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ProcessDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ProcessDataFragment.java index e527c7357..f4ebec5da 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ProcessDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ProcessDataFragment.java @@ -1,245 +1,390 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.bean.Process; -import ohos.devtools.views.trace.bean.ProcessData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.component.ContentPanel; -import ohos.devtools.views.trace.fragment.graph.ExpandGraph; -import ohos.devtools.views.trace.util.ColorUtils; -import ohos.devtools.views.trace.util.Db; -import ohos.devtools.views.trace.util.ImageUtils; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.List; -import java.util.concurrent.ForkJoinPool; - -/** - * process data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ProcessDataFragment extends AbstractDataFragment implements ExpandGraph.IClickListener { - private final ExpandGraph expandGraph; - private final Process process; - private int defaultHeight; - private boolean isLoading; - private int x1; - private int x2; - private Rectangle2D bounds; - - /** - * constructor - * - * @param root root - * @param process process - */ - public ProcessDataFragment(JComponent root, Process process) { - this.process = process; - this.setRoot(root); - expandGraph = new ExpandGraph(this, root); - expandGraph.setOnClickListener(this); - } - - /** - * draw method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - if (AnalystPanel.cpuNum == 0) { - return; - } - drawDefaultState(graphics); - - // left data info - String name; - if (process.getName() == null || process.getName().isEmpty()) { - process.setName("Process"); - } - name = process.getName() + " " + process.getPid(); - bounds = graphics.getFontMetrics().getStringBounds(name, graphics); - double wordWidth = bounds.getWidth() / name.length(); // Width per character - double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line - if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display - graphics.drawString(name, getDescRect().x + 30, (int) (getDescRect().y + bounds.getHeight() + 10)); - } else { - String substring = name.substring((int) wordNum); - if (substring.length() < wordNum) { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 30, - (int) (getDescRect().y + bounds.getHeight() + 8)); - graphics - .drawString(substring, getDescRect().x + 30, (int) (getDescRect().y + bounds.getHeight() * 2 + 8)); - } else { - graphics.drawString(name.substring(0, (int) wordNum), getDescRect().x + 30, - (int) (getDescRect().y + bounds.getHeight() + 2)); - graphics.drawString(substring.substring(0, (int) wordNum), getDescRect().x + 30, - (int) (getDescRect().y + bounds.getHeight() * 2 + 2)); - graphics.drawString(substring.substring((int) wordNum), getDescRect().x + 30, - (int) (getDescRect().y + bounds.getHeight() * 3 + 2)); - } - } - expandGraph.setRect(getDescRect().x + 8, getRect().y + getRect().height / 2 - 6, 12, 12); - expandGraph.draw(graphics); - } - - private void drawDefaultState(Graphics graphics) { - if (!expandGraph.isExpand()) { - int height = (getRect().height) / AnalystPanel.cpuNum; - if (processData != null) { - for (int index = 0; index < processData.size(); index++) { - ProcessData data = this.processData.get(index); - if (data.getStartTime() < startNS) { - x1 = getX(startNS); - } else { - x1 = getX(data.getStartTime()); - } - if (data.getStartTime() + data.getDuration() > endNS) { - x2 = getX(endNS); - } else { - x2 = getX(data.getStartTime() + data.getDuration()); - } - graphics.setColor(ColorUtils.MD_PALETTE[process.getPid() % ColorUtils.MD_PALETTE.length]); - graphics.fillRect(x1 + getDataRect().x, getDataRect().y + height * data.getCpu() + 2, - x2 - x1 <= 0 ? 1 : x2 - x1, height - 4); - } - } else { - if (process.getPid() != 0) { - graphics.setColor(getRoot().getForeground()); - graphics.drawString("Loading...", getDataRect().x, getDataRect().y + 12); - loadData(); - } - } - graphics.setColor(getRoot().getForeground()); - } else { - graphics.setColor(getRoot().getForeground()); - graphics.fillRect(getRect().x, getRect().y, getRect().width, getRect().height); - graphics.setColor(getRoot().getBackground()); - } - } - - /** - * click handler - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - if (expandGraph.edgeInspect(event)) { - expandGraph.onClick(event); - } - } - - /** - * mouse pressed handler - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * mouse exited handler - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - /** - * mouse entered handler - * - * @param event event - */ - @Override - public void mouseEntered(MouseEvent event) { - } - - /** - * mouse moved handler - * - * @param event event - */ - @Override - public void mouseMoved(MouseEvent event) { - clearFocus(event); - } - - /** - * mouse released handler - * - * @param event event - */ - @Override - public void mouseReleased(MouseEvent event) { - } - - /** - * click handler - * - * @param event event - */ - @Override - public void click(MouseEvent event) { - expandGraph.setExpand(!expandGraph.isExpand()); - if (this.getRoot() instanceof ContentPanel) { - ContentPanel contentPanel = (ContentPanel) this.getRoot(); - if (expandGraph.isExpand()) { - expandGraph.setImage(ImageUtils.getInstance().getArrowUpFocus()); - for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { - if (dataFragment.parentUuid.equals(uuid)) { - dataFragment.visible = true; - } - } - } else { - expandGraph.setImage(ImageUtils.getInstance().getArrowDownFocus()); - for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { - if (dataFragment.parentUuid.equals(uuid)) { - dataFragment.visible = false; - } - } - } - contentPanel.refresh(); - } - } - - private List processData; - - private void loadData() { - if (!isLoading) { - isLoading = true; - ForkJoinPool.commonPool().submit(() -> { - processData = Db.getInstance().queryProcessData(process.getPid()); - SwingUtilities.invokeLater(() -> { - isLoading = false; - repaint(); - }); - }); - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.Process; +import ohos.devtools.views.trace.bean.ProcessData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.component.ContentPanel; +import ohos.devtools.views.trace.fragment.graph.ExpandGraph; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.ImageUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * process data + * + * @date 2021/04/22 12:25 + */ +public class ProcessDataFragment extends AbstractDataFragment implements ExpandGraph.IClickListener { + /** + * current focus Process Data . + */ + public static ProcessData focusProcessData = null; + private final Process process; + private final float alpha60 = .6f; + private final float alpha100 = 1.0f; + private ExpandGraph expandGraph; + private boolean isLoading; + private int x1; + private int x2; + private Rectangle2D bounds; + private Color processColor; + private ProcessData tipProcessData = null; + private int tipX; // X position of the message + + /** + * constructor + * + * @param root root + * @param process process + */ + public ProcessDataFragment(JComponent root, Process process) { + super(root, false, false); + this.process = process; + processColor = ColorUtils.colorForTid(process.getPid()); + this.setRoot(root); + expandGraph = new ExpandGraph(this, root); + expandGraph.setOnClickListener(this); + } + + /** + * Gets the value of expandGraph . + * + * @return the value of ohos.devtools.views.trace.fragment.graph.ExpandGraph + */ + public ExpandGraph getExpandGraph() { + return expandGraph; + } + + /** + * Gets the value of process . + * + * @return the value of ohos.devtools.views.trace.bean.Process + */ + public Process getProcess() { + return process; + } + + /** + * draw method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + drawDefaultState(graphics); + + // left data info + String name; + if (process.getName() == null || process.getName().isEmpty()) { + process.setName("Process"); + } + name = process.getName() + " " + process.getPid(); + bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + double wordWidth = bounds.getWidth() / name.length(); // Width per character + double wordNum = (getDescRect().width - 40) / wordWidth; // How many characters can be displayed on each line + if (bounds.getWidth() < getDescRect().width - 40) { // Direct line display + graphics.drawString(name, Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 10)); + } else { + String substring = name.substring((int) wordNum); + if (substring.length() < wordNum) { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 8)); + graphics + .drawString(substring, Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 8)); + } else { + graphics.drawString(name.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() + 2)); + graphics.drawString(substring.substring(0, (int) wordNum), Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 2 + 2)); + graphics.drawString(substring.substring((int) wordNum), Utils.getX(getDescRect()) + 30, + (int) (Utils.getY(getDescRect()) + bounds.getHeight() * 3 + 2)); + } + } + expandGraph.setRect(Utils.getX(getDescRect()) + 8, Utils.getY(getRect()) + getRect().height / 2 - 6, 12, 12); + expandGraph.draw(graphics); + } + + private void drawDefaultState(Graphics graphics) { + if (!expandGraph.isExpand()) { + int height = (getRect().height) / (AnalystPanel.cpuNum == 0 ? 1 : AnalystPanel.cpuNum); + if (data != null) { + if (graphics instanceof Graphics2D) { + data.stream() + .filter(pd -> pd.getStartTime() + pd.getDuration() > startNS && pd.getStartTime() < endNS) + .forEach(pd -> drawProcessData(pd, height, (Graphics2D) graphics)); + drawTips((Graphics2D) graphics); + } + } else { + if (process.getPid() != 0) { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } + } + graphics.setColor(getRoot().getForeground()); + } else { + graphics.setColor(getRoot().getForeground()); + graphics.fillRect(Utils.getX(getRect()), Utils.getY(getRect()), getRect().width, getRect().height); + graphics.setColor(getRoot().getBackground()); + } + } + + private void drawProcessData(ProcessData pd, int height, Graphics2D graphics) { + if (pd.getStartTime() < startNS) { + x1 = getX(startNS); + } else { + x1 = getX(pd.getStartTime()); + } + if (pd.getStartTime() + pd.getDuration() > endNS) { + x2 = getX(endNS); + } else { + x2 = getX(pd.getStartTime() + pd.getDuration()); + } + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha100)); + if (CpuDataFragment.focusCpuData != null || focusProcessData != null) { + if (CpuDataFragment.focusCpuData != null) { + if (CpuDataFragment.focusCpuData.getProcessId() != pd.getPid()) { + graphics.setColor(Color.GRAY); + } else if (CpuDataFragment.focusCpuData.getTid() != pd.getTid()) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(processColor); + } else { + graphics.setColor(processColor); + } + } else { + if (focusProcessData.getPid() != pd.getPid()) { + graphics.setColor(Color.GRAY); + } else if (focusProcessData.getTid() != pd.getTid()) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha60)); + graphics.setColor(processColor); + } else { + graphics.setColor(processColor); + } + } + } else { + graphics.setColor(processColor); + } + pd.setRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()) + height * pd.getCpu() + 2, + x2 - x1 <= 0 ? 1 : x2 - x1, + height - 4); + graphics.fillRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()) + height * pd.getCpu() + 2, + x2 - x1 <= 0 ? 1 : x2 - x1, + height - 4); + } + + private void drawTips(Graphics2D graphics) { + if (tipProcessData != null) { + graphics.setComposite(java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha100)); + graphics.setFont(Final.NORMAL_FONT); + if (tipProcessData.getProcess() == null || tipProcessData.getProcess().isEmpty()) { + tipProcessData.setProcess(tipProcessData.getThread()); + } + String processName = "P:" + tipProcessData.getProcess() + " [" + tipProcessData.getPid() + "]"; + String threadName = "T:" + tipProcessData.getThread() + " [" + tipProcessData.getTid() + "]"; + Rectangle2D processBounds = + graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(processName, graphics); + Rectangle2D threadBounds = graphics.getFontMetrics(Final.NORMAL_FONT).getStringBounds(threadName, graphics); + int tipWidth = (int) (Math.max(processBounds.getWidth(), threadBounds.getWidth()) + 20); + graphics.setColor(getRoot().getForeground()); + graphics.fillRect(tipX, Utils.getY(getRect()), tipWidth, getRect().height); + graphics.setColor(getRoot().getBackground()); + graphics.drawString(processName, tipX + 10, Utils.getY(getRect()) + 12); + graphics.drawString(threadName, tipX + 10, Utils.getY(getRect()) + 24); + } + } + + /** + * click handler + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + if (expandGraph.edgeInspect(event)) { + expandGraph.onClick(event); + } + } + + /** + * mouse pressed handler + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * mouse exited handler + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * mouse entered handler + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * mouse moved handler + * + * @param ent event + */ + @Override + public void mouseMoved(MouseEvent ent) { + MouseEvent event = getRealMouseEvent(ent); + super.mouseMoved(event); + clearFocus(event); + if (!expandGraph.isExpand()) { + tipProcessData = null; + if (edgeInspect(event) && data != null) { + focusProcessData = null; + data.stream().filter(pd -> pd.getStartTime() + pd.getDuration() > startNS && pd.getStartTime() < endNS) + .forEach(pd -> { + if (pd.edgeInspect(event)) { + tipX = event.getX(); + focusProcessData = pd; + tipProcessData = pd; + repaint(); + } + }); + } + } + } + + /** + * mouse released handler + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + /** + * click handler + * + * @param event event + */ + @Override + public void click(MouseEvent event) { + expandGraph.setExpand(!expandGraph.isExpand()); + if (this.getRoot() instanceof ContentPanel) { + ContentPanel contentPanel = (ContentPanel) this.getRoot(); + if (expandGraph.isExpand()) { + expandGraph.setImage(ImageUtils.getInstance().getArrowUpFocus()); + for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { + if (dataFragment.parentUuid.equals(uuid)) { + dataFragment.visible = true; + } + } + } else { + expandGraph.setImage(ImageUtils.getInstance().getArrowDownFocus()); + for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { + if (dataFragment.parentUuid.equals(uuid)) { + dataFragment.visible = false; + } + } + } + contentPanel.refresh(); + } + } + + /** + * expandThreads + */ + public void expandThreads() { + expandGraph.setExpand(true); + if (this.getRoot() instanceof ContentPanel) { + ContentPanel contentPanel = (ContentPanel) this.getRoot(); + if (expandGraph.isExpand()) { + expandGraph.setImage(ImageUtils.getInstance().getArrowUpFocus()); + for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { + if (dataFragment.parentUuid.equals(uuid)) { + dataFragment.visible = true; + } + } + } else { + expandGraph.setImage(ImageUtils.getInstance().getArrowDownFocus()); + for (AbstractDataFragment dataFragment : contentPanel.fragmentList) { + if (dataFragment.parentUuid.equals(uuid)) { + dataFragment.visible = false; + } + } + } + contentPanel.refresh(); + } + } + + private void loadData() { + if (!isLoading) { + isLoading = true; + CompletableFuture.runAsync(() -> { + List list = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_PROCESS_DATA, list, process.getPid()); + data = list; + SwingUtilities.invokeLater(() -> { + isLoading = false; + repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ThreadDataFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ThreadDataFragment.java index 45aecfa87..618431944 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ThreadDataFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ThreadDataFragment.java @@ -1,305 +1,340 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.component.ContentPanel; -import ohos.devtools.views.trace.util.Db; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ForkJoinPool; - -/** - * Thread data row - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ThreadDataFragment extends AbstractDataFragment implements ThreadData.IEventListener { - /** - * graph event callback - */ - public static ThreadData currentSelectedThreadData; - - /** - * Thread data collection - */ - public List data; - - /** - * Thread object - */ - public ThreadData thread; - - private int x1; - - private int x2; - - private Rectangle2D bounds; - - private boolean isLoading; - - /** - * structure - * - * @param root root - * @param thread thread - */ - public ThreadDataFragment(JComponent root, ThreadData thread) { - this.thread = thread; - this.setRoot(root); - this.data = data; - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(Graphics2D graphics) { - super.draw(graphics); - - // Supplement the information on the left - graphics.setColor(getRoot().getForeground()); - String name = thread.getThreadName() + " " + thread.getTid(); - bounds = graphics.getFontMetrics().getStringBounds(name, graphics); - double wordWidth = bounds.getWidth() / name.length(); // Width per character - double wordNum = (getDescRect().getWidth() - 40) / wordWidth; - if (bounds.getWidth() < getDescRect().getWidth() - 40) { // Direct line display - graphics.drawString(name, (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + bounds.getHeight() + 10)); - } else { - String substring = name.substring((int) wordNum); - if (substring.length() < wordNum) { - graphics.drawString(name.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + bounds.getHeight() + 8)); - graphics.drawString(substring, getDescRect().x + 10, - (int) (getDescRect().getY() + bounds.getHeight() * 2 + 8)); - } else { - graphics.drawString(name.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + bounds.getHeight() + 2)); - graphics.drawString(substring.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + bounds.getHeight() * 2 + 2)); - graphics.drawString(substring.substring((int) wordNum), (int) (getDescRect().getX() + 10), - (int) (getDescRect().getY() + bounds.getHeight() * 3 + 2)); - } - } - drawData(graphics); - } - - private void drawData(Graphics2D graphics) { - if (data != null) { - data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS - && threadData.getStartTime() < endNS).forEach(threadData -> { - if (threadData.getStartTime() < startNS) { - x1 = getX(startNS); - } else { - x1 = getX(threadData.getStartTime()); - } - if (threadData.getStartTime() + threadData.getDuration() > endNS) { - x2 = getX(endNS); - } else { - x2 = getX(threadData.getStartTime() + threadData.getDuration()); - } - threadData.setRect(x1 + getDataRect().x, getDataRect().y + 5, x2 - x1 <= 0 ? 1 : x2 - x1, - getDataRect().height - 10); - threadData.root = getRoot(); - threadData.setEventListener(this); - threadData.draw(graphics); - }); - } else { - graphics.setColor(getRoot().getForeground()); - graphics.drawString("Loading...", getDataRect().x, getDataRect().y + 12); - loadData(); - } - } - - /** - * Mouse clicked event - * - * @param event event - */ - @Override - public void mouseClicked(MouseEvent event) { - if (data != null) { - data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS - && threadData.getStartTime() < endNS).filter(threadData -> threadData.edgeInspect(event)).findFirst() - .ifPresent(threadData -> { - threadData.onClick(event); - }); - } - } - - /** - * Mouse pressed event - * - * @param event event - */ - @Override - public void mousePressed(MouseEvent event) { - } - - /** - * Mouse exited event - * - * @param event event - */ - @Override - public void mouseExited(MouseEvent event) { - } - - /** - * Mouse entered event - * - * @param event event - */ - @Override - public void mouseEntered(MouseEvent event) { - } - - /** - * Mouse moved event - * - * @param event event - */ - @Override - public void mouseMoved(MouseEvent event) { - clearFocus(event); - if (edgeInspect(event)) { - if (data != null) { - data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS - && threadData.getStartTime() < endNS).filter(threadData -> threadData.edgeInspect(event)) - .findFirst().ifPresent(filter -> { - filter.onMouseMove(event); - if (filter.edgeInspect(event)) { - if (!filter.flagFocus) { - filter.flagFocus = true; - filter.onFocus(event); - } - } else { - if (filter.flagFocus) { - filter.flagFocus = false; - filter.onBlur(event); - } - } - }); - } - } - JComponent component = getRoot(); - if (component instanceof ContentPanel) { - ContentPanel root = ((ContentPanel) component); - root.refreshTab(); - } - } - - /** - * Mouse released event - * - * @param event event - */ - @Override - public void mouseReleased(MouseEvent event) { - } - - private void loadData() { - if (!isLoading) { - isLoading = true; - ForkJoinPool.commonPool().submit(() -> { - data = Db.getInstance().queryThreadData(thread.getTid()); - ArrayList functionBeans = Db.getInstance().getFunDataByTid(thread.getTid()); - SwingUtilities.invokeLater(() -> { - isLoading = false; - if (!functionBeans.isEmpty()) { - int maxHeight = - (functionBeans.stream().mapToInt(bean -> bean.getDepth()).max().getAsInt() + 1) * 20; - FunctionDataFragment functionDataFragment = - new FunctionDataFragment(this.getRoot(), functionBeans); - functionDataFragment.parentUuid = this.parentUuid; - functionDataFragment.thread = this.thread; - functionDataFragment.defaultHeight = maxHeight + 20; - functionDataFragment.visible = true; - if (this.getRoot() instanceof ContentPanel) { - ContentPanel contentPanel = (ContentPanel) this.getRoot(); - int index = contentPanel.fragmentList.indexOf(this) + 1; - contentPanel.addDataFragment(index, functionDataFragment); - contentPanel.refresh(); - } - } else { - repaint(); - } - }); - }); - } - } - - /** - * click event - * - * @param event event - * @param data data - */ - @Override - public void click(MouseEvent event, ThreadData data) { - clearSelected(); - data.select(true); - data.repaint(); - currentSelectedThreadData = data; - if (AnalystPanel.iThreadDataClick != null) { - AnalystPanel.iThreadDataClick.click(data); - } - } - - /** - * Mouse blur event - * - * @param event event - * @param data data - */ - @Override - public void blur(MouseEvent event, ThreadData data) { - } - - /** - * Mouse focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(MouseEvent event, ThreadData data) { - } - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(MouseEvent event, ThreadData data) { - getRoot().repaint(); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.FunctionBean; +import ohos.devtools.views.trace.bean.ThreadData; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.component.ContentPanel; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * Thread data row + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public class ThreadDataFragment extends AbstractDataFragment implements ThreadData.IEventListener { + /** + * graph event callback + */ + public static ThreadData currentSelectedThreadData; + + /** + * Thread object + */ + public ThreadData thread; + + /** + * delayClickStartTime + */ + public Long delayClickStartTime; + + private int x1; + private int x2; + private Rectangle2D bounds; + private boolean isLoading; + + /** + * structure + * + * @param root root + * @param thread thread + */ + public ThreadDataFragment(JComponent root, ThreadData thread) { + super(root, true, false); + this.thread = thread; + this.setRoot(root); + } + + /** + * getData + * + * @return List + */ + public List getData() { + return this.data; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(Graphics2D graphics) { + super.draw(graphics); + + // Supplement the information on the left + graphics.setColor(getRoot().getForeground()); + String name = thread.getThreadName() + " " + thread.getTid(); + bounds = graphics.getFontMetrics().getStringBounds(name, graphics); + double wordWidth = bounds.getWidth() / name.length(); // Width per character + double wordNum = (getDescRect().getWidth() - 40) / wordWidth; + if (bounds.getWidth() < getDescRect().getWidth() - 40) { // Direct line display + graphics.drawString(name, (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + bounds.getHeight() + 10)); + } else { + String substring = name.substring((int) wordNum); + if (substring.length() < wordNum) { + graphics.drawString(name.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + bounds.getHeight() + 8)); + graphics.drawString(substring, Utils.getX(getDescRect()) + 10, + (int) (getDescRect().getY() + bounds.getHeight() * 2 + 8)); + } else { + graphics.drawString(name.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + bounds.getHeight() + 2)); + graphics.drawString(substring.substring(0, (int) wordNum), (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + bounds.getHeight() * 2 + 2)); + graphics.drawString(substring.substring((int) wordNum), (int) (getDescRect().getX() + 10), + (int) (getDescRect().getY() + bounds.getHeight() * 3 + 2)); + } + } + drawData(graphics); + } + + private void drawData(Graphics2D graphics) { + if (data != null) { + data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS + && threadData.getStartTime() < endNS).forEach(threadData -> { + if (threadData.getStartTime() < startNS) { + x1 = getX(startNS); + } else { + x1 = getX(threadData.getStartTime()); + } + if (threadData.getStartTime() + threadData.getDuration() > endNS) { + x2 = getX(endNS); + } else { + x2 = getX(threadData.getStartTime() + threadData.getDuration()); + } + threadData.setRect(x1 + Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 5, + x2 - x1 <= 0 ? 1 : x2 - x1, + getDataRect().height - 10); + threadData.root = getRoot(); + threadData.setEventListener(this); + threadData.draw(graphics); + }); + } else { + graphics.setColor(getRoot().getForeground()); + graphics.drawString("Loading...", Utils.getX(getDataRect()), Utils.getY(getDataRect()) + 12); + loadData(); + } + } + + /** + * Mouse clicked event + * + * @param event event + */ + @Override + public void mouseClicked(MouseEvent event) { + super.mouseClicked(event); + if (data != null) { + data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS + && threadData.getStartTime() < endNS).filter(threadData -> threadData.edgeInspect(event)).findFirst() + .ifPresent(threadData -> { + threadData.setProcessName(thread.getProcessName()); + threadData.setThreadName(thread.getThreadName()); + threadData.onClick(event); + }); + } + } + + /** + * Mouse pressed event + * + * @param event event + */ + @Override + public void mousePressed(MouseEvent event) { + } + + /** + * Mouse exited event + * + * @param event event + */ + @Override + public void mouseExited(MouseEvent event) { + } + + /** + * Mouse entered event + * + * @param event event + */ + @Override + public void mouseEntered(MouseEvent event) { + } + + /** + * Mouse moved event + * + * @param evt event + */ + @Override + public void mouseMoved(MouseEvent evt) { + MouseEvent event = getRealMouseEvent(evt); + super.mouseMoved(event); + clearFocus(event); + if (edgeInspect(event)) { + if (data != null) { + data.stream().filter(threadData -> threadData.getStartTime() + threadData.getDuration() > startNS + && threadData.getStartTime() < endNS).filter(threadData -> threadData.edgeInspect(event)) + .findFirst().ifPresent(filter -> { + filter.onMouseMove(event); + if (filter.edgeInspect(event)) { + if (!filter.flagFocus) { + filter.flagFocus = true; + filter.onFocus(event); + } + } else { + if (filter.flagFocus) { + filter.flagFocus = false; + filter.onBlur(event); + } + } + }); + } + } + } + + /** + * Mouse released event + * + * @param event event + */ + @Override + public void mouseReleased(MouseEvent event) { + } + + /** + * key released event + * + * @param event event + */ + @Override + public void keyReleased(KeyEvent event) { + } + + private void loadData() { + if (!isLoading) { + isLoading = true; + CompletableFuture.runAsync(() -> { + List list = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_QUERY_THREAD_DATA, list, thread.getTid()); + data = list; + ArrayList functionBeans = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_FUN_DATA_BY_TID, functionBeans, thread.getTid()); + SwingUtilities.invokeLater(() -> { + isLoading = false; + if (!functionBeans.isEmpty()) { + int maxHeight = + (functionBeans.stream().mapToInt(bean -> bean.getDepth()).max().getAsInt() + 1) * 20; + FunctionDataFragment functionDataFragment = + new FunctionDataFragment(this.getRoot(), functionBeans); + functionDataFragment.parentUuid = this.parentUuid; + functionDataFragment.thread = this.thread; + functionDataFragment.defaultHeight = maxHeight + 20; + functionDataFragment.visible = true; + if (this.getRoot() instanceof ContentPanel) { + ContentPanel contentPanel = (ContentPanel) this.getRoot(); + int index = contentPanel.fragmentList.indexOf(this) + 1; + contentPanel.addDataFragment(index, functionDataFragment); + contentPanel.refresh(); + } + } else { + repaint(); + } + if (delayClickStartTime != null) { + data.stream().filter(it -> it.getStartTime() == delayClickStartTime).findFirst() + .ifPresent(it -> { + click(null, it); + delayClickStartTime = null; + }); + } + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + } + + /** + * click event + * + * @param event event + * @param data data + */ + @Override + public void click(MouseEvent event, ThreadData data) { + clearSelected(); + data.select(true); + data.repaint(); + currentSelectedThreadData = data; + if (AnalystPanel.iThreadDataClick != null) { + AnalystPanel.iThreadDataClick.click(data); + } + } + + /** + * Mouse blur event + * + * @param event event + * @param data data + */ + @Override + public void blur(MouseEvent event, ThreadData data) { + } + + /** + * Mouse focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(MouseEvent event, ThreadData data) { + } + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(MouseEvent event, ThreadData data) { + getRoot().repaint(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/AbstractGraph.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/AbstractGraph.java index 3497920d1..27e264368 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/AbstractGraph.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/AbstractGraph.java @@ -1,120 +1,120 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.fragment.ruler.AbstractNode; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; - -/** - * Data line graphics - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public abstract class AbstractGraph extends AbstractNode { - /** - * fragment - */ - public AbstractDataFragment fragment; - /** - * root - */ - public JComponent root; - /** - * rect - */ - public Rectangle rect = new Rectangle(0, 0, 0, 0); - - /** - * Drawing method - * - * @param graphics graphics - */ - public abstract void draw(Graphics2D graphics); - - /** - * Get focus event - * - * @param event event - */ - public abstract void onFocus(MouseEvent event); - - /** - * Loss of focus event - * - * @param event event - */ - public abstract void onBlur(MouseEvent event); - - /** - * Click event - * - * @param event event - */ - public abstract void onClick(MouseEvent event); - - /** - * Mouse movement event - * - * @param event event - */ - public abstract void onMouseMove(MouseEvent event); - - /** - * Control the focus blur event is triggered only once, the focus blur is initiated by mouseMove - */ - public boolean flagFocus; - - /** - * Whether the mouse is inside the graphics area - * - * @param event event - * @return boolean boolean - */ - public boolean edgeInspect(final MouseEvent event) { - return event.getX() >= rect.getX() && event.getX() <= rect.getX() + rect.getWidth() && event.getY() >= rect - .getY() && event.getY() <= rect.getY() + rect.getHeight(); - } - - /** - * Redraw the current graph - */ - public void repaint() { - if (root != null) { - root.repaint(rect); - } - } - - /** - * Set rect object - * - * @param xAxis x coordinate - * @param yAxis y coordinate - * @param width width - * @param height height - */ - public void setRect(final double xAxis, final double yAxis, final double width, final double height) { - if (rect == null) { - rect = new Rectangle(); - } - rect.setRect(xAxis, yAxis, width, height); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.fragment.ruler.AbstractNode; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * Data line graphics + * + * @date 2021/04/22 12:25 + */ +public abstract class AbstractGraph extends AbstractNode { + /** + * fragment + */ + public AbstractDataFragment fragment; + + /** + * root + */ + public JComponent root; + + /** + * rect + */ + public Rectangle rect = new Rectangle(0, 0, 0, 0); + + /** + * Control the focus blur event is triggered only once, the focus blur is initiated by mouseMove + */ + public boolean flagFocus; + + /** + * Drawing method + * + * @param graphics graphics + */ + public abstract void draw(Graphics2D graphics); + + /** + * Get focus event + * + * @param event event + */ + public abstract void onFocus(MouseEvent event); + + /** + * Loss of focus event + * + * @param event event + */ + public abstract void onBlur(MouseEvent event); + + /** + * Click event + * + * @param event event + */ + public abstract void onClick(MouseEvent event); + + /** + * Mouse movement event + * + * @param event event + */ + public abstract void onMouseMove(MouseEvent event); + + /** + * Whether the mouse is inside the graphics area + * + * @param event event + * @return boolean boolean + */ + public boolean edgeInspect(final MouseEvent event) { + return rect.contains(event.getPoint()); + } + + /** + * Redraw the current graph + */ + public void repaint() { + if (root != null) { + root.repaint(rect); + } + } + + /** + * Set rect object + * + * @param xAxis x coordinate + * @param yAxis y coordinate + * @param width width + * @param height height + */ + public void setRect(final double xAxis, final double yAxis, final double width, final double height) { + if (rect == null) { + rect = new Rectangle(); + } + rect.setRect(xAxis, yAxis, width, height); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/CheckGraph.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/CheckGraph.java index 8dbdb0c28..2af569dff 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/CheckGraph.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/CheckGraph.java @@ -1,125 +1,125 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.util.ImageUtils; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.event.MouseEvent; - -/** - * Data row selection CheckBox - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CheckGraph extends AbstractGraph { - private Boolean isChecked; - private Image checkNo = ImageUtils.getInstance().getCheckNo(); - private Image checkYes = ImageUtils.getInstance().getCheckYes(); - - /** - * Gets the value of isChecked . - * - * @return the value of java.lang.Boolean - */ - public Boolean getChecked() { - return isChecked; - } - - /** - * Sets the isChecked . - *

You can use getChecked() to get the value of isChecked

- * - * @param isChecked isChecked - */ - public void setChecked(final Boolean isChecked) { - this.isChecked = isChecked; - } - - /** - * structure - * - * @param fragment fragment - * @param root root - */ - public CheckGraph(final AbstractDataFragment fragment, final JComponent root) { - this.fragment = fragment; - this.root = root; - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - if (isChecked != null) { - final int size = 12; - final int xOffset = 18; - final int yOffset = 6; - rect.width = size; - rect.height = size; - rect.x = fragment.getDescRect().width - xOffset; - rect.y = fragment.getRect().y + fragment.getRect().height / 2 - yOffset; - if (isChecked) { - graphics.drawImage(checkYes, rect.x, rect.y, rect.width, rect.height, null); - } else { - graphics.drawImage(checkNo, rect.x, rect.y, rect.width, rect.height, null); - } - } - } - - /** - * Get focus event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - } - - /** - * Loss of focus event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.util.ImageUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.event.MouseEvent; + +/** + * Data row selection CheckBox + * + * @date 2021/04/22 12:25 + */ +public class CheckGraph extends AbstractGraph { + private Boolean isChecked; + private Image checkNo = ImageUtils.getInstance().getCheckNo(); + private Image checkYes = ImageUtils.getInstance().getCheckYes(); + + /** + * structure + * + * @param fragment fragment + * @param root root + */ + public CheckGraph(final AbstractDataFragment fragment, final JComponent root) { + this.fragment = fragment; + this.root = root; + } + + /** + * Gets the value of isChecked . + * + * @return the value of java.lang.Boolean + */ + public Boolean getChecked() { + return isChecked; + } + + /** + * Sets the isChecked . + *

You can use getChecked() to get the value of isChecked

+ * + * @param isChecked isChecked + */ + public void setChecked(final Boolean isChecked) { + this.isChecked = isChecked; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isChecked != null) { + final int size = 12; + final int xOffset = 18; + final int yOffset = 6; + rect.width = size; + rect.height = size; + Utils.setX(rect, fragment.getDescRect().width - xOffset); + Utils.setY(rect, Utils.getY(fragment.getRect()) + fragment.getRect().height / 2 - yOffset); + if (isChecked) { + graphics.drawImage(checkYes, Utils.getX(rect), Utils.getY(rect), rect.width, rect.height, null); + } else { + graphics.drawImage(checkNo, Utils.getX(rect), Utils.getY(rect), rect.width, rect.height, null); + } + } + } + + /** + * Get focus event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + } + + /** + * Loss of focus event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/ExpandGraph.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/ExpandGraph.java index a8733487d..b3ebdd1a9 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/ExpandGraph.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/ExpandGraph.java @@ -1,177 +1,176 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.util.ImageUtils; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.event.MouseEvent; - -/** - * dataPanel open - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class ExpandGraph extends AbstractGraph { - private boolean isExpand; - private Image image = ImageUtils.getInstance().getArrowDown(); - - /** - * Gets the value of image . - * - * @return the value of java.awt.Image - */ - public Image getImage() { - return image; - } - - /** - * Sets the image . - *

You can use getImage() to get the value of image

- * - * @param image image - */ - public void setImage(final Image image) { - this.image = image; - } - - /** - * Gets the value of isExpand . - * - * @return the value of boolean - */ - public boolean isExpand() { - return isExpand; - } - - /** - * Sets the isExpand . - *

You can use getExpand() to get the value of isExpand

- * - * @param expand expand - */ - public void setExpand(final boolean expand) { - this.isExpand = expand; - } - - /** - * class construct - * - * @param fragment fragment - * @param root root - */ - public ExpandGraph(final AbstractDataFragment fragment, final JComponent root) { - this.fragment = fragment; - this.root = root; - } - - /** - * draw by graphics - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - if (isExpand) { - image = ImageUtils.getInstance().getArrowUpFocus(); - } else { - if (flagFocus) { - image = ImageUtils.getInstance().getArrowDownFocus(); - } else { - image = ImageUtils.getInstance().getArrowDown(); - } - } - graphics.drawImage(image, rect.x, rect.y, 12, 12, null); - } - - /** - * when view onFocus - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - if (isExpand) { - image = ImageUtils.getInstance().getArrowUpFocus(); - } else { - image = ImageUtils.getInstance().getArrowDownFocus(); - } - repaint(); - } - - /** - * when view onBlur - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - if (isExpand) { - image = ImageUtils.getInstance().getArrowUp(); - } else { - image = ImageUtils.getInstance().getArrowDown(); - } - repaint(); - } - - /** - * when view onClick - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - if (clickListener != null) { - clickListener.click(event); - } - } - - /** - * when view onMouseMove - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } - - private IClickListener clickListener; - - /** - * setOnClickListener - * - * @param listener listener - */ - public void setOnClickListener(final IClickListener listener) { - clickListener = listener; - } - - /** - * click listener class - */ - public interface IClickListener { - /** - * click event - * - * @param event event - */ - void click(MouseEvent event); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.util.ImageUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.event.MouseEvent; + +/** + * dataPanel open + * + * @date 2021/04/22 12:25 + */ +public class ExpandGraph extends AbstractGraph { + private boolean isExpand; + private Image image = ImageUtils.getInstance().getArrowDown(); + private IClickListener clickListener; + + /** + * class construct + * + * @param fragment fragment + * @param root root + */ + public ExpandGraph(final AbstractDataFragment fragment, final JComponent root) { + this.fragment = fragment; + this.root = root; + } + + /** + * Gets the value of image . + * + * @return the value of java.awt.Image + */ + public Image getImage() { + return image; + } + + /** + * Sets the image . + *

You can use getImage() to get the value of image

+ * + * @param image image + */ + public void setImage(final Image image) { + this.image = image; + } + + /** + * Gets the value of isExpand . + * + * @return the value of boolean + */ + public boolean isExpand() { + return isExpand; + } + + /** + * Sets the isExpand . + *

You can use getExpand() to get the value of isExpand

+ * + * @param expand expand + */ + public void setExpand(final boolean expand) { + this.isExpand = expand; + } + + /** + * draw by graphics + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + if (isExpand) { + image = ImageUtils.getInstance().getArrowUpFocus(); + } else { + if (flagFocus) { + image = ImageUtils.getInstance().getArrowDownFocus(); + } else { + image = ImageUtils.getInstance().getArrowDown(); + } + } + graphics.drawImage(image, Utils.getX(rect), Utils.getY(rect), 12, 12, null); + } + + /** + * when view onFocus + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + if (isExpand) { + image = ImageUtils.getInstance().getArrowUpFocus(); + } else { + image = ImageUtils.getInstance().getArrowDownFocus(); + } + repaint(); + } + + /** + * when view onBlur + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + if (isExpand) { + image = ImageUtils.getInstance().getArrowUp(); + } else { + image = ImageUtils.getInstance().getArrowDown(); + } + repaint(); + } + + /** + * when view onClick + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (clickListener != null) { + clickListener.click(event); + } + } + + /** + * when view onMouseMove + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } + + /** + * setOnClickListener + * + * @param listener listener + */ + public void setOnClickListener(final IClickListener listener) { + clickListener = listener; + } + + /** + * click listener class + */ + public interface IClickListener { + /** + * click event + * + * @param event event + */ + void click(MouseEvent event); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraph.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraph.java index b7c4917c5..e8cae014a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraph.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraph.java @@ -1,171 +1,211 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.util.ImageUtils; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.event.MouseEvent; - -/** - * Data row collection button - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class FavoriteGraph extends AbstractGraph { - private boolean isFavorite; - private boolean isDisplay; - private Image img = ImageUtils.getInstance().getStar(); - private Image imgFill = ImageUtils.getInstance().getStarFill(); - private AbstractGraph rightGraph; - - /** - * Gets the value of rightGraph . - * - * @return the value of ohos.devtools.views.trace.fragment.graph.Graph - */ - public AbstractGraph getRightGraph() { - return rightGraph; - } - - /** - * Sets the rightGraph . - *

You can use getRightGraph() to get the value of rightGraph

- * - * @param rightGraph rightGraph - */ - public void setRightGraph(final AbstractGraph rightGraph) { - this.rightGraph = rightGraph; - } - - /** - * structure - * - * @param fragment fragment fragment - * @param root root root - */ - public FavoriteGraph(final AbstractDataFragment fragment, final JComponent root) { - this.fragment = fragment; - this.root = root; - } - - /** - * Determine whether to display - * - * @return boolean boolean - */ - public boolean isDisplay() { - return isDisplay; - } - - /** - * Show favorites - * - * @param show show - */ - public void display(final boolean show) { - isDisplay = show; - if (root != null) { - root.repaint(rect); - } - } - - /** - * Determine whether to save - * - * @return boolean boolean - */ - public boolean isFavorite() { - return isFavorite; - } - - /** - * favorite - * - * @param favorite favorite - */ - public void favorite(final boolean favorite) { - isFavorite = favorite; - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - final int size = 12; - final int xOffset = 18; - final int yOffset = 6; - final int padding = 10; - rect.width = size; - rect.height = size; - rect.y = fragment.getRect().y + fragment.getRect().height / 2 - yOffset; - if (rightGraph == null) { - rect.x = fragment.getDescRect().width - xOffset; - } else { - rect.x = fragment.getDescRect().width - xOffset - size - padding; - } - if (isFavorite) { - graphics.drawImage(ImageUtils.getInstance().getStarFill(), rect.x, rect.y, rect.width, rect.height, null); - } else { - if (isDisplay) { - graphics.drawImage(ImageUtils.getInstance().getStar(), rect.x, rect.y, rect.width, rect.height, null); - } - } - } - - /** - * Get focus event - * - * @param event event - */ - @Override - public void onFocus(final MouseEvent event) { - } - - /** - * Loss of focus event - * - * @param event event - */ - @Override - public void onBlur(final MouseEvent event) { - } - - /** - * Click event - * - * @param event event - */ - @Override - public void onClick(final MouseEvent event) { - } - - /** - * Mouse movement event - * - * @param event event - */ - @Override - public void onMouseMove(final MouseEvent event) { - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import ohos.devtools.views.trace.util.ImageUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.event.MouseEvent; +import java.util.Objects; + +/** + * Data row collection button + * + * @date 2021/04/22 12:25 + */ +public class FavoriteGraph extends AbstractGraph { + private boolean isFavorite; + private boolean isDisplay; + private Image img = ImageUtils.getInstance().getStar(); + private Image imgFill = ImageUtils.getInstance().getStarFill(); + private AbstractGraph rightGraph; + private IGraphListener listener; + + /** + * structure + * + * @param fragment fragment fragment + * @param root root root + * @param listener listener + */ + public FavoriteGraph(final AbstractDataFragment fragment, final JComponent root, IGraphListener listener) { + this.fragment = fragment; + this.root = root; + this.listener = listener; + } + + /** + * Gets the value of rightGraph . + * + * @return the value of ohos.devtools.views.trace.fragment.graph.Graph + */ + public AbstractGraph getRightGraph() { + return rightGraph; + } + + /** + * Sets the rightGraph . + *

You can use getRightGraph() to get the value of rightGraph

+ * + * @param rightGraph rightGraph + */ + public void setRightGraph(final AbstractGraph rightGraph) { + this.rightGraph = rightGraph; + } + + /** + * Determine whether to display + * + * @return boolean boolean + */ + public boolean isDisplay() { + return isDisplay; + } + + /** + * Show favorites + * + * @param show show + */ + public void display(final boolean show) { + isDisplay = show; + if (root != null) { + root.repaint(rect); + } + } + + /** + * Determine whether to save + * + * @return boolean boolean + */ + public boolean isFavorite() { + return isFavorite; + } + + /** + * favorite + * + * @param favorite favorite + */ + public void favorite(final boolean favorite) { + isFavorite = favorite; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + final int size = 12; + final int xOffset = 18; + final int yOffset = 6; + final int padding = 10; + rect.width = size; + rect.height = size; + Utils.setY(rect, Utils.getY(fragment.getRect()) + fragment.getRect().height / 2 - yOffset); + if (rightGraph == null) { + Utils.setX(rect, fragment.getDescRect().width - xOffset); + } else { + Utils.setX(rect, fragment.getDescRect().width - xOffset - size - padding); + } + if (isFavorite) { + graphics.drawImage(ImageUtils.getInstance().getStarFill(), Utils.getX(rect), Utils.getY(rect), rect.width, + rect.height, null); + } else { + if (isDisplay) { + graphics.drawImage(ImageUtils.getInstance().getStar(), Utils.getX(rect), Utils.getY(rect), rect.width, + rect.height, null); + } + } + } + + /** + * Get focus event + * + * @param event event + */ + @Override + public void onFocus(final MouseEvent event) { + } + + /** + * Loss of focus event + * + * @param event event + */ + @Override + public void onBlur(final MouseEvent event) { + } + + /** + * Click event + * + * @param event event + */ + @Override + public void onClick(final MouseEvent event) { + if (Objects.nonNull(listener)) { + listener.click(event); + } + } + + /** + * Mouse movement event + * + * @param event event + */ + @Override + public void onMouseMove(final MouseEvent event) { + } + + /** + * Gets the value of listener . + * + * @return the value of ohos.devtools.views.trace.fragment.graph.FavoriteGraph.IGraphListener + */ + public IGraphListener getListener() { + return listener; + } + + /** + * Sets the listener . + *

You can use getListener() to get the value of listener

+ * + * @param listener listener + */ + public void setListener(IGraphListener listener) { + this.listener = listener; + } + + /** + * IGraphListener + */ + public interface IGraphListener { + /** + * click + * + * @param event event + */ + void click(MouseEvent event); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragment.java index da34c6288..4776d7269 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragment.java @@ -1,188 +1,188 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.component.AnalystPanel; - -import javax.swing.JComponent; -import java.awt.Color; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; - -/** - * basic data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public abstract class AbstractFragment extends AbstractNode implements IFragment { - private Rectangle rect = new Rectangle(0, 0, 0, 0); - private Rectangle descRect = new Rectangle(0, 0, 0, 0); - private Rectangle dataRect = new Rectangle(0, 0, 0, 0); - private JComponent root; - private final Color lineColor = new Color(255, 255, 255, 80); - private final Color textColor = new Color(0x999999); - - /** - * Gets the value of rect . - * - * @return the value of java.awt.Rectangle - */ - public Rectangle getRect() { - return rect; - } - - /** - * Sets the rect . - *

You can use getRect() to get the value of rect

- * - * @param rect rect - */ - public void setRect(final Rectangle rect) { - this.rect = rect; - } - - /** - * Gets the value of descRect . - * - * @return the value of java.awt.Rectangle - */ - public Rectangle getDescRect() { - return descRect; - } - - /** - * Sets the descRect . - *

You can use getDescRect() to get the value of descRect

- * - * @param descRect descRect - */ - public void setDescRect(final Rectangle descRect) { - this.descRect = descRect; - } - - /** - * Gets the value of dataRect . - * - * @return the value of java.awt.Rectangle - */ - public Rectangle getDataRect() { - return dataRect; - } - - /** - * Sets the dataRect . - *

You can use getDataRect() to get the value of dataRect

- * - * @param dataRect dataRect - */ - public void setDataRect(final Rectangle dataRect) { - this.dataRect = dataRect; - } - - /** - * Gets the value of root . - * - * @return the value of javax.swing.JComponent - */ - public JComponent getRoot() { - return root; - } - - /** - * Sets the root . - *

You can use getRoot() to get the value of root

- * - * @param jComponent component - */ - public void setRoot(final JComponent jComponent) { - this.root = jComponent; - } - - /** - * Gets the value of lineColor . - * - * @return the value of java.awt.Color - */ - public Color getLineColor() { - return lineColor; - } - - /** - * Gets the value of textColor . - * - * @return the value of java.awt.Color - */ - public Color getTextColor() { - return textColor; - } - - /** - * repaint. - */ - public void repaint() { - if (root != null) { - root.repaint(rect); - } - } - - /** - * x to time. - * - * @param xValue x - * @return long time - */ - public long x2ns(final int xValue) { - long ns = (xValue - rect.x) * AnalystPanel.DURATION / (root.getWidth() - rect.x); - return ns; - } - - /** - * time to x. - * - * @param ns time - * @return int x - */ - public int ns2x(final long ns) { - long xValue = ns * (root.getWidth() - rect.x) / AnalystPanel.DURATION; - return (int) xValue + rect.x; - } - - /** - - * edge inspect - * - * @param event event - * @return boolean boolean - */ - public boolean edgeInspect(final MouseEvent event) { - return event.getX() >= rect.x && event.getX() <= rect.x + rect.width && event.getY() >= rect.y - && event.getY() <= rect.y + rect.height; - } - - /** - * edge inspect - * - * @param rectangle rectangle - * @param event event - * @return boolean boolean - */ - public boolean edgeInspectRect(final Rectangle rectangle, final MouseEvent event) { - return event.getX() >= rectangle.x && event.getX() <= rectangle.x + rectangle.width - && event.getY() >= rectangle.y && event.getY() <= rectangle.y + rectangle.height; - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.Color; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; + +/** + * basic data + * + * @date 2021/04/22 12:25 + */ +public abstract class AbstractFragment extends AbstractNode implements IFragment { + private final Color lineColor = new Color(255, 255, 255, 80); + private final Color textColor = new Color(0x999999); + private Rectangle rect = new Rectangle(0, 0, 0, 0); + private Rectangle descRect = new Rectangle(0, 0, 0, 0); + private Rectangle dataRect = new Rectangle(0, 0, 0, 0); + private JComponent root; + + /** + * Gets the value of rect . + * + * @return the value of java.awt.Rectangle + */ + public Rectangle getRect() { + return rect; + } + + /** + * Sets the rect . + *

You can use getRect() to get the value of rect

+ * + * @param rect rect + */ + public void setRect(final Rectangle rect) { + this.rect = rect; + } + + /** + * Gets the value of descRect . + * + * @return the value of java.awt.Rectangle + */ + public Rectangle getDescRect() { + return descRect; + } + + /** + * Sets the descRect . + *

You can use getDescRect() to get the value of descRect

+ * + * @param descRect descRect + */ + public void setDescRect(final Rectangle descRect) { + this.descRect = descRect; + } + + /** + * Gets the value of dataRect . + * + * @return the value of java.awt.Rectangle + */ + public Rectangle getDataRect() { + return dataRect; + } + + /** + * Sets the dataRect . + *

You can use getDataRect() to get the value of dataRect

+ * + * @param dataRect dataRect + */ + public void setDataRect(final Rectangle dataRect) { + this.dataRect = dataRect; + } + + /** + * Gets the value of root . + * + * @return the value of javax.swing.JComponent + */ + public JComponent getRoot() { + return root; + } + + /** + * Sets the root . + *

You can use getRoot() to get the value of root

+ * + * @param jComponent component + */ + public void setRoot(final JComponent jComponent) { + this.root = jComponent; + } + + /** + * Gets the value of lineColor . + * + * @return the value of java.awt.Color + */ + public Color getLineColor() { + return lineColor; + } + + /** + * Gets the value of textColor . + * + * @return the value of java.awt.Color + */ + public Color getTextColor() { + return textColor; + } + + /** + * repaint. + */ + public void repaint() { + if (root != null) { + root.repaint(rect); + } + } + + /** + * x to time. + * + * @param xValue x + * @return long time + */ + public long x2ns(final int xValue) { + long ns = (xValue - Utils.getX(rect)) * AnalystPanel.DURATION / (root.getWidth() - Utils.getX(rect)); + return ns; + } + + /** + * time to x. + * + * @param ns time + * @return int x + */ + public int ns2x(final long ns) { + long xValue = ns * (root.getWidth() - Utils.getX(rect)) / AnalystPanel.DURATION; + return (int) xValue + Utils.getX(rect); + } + + /** + * edge inspect + * + * @param event event + * @return boolean boolean + */ + public boolean edgeInspect(final MouseEvent event) { + return event.getX() >= Utils.getX(rect) && event.getX() <= Utils.getX(rect) + rect.width + && event.getY() >= Utils.getY(rect) + && event.getY() <= Utils.getY(rect) + rect.height; + } + + /** + * edge inspect + * + * @param rectangle rectangle + * @param event event + * @return boolean boolean + */ + public boolean edgeInspectRect(final Rectangle rectangle, final MouseEvent event) { + return event.getX() >= Utils.getX(rectangle) && event.getX() <= Utils.getX(rectangle) + rectangle.width + && event.getY() >= Utils.getY(rectangle) && event.getY() <= Utils.getY(rectangle) + rectangle.height; + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractNode.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractNode.java index 6aab31069..21ed816d2 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractNode.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/AbstractNode.java @@ -1,123 +1,112 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.fragment.graph.AbstractGraph; - -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; - -/** - * all of data node graph node - * - * @version 1.0 - * @date 2021/4/26 14:33 - **/ -public abstract class AbstractNode { - /** - * Left padding - */ - static final int LEFT_PADDING = 5; - - /** - * Right padding - */ - static final int RIGHT_PADDING = 5; - - /** - * Direction Enum - */ - public enum Placement { - /** - * center - */ - CENTER, - /** - * Multi-line - */ - MULTILINE, - /** - * Middle row - */ - CENTER_LINE - } - - /** - * Draw string - * - * @param graphics graphics - * @param rectangle rectangle - * @param str str - * @param placement placement - */ - public void drawString(final Graphics graphics, final Rectangle rectangle, final String str, - final AbstractGraph.Placement placement) { - if (str == null) { - return; - } - final int len = 3; - if (placement == Placement.CENTER) { - Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); - double chartWidth = bounds.getWidth() / str.length(); // The width of each character - /** - * How many characters can be displayed in the rectangle - */ - double chartNum = (rectangle.getWidth() - LEFT_PADDING - RIGHT_PADDING) / chartWidth; - int mY = (int) (rectangle.getY() + bounds.getHeight()); - /** - * If the width is enough to display, the display text is in the middle of the rectangle - */ - if (chartNum >= str.length()) { - graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); - } else if (chartNum >= len + 1) { - /** - * If the width is not enough to display, cut out the part that can be displayed with an ellipsis behind - */ - graphics - .drawString(str.substring(0, (int) chartNum - len) + "...", (int) (rectangle.getX() + LEFT_PADDING), - mY); - } else if (chartNum > 1 && chartNum < len) { // If only one character can be displayed - graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); - } else { - graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); - } - } - if (placement == Placement.CENTER_LINE) { - Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); - double chartWidth = bounds.getWidth() / str.length(); // The width of each character - /** - * How many characters can be displayed in the rectangle - */ - double chartNum = (rectangle.width - LEFT_PADDING - RIGHT_PADDING) / chartWidth; - int mY = (int) (rectangle.getY() + rectangle.height / 2 + bounds.getHeight() / 2); - if (chartNum >= str.length()) { - /** - * If the width is enough to display, the display text is in the middle of the rectangle - */ - graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); - } else if (chartNum >= len + 1) { - graphics - .drawString(str.substring(0, (int) chartNum - len) + "...", (int) (rectangle.getX() + LEFT_PADDING), - mY); - } else if (chartNum > 1 && chartNum < len) { // If only one character can be displayed - graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); - } else { - graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.fragment.graph.AbstractGraph; + +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.geom.Rectangle2D; + +/** + * all of data node graph node + * + * @date 2021/4/26 14:33 + */ +public abstract class AbstractNode { + /** + * Left padding + */ + static final int LEFT_PADDING = 5; + + /** + * Right padding + */ + static final int RIGHT_PADDING = 5; + + /** + * Draw string + * + * @param graphics graphics + * @param rectangle rectangle + * @param str str + * @param placement placement + */ + public void drawString(final Graphics graphics, final Rectangle rectangle, final String str, + final AbstractGraph.Placement placement) { + if (str == null || rectangle.width < 5) { + return; + } + final int len = 3; + if (placement == Placement.CENTER) { + Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); + double chartWidth = bounds.getWidth() / str.length(); // The width of each character + // How many characters can be displayed in the rectangle + double chartNum = (rectangle.getWidth() - LEFT_PADDING - RIGHT_PADDING) / chartWidth; + int mY = (int) (rectangle.getY() + bounds.getHeight()); + // If the width is enough to display, the display text is in the middle of the rectangle + if (chartNum >= str.length()) { + graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); + } else if (chartNum >= len + 1) { + // If the width is not enough to display, cut out the part that can be displayed with an ellipsis behind + graphics + .drawString(str.substring(0, (int) chartNum - len) + "...", (int) (rectangle.getX() + LEFT_PADDING), + mY); + } else if (chartNum > 1 && chartNum < len) { // If only one character can be displayed + graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); + } else { + graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); + } + } + if (placement == Placement.CENTER_LINE) { + Rectangle2D bounds = graphics.getFontMetrics(graphics.getFont()).getStringBounds(str, graphics); + double chartWidth = bounds.getWidth() / str.length(); // The width of each character + // How many characters can be displayed in the rectangle + double chartNum = (rectangle.width - LEFT_PADDING - RIGHT_PADDING) / chartWidth; + int mY = (int) (rectangle.getY() + rectangle.height / 2 + bounds.getHeight() / 2); + if (chartNum >= str.length()) { + // If the width is enough to display, the display text is in the middle of the rectangle + graphics.drawString(str, (int) (rectangle.getX() + (rectangle.width - bounds.getWidth()) / 2), mY); + } else if (chartNum >= len + 1) { + graphics + .drawString(str.substring(0, (int) chartNum - len) + "...", (int) (rectangle.getX() + LEFT_PADDING), + mY); + } else if (chartNum > 1 && chartNum < len) { // If only one character can be displayed + graphics.drawString(str.substring(0, 1), (int) (rectangle.getX() + LEFT_PADDING), mY); + } else { + graphics.drawString("", (int) (rectangle.getX() + LEFT_PADDING), mY); + } + } + } + + /** + * Direction Enum + */ + public enum Placement { + /** + * center + */ + CENTER, + /** + * Multi-line + */ + MULTILINE, + /** + * Middle row + */ + CENTER_LINE + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/CpuFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/CpuFragment.java index 3451fcb33..0ef21c85f 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/CpuFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/CpuFragment.java @@ -1,217 +1,238 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.bean.CpuRateBean; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.listener.IRangeChangeListener; -import ohos.devtools.views.trace.util.ColorUtils; -import ohos.devtools.views.trace.util.Db; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ForkJoinPool; -import java.util.stream.Collectors; - -/** - * cpu graphics - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class CpuFragment extends AbstractFragment { - private final Color shadowColor = new Color(0x99, 0x99, 0x99, 0xCE); - private int leftX; - private int rightX; - private int selectX; - private int selectY; - - /** - * scale center x ,centerX is leftX or rightX - */ - private int centerX; - private IRangeChangeListener rangeChangeListener; - - /** - * Gets the value of selectX . - * - * @return the value of int - */ - public int getSelectX() { - return selectX; - } - - /** - * Sets the selectX . - *

You can use getSelectX() to get the value of selectX

- * - * @param selectX selectX - */ - public void setSelectX(final int selectX) { - this.selectX = selectX; - } - - /** - * Gets the value of selectY . - * - * @return the value of int - */ - public int getSelectY() { - return selectY; - } - - /** - * Sets the selectY . - *

You can use getSelectY() to get the value of selectY

- * - * @param selectY selectY - */ - public void setSelectY(final int selectY) { - this.selectY = selectY; - } - - private Map> listMap; - - /** - * CpuFragment Constructor - * - * @param root parent - * @param listener listener - */ - public CpuFragment(final JComponent root, final IRangeChangeListener listener) { - this.setRoot(root); - getRect().setBounds(200, 22, root.getWidth() - 200, 72); - this.rangeChangeListener = listener; - ForkJoinPool.commonPool().submit(() -> { - ArrayList cpus = Db.getInstance().getCpuUtilizationRate(); - listMap = cpus.stream().collect(Collectors.groupingBy(cpuRateBean -> cpuRateBean.getCpu())); - SwingUtilities.invokeLater(() -> { - repaint(); - }); - }); - } - - /** - * listener - * - * @param listener listener - */ - public void setRangeChangeListener(final IRangeChangeListener listener) { - this.rangeChangeListener = listener; - } - - /** - * draw method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - getRect().width = getRoot().getWidth() - getRect().x; - graphics.setColor(Color.white); - graphics.fillRect(getRect().x, getRect().y, getRect().width, getRect().height); - if (listMap != null && !listMap.isEmpty()) { - int height = getRect().height / listMap.size(); - double rw = (getRect().width) / 100.00; - listMap.forEach((map, beanList) -> { - for (int index = 0, len = beanList.size(); index < len; index++) { - CpuRateBean cpuRateBean = beanList.get(index); - graphics.setStroke(new BasicStroke(0)); - graphics.setComposite( - AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) cpuRateBean.getRate())); - graphics.setColor(ColorUtils.MD_PALETTE[map]); - int side = (int) (getRect().x + rw * index); - graphics.fillRect(side, getRect().y + map * height, (int) rw + 1, height); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); - } - }); - } - if (leftX == rightX && leftX != 0) { - rightX = leftX + 1; - } - if (leftX > 0 && leftX <= getRect().x + getRect().width) { - graphics.setColor(getRoot().getForeground()); - graphics.drawLine(leftX, getRect().y, leftX, getRect().y + getRect().height); - graphics.setColor(shadowColor); - graphics.fillRect(getRect().x, getRect().y, leftX - getRect().x, getRect().height); - graphics.drawRect(getRect().x, getRect().y, leftX - getRect().x, getRect().height); - } - if (rightX < getRoot().getWidth() && rightX >= getRect().x) { - graphics.setColor(getRoot().getForeground()); - graphics.drawLine(rightX, getRect().y, rightX, getRect().y + getRect().height); - graphics.setColor(shadowColor); - graphics.fillRect(rightX, getRect().y, getRect().x + getRect().width - rightX, getRect().height); - graphics.drawRect(rightX, getRect().y, getRect().x + getRect().width - rightX, getRect().height); - } - graphics.setColor(getRoot().getForeground()); - graphics.drawRect(leftX, getRect().y, rightX - leftX, getRect().height); - } - - /** - * mouse dragged listener - * - * @param event event - */ - public void mouseDragged(final MouseEvent event) { - if (selectY > getRect().y && selectY < getRect().y + getRect().height) { - if (event.getX() < selectX) { - rightX = selectX; - leftX = event.getX() <= getRect().x ? getRect().x : event.getX(); - } else { - rightX = event.getX() >= getRoot().getWidth() ? getRoot().getWidth() : event.getX(); - leftX = selectX; - } - if (leftX == rightX) { - if (leftX == getRect().x) { - rightX = leftX + 2; - } - if (rightX == getRoot().getWidth()) { - leftX = rightX - 2; - } - } - if (rangeChangeListener != null) { - if (selectX == leftX) { - centerX = leftX; - } - if (selectX == rightX) { - centerX = rightX; - } - rangeChangeListener.change(leftX, rightX, x2ns(leftX), x2ns(rightX), x2ns(centerX)); - } - getRoot().repaint(); - } - } - - /** - * change time range - * - * @param sn startNs - * @param en endNs - */ - public void setRange(final long sn, final long en) { - leftX = (int) (sn * getRect().width / AnalystPanel.DURATION) + getRect().x; - rightX = (int) (en * getRect().width / AnalystPanel.DURATION) + getRect().x; - repaint(); - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.Sql; +import ohos.devtools.views.trace.bean.CpuRateBean; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.listener.IRangeChangeListener; +import ohos.devtools.views.trace.util.ColorUtils; +import ohos.devtools.views.trace.util.Db; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +/** + * cpu graphics + * + * @date 2021/04/22 12:25 + */ +public class CpuFragment extends AbstractFragment { + private static Map> listMap; + private final Color shadowColor = new Color(0x99, 0x99, 0x99, 0xCE); + private int leftX; + private int rightX; + private int selectX; + private int selectY; + + /** + * scale center x ,centerX is leftX or rightX + */ + private int centerX; + private IRangeChangeListener rangeChangeListener; + + /** + * CpuFragment Constructor + * + * @param root parent + * @param listener listener + */ + public CpuFragment(final JComponent root, final IRangeChangeListener listener) { + this.setRoot(root); + getRect().setBounds(200, 22, root.getWidth() - 200, 72); + this.rangeChangeListener = listener; + } + + /** + * Gets the value of selectX . + * + * @return the value of int + */ + public int getSelectX() { + return selectX; + } + + /** + * Sets the selectX . + *

You can use getSelectX() to get the value of selectX

+ * + * @param selectX selectX + */ + public void setSelectX(final int selectX) { + this.selectX = selectX; + } + + /** + * Gets the value of selectY . + * + * @return the value of int + */ + public int getSelectY() { + return selectY; + } + + /** + * Sets the selectY . + *

You can use getSelectY() to get the value of selectY

+ * + * @param selectY selectY + */ + public void setSelectY(final int selectY) { + this.selectY = selectY; + } + + /** + * reload cpu usage data + */ + public void reloadData() { + CompletableFuture.runAsync(() -> { + if (Objects.nonNull(listMap)) { + listMap.values().forEach(List::clear); + listMap.clear(); + } + ArrayList cpus = new ArrayList<>() { + }; + Db.getInstance().query(Sql.SYS_GET_CPU_UTILIZATION_RATE, cpus); + listMap = cpus.stream().collect(Collectors.groupingBy(cpuRateBean -> cpuRateBean.getCpu())); + SwingUtilities.invokeLater(() -> { + repaint(); + }); + }, Utils.getPool()).whenComplete((unused, throwable) -> { + if (Objects.nonNull(throwable)) { + throwable.printStackTrace(); + } + }); + } + + /** + * listener + * + * @param listener listener + */ + public void setRangeChangeListener(final IRangeChangeListener listener) { + this.rangeChangeListener = listener; + } + + /** + * draw method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + getRect().width = getRoot().getWidth() - Utils.getX(getRect()); + graphics.setColor(Color.white); + graphics.fillRect(Utils.getX(getRect()), Utils.getY(getRect()), getRect().width, getRect().height); + if (listMap != null && !listMap.isEmpty()) { + int height = getRect().height / listMap.size(); + double rw = (getRect().width) / 100.00; + listMap.forEach((map, beanList) -> { + for (int index = 0, len = beanList.size(); index < len; index++) { + CpuRateBean cpuRateBean = beanList.get(index); + graphics.setStroke(new BasicStroke(0)); + graphics.setComposite( + AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) cpuRateBean.getRate())); + graphics.setColor(ColorUtils.MD_PALETTE[map]); + int side = (int) (Utils.getX(getRect()) + rw * index); + graphics.fillRect(side, Utils.getY(getRect()) + map * height, (int) rw + 1, height); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); + } + }); + } + if (leftX == rightX && leftX != 0) { + rightX = leftX + 1; + } + if (leftX > 0 && leftX <= Utils.getX(getRect()) + getRect().width) { + graphics.setColor(getRoot().getForeground()); + graphics.drawLine(leftX, Utils.getY(getRect()), leftX, Utils.getY(getRect()) + getRect().height); + graphics.setColor(shadowColor); + graphics.fillRect(Utils.getX(getRect()), Utils.getY(getRect()), leftX - Utils.getX(getRect()), + getRect().height); + graphics.drawRect(Utils.getX(getRect()), Utils.getY(getRect()), leftX - Utils.getX(getRect()), + getRect().height); + } + if (rightX < getRoot().getWidth() && rightX >= Utils.getX(getRect())) { + graphics.setColor(getRoot().getForeground()); + graphics.drawLine(rightX, Utils.getY(getRect()), rightX, Utils.getY(getRect()) + getRect().height); + graphics.setColor(shadowColor); + graphics.fillRect(rightX, Utils.getY(getRect()), Utils.getX(getRect()) + getRect().width - rightX, + getRect().height); + graphics.drawRect(rightX, Utils.getY(getRect()), Utils.getX(getRect()) + getRect().width - rightX, + getRect().height); + } + graphics.setColor(getRoot().getForeground()); + graphics.drawRect(leftX, Utils.getY(getRect()), rightX - leftX, getRect().height); + } + + /** + * mouse dragged listener + * + * @param event event + */ + public void mouseDragged(final MouseEvent event) { + if (selectY > Utils.getY(getRect()) && selectY < Utils.getY(getRect()) + getRect().height) { + if (event.getX() < selectX) { + rightX = selectX; + leftX = event.getX() <= Utils.getX(getRect()) ? Utils.getX(getRect()) : event.getX(); + } else { + rightX = event.getX() >= getRoot().getWidth() ? getRoot().getWidth() : event.getX(); + leftX = selectX; + } + if (leftX == rightX) { + if (leftX == Utils.getX(getRect())) { + rightX = leftX + 2; + } + if (rightX == getRoot().getWidth()) { + leftX = rightX - 2; + } + } + if (rangeChangeListener != null) { + if (selectX == leftX) { + centerX = leftX; + } + if (selectX == rightX) { + centerX = rightX; + } + rangeChangeListener.change(leftX, rightX, x2ns(leftX), x2ns(rightX), x2ns(centerX)); + } + getRoot().repaint(); + } + } + + /** + * change time range + * + * @param sn startNs + * @param en endNs + */ + public void setRange(final long sn, final long en) { + leftX = (int) (sn * getRect().width / AnalystPanel.DURATION) + Utils.getX(getRect()); + rightX = (int) (en * getRect().width / AnalystPanel.DURATION) + Utils.getX(getRect()); + repaint(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/IFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/IFragment.java index 5b9d9bd32..3488e9158 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/IFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/IFragment.java @@ -1,33 +1,32 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import java.awt.Graphics2D; - -/** - * Interface specification for drawing data - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public interface IFragment { - /** - * Drawing graphics method - * - * @param graphics graphics - */ - void draw(Graphics2D graphics); -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import java.awt.Graphics2D; + +/** + * Interface specification for drawing data + * + * @date 2021/04/22 12:25 + */ +public interface IFragment { + /** + * Drawing graphics method + * + * @param graphics graphics + */ + void draw(Graphics2D graphics); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/LeftFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/LeftFragment.java index 0b7c460ba..f352a43d5 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/LeftFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/LeftFragment.java @@ -1,168 +1,167 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.util.TimeUtils; - -import javax.swing.JComponent; -import java.awt.AlphaComposite; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; - -import static ohos.devtools.views.trace.component.AnalystPanel.DURATION; - -/** - * The left part of the timeline display area - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public class LeftFragment extends AbstractFragment { - private String startTimeS = "0.0s"; - private long startNS; - private int extendHeight; - private String logString; - - /** - * Gets the value of startTimeS . - * - * @return the value of java.lang.String - */ - public String getStartTimeS() { - return startTimeS; - } - - /** - * Sets the startTimeS . - *

You can use getStartTimeS() to get the value of startTimeS

- * - * @param time time - */ - public void setStartTimeS(final String time) { - this.startTimeS = time; - } - - /** - * Sets the startNS . - *

You can use getStartNS() to get the value of startNS

- * - * @param ns Starting time - */ - public void setStartNS(final long ns) { - this.startNS = ns; - } - - /** - * Gets the value of extendHeight . - * - * @return the value of int - */ - public int getExtendHeight() { - return extendHeight; - } - - /** - * Sets the extendHeight . - *

You can use getExtendHeight() to get the value of extendHeight

- * - * @param height height - */ - public void setExtendHeight(final int height) { - this.extendHeight = height; - } - - /** - * Gets the value of logString . - * - * @return the value of java.lang.String - */ - public String getLogString() { - return logString; - } - - /** - * Sets the logString . - *

You can use getLogString() to get the value of logString

- * - * @param log log - */ - public void setLogString(final String log) { - this.logString = log; - } - - /** - * @param root Component - */ - public LeftFragment(final JComponent root) { - this.setRoot(root); - final int width = 200; - final int height = 134; - getRect().setBounds(0, 0, width, height); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - final int yAxis = 94; - final float alpha50 = 0.5f; - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha50)); - graphics.setColor(getRoot().getForeground()); - graphics.drawLine(0, yAxis, getRect().width, yAxis); - graphics.drawLine(getRect().width, 0, getRect().width, getRect().height + extendHeight); - final int pad = 4; - graphics.drawLine(0, getRect().height, getRoot().getWidth(), getRect().height); - graphics.drawLine(0, 0, 0, getRect().height + extendHeight); - graphics.drawRect(getRect().x, getRect().y, getRect().width, getRect().height); - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); - Rectangle2D rectangle2D = graphics.getFontMetrics().getStringBounds(startTimeS, graphics); - int strHeight = (int) rectangle2D.getHeight(); - int strWidth = (int) rectangle2D.getWidth() + pad; - graphics.drawString(TimeUtils.getSecondFromNSecond(DURATION), 2, yAxis + strHeight); - graphics.drawString(startTimeS, getRect().width - strWidth, yAxis + strHeight); - - if (logString != null && !logString.isEmpty()) { - int index = 0; - for (String str : logString.split(System.getProperty("line.separator"))) { - graphics.drawString(str, 1, index * 12 + 10); - index++; - } - } - } - - /** - * set Start Time - * - * @param leftNS leftNS - */ - public void setStartTime(final long leftNS) { - this.startNS = leftNS; - startTimeS = TimeUtils.getSecondFromNSecond(leftNS); - repaint(); - } - - /** - * get Start Time - * - * @return long Starting time - */ - public long getStartNS() { - return this.startNS; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.AlphaComposite; +import java.awt.Graphics2D; +import java.awt.geom.Rectangle2D; + +import static ohos.devtools.views.trace.component.AnalystPanel.DURATION; + +/** + * The left part of the timeline display area + * + * @date 2021/04/22 12:25 + */ +public class LeftFragment extends AbstractFragment { + private String startTimeS = "0.0s"; + private long startNS; + private int extendHeight; + private String logString; + + /** + * @param root Component + */ + public LeftFragment(final JComponent root) { + this.setRoot(root); + final int width = 200; + final int height = 134; + getRect().setBounds(0, 0, width, height); + } + + /** + * Gets the value of startTimeS . + * + * @return the value of java.lang.String + */ + public String getStartTimeS() { + return startTimeS; + } + + /** + * Sets the startTimeS . + *

You can use getStartTimeS() to get the value of startTimeS

+ * + * @param time time + */ + public void setStartTimeS(final String time) { + this.startTimeS = time; + } + + /** + * Gets the value of extendHeight . + * + * @return the value of int + */ + public int getExtendHeight() { + return extendHeight; + } + + /** + * Sets the extendHeight . + *

You can use getExtendHeight() to get the value of extendHeight

+ * + * @param height height + */ + public void setExtendHeight(final int height) { + this.extendHeight = height; + } + + /** + * Gets the value of logString . + * + * @return the value of java.lang.String + */ + public String getLogString() { + return logString; + } + + /** + * Sets the logString . + *

You can use getLogString() to get the value of logString

+ * + * @param log log + */ + public void setLogString(final String log) { + this.logString = log; + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + final int yaxis = 94; + final float alpha50 = 0.5f; + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha50)); + graphics.setColor(getRoot().getForeground()); + graphics.drawLine(0, yaxis, getRect().width, yaxis); + graphics.drawLine(getRect().width, 0, getRect().width, getRect().height + extendHeight); + final int pad = 4; + graphics.drawLine(0, getRect().height, getRoot().getWidth(), getRect().height); + graphics.drawLine(0, 0, 0, getRect().height + extendHeight); + graphics.drawRect(Utils.getX(getRect()), Utils.getY(getRect()), getRect().width, getRect().height); + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + Rectangle2D rectangle2D = graphics.getFontMetrics().getStringBounds(startTimeS, graphics); + int strHeight = (int) rectangle2D.getHeight(); + int strWidth = (int) rectangle2D.getWidth() + pad; + graphics.drawString(TimeUtils.getSecondFromNSecond(DURATION), 2, yaxis + strHeight); + graphics.drawString(startTimeS, getRect().width - strWidth, yaxis + strHeight); + if (logString != null && !logString.isEmpty()) { + int index = 0; + for (String str : logString.split(System.getProperty("line.separator"))) { + graphics.drawString(str, 1, index * 12 + 10); + index++; + } + } + } + + /** + * set Start Time + * + * @param leftNS leftNS + */ + public void setStartTime(final long leftNS) { + this.startNS = leftNS; + startTimeS = TimeUtils.getSecondFromNSecond(leftNS); + repaint(); + } + + /** + * get Start Time + * + * @return long Starting time + */ + public long getStartNS() { + return this.startNS; + } + + /** + * Sets the startNS . + *

You can use getStartNS() to get the value of startNS

+ * + * @param ns Starting time + */ + public void setStartNS(final long ns) { + this.startNS = ns; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/RulerFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/RulerFragment.java index 3f45bd451..d691139da 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/RulerFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/RulerFragment.java @@ -1,516 +1,544 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.bean.FlagBean; -import ohos.devtools.views.trace.component.AnalystPanel; -import ohos.devtools.views.trace.util.Final; -import ohos.devtools.views.trace.util.TimeUtils; - -import javax.swing.JComponent; -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * Timeline zoom size - * - * @version 1.0 - * @date 2021/4/22 12:25 - **/ -public class RulerFragment extends AbstractFragment implements FlagBean.IEventListener { - private static final BasicStroke BOLD_STORE = new BasicStroke(2); - private long leftNS; - private long rightNS; - private final long[] scales = - new long[] {50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 50_000, 100_000, 200_000, 500_000, - 1_000_000, 2_000_000, 5_000_000, 10_000_000, 20_000_000, 50_000_000, 100_000_000, 200_000_000, 500_000_000, - 1_000_000_000, 2_000_000_000, 5_000_000_000L, 10_000_000_000L, 20_000_000_000L, 50_000_000_000L, - 100_000_000_000L, 200_000_000_000L, 500_000_000_000L}; - - // The current time selection range is based on 20 units. - // The zoom level obtained by the position in the scales array is 70ns if calculated - private long min; - - // Then in the middle of 50L 100L min=50L - // The current time selection range The position in the zoom level scales array based on 20 units. - // If calculated, it is 70ns - private long max; - - // Then it is in the middle of 50L 100L max = 100L - private long l20; // The current time selection range is based on 20 units - - // When the weight ratio is greater than 24.3%, scale=max; otherwise, scale=min schematic diagram - private long scale; - - // min---l20-------max - private long centerNS; // Select from left to right is true - - // From right to left is false; - // when moving from left to right, use the left as the reference, - // and fill the cell to the left; when moving from right to left, fill the cell to the right - private double weight; // (l20-min)/(max-min) to get the proportion - private int extendHeight; - private int selectX; - private int selectY; - private FlagBean focusFlag = new FlagBean(); - private List flags = new ArrayList<>(); - private double realW; - private double startX; - private IChange changeListener; - - /** - * time range change listener - */ - public interface IChange { - /** - * Time range change monitoring - * - * @param startNS Starting time - * @param endNS End Time - */ - void change(long startNS, long endNS); - } - - /** - * Constructor - * - * @param root Parent component - * @param listener monitor - */ - public RulerFragment(final JComponent root, final IChange listener) { - this.changeListener = listener; - this.setRoot(root); - getRect().setBounds(200, 94, root.getWidth(), 40); - setRange(0, AnalystPanel.DURATION, 0); - } - - /** - * Set time range - * - * @param left left - * @param right right - * @param center center - */ - public void setRange(final long left, final long right, final long center) { - this.centerNS = center; - this.leftNS = left; - this.rightNS = right; - l20 = (this.rightNS - left) / 20; - for (int index = 0; index < scales.length; index++) { - if (scales[index] > l20) { - if (index > 0) { - min = scales[index - 1]; - } else { - min = 0; - } - max = scales[index]; - weight = (l20 - min) * 1.0 / (max - min); - if (weight > 0.243) { - scale = max; - } else { - scale = min; - } - break; - } - } - if (scale == 0) { - scale = scales[0]; - } - for (FlagBean flag : flags) { - flag.rect.x = getX(flag.getNs()); - } - repaint(); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - getRect().width = getRoot().getWidth() - getRect().x; - graphics.setFont(Final.SMALL_FONT); - graphics.setColor(getRoot().getForeground()); - if (rightNS - leftNS == 0) { - return; - } - if (scale == 0) { - setRange(0, AnalystPanel.DURATION, 0); - } - if (changeListener != null) { - changeListener.change(leftNS, rightNS); - } - if (centerNS == leftNS) { // Fill from left to right - drawLeft2Right(graphics); - } - if (centerNS == rightNS) { // Fill from right to left - drawRight2Left(graphics); - } - for (FlagBean flagBean : flags) { - graphics.setColor(flagBean.getColor()); - graphics.setStroke(new BasicStroke(2)); - int xAxis = flagBean.rect.x; - if (xAxis > 0) { - graphics.drawLine(xAxis + getRect().x, getRect().y + getRect().height / 2, getRect().x + xAxis, - getRect().y + getRect().height - 2); - graphics.fillRect(xAxis + getRect().x, getRect().y + getRect().height / 2, 10, 10); - graphics.fillRect(xAxis + getRect().x + 7, getRect().y + getRect().height / 2 + 2, 7, 7); - flagBean.draw(graphics); - } - } - drawFocusFlag(graphics); - } - - private void drawRight2Left(Graphics2D graphics) { - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); - graphics.setComposite(alpha); - graphics.drawLine(getRect().x, getRect().y, getRect().x + getRect().width, getRect().y); - long tmpNs = rightNS - leftNS; - startX = getRect().x + getRect().width; - realW = (scale * getRect().width) / (rightNS - leftNS); - String str; - while (tmpNs > 0) { - str = TimeUtils.getSecondFromNSecond(tmpNs); - if (str.isEmpty()) { - str = "0s"; - } - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alpha50 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); - graphics.setComposite(alpha50); - graphics.drawLine((int) startX, getRect().y, (int) startX, getRect().y + getRect().height + extendHeight); - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alphaFul = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); - graphics.setComposite(alphaFul); - graphics.drawString("+" + str, (int) startX, - getRect().y + (int) (graphics.getFontMetrics().getStringBounds("+" + str, graphics).getHeight())); - startX -= realW; - tmpNs -= scale; - } - } - - private void drawLeft2Right(Graphics2D graphics) { - if (scale == 0) { - return; - } - long tmpNs = 0; - long yu = leftNS % scale; - realW = (scale * getRect().width) / (rightNS - leftNS); - startX = getRect().x; - if (yu != 0) { - float firstNodeWidth = (float) ((yu * 1.0) / scale * realW); - startX += firstNodeWidth; - tmpNs += yu; - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); - graphics.setComposite(alpha); - graphics.drawLine((int) startX, getRect().y, (int) startX, getRect().y + getRect().height); - } - graphics.setColor(getRoot().getForeground()); - graphics.drawLine(getRect().x, getRect().y, getRect().x + getRect().width, getRect().y); - String str; - while (tmpNs < rightNS - leftNS) { - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); - graphics.setComposite(alpha); - graphics.drawLine((int) startX, getRect().y, (int) startX, getRect().y + getRect().height + extendHeight); - str = TimeUtils.getSecondFromNSecond(tmpNs); - if (str.isEmpty()) { - str = "0s"; - } - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alphaFull = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); - graphics.setComposite(alphaFull); - String timS = "+" + str; - Rectangle2D bounds = graphics.getFontMetrics(Final.SMALL_FONT).getStringBounds(timS, graphics); - graphics.drawString(timS, (int) startX, (int) (getRect().y + bounds.getHeight())); - startX += realW; - tmpNs += scale; - } - } - - private void drawFocusFlag(Graphics2D graphics) { - if (focusFlag.isVisible()) { - final int side = 10; - graphics.setColor(focusFlag.getColor()); - graphics.setStroke(BOLD_STORE); - graphics.drawLine(focusFlag.rect.x + getRect().x, getRect().y + getRect().height / 2, - getRect().x + focusFlag.rect.x, getRect().y + getRect().height + extendHeight); - graphics.fillRect(focusFlag.rect.x + getRect().x, getRect().y + getRect().height / 2, side, side); - final int offset = 7; - graphics - .fillRect(focusFlag.rect.x + getRect().x + offset, getRect().y + getRect().height / 2 + 2, side, side); - } - } - - /** - * Convert x coordinate according to time - * - * @param ns ns - * @return int int - */ - public int getX(final long ns) { - return (int) ((ns - leftNS) * getRect().width / ((rightNS - leftNS) * 1.0)); - } - - /** - * Mouse movement event - * - * @param event event - */ - public void mouseMoved(final MouseEvent event) { - final int leftW = 200; - if (selectY > getRect().y && selectY < getRect().y + getRect().height && event.getX() >= leftW) { - Optional first = flags.stream().filter(bean -> event.getX() >= bean.rect.x + getRect().x - && event.getX() <= bean.rect.x + getRect().x + bean.rect.width).findFirst(); - if (first.isPresent()) { - focusFlag.setVisible(false); - } else { - focusFlag.setVisible(true); - focusFlag.rect.x = event.getX() - getRect().x; - focusFlag.rect.y = getRect().y + getRect().height / 2; - focusFlag.rect.width = 17; - focusFlag.rect.height = getRect().height / 2; - } - } else { - focusFlag.setVisible(false); - } - getRoot().repaint(); - } - - /** - * Mouse pressed event - * - * @param event event - */ - public void mousePressed(final MouseEvent event) { - final int leftW = 200; - if (selectY > getRect().y && selectY < getRect().y + getRect().height && event.getX() >= leftW) { - Optional first = flags.stream().filter(bean -> event.getX() >= bean.rect.x + getRect().x - && event.getX() <= bean.rect.x + getRect().x + bean.rect.width).findFirst(); - if (first.isPresent()) { - FlagBean flagBean = first.get(); - flagBean.onClick(event); - } else { - FlagBean flagBean = new FlagBean(); - flagBean.root = getRoot(); - flagBean.rect.x = event.getX() - getRect().x; - flagBean.rect.y = getRect().y + getRect().height / 2; - flagBean.setEventListener(this); - flagBean.rect.width = 17; - flagBean.rect.height = getRect().height / 2; - flagBean.setNs((long) ((rightNS - leftNS) / (getRect().width * 1.0) * flagBean.rect.x) + leftNS); - flagBean.setVisible(true); - flags.add(flagBean); - } - repaint(); - } - } - - /** - * FlagBean object click event - * - * @param event event - * @param data data - */ - @Override - public void click(final MouseEvent event, final FlagBean data) { - if (AnalystPanel.iFlagClick != null) { - AnalystPanel.iFlagClick.click(data); - } - } - - /** - * Loss of focus event - * - * @param event event - * @param data data - */ - @Override - public void blur(final MouseEvent event, final FlagBean data) { - } - - /** - * Get focus event - * - * @param event event - * @param data data - */ - @Override - public void focus(final MouseEvent event, final FlagBean data) { - } - - /** - * Mouse move event - * - * @param event event - * @param data data - */ - @Override - public void mouseMove(final MouseEvent event, final FlagBean data) { - } - - /** - * Remove the flag mark - * - * @param data data - */ - @Override - public void delete(final FlagBean data) { - flags.removeIf(bean -> bean.getNs() == data.getNs()); - repaint(); - } - - /** - * Gets the value of leftNS . - * - * @return the value of long - */ - public long getLeftNS() { - return leftNS; - } - - /** - * Sets the leftNS . - *

You can use getLeftNS() to get the value of leftNS

- * - * @param ns ns - */ - public void setLeftNS(final long ns) { - this.leftNS = ns; - } - - /** - * Gets the value of rightNS . - * - * @return the value of long - */ - public long getRightNS() { - return rightNS; - } - - /** - * Sets the rightNS . - *

You can use getRightNS() to get the value of rightNS

- * - * @param ns ns - */ - public void setRightNS(final long ns) { - this.rightNS = ns; - } - - /** - * Gets the value of scale . - * - * @return the value of long - */ - public long getScale() { - return scale; - } - - /** - * Sets the scale . - *

You can use getScale() to get the value of scale

- * - * @param scale scale - */ - public void setScale(final long scale) { - this.scale = scale; - } - - /** - * Gets the value of centerNS . - * - * @return the value of long - */ - public long getCenterNS() { - return centerNS; - } - - /** - * Sets the centerNS . - *

You can use getCenterNS() to get the value of centerNS

- * - * @param ns ns - */ - public void setCenterNS(final long ns) { - this.centerNS = ns; - } - - /** - * Gets the value of extendHeight . - * - * @return the value of int - */ - public int getExtendHeight() { - return extendHeight; - } - - /** - * Sets the extendHeight . - *

You can use getExtendHeight() to get the value of extendHeight

- * - * @param height height - */ - public void setExtendHeight(final int height) { - this.extendHeight = height; - } - - /** - * Gets the value of selectX . - * - * @return the value of int - */ - public int getSelectX() { - return selectX; - } - - /** - * Sets the selectX . - *

You can use getSelectX() to get the value of selectX

- * - * @param select select - */ - public void setSelectX(final int select) { - this.selectX = select; - } - - /** - * Gets the value of selectY . - * - * @return the value of int - */ - public int getSelectY() { - return selectY; - } - - /** - * Sets the selectY . - *

You can use getSelectY() to get the value of selectY

- * - * @param select select - */ - public void setSelectY(final int select) { - this.selectY = select; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.bean.FlagBean; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Final; +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Timeline zoom size + * + * @date 2021/4/22 12:25 + */ +public class RulerFragment extends AbstractFragment implements FlagBean.IEventListener { + private static final BasicStroke BOLD_STORE = new BasicStroke(2); + private final long[] scales = + new long[] {50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 50_000, 100_000, 200_000, 500_000, + 1_000_000, 2_000_000, 5_000_000, 10_000_000, 20_000_000, 50_000_000, 100_000_000, 200_000_000, 500_000_000, + 1_000_000_000, 2_000_000_000, 5_000_000_000L, 10_000_000_000L, 20_000_000_000L, 50_000_000_000L, + 100_000_000_000L, 200_000_000_000L, 500_000_000_000L}; + private long leftNS; + private long rightNS; + /** + * The current time selection range is based on 20 units. + * The zoom level obtained by the position in the scales array is 70ns if calculated + */ + private long min; + + /** + * Then in the middle of 50L 100L min=50L + * The current time selection range The position in the zoom level scales array based on 20 units. + * If calculated, it is 70ns + */ + private long max; + + // Then it is in the middle of 50L 100L max = 100L + private long l20; // The current time selection range is based on 20 units + + // When the weight ratio is greater than 24.3%, scale=max; otherwise, scale=min schematic diagram + private long scale; + + // min---l20-------max + private long centerNS; // Select from left to right is true + + // From right to left is false; + // when moving from left to right, use the left as the reference, + // and fill the cell to the left; when moving from right to left, fill the cell to the right + private double weight; // (l20-min)/(max-min) to get the proportion + private int extendHeight; + private int selectX; + private int selectY; + private FlagBean focusFlag = new FlagBean(); + private List flags = new ArrayList<>(); + private double realW; + private double startX; + private IChange changeListener; + + /** + * Constructor + * + * @param root Parent component + * @param listener monitor + */ + public RulerFragment(final JComponent root, final IChange listener) { + this.changeListener = listener; + this.setRoot(root); + getRect().setBounds(200, 94, root.getWidth(), 40); + setRange(0, AnalystPanel.DURATION, 0); + } + + /** + * Set time range + * + * @param left left + * @param right right + * @param center center + */ + public void setRange(final long left, final long right, final long center) { + this.centerNS = center; + this.leftNS = left; + this.rightNS = right; + l20 = (this.rightNS - left) / 20; + for (int index = 0; index < scales.length; index++) { + if (scales[index] > l20) { + if (index > 0) { + min = scales[index - 1]; + } else { + min = 0; + } + max = scales[index]; + weight = (l20 - min) * 1.0 / (max - min); + if (weight > 0.243) { + scale = max; + } else { + scale = min; + } + break; + } + } + if (scale == 0) { + scale = scales[0]; + } + for (FlagBean flag : flags) { + Utils.setX(flag.rect, getX(flag.getNs())); + } + repaint(); + } + + /** + * clear the flags + */ + public void recycle() { + flags.clear(); + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + getRect().width = getRoot().getWidth() - Utils.getX(getRect()); + graphics.setFont(Final.SMALL_FONT); + graphics.setColor(getRoot().getForeground()); + if (rightNS - leftNS == 0) { + return; + } + if (scale == 0) { + setRange(0, AnalystPanel.DURATION, 0); + } + if (changeListener != null) { + changeListener.change(leftNS, rightNS); + } + if (centerNS == leftNS) { // Fill from left to right + drawLeft2Right(graphics); + } + if (centerNS == rightNS) { // Fill from right to left + drawRight2Left(graphics); + } + for (FlagBean flagBean : flags) { + graphics.setColor(flagBean.getColor()); + graphics.setStroke(new BasicStroke(2)); + int xAxis = Utils.getX(flagBean.rect); + if (xAxis > 0) { + graphics.drawLine(xAxis + Utils.getX(getRect()), Utils.getY(getRect()) + getRect().height / 2, + Utils.getX(getRect()) + xAxis, Utils.getY(getRect()) + getRect().height - 2); + graphics.fillRect(xAxis + Utils.getX(getRect()), Utils.getY(getRect()) + getRect().height / 2, 10, 10); + graphics + .fillRect(xAxis + Utils.getX(getRect()) + 7, Utils.getY(getRect()) + getRect().height / 2 + 2, 7, + 7); + flagBean.draw(graphics); + } + } + drawFocusFlag(graphics); + } + + private void drawRight2Left(Graphics2D graphics) { + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); + graphics.setComposite(alpha); + graphics.drawLine(Utils.getX(getRect()), Utils.getY(getRect()), Utils.getX(getRect()) + getRect().width, + Utils.getY(getRect())); + long tmpNs = rightNS - leftNS; + startX = Utils.getX(getRect()) + getRect().width; + realW = (scale * getRect().width) / (rightNS - leftNS); + String str; + while (tmpNs > 0) { + str = TimeUtils.getSecondFromNSecond(tmpNs); + if (str.isEmpty()) { + str = "0s"; + } + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alpha50 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); + graphics.setComposite(alpha50); + graphics.drawLine((int) startX, Utils.getY(getRect()), (int) startX, + Utils.getY(getRect()) + getRect().height + extendHeight); + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alphaFul = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); + graphics.setComposite(alphaFul); + graphics.drawString("+" + str, (int) startX, + Utils.getY(getRect()) + (int) (graphics.getFontMetrics().getStringBounds("+" + str, graphics) + .getHeight())); + startX -= realW; + tmpNs -= scale; + } + } + + private void drawLeft2Right(Graphics2D graphics) { + if (scale == 0) { + return; + } + long tmpNs = 0; + long yu = leftNS % scale; + realW = (scale * getRect().width) / (rightNS - leftNS); + startX = Utils.getX(getRect()); + if (yu != 0) { + float firstNodeWidth = (float) ((yu * 1.0) / scale * realW); + startX += firstNodeWidth; + tmpNs += yu; + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); + graphics.setComposite(alpha); + graphics + .drawLine((int) startX, Utils.getY(getRect()), (int) startX, Utils.getY(getRect()) + getRect().height); + } + graphics.setColor(getRoot().getForeground()); + graphics.drawLine(Utils.getX(getRect()), Utils.getY(getRect()), Utils.getX(getRect()) + getRect().width, + Utils.getY(getRect())); + String str; + while (tmpNs < rightNS - leftNS) { + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); + graphics.setComposite(alpha); + graphics.drawLine((int) startX, Utils.getY(getRect()), (int) startX, + Utils.getY(getRect()) + getRect().height + extendHeight); + str = TimeUtils.getSecondFromNSecond(tmpNs); + if (str.isEmpty()) { + str = "0s"; + } + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alphaFull = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); + graphics.setComposite(alphaFull); + String timS = "+" + str; + Rectangle2D bounds = graphics.getFontMetrics(Final.SMALL_FONT).getStringBounds(timS, graphics); + graphics.drawString(timS, (int) startX, (int) (Utils.getY(getRect()) + bounds.getHeight())); + startX += realW; + tmpNs += scale; + } + } + + private void drawFocusFlag(Graphics2D graphics) { + if (focusFlag != null && focusFlag.isVisible()) { + final int side = 10; + graphics.setColor(focusFlag.getColor()); + graphics.setStroke(BOLD_STORE); + graphics.drawLine(Utils.getX(focusFlag.rect) + Utils.getX(getRect()), + Utils.getY(getRect()) + getRect().height / 2, Utils.getX(getRect()) + Utils.getX(focusFlag.rect), + Utils.getY(getRect()) + getRect().height + extendHeight); + graphics.fillRect(Utils.getX(focusFlag.rect) + Utils.getX(getRect()), + Utils.getY(getRect()) + getRect().height / 2, side, side); + final int offset = 7; + graphics.fillRect(Utils.getX(focusFlag.rect) + Utils.getX(getRect()) + offset, + Utils.getY(getRect()) + getRect().height / 2 + 2, side, side); + } + } + + /** + * Convert x coordinate according to time + * + * @param ns ns + * @return int int + */ + public int getX(final long ns) { + return (int) ((ns - leftNS) * getRect().width / ((rightNS - leftNS) * 1.0)); + } + + /** + * Mouse movement event + * + * @param event event + */ + public void mouseMoved(final MouseEvent event) { + final int leftW = 200; + if (selectY > Utils.getY(getRect()) && selectY < Utils.getY(getRect()) + getRect().height + && event.getX() >= leftW) { + Optional first = flags.stream().filter( + bean -> event.getX() >= Utils.getX(bean.rect) + Utils.getX(getRect()) + && event.getX() <= Utils.getX(bean.rect) + Utils.getX(getRect()) + bean.rect.width).findFirst(); + if (first.isPresent()) { + focusFlag.setVisible(false); + } else { + focusFlag.setVisible(true); + focusFlag.rect + .setLocation(event.getX() - Utils.getX(getRect()), Utils.getY(getRect()) + getRect().height / 2); + focusFlag.rect.width = 17; + focusFlag.rect.height = getRect().height / 2; + } + } else { + focusFlag.setVisible(false); + } + getRoot().repaint(); + } + + /** + * Mouse click event + * + * @param event event + */ + public void mouseClicked(final MouseEvent event) { + if (edgeInspect(event)) { + final int leftW = 200; + if (selectY > Utils.getY(getRect()) && selectY < Utils.getY(getRect()) + getRect().height + && event.getX() >= leftW) { + Optional first = flags.stream().filter( + bean -> event.getX() >= Utils.getX(bean.rect) + Utils.getX(getRect()) + && event.getX() <= Utils.getX(bean.rect) + Utils.getX(getRect()) + bean.rect.width).findFirst(); + if (first.isPresent()) { + FlagBean flagBean = first.get(); + flagBean.onClick(event); + } else { + FlagBean flagBean = new FlagBean(); + flagBean.root = getRoot(); + flagBean.rect.setLocation(event.getX() - Utils.getX(getRect()), + Utils.getY(getRect()) + getRect().height / 2); + flagBean.setEventListener(this); + flagBean.rect.width = 17; + flagBean.rect.height = getRect().height / 2; + flagBean.setNs( + (long) ((rightNS - leftNS) / (getRect().width * 1.0) * Utils.getX(flagBean.rect)) + leftNS); + flagBean.setVisible(true); + flagBean.onClick(event); + flags.add(flagBean); + } + repaint(); + } + } + } + + /** + * FlagBean object click event + * + * @param event event + * @param data data + */ + @Override + public void click(final MouseEvent event, final FlagBean data) { + if (AnalystPanel.iFlagClick != null) { + AnalystPanel.iFlagClick.click(data); + } + } + + /** + * Loss of focus event + * + * @param event event + * @param data data + */ + @Override + public void blur(final MouseEvent event, final FlagBean data) { + } + + /** + * Get focus event + * + * @param event event + * @param data data + */ + @Override + public void focus(final MouseEvent event, final FlagBean data) { + } + + /** + * Mouse move event + * + * @param event event + * @param data data + */ + @Override + public void mouseMove(final MouseEvent event, final FlagBean data) { + } + + /** + * Remove the flag mark + * + * @param data data + */ + @Override + public void delete(final FlagBean data) { + flags.removeIf(bean -> bean.getNs() == data.getNs()); + repaint(); + } + + /** + * Gets the value of leftNS . + * + * @return the value of long + */ + public long getLeftNS() { + return leftNS; + } + + /** + * Sets the leftNS . + *

You can use getLeftNS() to get the value of leftNS

+ * + * @param ns ns + */ + public void setLeftNS(final long ns) { + this.leftNS = ns; + } + + /** + * Gets the value of rightNS . + * + * @return the value of long + */ + public long getRightNS() { + return rightNS; + } + + /** + * Sets the rightNS . + *

You can use getRightNS() to get the value of rightNS

+ * + * @param ns ns + */ + public void setRightNS(final long ns) { + this.rightNS = ns; + } + + /** + * Gets the value of scale . + * + * @return the value of long + */ + public long getScale() { + return scale; + } + + /** + * Sets the scale . + *

You can use getScale() to get the value of scale

+ * + * @param scale scale + */ + public void setScale(final long scale) { + this.scale = scale; + } + + /** + * Gets the value of centerNS . + * + * @return the value of long + */ + public long getCenterNS() { + return centerNS; + } + + /** + * Sets the centerNS . + *

You can use getCenterNS() to get the value of centerNS

+ * + * @param ns ns + */ + public void setCenterNS(final long ns) { + this.centerNS = ns; + } + + /** + * Gets the value of extendHeight . + * + * @return the value of int + */ + public int getExtendHeight() { + return extendHeight; + } + + /** + * Sets the extendHeight . + *

You can use getExtendHeight() to get the value of extendHeight

+ * + * @param height height + */ + public void setExtendHeight(final int height) { + this.extendHeight = height; + } + + /** + * Gets the value of selectX . + * + * @return the value of int + */ + public int getSelectX() { + return selectX; + } + + /** + * Sets the selectX . + *

You can use getSelectX() to get the value of selectX

+ * + * @param select select + */ + public void setSelectX(final int select) { + this.selectX = select; + } + + /** + * Gets the value of selectY . + * + * @return the value of int + */ + public int getSelectY() { + return selectY; + } + + /** + * Sets the selectY . + *

You can use getSelectY() to get the value of selectY

+ * + * @param select select + */ + public void setSelectY(final int select) { + this.selectY = select; + } + + /** + * time range change listener + */ + public interface IChange { + /** + * Time range change monitoring + * + * @param startNS Starting time + * @param endNS End Time + */ + void change(long startNS, long endNS); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/TopFragment.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/TopFragment.java index 83c03d79e..178551165 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/TopFragment.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/fragment/ruler/TopFragment.java @@ -1,87 +1,86 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import ohos.devtools.views.trace.util.TimeUtils; - -import javax.swing.JComponent; -import java.awt.AlphaComposite; -import java.awt.Font; -import java.awt.Graphics2D; - -import static ohos.devtools.views.trace.component.AnalystPanel.DURATION; - - -/** - * Time axis scale - * - * @version 1.0 - * @date 2021/4/22 12:25 - **/ -public class TopFragment extends AbstractFragment { - private final Font smallFont = new Font("宋体", Font.ITALIC, 10); - - /** - * constructor - * - * @param root parent component - */ - public TopFragment(final JComponent root) { - this.setRoot(root); - final int leftW = 200; - final int height = 18; - getRect().setBounds(leftW, 0, root.getWidth(), height); - } - - /** - * Drawing method - * - * @param graphics graphics - */ - @Override - public void draw(final Graphics2D graphics) { - int width = getRoot().getWidth() - getRect().x; - final int height = 18; - final double sq = 10.00; // 10 equal parts - double wid = width / sq; - double sqWidth = wid / sq; - graphics.setFont(getRoot().getFont()); - graphics.setColor(getRoot().getForeground()); - final AlphaComposite alpha50 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); - graphics.setComposite(alpha50); - int yAxis = 0; - graphics.drawLine(getRect().x, yAxis, getRect().x + width, yAxis); - final int num = 10; - long second = DURATION / num; - final AlphaComposite alpha100 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); - for (int index = 0; index <= num; index++) { - int tx = (int) (index * wid) + getRect().x; - graphics.setColor(getRoot().getForeground()); - graphics.setComposite(alpha50); - graphics.drawLine(tx, yAxis, tx, height); - String str = TimeUtils.getSecondFromNSecond(second * index); - graphics.setColor(getRoot().getForeground()); - graphics.setComposite(alpha100); - final int offset = 3; - graphics.drawString(str, tx + offset, height); - for (int numIndex = 1; numIndex < num; numIndex++) { - int side = (int) (numIndex * sqWidth) + tx; - graphics.setColor(getRoot().getForeground()); - graphics.drawLine(side, yAxis, side, height / offset); - } - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import ohos.devtools.views.trace.util.TimeUtils; +import ohos.devtools.views.trace.util.Utils; + +import javax.swing.JComponent; +import java.awt.AlphaComposite; +import java.awt.Font; +import java.awt.Graphics2D; + +import static ohos.devtools.views.trace.component.AnalystPanel.DURATION; + +/** + * Time axis scale + * + * @date 2021/4/22 12:25 + */ +public class TopFragment extends AbstractFragment { + private final Font smallFont = new Font("宋体", Font.ITALIC, 10); + + /** + * constructor + * + * @param root parent component + */ + public TopFragment(final JComponent root) { + this.setRoot(root); + final int leftW = 200; + final int height = 18; + getRect().setBounds(leftW, 0, root.getWidth(), height); + } + + /** + * Drawing method + * + * @param graphics graphics + */ + @Override + public void draw(final Graphics2D graphics) { + int width = getRoot().getWidth() - Utils.getX(getRect()); + final int height = 18; + final double sq = 10.00; // 10 equal parts + double wid = width / sq; + double sqWidth = wid / sq; + graphics.setFont(getRoot().getFont()); + graphics.setColor(getRoot().getForeground()); + final AlphaComposite alpha50 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f); + graphics.setComposite(alpha50); + int yAxis = 0; + graphics.drawLine(Utils.getX(getRect()), yAxis, Utils.getX(getRect()) + width, yAxis); + final int num = 10; + long second = DURATION / num; + final AlphaComposite alpha100 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f); + for (int index = 0; index <= num; index++) { + int tx = (int) (index * wid) + Utils.getX(getRect()); + graphics.setColor(getRoot().getForeground()); + graphics.setComposite(alpha50); + graphics.drawLine(tx, yAxis, tx, height); + String str = TimeUtils.getSecondFromNSecond(second * index); + graphics.setColor(getRoot().getForeground()); + graphics.setComposite(alpha100); + final int offset = 3; + graphics.drawString(str, tx + offset, height); + for (int numIndex = 1; numIndex < num; numIndex++) { + int side = (int) (numIndex * sqWidth) + tx; + graphics.setColor(getRoot().getForeground()); + graphics.drawLine(side, yAxis, side, height / offset); + } + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IFlagListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IFlagListener.java index 16c871dd8..0aa1ed637 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IFlagListener.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IFlagListener.java @@ -1,40 +1,39 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.listener; - -import ohos.devtools.views.trace.bean.FlagBean; - -/** - * Small flag change callback - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public interface IFlagListener { - /** - * Remove the small flag callback. - * - * @param flag flag - */ - void flagRemove(FlagBean flag); - - /** - * The color of the small flag and the name change callback. - * - * @param flag flag - */ - void flagChange(FlagBean flag); -} +/* + * 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. + */ + +package ohos.devtools.views.trace.listener; + +import ohos.devtools.views.trace.bean.FlagBean; + +/** + * Small flag change callback + * + * @date 2021/04/22 12:25 + */ +public interface IFlagListener { + /** + * Remove the small flag callback. + * + * @param flag flag + */ + void flagRemove(FlagBean flag); + + /** + * The color of the small flag and the name change callback. + * + * @param flag flag + */ + void flagChange(FlagBean flag); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IRangeChangeListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IRangeChangeListener.java index 756335f97..b2418bce0 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IRangeChangeListener.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IRangeChangeListener.java @@ -1,35 +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. - */ - -package ohos.devtools.views.trace.listener; - -/** - * Timeline range change callback listener - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public interface IRangeChangeListener { - /** - * Range change callback - * - * @param leftX x-axis left coordinate - * @param rightX x-axis right coordinate - * @param leftNS Nanoseconds on the left - * @param rightNS Nanoseconds on the right - * @param centerNS Nanoseconds on the center - */ - void change(int leftX, int rightX, long leftNS, long rightNS, long centerNS); -} +/* + * 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. + */ + +package ohos.devtools.views.trace.listener; + +/** + * Timeline range change callback listener + * + * @date 2021/04/22 12:25 + */ +public interface IRangeChangeListener { + /** + * Range change callback + * + * @param leftX x-axis left coordinate + * @param rightX x-axis right coordinate + * @param leftNS Nanoseconds on the left + * @param rightNS Nanoseconds on the right + * @param centerNS Nanoseconds on the center + */ + void change(int leftX, int rightX, long leftNS, long rightNS, long centerNS); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IScrollSliceLinkListener.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IScrollSliceLinkListener.java index 129060dda..85aa8831e 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IScrollSliceLinkListener.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/listener/IScrollSliceLinkListener.java @@ -1,31 +1,30 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.listener; - -/** - * Scroll distance change listener - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public interface IScrollSliceLinkListener { - /** - * The currently clicked data object - * - * @param bean bean - */ - void linkClick(Object bean); -} +/* + * 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. + */ + +package ohos.devtools.views.trace.listener; + +/** + * Scroll distance change listener + * + * @date 2021/04/22 12:25 + */ +public interface IScrollSliceLinkListener { + /** + * The currently clicked data object + * + * @param bean bean + */ + void linkClick(Object bean); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/InfoStatsPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/InfoStatsPanel.java new file mode 100644 index 000000000..14c34163d --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/InfoStatsPanel.java @@ -0,0 +1,245 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.metrics.bean.Metadata; +import ohos.devtools.views.trace.metrics.bean.Stats; +import ohos.devtools.views.trace.util.Db; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableRowSorter; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.List; + +/** + * Info Stats Panel + */ +public class InfoStatsPanel extends JBPanel { + /** + * margin bottom + */ + private static final int MARGIN_BOTTOM = 150; + + /** + * margin right + */ + private static final int MARGIN_RIGHT = 100; + + /** + * font size + */ + private static final int FONT_SIZE = 16; + + /** + * half + */ + private static final int HALF = 2; + + private JBLabel previousButton; + private JBPanel optionJPanel; + private JBPanel topJPanel; + private AnalystPanel analystPanel; + private JButton infoButton; + private JBPanel centerJPanel; + private JBLabel centerLabel; + private JScrollPane centerScrollPane; + private JBPanel bottomJPanel; + private JBLabel bottomLabel; + private JScrollPane bottomScrollPane; + + /** + * Info Stats Panel + */ + public InfoStatsPanel(JBPanel optionJPanel, AnalystPanel analystPanel, JButton infoButton) { + this.optionJPanel = optionJPanel; + this.analystPanel = analystPanel; + this.infoButton = infoButton; + initComponents(); + // 设置属性 + setAttributes(); + addComponent(); + componentAddListener(); + MetricsDb.setDbName(Db.getDbName()); + MetricsDb.load(true); + getMetadata(); + getStats(); + } + + /** + * initComponents + */ + private void initComponents() { + previousButton = new JBLabel(); + topJPanel = new JBPanel(); + centerJPanel = new JBPanel(); + centerLabel = new JBLabel(); + centerScrollPane = new JScrollPane(); + bottomJPanel = new JBPanel(); + bottomLabel = new JBLabel(); + bottomScrollPane = new JScrollPane(); + } + + private void setAttributes() { + infoButton.setIcon(IconLoader.getIcon("/images/notificationInfo.png", getClass())); + MigLayout layout = new MigLayout(); + this.setLayout(layout); + this.setOpaque(true); + MigLayout topLayout = new MigLayout(); + topJPanel.setLayout(topLayout); + MigLayout centerLayout = new MigLayout(); + centerJPanel.setLayout(centerLayout); + MigLayout bottomLayout = new MigLayout(); + bottomJPanel.setLayout(bottomLayout); + previousButton.setText("Info and stats"); + Font font = new Font("PingFang SC", Font.PLAIN, FONT_SIZE); + previousButton.setFont(font); + previousButton.setIcon(AllIcons.Actions.Play_back); + topJPanel.setBackground(ColorConstants.ABILITY_COLOR); + topJPanel.add(previousButton, "gapleft 10"); + centerJPanel.setBackground(ColorConstants.ABILITY_COLOR); + this.setPreferredSize(new Dimension(optionJPanel.getWidth(), optionJPanel.getHeight() / HALF)); + centerLabel.setFont(font); + centerLabel.setText("System info and metadata"); + bottomJPanel.setBackground(ColorConstants.ABILITY_COLOR); + bottomLabel.setFont(font); + bottomLabel.setText("Debugging stats"); + } + + private void addComponent() { + this.add(topJPanel, "width " + optionJPanel.getWidth() + ",height 42,wrap"); + centerJPanel.add(centerLabel, "gapleft 12,width 500,height 30,wrap"); + this.add(centerJPanel, "width " + (optionJPanel.getWidth() - MARGIN_RIGHT) + ",wrap,height " + + (optionJPanel.getHeight() - MARGIN_BOTTOM) / HALF); + bottomJPanel.add(bottomLabel, "gapleft 12,width 500,height 30,wrap"); + this.add(bottomJPanel, "width " + (optionJPanel.getWidth() - MARGIN_RIGHT) + ",height " + + (optionJPanel.getHeight() - MARGIN_BOTTOM) / HALF); + } + + private void componentAddListener() { + previousButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + Component[] components = optionJPanel.getComponents(); + for (Component item : components) { + if (item instanceof InfoStatsPanel) { + optionJPanel.remove(item); + } + } + infoButton.setIcon(IconLoader.getIcon("/images/notificationInfo_normal.png", getClass())); + optionJPanel.add(analystPanel); + } + }); + } + + private void getStats() { + JTable table; + DefaultTableModel tableModel; + String[] columnNames = {"Name", "Value", "Type"}; + List stats = new ArrayList<>() { + }; + MetricsDb.getInstance().query(MetricsSql.TRACE_STATS, stats); + String[][] tableValues = new String[stats.size()][columnNames.length]; + int rows = 0; + for (Stats item : stats) { + int columns = 0; + tableValues[rows][columns++] = item.getName() + "_" + item.getType(); + tableValues[rows][columns++] = item.getCount() + ""; + tableValues[rows][columns++] = item.getSeverity() + "(" + item.getSource() + ")"; + rows++; + } + tableModel = new DefaultTableModel(tableValues, columnNames); + table = new JTable(tableModel); + addTableListener(table); + DefaultTableCellRenderer hr = new DefaultTableCellRenderer(); + hr.setHorizontalAlignment(JLabel.LEFT); + table.getTableHeader().setDefaultRenderer(hr); + bottomScrollPane.setViewportView(table); + table.setRowSorter(new TableRowSorter(tableModel)); + bottomJPanel.add(bottomScrollPane, "gapleft 12,width " + (optionJPanel.getWidth() - MARGIN_RIGHT) + ",height " + + (optionJPanel.getHeight() - MARGIN_BOTTOM) / HALF); + } + + /** + * addTableListener + * + * @param table table + */ + private void addTableListener(JTable table) { + table.addMouseMotionListener(new MouseAdapter() { + /** + * mouseMoved + * + * @param event event + */ + public void mouseMoved(MouseEvent event) { + int row = table.rowAtPoint(event.getPoint()); + int col = table.columnAtPoint(event.getPoint()); + if (row > -1 && col > -1) { + Object value = table.getValueAt(row, col); + if (value != null && !"".equals(value)) { + table.setToolTipText(value.toString()); + } else { + table.setToolTipText(null); + } + } + } + }); + } + + private void getMetadata() { + JTable table; + DefaultTableModel tableModel; + String[] columnNames = {"Name", "Value"}; + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(MetricsSql.TRACE_METADATA, list); + String[][] tableValues = new String[list.size()][columnNames.length]; + int rows = 0; + for (Metadata item : list) { + int columns = 0; + tableValues[rows][columns++] = item.getName(); + tableValues[rows][columns++] = item.getValue(); + rows++; + } + tableModel = new DefaultTableModel(tableValues, columnNames); + table = new JTable(tableModel); + addTableListener(table); + DefaultTableCellRenderer hr = new DefaultTableCellRenderer(); + hr.setHorizontalAlignment(JLabel.LEFT); + table.getTableHeader().setDefaultRenderer(hr); + centerScrollPane.setViewportView(table); + table.setRowSorter(new TableRowSorter(tableModel)); + centerJPanel.add(centerScrollPane, "gapleft 12,width " + (optionJPanel.getWidth() - MARGIN_RIGHT) + ",height " + + (optionJPanel.getHeight() - MARGIN_BOTTOM) / HALF); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsDb.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsDb.java new file mode 100644 index 000000000..f8f0debde --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsDb.java @@ -0,0 +1,332 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.util.DataUtils; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.URL; +import java.nio.charset.Charset; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Metric Db + */ +public final class MetricsDb { + private static boolean isLocal; + private static volatile MetricsDb db = new MetricsDb(); + private static String dbName; + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + + /** + * Gets the value of dbName . + * + * @return the value of java.lang.String + */ + public static String getDbName() { + return dbName; + } + + /** + * Sets the dbName . + *

You can use getDbName() to get the value of dbName

+ * + * @param dbName dbName + */ + public static void setDbName(final String dbName) { + MetricsDb.dbName = dbName; + } + + private MetricsDb() { + } + + private LinkedBlockingQueue pool = new LinkedBlockingQueue<>(); + + /** + * Get database connection + * + * @return Connection + */ + public Connection getConn() { + Connection connection = null; + try { + connection = pool.take(); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + return connection; + } + + /** + * Return the connection to the database connection pool after use + * + * @param conn conn + */ + public void free(final Connection conn) { + try { + pool.put(conn); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + } + + private Optional newConn() { + URL path = DataUtils.class.getClassLoader().getResource(dbName); + Connection conn = null; + try { + if (isLocal) { + conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); + } else { + conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + return Optional.ofNullable(conn); + } + + /** + * Load the database file according to the file location variable + * + * @param isLocal isLocal + */ + public static void load(final boolean isLocal) { + MetricsDb.isLocal = isLocal; + final int maxConnNum = 10; + try { + Class.forName("org.sqlite.JDBC"); + for (Connection connection : db.pool) { + connection.close(); + } + db.pool.clear(); + for (int size = 0; size < maxConnNum; size++) { + db.newConn().ifPresent(connection -> { + try { + db.pool.put(connection); + } catch (InterruptedException interruptedException) { + interruptedException.printStackTrace(); + } + }); + } + db.newConn().ifPresent(con -> { + try { + Statement statement = con.createStatement(); + String views = getSql("cpu_views"); + for (String view : views.split(";")) { + statement.execute(view + ";"); + } + statement.close(); + con.close(); + } catch (SQLException exception) { + exception.printStackTrace(); + } + }); + } catch (SQLException | ClassNotFoundException throwables) { + throwables.printStackTrace(); + } + } + + /** + * Get the current current db object + * + * @return CpuDb + */ + public static MetricsDb getInstance() { + if (db == null) { + db = new MetricsDb(); + } + return db; + } + + /** + * Read the sql directory under resource + * + * @param sqlName sqlName + * @return String sql + */ + public static String getSql(String sqlName) { + String path = "metrics-sql/" + sqlName + ".txt"; + try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) { + return IOUtils.toString(STREAM, Charset.forName("UTF-8")); + } catch (IOException exception) { + exception.printStackTrace(); + } + return ""; + } + + /** + * query data by sql str + * + * @param em em + * @param res res + * @param args args + * @param T + */ + public void query(MetricsSql em, List res, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + query(sql, res); + } + + /** + * query data by sql str + * + * @param sql sql + * @param res res + * @param T + */ + public void query(String sql, List res) { + Statement stat = null; + ResultSet rs = null; + Connection conn = getConn(); + Type argument = getType(res); + try { + Class aClass = (Class) Class.forName(argument.getTypeName()); + stat = conn.createStatement(); + rs = stat.executeQuery(sql); + ArrayList columnList = new ArrayList<>(); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + for (int count = 1; count <= columnCount; count++) { + columnList.add(rsMeta.getColumnName(count)); + } + while (rs.next()) { + T data = aClass.getConstructor().newInstance(); + for (Field declaredField : aClass.getDeclaredFields()) { + declaredField.setAccessible(true); + DField annotation = declaredField.getAnnotation(DField.class); + if (Objects.nonNull(annotation) && columnList.contains(annotation.name())) { + setData(declaredField, data, rs, annotation); + } + } + res.add(data); + } + } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + } + + /** + * query data by sql str + * + * @param sql sql + * @return List > + */ + public List> queryBySql(String sql) { + Statement stat = null; + ResultSet rs = null; + Connection conn = getConn(); + List> list = new ArrayList<>(); + try { + stat = conn.createStatement(); + rs = stat.executeQuery(sql); + ArrayList columnList = new ArrayList<>(); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + for (int count = 1; count <= columnCount; count++) { + columnList.add(rsMeta.getColumnName(count)); + } + while (rs.next()) { + Map map = new LinkedHashMap<>(); + for (String column : columnList) { + map.put(column, rs.getString(column)); + } + list.add(map); + } + } catch (SQLException exception) { + Map errorMap = new LinkedHashMap<>(); + String errorStr = exception.getMessage(); + if (errorStr.contains("[SQLITE_ERROR]")) { + errorStr = errorStr.replaceAll("\\[SQLITE_ERROR\\]", ""); + } + errorMap.put("error", errorStr); + list.add(errorMap); + } finally { + release(rs, stat, conn); + } + return list; + } + + private void setData(Field declaredField, T data, ResultSet rs, DField annotation) + throws SQLException, IllegalAccessException { + if (declaredField.getType() == Long.class || declaredField.getType() == long.class) { + declaredField.set(data, rs.getLong(annotation.name())); + } else if (declaredField.getType() == Integer.class || declaredField.getType() == int.class) { + declaredField.set(data, rs.getInt(annotation.name())); + } else if (declaredField.getType() == Double.class || declaredField.getType() == double.class) { + declaredField.set(data, rs.getDouble(annotation.name())); + } else if (declaredField.getType() == Float.class || declaredField.getType() == float.class) { + declaredField.set(data, rs.getFloat(annotation.name())); + } else if (declaredField.getType() == Boolean.class || declaredField.getType() == boolean.class) { + declaredField.set(data, rs.getBoolean(annotation.name())); + } else if (declaredField.getType() == Blob.class) { + declaredField.set(data, rs.getBytes(annotation.name())); + } else { + declaredField.set(data, rs.getObject(annotation.name())); + } + } + + private Type getType(List res) { + Type clazz = res.getClass().getGenericSuperclass(); + ParameterizedType pt = null; + if (clazz instanceof ParameterizedType) { + pt = (ParameterizedType) clazz; + } + if (pt == null) { + return clazz; + } + Type argument = pt.getActualTypeArguments()[0]; + return argument; + } + + private void release(ResultSet rs, Statement stat, Connection conn) { + try { + if (Objects.nonNull(rs)) { + rs.close(); + } + if (Objects.nonNull(stat)) { + stat.close(); + } + if (Objects.nonNull(conn)) { + free(conn); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsPanel.java new file mode 100644 index 000000000..f5434ba7c --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsPanel.java @@ -0,0 +1,346 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.layout.SystemPanel; + +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.metrics.strategy.MetricsContext; +import ohos.devtools.views.trace.util.Db; +import org.apache.commons.lang.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.net.URL; +import java.util.Locale; +import java.util.Objects; +import java.util.concurrent.ExecutionException; + +import static java.awt.Image.SCALE_DEFAULT; +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.LOADING_SIZE; + +/** + * Metrics Panel + */ +public class MetricsPanel extends JBPanel { + private static final Logger LOGGER = LogManager.getLogger(MetricsPanel.class); + + /** + * COLUMNS + */ + private static final int COLUMNS = 28; + + /** + * rows + */ + private static final int ROWS = 20; + + /** + * button x + */ + private static final int BUTTON_X = 30; + + /** + * previous Button width + */ + private static final int PREVIOUS_BUTTON_WIDTH = 200; + + /** + * previous Button height + */ + private static final int PREVIOUS_BUTTON_HEIGHT = 45; + + /** + * run Button height + */ + private static final int RUN_BUTTON_HEIGHT = 40; + + /** + * run Button WIDTH + */ + private static final int RUN_BUTTON_WIDTH = 100; + + /** + * run Button margin left + */ + private static final int RUN_BUTTON_MARGIN_LEFT = 15; + + /** + * bottom x + */ + private static final int BOTTOM_X = 35; + + /** + * bottom y + */ + private static final int BOTTOM_Y = 155; + + /** + * bottom JPanel margin right + */ + private static final int BOTTOM_PANEL_MARGIN_RIGHT = 80; + + /** + * top JPanel height + */ + private static final int TOP_PANEL_HEIGHT = 50; + + /** + * center JPanel height + */ + private static final int CENTER_PANEL_HEIGHT = 80; + + /** + * center JPanel X + */ + private static final int CENTER_PANEL_X = 35; + + /** + * center JPanel Y + */ + private static final int CENTER_PANEL_Y = 70; + + /** + * font size + */ + private static final int FONT_SIZE = 14; + + /** + * label height + */ + private static final int LABEL_HEIGHT = 20; + + /** + * label width + */ + private static final int LABEL_WIDTH = 300; + + /** + * select y + */ + private static final int SELECT_Y = 35; + + /** + * quarter + */ + private static final int QUARTER = 4; + + /** + * half + */ + private static final int HALF = 2; + + /** + * other height + */ + private static final int OTHER_HEIGHT = 100; + + + + private JBLabel previousButton; + private JBPanel optionJPanel; + private JBPanel topJPanel; + private JBPanel centerJPanel; + private JBLabel inputLabel; + private AnalystPanel analystPanel; + private JComboBox metricSelect; + private JButton metricsButton; + private JBPanel bottomJPanel; + private JButton runButton; + private JTextArea resultTextArea; + private JScrollPane resultScroll; + + /** + * System Tuning Panel + */ + public MetricsPanel(JBPanel optionJPanel, AnalystPanel analystPanel, JButton metricsButton) { + this.optionJPanel = optionJPanel; + this.analystPanel = analystPanel; + this.metricsButton = metricsButton; + initComponents(); + // 设置属性 + setAttributes(); + addComponent(); + componentAddListener(); + MetricsDb.setDbName(Db.getDbName()); + MetricsDb.load(true); + } + + /** + * initComponents + */ + private void initComponents() { + previousButton = new JBLabel(); + topJPanel = new JBPanel(); + centerJPanel = new JBPanel(); + inputLabel = new JBLabel(); + metricSelect = new JComboBox<>(); + bottomJPanel = new JBPanel(); + runButton = new JButton(); + resultTextArea = new JTextArea(ROWS, COLUMNS); + } + + private void setAttributes() { + metricsButton.setIcon(IconLoader.getIcon("/images/overhead.png", getClass())); + this.setLayout(null); + this.setOpaque(true); + topJPanel.setLayout(null); + centerJPanel.setLayout(null); + bottomJPanel.setLayout(null); + previousButton.setText("Metrics"); + Font font = new Font("PingFang SC", Font.PLAIN, FONT_SIZE); + previousButton.setFont(font); + previousButton.setIcon(AllIcons.Actions.Play_back); + previousButton.setBounds(BUTTON_X, 0, PREVIOUS_BUTTON_WIDTH, PREVIOUS_BUTTON_HEIGHT); + Color color = new Color(0xFF494E52, true); + topJPanel.setBounds(0, 0, optionJPanel.getWidth(), TOP_PANEL_HEIGHT); + topJPanel.setBackground(color); + topJPanel.add(previousButton); + inputLabel.setFont(font); + inputLabel.setText("Select a metric"); + inputLabel.setBounds(0, 0, LABEL_WIDTH, LABEL_HEIGHT); + metricSelect.setBounds(0, SELECT_Y, optionJPanel.getWidth() / QUARTER, RUN_BUTTON_HEIGHT); + addSelectItem(); + runButton.setFont(font); + runButton.setText("Run"); + runButton.setBounds(optionJPanel.getWidth() / QUARTER + RUN_BUTTON_MARGIN_LEFT, SELECT_Y, RUN_BUTTON_WIDTH, + RUN_BUTTON_HEIGHT); + centerJPanel.setBounds(CENTER_PANEL_X, CENTER_PANEL_Y, optionJPanel.getWidth(), CENTER_PANEL_HEIGHT); + resultTextArea.setFont(font); + resultTextArea.setText(""); + resultTextArea.setEditable(false); + resultScroll = new JScrollPane(resultTextArea); + resultScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + resultScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + int bottomHeight = optionJPanel.getHeight() - (TOP_PANEL_HEIGHT + CENTER_PANEL_HEIGHT + OTHER_HEIGHT); + resultScroll.setBounds(0, 0, optionJPanel.getWidth() - BOTTOM_PANEL_MARGIN_RIGHT, bottomHeight); + bottomJPanel + .setBounds(BOTTOM_X, BOTTOM_Y, optionJPanel.getWidth() - BOTTOM_PANEL_MARGIN_RIGHT, bottomHeight); + bottomJPanel.setBackground(color); + this.setPreferredSize(new Dimension(optionJPanel.getWidth(), optionJPanel.getHeight() / HALF)); + } + + private void addSelectItem() { + MetricsSql[] values = MetricsSql.values(); + for (MetricsSql sql : values) { + metricSelect.addItem(sql.getName()); + } + metricSelect.setSelectedItem(MetricsSql.TRACE_TASK_NAMES.getName()); + } + + private void addComponent() { + centerJPanel.add(inputLabel); + centerJPanel.add(metricSelect); + centerJPanel.add(runButton); + bottomJPanel.add(resultScroll); + this.add(centerJPanel); + this.add(topJPanel); + this.add(bottomJPanel); + } + + private void componentAddListener() { + previousButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + Component[] components = optionJPanel.getComponents(); + for (Component item : components) { + if (!(item instanceof SystemPanel)) { + optionJPanel.remove(item); + break; + } + } + metricsButton.setIcon(IconLoader.getIcon("/images/overhead_normal.png", getClass())); + optionJPanel.add(analystPanel); + } + }); + runButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + resultTextArea.setText(""); + String selectStr = Objects.requireNonNull(metricSelect.getSelectedItem()).toString(); + JBLabel loadingLabel = new JBLabel(); + showLoadingLabel(loadingLabel); + MetricsContext context = new MetricsContext(); + new SwingWorker() { + @Override + protected String doInBackground() { + // get query Result + return context.getQueryResult(MetricsSql.valueOf(selectStr.toUpperCase(Locale.ENGLISH))); + } + + @Override + protected void done() { + try { + String result = get(); + resultTextArea.remove(loadingLabel); + resultTextArea.repaint(); + showText(result); + } catch (InterruptedException | ExecutionException exception) { + LOGGER.error(exception.getMessage()); + } + } + }.execute(); + } + }); + } + + private void showLoadingLabel(JBLabel loadingLabel) { + URL url = TaskScenePanelChart.class.getClassLoader().getResource("/images/loading.gif"); + if (url != null) { + ImageIcon icon = new ImageIcon(url); + icon.setImage(icon.getImage().getScaledInstance(LOADING_SIZE, LOADING_SIZE, SCALE_DEFAULT)); + loadingLabel.setIcon(icon); + } + loadingLabel + .setBounds(bottomJPanel.getWidth() / HALF, bottomJPanel.getHeight() / HALF, LOADING_SIZE, LOADING_SIZE); + resultTextArea.add(loadingLabel); + resultTextArea.revalidate(); + resultScroll.revalidate(); + bottomJPanel.revalidate(); + optionJPanel.revalidate(); + } + + private void showText(String result) { + if (!StringUtils.isEmpty(result)) { + SwingUtilities.invokeLater(new Runnable() { + /** + * run + */ + public void run() { + resultTextArea.setText(result); + } + }); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsSql.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsSql.java new file mode 100644 index 000000000..7d5194975 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/MetricsSql.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics; + +/** + * sql text file path + * + */ +public enum MetricsSql { + DISTRIBUTED_TERM("distributed_term"), + TRACE_CPU("trace_cpu"), + TRACE_CPU_TOP10("trace_cpu_top10"), + TRACE_MEM("trace_mem"), + TRACE_MEM_TOP10("trace_mem_top10"), + TRACE_MEM_UNAGG("trace_mem_unagg"), + TRACE_TASK_NAMES("trace_task_names"), + TRACE_STATS("trace_stats"), + TRACE_METADATA("trace_metadata"), + SYS_CALLS("sys_calls"), + SYS_CALLS_TOP10("sys_calls_top10"); + + /** + * get name + * + * @return name name + */ + public String getName() { + return name; + } + + private final String name; + + MetricsSql(String name) { + this.name = name; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/QuerySqlPanel.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/QuerySqlPanel.java new file mode 100644 index 000000000..e35a8a668 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/QuerySqlPanel.java @@ -0,0 +1,317 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.util.IconLoader; +import com.intellij.ui.JBColor; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBPanel; +import net.miginfocom.swing.MigLayout; +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.trace.component.AnalystPanel; +import ohos.devtools.views.trace.util.Db; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableRowSorter; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Query Sql Panel + */ +public class QuerySqlPanel extends JBPanel { + /** + * COLUMNS + */ + private static final int COLUMNS = 28; + + /** + * button x + */ + private static final int BUTTON_X = 30; + + /** + * panel margin x + */ + private static final int PANEL_MARGIN_X = 35; + + /** + * margin x + */ + private static final int MARGIN_X = 50; + + /** + * previous Button width + */ + private static final int PREVIOUS_BUTTON_WIDTH = 200; + + /** + * previous Button height + */ + private static final int PREVIOUS_BUTTON_HEIGHT = 45; + + /** + * font size + */ + private static final int FONT_SIZE = 14; + + /** + * top JPanel height + */ + private static final int TOP_HEIGHT = 50; + + /** + * input y + */ + private static final int INPUT_Y = 10; + + /** + * label height + */ + private static final int LABEL_HEIGHT = 20; + + /** + * label width + */ + private static final int LABEL_WIDTH = 500; + + /** + * bottom JPanel height + */ + private static final int BOTTOM_HEIGHT = 115; + + /** + * bottom JPanel y + */ + private static final int BOTTOM_Y = 185; + + /** + * center JPanel y + */ + private static final int CENTER_Y = 80; + + /** + * center JPanel height + */ + private static final int CENTER_HEIGHT = 80; + + /** + * text filed y + */ + private static final int TEXT_FIELD_Y = 35; + + /** + * text filed height + */ + private static final int TEXT_FIELD_HEIGHT = 40; + + /** + * half + */ + private static final int HALF = 2; + + private JBLabel previousButton; + private JBPanel optionJPanel; + private JBPanel topJPanel; + private JBPanel centerJPanel; + private JBLabel inputLabel; + private AnalystPanel analystPanel; + private JTextField textField; + private JButton queryButton; + private JBPanel bottomJPanel; + private JBLabel bottomLabel; + private JBLabel errorLabel; + private JScrollPane scrollPane; + + /** + * System Tuning Panel + */ + public QuerySqlPanel(JBPanel optionJPanel, AnalystPanel analystPanel, JButton queryButton) { + this.optionJPanel = optionJPanel; + this.analystPanel = analystPanel; + this.queryButton = queryButton; + initComponents(); + // 设置属性 + setAttributes(); + addComponent(); + componentAddListener(); + MetricsDb.setDbName(Db.getDbName()); + MetricsDb.load(true); + } + + /** + * initComponents + */ + private void initComponents() { + previousButton = new JBLabel(); + topJPanel = new JBPanel(); + centerJPanel = new JBPanel(); + inputLabel = new JBLabel(); + textField = new JTextField(COLUMNS); + bottomJPanel = new JBPanel(); + bottomLabel = new JBLabel(); + errorLabel = new JBLabel(); + scrollPane = new JScrollPane(); + } + + private void setAttributes() { + queryButton.setIcon(IconLoader.getIcon("/images/preview.png", getClass())); + this.setLayout(null); + this.setOpaque(true); + topJPanel.setLayout(null); + centerJPanel.setLayout(null); + MigLayout layout = new MigLayout(); + bottomJPanel.setLayout(layout); + previousButton.setText("Query (SQL)"); + Font font = new Font("PingFang SC", Font.PLAIN, FONT_SIZE); + previousButton.setFont(font); + previousButton.setIcon(AllIcons.Actions.Play_back); + previousButton.setBounds(BUTTON_X, 0, PREVIOUS_BUTTON_WIDTH, PREVIOUS_BUTTON_HEIGHT); + topJPanel.setBounds(0, 0, optionJPanel.getWidth(), TOP_HEIGHT); + topJPanel.setBackground(ColorConstants.ABILITY_COLOR); + topJPanel.add(previousButton); + inputLabel.setFont(font); + inputLabel.setText("Enter query and press cmd/ctrl + Enter"); + inputLabel.setBounds(MARGIN_X, INPUT_Y, LABEL_WIDTH, LABEL_HEIGHT); + textField.setBounds(MARGIN_X, TEXT_FIELD_Y, optionJPanel.getWidth() - 100, TEXT_FIELD_HEIGHT); + centerJPanel.setBounds(PANEL_MARGIN_X, CENTER_Y, optionJPanel.getWidth(), CENTER_HEIGHT); + centerJPanel.setBackground(ColorConstants.ABILITY_COLOR); + bottomLabel.setFont(font); + bottomLabel.setText(""); + errorLabel.setFont(font); + Color errorColor = new JBColor(new Color(0xFFFF9201, true), new Color(255, 146, 1)); + errorLabel.setForeground(errorColor); + errorLabel.setText(""); + bottomJPanel.setBounds(PANEL_MARGIN_X, BOTTOM_Y, optionJPanel.getWidth(), BOTTOM_HEIGHT); + bottomJPanel.setBackground(ColorConstants.ABILITY_COLOR); + this.setPreferredSize(new Dimension(optionJPanel.getWidth(), optionJPanel.getHeight() / HALF)); + } + + private void addComponent() { + centerJPanel.add(inputLabel); + centerJPanel.add(textField); + this.add(centerJPanel); + this.add(topJPanel); + this.add(bottomJPanel); + } + + private void componentAddListener() { + previousButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + Component[] components = optionJPanel.getComponents(); + for (Component item : components) { + if (item instanceof QuerySqlPanel) { + optionJPanel.remove(item); + } + } + queryButton.setIcon(IconLoader.getIcon("/images/preview_normal.png", getClass())); + optionJPanel.add(analystPanel); + } + }); + + textField.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent event) { + if ((event.getKeyCode() == KeyEvent.VK_ENTER) && (event.isControlDown())) { + bottomJPanel.removeAll(); + long start = System.currentTimeMillis(); + List> list = MetricsDb.getInstance().queryBySql(textField.getText()); + long spendTime = System.currentTimeMillis() - start; + bottomLabel.setText("Query result - " + spendTime + " ms " + textField.getText()); + bottomJPanel.add(bottomLabel, "gapleft 6,width 500,height 25,wrap"); + if (list.size() == 1 && list.get(0).containsKey("error")) { + errorLabel.setText(list.get(0).get("error")); + bottomJPanel.add(errorLabel, "gapleft 6,width 500,height 25"); + } else { + keyPressHandle(list); + } + bottomJPanel.revalidate(); + bottomJPanel.repaint(); + } + } + }); + } + + private void keyPressHandle(List> list) { + if (list.size() <= 0) { + return; + } + JTable table; + DefaultTableModel tableModel; + Map columnMap = list.get(0); + String[] columnNames = new String[columnMap.size()]; + Set keys = columnMap.keySet(); + int index = 0; + for (String key : keys) { + columnNames[index++] = key; + } + String[][] tableValues = new String[list.size()][columnMap.size()]; + int rows = 0; + for (Map item : list) { + Set> entries = item.entrySet(); + int columns = 0; + for (Map.Entry entry : entries) { + tableValues[rows][columns++] = entry.getValue(); + } + rows++; + } + tableModel = new DefaultTableModel(tableValues, columnNames); + table = new JTable(tableModel); + table.addMouseMotionListener(new MouseAdapter() { + /** + * Mouse move Handle + * + * @param event mouse event + */ + public void mouseMoved(MouseEvent event) { + int row = table.rowAtPoint(event.getPoint()); + int col = table.columnAtPoint(event.getPoint()); + if (row > -1 && col > -1) { + Object value = table.getValueAt(row, col); + if (value != null && !"".equals(value)) { + table.setToolTipText(value.toString()); + } else { + table.setToolTipText(null); + } + } + } + }); + DefaultTableCellRenderer hr = new DefaultTableCellRenderer(); + hr.setHorizontalAlignment(JLabel.LEFT); + table.getTableHeader().setDefaultRenderer(hr); + scrollPane.setViewportView(table); + table.setRowSorter(new TableRowSorter(tableModel)); + bottomJPanel.add(scrollPane, "gapleft 6,width " + (optionJPanel.getWidth() - 100) + ",wrap"); + bottomJPanel.setBounds(PANEL_MARGIN_X, BOTTOM_Y, optionJPanel.getWidth() - 80, optionJPanel.getHeight() - 180); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Cpu.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Cpu.java new file mode 100644 index 000000000..9c7153b15 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Cpu.java @@ -0,0 +1,122 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +/** + * cpu data + * + */ +public class Cpu { + @DField(name = "tid") + private Integer tid; + @DField(name = "pid") + private Integer pid; + @DField(name = "cpu") + private String cpu; + @DField(name = "duration") + private String duration; + @DField(name = "min_freq") + private String minFreq; + @DField(name = "max_freq") + private String maxFreq; + @DField(name = "avg_frequency") + private String avgFrequency; + @DField(name = "process_name") + private String processName; + @DField(name = "thread_name") + private String threadName; + + public Integer getTid() { + return tid; + } + + public void setTid(Integer tid) { + this.tid = tid; + } + + public Integer getPid() { + return pid; + } + + public void setPid(Integer pid) { + this.pid = pid; + } + + public String getCpu() { + return cpu; + } + + public void setCpu(String cpu) { + this.cpu = cpu; + } + + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + public String getMinFreq() { + return minFreq; + } + + public void setMinFreq(String minFreq) { + this.minFreq = minFreq; + } + + public String getMaxFreq() { + return maxFreq; + } + + public void setMaxFreq(String maxFreq) { + this.maxFreq = maxFreq; + } + + public String getAvgFrequency() { + return avgFrequency; + } + + public void setAvgFrequency(String avgFrequency) { + this.avgFrequency = avgFrequency; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public String getThreadName() { + return threadName; + } + + public void setThreadName(String threadName) { + this.threadName = threadName; + } + + @Override + public String toString() { + return "Cpu{" + "tid=" + tid + ", pid=" + pid + ", cpu='" + cpu + '\'' + ", duration='" + duration + '\'' + + ", minFreq='" + minFreq + '\'' + ", maxFreq='" + maxFreq + '\'' + ", avgFrequency='" + avgFrequency + '\'' + + ", processName='" + processName + '\'' + ", threadName='" + threadName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/DistributeTerm.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/DistributeTerm.java new file mode 100644 index 000000000..0cd07ac47 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/DistributeTerm.java @@ -0,0 +1,188 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +import java.util.Objects; + +/** + * Distribute Term entity + */ +public class DistributeTerm { + @DField(name = "threadId") + private String threadId; + + @DField(name = "threadName") + private String threadName; + + @DField(name = "processId") + private String processId; + + @DField(name = "process_name") + private String processName; + + @DField(name = "funName") + private String funName; + + @DField(name = "dur") + private String dur; + + @DField(name = "ts") + private String time; + + @DField(name = "chainId") + private String chainId; + + @DField(name = "spanId") + private int spanId; + + @DField(name = "parentSpanId") + private int parentSpanId; + + @DField(name = "flag") + private String flag; + + @DField(name = "trace_name") + private String traceName; + + public String getThreadName() { + return threadName; + } + + public void setThreadName(String threadName) { + this.threadName = threadName; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public String getFunName() { + return funName; + } + + public void setFunName(String funName) { + this.funName = funName; + } + + public String getDur() { + return dur; + } + + public void setDur(String dur) { + this.dur = dur; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getChainId() { + return chainId; + } + + public void setChainId(String chainId) { + this.chainId = chainId; + } + + public int getSpanId() { + return spanId; + } + + public void setSpanId(int spanId) { + this.spanId = spanId; + } + + public int getParentSpanId() { + return parentSpanId; + } + + public void setParentSpanId(int parentSpanId) { + this.parentSpanId = parentSpanId; + } + + public String getFlag() { + return flag; + } + + public void setFlag(String flag) { + this.flag = flag; + } + + public String getTraceName() { + return traceName; + } + + public void setTraceName(String traceName) { + this.traceName = traceName; + } + + public String getThreadId() { + return threadId; + } + + public void setThreadId(String threadId) { + this.threadId = threadId; + } + + public String getProcessId() { + return processId; + } + + public void setProcessId(String processId) { + this.processId = processId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DistributeTerm that = (DistributeTerm) o; + return spanId == that.spanId && parentSpanId == that.parentSpanId && Objects.equals(threadId, that.threadId) + && Objects.equals(threadName, that.threadName) && Objects.equals(processId, that.processId) && Objects + .equals(processName, that.processName) && Objects.equals(funName, that.funName) && Objects + .equals(dur, that.dur) && Objects.equals(time, that.time) && Objects.equals(chainId, that.chainId) + && Objects.equals(flag, that.flag) && Objects.equals(traceName, that.traceName); + } + + @Override + public int hashCode() { + return Objects + .hash(threadId, threadName, processId, processName, funName, dur, time, chainId, spanId, parentSpanId, flag, + traceName); + } + + @Override + public String toString() { + return "DistributeTerm{" + "threadId='" + threadId + '\'' + ", threadName='" + threadName + '\'' + + ", processId='" + processId + '\'' + ", processName='" + processName + '\'' + ", funName='" + funName + + '\'' + ", dur=" + dur + ", time=" + time + ", chainId='" + chainId + '\'' + ", spanId=" + spanId + + ", parentSpanId=" + parentSpanId + ", flag='" + flag + '\'' + ", traceName='" + traceName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/MemAgg.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/MemAgg.java new file mode 100644 index 000000000..746a00a35 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/MemAgg.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Mem Agg + * + */ +public class MemAgg { + @DField(name = "value") + private String value; + @DField(name = "ts") + private String time; + @DField(name = "name") + private String name; + @DField(name = "processName") + private String processName; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + @Override + public String toString() { + return "MemAgg{" + "value='" + value + '\'' + ", time='" + time + '\'' + ", name='" + name + '\'' + + ", processName='" + processName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Memory.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Memory.java new file mode 100644 index 000000000..e9f7d177f --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Memory.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Memory data + * + */ +public class Memory { + @DField(name = "maxNum") + private Integer maxNum; + @DField(name = "minNum") + private Integer minNum; + @DField(name = "avgNum") + private float avgNum; + @DField(name = "name") + private String name; + @DField(name = "processName") + private String processName; + + public Integer getMaxNum() { + return maxNum; + } + + public void setMaxNum(Integer maxNum) { + this.maxNum = maxNum; + } + + public Integer getMinNum() { + return minNum; + } + + public void setMinNum(Integer minNum) { + this.minNum = minNum; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public float getAvgNum() { + return avgNum; + } + + public void setAvgNum(float avgNum) { + this.avgNum = avgNum; + } + + @Override + public String toString() { + return "Memory{" + "maxNum=" + maxNum + ", minNum=" + minNum + ", avgNum=" + avgNum + ", name='" + name + '\'' + + ", processName='" + processName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Metadata.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Metadata.java new file mode 100644 index 000000000..a5ca34b45 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Metadata.java @@ -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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Metadata bean + * + */ +public class Metadata { + @DField(name = "name") + private String name; + + @DField(name = "value") + private String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return "Metadata{" + "name='" + name + '\'' + ", value='" + value + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/ProcessThread.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/ProcessThread.java new file mode 100644 index 000000000..1cc9f8436 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/ProcessThread.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; +import org.apache.commons.lang.StringUtils; + +/** + * Process entity class + * + */ +public class ProcessThread { + @DField(name = "pid") + private Integer pid; + + @DField(name = "process_name") + private String processName; + + @DField(name = "thread_name") + private String threadName; + + /** + * Gets the value of pid . + * + * @return the value of int + */ + public Integer getPid() { + return pid; + } + + /** + * Sets the pid . + *

You can use getPid() to get the value of pid

+ * + * @param id id + */ + public void setPid(final Integer id) { + this.pid = id; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public String getThreadName() { + return threadName; + } + + public void setThreadName(String threadName) { + this.threadName = threadName; + } + + @Override + public String toString() { + return "ProcessThread{" + "pid=" + pid + ", processName='" + (StringUtils.isEmpty(processName) ? null : + processName) + '\'' + ", threadName='" + threadName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Stats.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Stats.java new file mode 100644 index 000000000..5a0a3f185 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/Stats.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +/** + * Metadata bean + * + */ +public class Stats { + @DField(name = "event_name") + private String name; + + @DField(name = "stat_type") + private String type; + + @DField(name = "count") + private int count; + + @DField(name = "serverity") + private String severity; + + @DField(name = "source") + private String source; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + @Override + public String toString() { + return "Stats{" + "name='" + name + '\'' + ", type='" + type + '\'' + ", count=" + count + ", severity='" + + severity + '\'' + ", source='" + source + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCalls.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCalls.java new file mode 100644 index 000000000..03535fde5 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCalls.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +import java.util.Objects; + +/** + * Sys Calls + * + */ +public class SysCalls { + @DField(name = "minDur") + private int minDur; + @DField(name = "avgDur") + private int avgDur; + @DField(name = "maxDur") + private int maxDur; + @DField(name = "funName") + private String funName; + + public int getMinDur() { + return minDur; + } + + public void setMinDur(int minDur) { + this.minDur = minDur; + } + + public int getAvgDur() { + return avgDur; + } + + public void setAvgDur(int avgDur) { + this.avgDur = avgDur; + } + + public int getMaxDur() { + return maxDur; + } + + public void setMaxDur(int maxDur) { + this.maxDur = maxDur; + } + + public String getFunName() { + return funName; + } + + public void setFunName(String funName) { + this.funName = funName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SysCalls sysCalls = (SysCalls) o; + return minDur == sysCalls.minDur && avgDur == sysCalls.avgDur && maxDur == sysCalls.maxDur && Objects + .equals(funName, sysCalls.funName); + } + + @Override + public int hashCode() { + return Objects.hash(minDur, avgDur, maxDur, funName); + } + + @Override + public String toString() { + return "SysCalls{" + "minDur=" + minDur + ", avgDur=" + avgDur + ", maxDur=" + maxDur + ", funName='" + funName + + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCallsTop.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCallsTop.java new file mode 100644 index 000000000..24a862bf7 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/bean/SysCallsTop.java @@ -0,0 +1,133 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.bean; + +import ohos.devtools.views.trace.DField; + +import java.util.Objects; + +/** + * Sys Calls Top + * + */ +public class SysCallsTop { + @DField(name = "tid") + private int tid; + @DField(name = "pid") + private int pid; + @DField(name = "minDur") + private int minDur; + @DField(name = "avgDur") + private int avgDur; + @DField(name = "maxDur") + private int maxDur; + @DField(name = "funName") + private String funName; + @DField(name = "process_name") + private String processName; + @DField(name = "thread_name") + private String threadName; + + public int getTid() { + return tid; + } + + public void setTid(int tid) { + this.tid = tid; + } + + public int getPid() { + return pid; + } + + public void setPid(int pid) { + this.pid = pid; + } + + public int getMinDur() { + return minDur; + } + + public void setMinDur(int minDur) { + this.minDur = minDur; + } + + public int getAvgDur() { + return avgDur; + } + + public void setAvgDur(int avgDur) { + this.avgDur = avgDur; + } + + public int getMaxDur() { + return maxDur; + } + + public void setMaxDur(int maxDur) { + this.maxDur = maxDur; + } + + public String getFunName() { + return funName; + } + + public void setFunName(String funName) { + this.funName = funName; + } + + public String getProcessName() { + return processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public String getThreadName() { + return threadName; + } + + public void setThreadName(String threadName) { + this.threadName = threadName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SysCallsTop that = (SysCallsTop) o; + return tid == that.tid && pid == that.pid && minDur == that.minDur && avgDur == that.avgDur + && maxDur == that.maxDur && Objects.equals(funName, that.funName) && Objects + .equals(processName, that.processName) && Objects.equals(threadName, that.threadName); + } + + @Override + public int hashCode() { + return Objects.hash(tid, pid, minDur, avgDur, maxDur, funName, processName, threadName); + } + + @Override + public String toString() { + return "SysCallsTop{" + "tid=" + tid + ", pid=" + pid + ", minDur=" + minDur + ", avgDur=" + avgDur + + ", maxDur=" + maxDur + ", funName='" + funName + '\'' + ", processName='" + processName + '\'' + + ", threadName='" + threadName + '\'' + '}'; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/CpuStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/CpuStrategy.java new file mode 100644 index 000000000..00dca5537 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/CpuStrategy.java @@ -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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.Cpu; +import org.apache.commons.lang.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * cpu Strategy + */ +public class CpuStrategy implements Strategy { + /** + * Separator + */ + private static final String SEPARATOR = ","; + + /** + * get Query cpu Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List cpuList = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, cpuList); + return handleCpuInfo(cpuList); + } + + private String handleCpuInfo(List result) { + StringBuilder builder = new StringBuilder(); + if (result.size() == 10) { + builder.append("trace_cpu_top10 {").append(System.lineSeparator()); + } else { + builder.append("trace_cpu {").append(System.lineSeparator()); + } + for (Cpu item : result) { + // filter the data with duration 0, which will result in AVG_ Frequency calculation error null + if (item.getAvgFrequency() == null) { + continue; + } + builder.append(" process_info {").append(System.lineSeparator()); + builder.append(" name: ") + .append(StringUtils.isEmpty(item.getProcessName()) ? null : item.getProcessName()) + .append(System.lineSeparator()); + builder.append(" threads {").append(System.lineSeparator()); + builder.append(" name: ").append(item.getThreadName()).append(System.lineSeparator()); + String[] avgFrequency = item.getAvgFrequency().split(SEPARATOR); + String[] cpuIds = item.getCpu().split(SEPARATOR); + String[] durations = item.getDuration().split(SEPARATOR); + String[] minFreq = item.getMinFreq().split(SEPARATOR); + String[] maxFreq = item.getMaxFreq().split(SEPARATOR); + for (int index = 0; index < cpuIds.length; index++) { + builder.append(" cpu {").append(System.lineSeparator()); + builder.append(" id: ").append(cpuIds[index]).append(System.lineSeparator()); + builder.append(" min_freq_khz: ").append(minFreq[index]).append(System.lineSeparator()); + builder.append(" max_freq_khz: ").append(maxFreq[index]).append(System.lineSeparator()); + builder.append(" avg_freq_khz: ").append(avgFrequency[index]).append(System.lineSeparator()); + builder.append(" duration_ns: ").append(durations[index]).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + builder.append(" }").append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/DistributeTermStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/DistributeTermStrategy.java new file mode 100644 index 000000000..a13ae1ae6 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/DistributeTermStrategy.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.DistributeTerm; + +import java.util.ArrayList; +import java.util.List; + +/** + * Distribute Term Strategy + */ +public class DistributeTermStrategy implements Strategy { + /** + * Query DistributeTerm Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, list); + return handleDistributeTermInfo(list); + } + + private String handleDistributeTermInfo(List result) { + StringBuilder builder = new StringBuilder(); + builder.append("distributed_term {").append(System.lineSeparator()); + for (DistributeTerm item : result) { + String[] threadIds = item.getThreadId().split(","); + String[] threadNames = item.getThreadName().split(","); + String[] processIds = item.getProcessId().split(","); + String[] processNames = + item.getProcessName() == null ? new String[threadIds.length] : item.getProcessName().split(","); + String[] funNames = item.getFunName().split(","); + String[] durations = item.getDur().split(","); + String[] times = item.getTime().split(","); + String[] flags = item.getFlag().split(","); + builder.append("\tdistributed_term_item{").append(System.lineSeparator()); + long receiverTime = 0; + long senderTime = 0; + for (int index = 0; index < flags.length; index++) { + String sendOrRecv = "C".equals(flags[index]) ? "\t\tsender {" : "\t\treceiver {"; + builder.append(sendOrRecv).append(System.lineSeparator()); + if (item.getFlag().contains("C,S") || item.getFlag().contains("S,C")) { + builder.append("\t\t\tAcross the device:").append(false).append(System.lineSeparator()); + if ("S".equals(flags[index])) { + receiverTime = Long.parseLong(times[index]); + } + if ("C".equals(flags[index])) { + senderTime = Long.parseLong(times[index]); + } + } else { + builder.append("\t\t\tAcross the device:").append(true).append(System.lineSeparator()); + } + appendId(builder, item); + builder.append("\t\t\tfunction_name:").append(funNames[index]).append(System.lineSeparator()); + builder.append("\t\t\tprocess_info{").append(System.lineSeparator()); + builder.append("\t\t\t\tprocess_id:").append(processIds[index]).append(System.lineSeparator()); + builder.append("\t\t\t\tprocess_name:").append(processNames[index]).append(System.lineSeparator()); + builder.append("\t\t\t}").append(System.lineSeparator()); + builder.append("\t\t\tthread_info{").append(System.lineSeparator()); + builder.append("\t\t\t\tthread_id:").append(threadIds[index]).append(System.lineSeparator()); + builder.append("\t\t\t\tthread_name:").append(threadNames[index]).append(System.lineSeparator()); + builder.append("\t\t\t}").append(System.lineSeparator()); + builder.append("\t\t\tdur:").append(durations[index]).append(System.lineSeparator()); + appendDelay(item, builder, flags, index, receiverTime - senderTime); + builder.append("\t\t }").append(System.lineSeparator()); + } + builder.append("\t}").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } + + private void appendDelay(DistributeTerm item, StringBuilder builder, String[] flags, int index, long delay) { + if (item.getFlag().contains("C,S") || item.getFlag().contains("S,C")) { + if ("S".equals(flags[index])) { + builder.append("\t\t\tdelay:").append(delay).append(System.lineSeparator()); + } + } else { + if ("S".equals(flags[index])) { + builder.append("\t\t\tdelay:").append("").append(System.lineSeparator()); + } + } + } + + private void appendId(StringBuilder builder, DistributeTerm item) { + builder.append("\t\t\ttrace_name:").append(item.getTraceName()).append(System.lineSeparator()); + builder.append("\t\t\ttrace_id {").append(System.lineSeparator()); + builder.append("\t\t\t\tchainID:").append(item.getChainId()).append(System.lineSeparator()); + builder.append("\t\t\t\tspanID:").append(item.getSpanId()).append(System.lineSeparator()); + builder.append("\t\t\t\tparentSpanID:").append(item.getParentSpanId()).append(System.lineSeparator()); + builder.append("\t\t\t}").append(System.lineSeparator()); + } + +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemAggStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemAggStrategy.java new file mode 100644 index 000000000..2dddd7522 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemAggStrategy.java @@ -0,0 +1,105 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.MemAgg; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory unagg Strategy + */ +public class MemAggStrategy implements Strategy { + /** + * Query Memory Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, list); + return handleMemoryInfo(list); + } + + private String handleMemoryInfo(List result) { + StringBuilder builder = new StringBuilder(); + builder.append("trace_mem_unagg: {").append(System.lineSeparator()); + for (MemAgg item : result) { + builder.append(" process_values: {").append(System.lineSeparator()); + builder.append(" process_name: ").append(item.getProcessName()).append(System.lineSeparator()); + String[] names = item.getName().split(","); + String[] values = item.getValue().split(","); + String[] times = item.getTime().split(","); + long anonTs = 0; + int anonValue = 0; + int swapValue = 0; + int oomScoreValue = getOomScoreValue(names, values); + for (int index = 0; index < names.length; index++) { + if ("mem.rss.anon".equals(names[index])) { + builder.append(" anon_rss: {").append(System.lineSeparator()); + anonTs = Long.parseLong(times[index]); + anonValue = Integer.parseInt(values[index]); + builder.append(" ts: ").append(anonTs).append(System.lineSeparator()); + builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); + builder.append(" value: ").append(anonValue).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + if ("mem.swap".equals(names[index])) { + swapValue = Integer.parseInt(values[index]); + builder.append(" swap: {").append(System.lineSeparator()); + builder.append(" ts: ").append(times[index]).append(System.lineSeparator()); + builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); + builder.append(" value: ").append(swapValue).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + if ("mem.rss.file".equals(names[index])) { + builder.append(" file_rss: { ").append(System.lineSeparator()); + builder.append(" ts: ").append(times[index]).append(System.lineSeparator()); + builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); + builder.append(" value: ").append(values[index]).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + if ("oom_score_adj".equals(names[index])) { + builder.append(" anon_and_swap: { ").append(System.lineSeparator()); + builder.append(" ts: ").append(anonTs).append(System.lineSeparator()); + builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); + builder.append(" value: ").append(anonValue + swapValue).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + } + builder.append(" }").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } + + private int getOomScoreValue(String[] names, String[] values) { + int oomScoreValue = 0; + for (int index = 0; index < names.length; index++) { + if ("oom_score_adj".equals(names[index])) { + oomScoreValue = Integer.parseInt(values[index]); + break; + } + } + return oomScoreValue; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemStrategy.java new file mode 100644 index 000000000..79992d289 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemStrategy.java @@ -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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.Memory; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory Strategy + */ +public class MemStrategy implements Strategy { + /** + * Query Memory Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + if ("trace_mem_top10".equals(sql.getName())) { + MetricsDb.getInstance().query(MetricsSql.TRACE_MEM, list); + } else { + MetricsDb.getInstance().query(sql, list); + } + List newList; + if ("trace_mem_top10".equals(sql.getName()) && list.size() >= 10) { + newList = list.subList(0, 10); + } else { + newList = list; + } + return handleMemoryInfo(newList); + } + + private String handleMemoryInfo(List result) { + StringBuilder builder = new StringBuilder(); + if (result.size() == 10) { + builder.append("trace_mem_top10 {").append(System.lineSeparator()); + } else { + builder.append("trace_mem {").append(System.lineSeparator()); + } + for (Memory item : result) { + builder.append(" process_metrics {").append(System.lineSeparator()); + builder.append(" process_name: \"").append(item.getProcessName()).append("\"") + .append(System.lineSeparator()); + builder.append(" overall_counters {").append(System.lineSeparator()); + builder.append(" anon_rss {").append(System.lineSeparator()); + builder.append(" min: ").append(item.getMinNum()).append(System.lineSeparator()); + builder.append(" max: ").append(item.getMaxNum()).append(System.lineSeparator()); + builder.append(" avg: ").append(item.getAvgNum()).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetadataStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetadataStrategy.java new file mode 100644 index 000000000..26a1fd5c0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetadataStrategy.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.Metadata; + +import java.util.ArrayList; +import java.util.List; + +/** + * Metadata Strategy + * + */ +public class MetadataStrategy implements Strategy { + /** + * get Query Metadata Result + * + * @param sql sql + * @return String String + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, list); + StringBuilder builder = new StringBuilder(); + builder.append("trace_metadata: {").append(System.lineSeparator()); + for (Metadata item : list) { + String regex = "^-?\\d+$"; + String value = ""; + if (item.getValue().matches(regex)) { + value = item.getValue(); + } else { + value = "\"" + item.getValue().replaceAll("\r|\n", "") + "\""; + } + builder.append(" ").append(item.getName()).append(":").append(" ").append(value) + .append(System.lineSeparator()); + } + builder.append("}"); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsContext.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsContext.java new file mode 100644 index 000000000..cd1c635e0 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsContext.java @@ -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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsSql; + +/** + * MetadataStrategy + */ +public class MetricsContext { + /** + * Query according to the specific instance obtained + * + * @param sql sql + * @return String + */ + public String getQueryResult(MetricsSql sql) { + Strategy strategy = MetricsFactory.getInstance().getStrategy(sql); + return strategy.getQueryResult(sql); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsFactory.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsFactory.java new file mode 100644 index 000000000..76af68463 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MetricsFactory.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsSql; + +import java.util.HashMap; +import java.util.Map; + +/** + * MetadataStrategy + */ +public class MetricsFactory { + private static final MetricsFactory factory = new MetricsFactory(); + private static final MetricsFactory METRICS_FACTORY = new MetricsFactory(); + + private final Map strategyMap = new HashMap<>(); + + private MetricsFactory() { + strategyMap.put(MetricsSql.TRACE_METADATA, new MetadataStrategy()); + strategyMap.put(MetricsSql.TRACE_CPU, new CpuStrategy()); + strategyMap.put(MetricsSql.TRACE_CPU_TOP10, new CpuStrategy()); + strategyMap.put(MetricsSql.TRACE_TASK_NAMES, new TraceTaskStrategy()); + strategyMap.put(MetricsSql.TRACE_STATS, new TraceStatsStrategy()); + strategyMap.put(MetricsSql.TRACE_MEM, new MemStrategy()); + strategyMap.put(MetricsSql.TRACE_MEM_TOP10, new MemStrategy()); + strategyMap.put(MetricsSql.TRACE_MEM_UNAGG, new MemAggStrategy()); + strategyMap.put(MetricsSql.DISTRIBUTED_TERM, new DistributeTermStrategy()); + strategyMap.put(MetricsSql.SYS_CALLS_TOP10, new SysCallsTopStrategy()); + strategyMap.put(MetricsSql.SYS_CALLS, new SysCallsStrategy()); + } + + /** + * Get singleton + * + * @return MetricsFactory MetricsFactory + */ + public static MetricsFactory getInstance() { + return METRICS_FACTORY; + } + + /** + * Get Strategy + * + * @param sql sql + * @return Strategy Strategy + */ + public Strategy getStrategy(MetricsSql sql) { + return strategyMap.get(sql); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/Strategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/Strategy.java new file mode 100644 index 000000000..c6cdd614a --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/Strategy.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsSql; + +/** + * Strategy + */ +public interface Strategy { + /** + * get Query Result + * + * @param sql sql + * @return String String + */ + String getQueryResult(MetricsSql sql); +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsStrategy.java new file mode 100644 index 000000000..af2295387 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsStrategy.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.Memory; +import ohos.devtools.views.trace.metrics.bean.SysCalls; + +import java.util.ArrayList; +import java.util.List; + +/** + * SysCalls Strategy + */ +public class SysCallsStrategy implements Strategy { + /** + * Query SysCalls Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, list); + return handleSysCallsInfo(list); + } + + private String handleSysCallsInfo(List result) { + StringBuilder builder = new StringBuilder(); + builder.append("sys_calls{").append(System.lineSeparator()); + for (SysCalls item : result) { + builder.append("\tfunction{").append(System.lineSeparator()); + builder.append("\t\tfunction_name:").append(item.getFunName()).append(System.lineSeparator()); + builder.append("\t\tdurMax:").append(item.getMaxDur()).append(System.lineSeparator()); + builder.append("\t\tdurMin:").append(item.getMinDur()).append(System.lineSeparator()); + builder.append("\t\tdurAvg:").append(item.getAvgDur()).append(System.lineSeparator()); + builder.append("\t}").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsTopStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsTopStrategy.java new file mode 100644 index 000000000..adda7f158 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/SysCallsTopStrategy.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.SysCallsTop; + +import java.util.ArrayList; +import java.util.List; + +/** + * SysCalls Strategy + */ +public class SysCallsTopStrategy implements Strategy { + /** + * Query Sys Calls top10 Result + * + * @param sql sql + * @return string string + */ + @Override + public String getQueryResult(MetricsSql sql) { + List list = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, list); + return handleSysCallsInfo(list); + } + + private String handleSysCallsInfo(List result) { + StringBuilder builder = new StringBuilder(); + builder.append("sys_calls_top10{").append(System.lineSeparator()); + for (SysCallsTop item : result) { + builder.append("\tprocess_info {").append(System.lineSeparator()); + builder.append("\t\tname:").append(item.getProcessName()).append(System.lineSeparator()); + builder.append("\t\tpid:").append(item.getPid()).append(System.lineSeparator()); + builder.append("\t\tthreads{").append(System.lineSeparator()); + builder.append("\t\t\tname:").append(item.getThreadName()).append(System.lineSeparator()); + builder.append("\t\t\ttid:").append(item.getTid()).append(System.lineSeparator()); + builder.append("\t\t\tfunction{").append(System.lineSeparator()); + builder.append("\t\t\t\tfunction_name:").append(item.getFunName()).append(System.lineSeparator()); + builder.append("\t\t\t\tdurMax:").append(item.getMaxDur()).append(System.lineSeparator()); + builder.append("\t\t\t\tdurMin:").append(item.getMinDur()).append(System.lineSeparator()); + builder.append("\t\t\t\tdurAvg:").append(item.getAvgDur()).append(System.lineSeparator()); + builder.append("\t\t\t}").append(System.lineSeparator()); + builder.append("\t\t}").append(System.lineSeparator()); + builder.append("\t}").append(System.lineSeparator()); + } + builder.append("}").append(System.lineSeparator()); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceStatsStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceStatsStrategy.java new file mode 100644 index 000000000..8d81724c9 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceStatsStrategy.java @@ -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. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.Stats; + +import java.util.ArrayList; +import java.util.List; + +/** + * Trace Stats Strategy + */ +public class TraceStatsStrategy implements Strategy { + /** + * get Query stats Result + * + * @param sql sql + * @return String String + */ + @Override + public String getQueryResult(MetricsSql sql) { + List stats = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, stats); + StringBuilder builder = new StringBuilder(); + builder.append("trace_stats: {").append(System.lineSeparator()); + for (Stats item : stats) { + builder.append(" stat:{").append(System.lineSeparator()); + builder.append(" name: ").append(item.getName()).append("_").append(item.getType()) + .append(System.lineSeparator()); + builder.append(" count: ").append(item.getCount()).append(System.lineSeparator()); + builder.append(" source: ").append(item.getSource()).append(System.lineSeparator()); + builder.append(" severity: ").append(item.getSeverity()).append(System.lineSeparator()); + builder.append(" }").append(System.lineSeparator()); + } + builder.append("}"); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceTaskStrategy.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceTaskStrategy.java new file mode 100644 index 000000000..f472e9798 --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/TraceTaskStrategy.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.metrics.strategy; + +import ohos.devtools.views.trace.metrics.MetricsDb; +import ohos.devtools.views.trace.metrics.MetricsSql; +import ohos.devtools.views.trace.metrics.bean.ProcessThread; +import org.apache.commons.lang.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * trace task Strategy + */ +public class TraceTaskStrategy implements Strategy { + /** + * Separator + */ + private static final String SEPARATOR = ","; + + /** + * get Query trace task Result + * + * @param sql sql + * @return String String + */ + @Override + public String getQueryResult(MetricsSql sql) { + List processThreads = new ArrayList<>() { + }; + MetricsDb.getInstance().query(sql, processThreads); + StringBuilder builder = new StringBuilder(); + builder.append("trace_task_names: {").append(System.lineSeparator()); + for (ProcessThread item : processThreads) { + builder.append(" process: {").append(System.lineSeparator()); + builder.append(" pid: ").append(item.getPid()).append(System.lineSeparator()); + builder.append(" process_name: ") + .append(StringUtils.isEmpty(item.getProcessName()) ? null : item.getProcessName()) + .append(System.lineSeparator()); + String[] thread_names = item.getThreadName().split(SEPARATOR); + for (String str : thread_names) { + builder.append(" thread_name: ").append("\"").append(str).append("\"") + .append(System.lineSeparator()); + } + builder.append(" }").append(System.lineSeparator()); + } + builder.append("}"); + return builder.toString(); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ColorUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ColorUtils.java index e5e4d44ce..667e6821a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ColorUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ColorUtils.java @@ -1,137 +1,135 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import ohos.devtools.views.trace.bean.CpuData; - -import java.awt.Color; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Color tool - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class ColorUtils { - /** - * Gray color object - */ - public static final Color GREY_COLOR = Color.getHSBColor(0, 0, 62); // grey - - /** - * Color array of all current columns - */ - public static final Color[] MD_PALETTE = new Color[] {new Color(0xf44034), // red - new Color(0xe92063), // pink - new Color(0x9b27b0), // purple - new Color(0x673ab6), // deep purple - new Color(0x4051b5), // indigo - new Color(0x2094f3), // blue - new Color(0x02a6f2), // light blue - new Color(0x00bdd6), // cyan - new Color(0x009485), // teal - new Color(0x4cae4f), // green - new Color(0x8bc34b), // light green - new Color(0xcbdc38), // lime - new Color(0xff9105), // amber 0xffc105 - new Color(0xff9900), // orange - new Color(0xff5724), // deep orange - new Color(0x795649), // brown - new Color(0x607c8a), // blue gray - new Color(0xbdaa00), // yellow 0xffec3d - }; - - /** - * Current method color array - */ - public static final Color[] FUNC_COLOR = new Color[] {new Color(0x9b27b0), // purple - new Color(0x317d31), new Color(0x673ab6), // deep purple - new Color(0xa25b57), new Color(0x4051b5), // indigo - new Color(0x2094f3), // blue - new Color(0x99ba36), new Color(0x4051b5) }; - - private static Map colorHashMap = new ConcurrentHashMap(); - - private ColorUtils() { - } - - /** - * Get color according to id - * - * @param id id - * @return Color Color - */ - public static Color getColor(final int id) { - if (colorHashMap.containsKey(id)) { - return colorHashMap.get(id); - } else { - final int red = ((id * 10000000) & 0xff0000) >> 16; - final int green = ((id * 10000000) & 0x00ff00) >> 8; - final int blue = id * 10000000 & 0x0000ff; - final Color color = new Color(red, green, blue, 255); - colorHashMap.put(id, color); - return color; - } - } - - /** - * Get the color value according to the length of the string - * - * @param str str - * @param max max - * @return int - */ - public static int hash(final String str, final int max) { - final int colorA = 0x811c9dc5; - final int colorB = 0xfffffff; - final int colorC = 16777619; - final int colorD = 0xffffffff; - int hash = colorA & colorB; - for (int index = 0; index < str.length(); index++) { - hash ^= str.charAt(index); - hash = (hash * colorC) & colorD; - } - return Math.abs(hash) % max; - } - - /** - * Get color based on cpu object data - * - * @param thread thread - * @return Color - */ - public static Color colorForThread(final CpuData thread) { - if (thread == null) { - return GREY_COLOR; - } - int tid = thread.getProcessId() >= 0 ? thread.getProcessId() : thread.getTid(); - return colorForTid(tid); - } - - /** - * Get color according to tid - * - * @param tid tid - * @return Color - */ - public static Color colorForTid(final int tid) { - int colorIdx = hash(String.valueOf(tid), MD_PALETTE.length); - return MD_PALETTE[colorIdx]; - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import ohos.devtools.views.trace.bean.CpuData; + +import java.awt.Color; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Color tool + * + * @date 2021/04/22 12:25 + */ +public final class ColorUtils { + /** + * Gray color object + */ + public static final Color GREY_COLOR = Color.getHSBColor(0, 0, 62); // grey + + /** + * Color array of all current columns + */ + public static final Color[] MD_PALETTE = new Color[] {new Color(0x3391ff), // red + new Color(0x0076ff), // pink + new Color(0x66adff), // purple + new Color(0x2db3aa), // deep purple + new Color(0x008078), // indigo + new Color(0x73e6de), // blue + new Color(0x535da6), // light blue + new Color(0x38428c), // cyan + new Color(0x7a84cc), // teal + new Color(0xff9201), // green + new Color(0xff7500), // light green + new Color(0xffab40), // lime + new Color(0x2db4e2), // amber 0xffc105 + new Color(0x0094c6), // orange + new Color(0x7cdeff), // deep orange + new Color(0xffd44a), // brown + new Color(0xfbbf00), // blue gray + new Color(0xffe593), // yellow 0xffec3d + }; + + /** + * Current method color array + */ + public static final Color[] FUNC_COLOR = new Color[] {new Color(0x3391ff), // purple + new Color(0x2db4e2), new Color(0x2db3aa), // deep purple + new Color(0xffd44a), new Color(0x535da6), // indigo + new Color(0x008078), // blue + new Color(0xff9201), new Color(0x38428c)}; + + private static Map colorHashMap = new ConcurrentHashMap(); + + private ColorUtils() { + } + + /** + * Get color according to id + * + * @param id id + * @return Color Color + */ + public static Color getColor(final int id) { + if (colorHashMap.containsKey(id)) { + return colorHashMap.get(id); + } else { + final int red = ((id * 10000000) & 0xff0000) >> 16; + final int green = ((id * 10000000) & 0x00ff00) >> 8; + final int blue = id * 10000000 & 0x0000ff; + final Color color = new Color(red, green, blue, 255); + colorHashMap.put(id, color); + return color; + } + } + + /** + * Get the color value according to the length of the string + * + * @param str str + * @param max max + * @return int + */ + public static int hash(final String str, final int max) { + final int colorA = 0x811c9dc5; + final int colorB = 0xfffffff; + final int colorC = 16777619; + final int colorD = 0xffffffff; + int hash = colorA & colorB; + for (int index = 0; index < str.length(); index++) { + hash ^= str.charAt(index); + hash = (hash * colorC) & colorD; + } + return Math.abs(hash) % max; + } + + /** + * Get color based on cpu object data + * + * @param thread thread + * @return Color + */ + public static Color colorForThread(final CpuData thread) { + if (thread == null) { + return GREY_COLOR; + } + int tid = thread.getProcessId() >= 0 ? thread.getProcessId() : thread.getTid(); + return colorForTid(tid); + } + + /** + * Get color according to tid + * + * @param tid tid + * @return Color + */ + public static Color colorForTid(final int tid) { + int colorIdx = hash(String.valueOf(tid), MD_PALETTE.length); + return MD_PALETTE[colorIdx]; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ComparatorUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ComparatorUtils.java new file mode 100644 index 000000000..10e898aaf --- /dev/null +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ComparatorUtils.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.util; + +import java.util.Comparator; + +/** + * ComparatorUtils + * + * @date: 2021/5/27 12:29 + */ +public class ComparatorUtils { + /** + * generate Comparator Ruler + * + * @param filter filter the row when row value equals filter + * @return Comparator + */ + public static Comparator generateComparator(String filter) { + Comparator comparator = (str1, str2) -> { + if (filter == null) { + return 0; + } + if (filter.equals(String.valueOf(str1)) || filter.equals(String.valueOf(str2))) { + return 0; + } + try { + Double d1 = Double.parseDouble(String.valueOf(str1)); + Double d2 = Double.parseDouble(String.valueOf(str2)); + int val = 0; + if (d1 < d2) { + val = -1; + } else if (d1 == d2) { + val = 0; + } else { + val = 1; + } + return val; + } catch (NumberFormatException exception) { + String s1 = String.valueOf(str1); + String s2 = String.valueOf(str2); + return s1.compareTo(s2); + } + }; + return comparator; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/DataUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/DataUtils.java index 67c32cbde..91d174bc4 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/DataUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/DataUtils.java @@ -1,53 +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. - */ - -package ohos.devtools.views.trace.util; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -/** - * Data tools - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class DataUtils { - private DataUtils() { - } - - /** - * Get the json object - * - * @return JsonObject - */ - public static JsonObject getJson() { - JsonObject jsonObject = null; - try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream("data.json")) { - jsonObject = new Gson().fromJson(new InputStreamReader(STREAM, "UTF-8"), JsonObject.class); - } catch (UnsupportedEncodingException unsupportedEncodingException) { - unsupportedEncodingException.printStackTrace(); - } catch (IOException ioException) { - ioException.printStackTrace(); - } - return jsonObject; - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; + +/** + * Data tools + * + * @date 2021/04/22 12:25 + */ +public final class DataUtils { + private DataUtils() { + } + + /** + * Get the json object + * + * @return JsonObject + */ + public static JsonObject getJson() { + JsonObject jsonObject = null; + try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream("data.json")) { + jsonObject = new Gson().fromJson(new InputStreamReader(STREAM, "UTF-8"), JsonObject.class); + } catch (UnsupportedEncodingException unsupportedEncodingException) { + unsupportedEncodingException.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + return jsonObject; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Db.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Db.java index 78a4f45b3..ec992189a 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Db.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Db.java @@ -1,833 +1,353 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.bean.CpuRateBean; -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.Process; -import ohos.devtools.views.trace.bean.ProcessData; -import ohos.devtools.views.trace.bean.ProcessMem; -import ohos.devtools.views.trace.bean.ProcessMemData; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.bean.WakeupBean; -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.nio.charset.Charset; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Database operation class - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class Db { - private static boolean isLocal; - private static volatile Db db; - private static String dbName = "trace.db"; - private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; - - /** - * Gets the value of dbName . - * - * @return the value of java.lang.String - */ - public static String getDbName() { - return dbName; - } - - /** - * Sets the dbName . - *

You can use getDbName() to get the value of dbName

- * - * @param dbName dbName - */ - public static void setDbName(final String dbName) { - Db.dbName = dbName; - } - - private Db() { - } - - private LinkedBlockingQueue pool = new LinkedBlockingQueue(); - - /** - * Get database connection - * - * @return Connection - */ - public Connection getConn() { - Connection connection = null; - try { - connection = pool.take(); - } catch (InterruptedException exception) { - exception.printStackTrace(); - } - return connection; - } - - /** - * Return the connection to the database connection pool after use - * - * @param conn conn - */ - public void free(final Connection conn) { - try { - pool.put(conn); - } catch (InterruptedException exception) { - exception.printStackTrace(); - } - } - - private Optional newConn() { - URL path = DataUtils.class.getClassLoader().getResource(dbName); - Connection conn = null; - try { - if (isLocal) { - conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); - } else { - conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } - return Optional.ofNullable(conn); - } - - /** - * Load the database file according to the file location variable - * - * @param isLocal isLocal - */ - public static void load(final boolean isLocal) { - Db.isLocal = isLocal; - final int maxConnNum = 10; - try { - Class.forName("org.sqlite.JDBC"); - for (Connection connection : db.pool) { - connection.close(); - } - db.pool.clear(); - for (int size = 0; size < maxConnNum; size++) { - db.newConn().ifPresent(c -> { - try { - db.pool.put(c); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - } - db.newConn().ifPresent(c -> { - try { - Statement statement = c.createStatement(); - statement.execute("CREATE VIEW IF NOT EXISTS thread AS SELECT id as utid, * FROM internal_thread;"); - statement - .execute("CREATE VIEW IF NOT EXISTS process AS SELECT id as upid, * FROM internal_process;"); - statement - .execute("CREATE VIEW IF NOT EXISTS sched AS SELECT *, ts + dur as ts_end FROM sched_slice;"); - statement.execute("CREATE VIEW IF NOT EXISTS instants AS SELECT *, 0.0 as value FROM instant;"); - statement.close(); - c.close(); - } catch (SQLException exception) { - exception.printStackTrace(); - } - }); - } catch (SQLException throwables) { - throwables.printStackTrace(); - } catch (ClassNotFoundException classNotFoundException) { - classNotFoundException.printStackTrace(); - } - } - - /** - * Get the current current db object - * - * @return Db - */ - public static Db getInstance() { - if (db == null) { - db = new Db(); - } - return db; - } - - /** - * Read the sql directory under resource - * - * @param sqlName sqlName - * @return String sql - */ - public static String getSql(String sqlName) { - String path = "sql/" + sqlName + ".txt"; - try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) { - return IOUtils.toString(STREAM, Charset.forName("UTF-8")); - } catch (UnsupportedEncodingException exception) { - exception.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * Query the current maximum and minimum time - * - * @return long - */ - public long queryTotalTime() { - long res = 0; - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(getSql("QueryTotalTime")); // Query data - while (rs.next()) { // Print out the queried data - res = rs.getLong("total"); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Get the number of cpu - * - * @return List - */ - public List queryCpu() { - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = - stat.executeQuery("select cpu from cpu_counter_track where name='cpuidle' order by cpu;"); // Query data - while (rs.next()) { // Print out the queried data - res.add(rs.getInt("cpu")); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException throwables) { - throwables.printStackTrace(); - } - } - return res; - } - - /** - * Get the number of cpu according to the cpu frequency - * - * @return List Integer - */ - public List queryCpuFreq() { - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery( - "select cpu from cpu_counter_track where (name='cpufreq' or name='cpu_frequency') order by cpu;"); - while (rs.next()) { // Print out the queried data - res.add(rs.getInt("cpu")); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Get the maximum number of cpu - * - * @return int - */ - public int queryCpuMax() { - String queryCpuSql = "select cpu from sched_slice order by cpu desc limit 1"; - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(queryCpuSql); // Query data - while (rs.next()) { // Print out the queried data - return rs.getInt("cpu"); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return -1; - } - - /** - * Query cpu data list according to cpu - * - * @param cpu cpu - * @return List CpuData - */ - public List queryCpuData(final int cpu) { - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - String sql = String.format(Locale.ENGLISH, getSql("QueryCpuData"), cpu); - rs = stat.executeQuery(sql); - while (rs.next()) { // Print out the queried data - CpuData cpuData = new CpuData(); - cpuData.setCpu(rs.getInt("cpu")); - cpuData.setProcessId(rs.getInt("processId")); - cpuData.setProcessName(rs.getString("processName")); - cpuData.setProcessCmdLine(rs.getString("processCmdLine")); - cpuData.setName(rs.getString("name")); - cpuData.setTid(rs.getInt("tid")); - cpuData.setId(rs.getInt("id")); - cpuData.setSchedId(rs.getInt("schedId")); - cpuData.setType(rs.getString("type")); - cpuData.setDuration(rs.getLong("dur")); - cpuData.setStartTime(rs.getLong("startTime")); - cpuData.setPriority(rs.getInt("priority")); - cpuData.setEndState(rs.getString("end_state")); - res.add(cpuData); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Get the maximum frequency of the cpu - * - * @return String - */ - public Map queryCpuMaxFreq() { - String queryMaxFreqSql = "select max(value) as maxFreq\n" + " from counter c\n" - + " inner join cpu_counter_track t on c.track_id = t.id\n" - + " where (name = 'cpufreq' or name='cpu_frequency');"; - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - StringBuilder maxFreq = new StringBuilder(); - Map resMap = new HashMap<>(); - resMap.put("name", "0 Ghz"); - resMap.put("value", 0); - try { - int maxIntFreq = 0; - stat = conn.createStatement(); - rs = stat.executeQuery(queryMaxFreqSql); // Query data - while (rs.next()) { // Print out the queried data - maxIntFreq = rs.getInt("maxFreq"); - } - if (maxIntFreq > 0) { - double log10 = Math.ceil(Math.log10(maxIntFreq)); - double pow10 = Math.pow(10, log10); - double afterCeil = Math.ceil(maxIntFreq / (pow10 / 4)) * (pow10 / 4); - resMap.put("value", afterCeil); - double unitIndex = Math.floor(log10 / 3); - maxFreq.append(afterCeil / Math.pow(10, unitIndex * 3)); - maxFreq.append(units[(int) unitIndex + 1]); - } else { - maxFreq.append(maxIntFreq); - } - maxFreq.append("hz"); - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - resMap.put("name", maxFreq.toString()); - return resMap; - } - - /** - * Query cpu frequency information - * - * @param cpu cpu - * @return List CpuFreqData - */ - public List queryCpuFreqData(final int cpu) { - ArrayList res = new ArrayList<>(); - String queryCpuFreqDataSql = - "select cpu,value,ts-tb.start_ts as startNS \n" + " from counter c ,trace_bounds tb\n" - + " inner join cpu_counter_track t on c.track_id = t.id\n" - // The id in cpu_counter_track is invalid, here change t.id to t.cpu - + " where (name = 'cpufreq' or name='cpu_frequency') and cpu=" + cpu + " order by " + "ts ;"; - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(queryCpuFreqDataSql); // Query data - while (rs.next()) { // Print out the queried data - CpuFreqData cpuData = new CpuFreqData(); - cpuData.setCpu(rs.getInt("cpu")); - cpuData.setValue(rs.getLong("value")); - cpuData.setStartTime(rs.getLong("startNS")); - res.add(cpuData); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Get all process information. - * - * @return List Process - */ - public List queryProcess() { - String sql = getSql("QueryProcess"); - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(sql); // Query data - while (rs.next()) { // Print out the queried data - Process data = new Process(); - data.setName(rs.getString("processName")); - data.setPid(rs.getInt("pid")); - res.add(data); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Obtain process process thread information, group by the above process information - * - * @return List ThreadData - */ - public List queryProcessThreads() { - String sql = getSql("QueryProcessThreads"); - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(sql); // Query data - while (rs.next()) { // Print out the queried data - ThreadData threadData = new ThreadData(); - threadData.setuPid(rs.getInt("upid")); - threadData.setuTid(rs.getInt("utid")); - threadData.setTid(rs.getInt("tid")); - threadData.setPid(rs.getInt("pid")); - threadData.setProcessName(rs.getString("processName")); - threadData.setThreadName(rs.getString("threadName")); - res.add(threadData); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Drawing process information is related to multiple CPUs. - * - * @param id id - * @return List ProcessData - */ - public List queryProcessData(final int id) { - String sql = - "select thread_state.*,ts-tb.start_ts as startTime from thread_state,trace_bounds tb where utid in(\n" - + "select it.id from internal_thread as it\n" + " left join internal_process ip on it.upid = ip.id\n" - + "where ip.pid=" + id + ") and cpu is not null order by startTime"; - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(sql); // Query data - while (rs.next()) { // Print out the queried data - ProcessData data = new ProcessData(); - data.setId(rs.getInt("id")); - data.setUtid(rs.getInt("utid")); - data.setCpu(rs.getInt("cpu")); - data.setStartTime(rs.getLong("startTime")); - data.setDuration(rs.getLong("dur")); - data.setState(rs.getString("state")); - res.add(data); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Thread information. - * - * @param id id - * @return List ThreadData - */ - public List queryThreadData(final int id) { - String sql = String.format(Locale.ENGLISH, getSql("QueryThreadData"), id); - ArrayList res = new ArrayList<>(); - Statement stat = null; - ResultSet rs = null; - Connection conn = getConn(); - try { - stat = conn.createStatement(); - rs = stat.executeQuery(sql); // Query data - while (rs.next()) { // Print out the queried data - ThreadData data = new ThreadData(); - data.setTid(rs.getInt("tid")); - data.setPid(rs.getInt("pid")); - data.setCpu(rs.getInt("cpu")); - data.setStartTime(rs.getLong("startTime")); - data.setDuration(rs.getLong("dur")); - data.setProcessName(rs.getString("processName")); - data.setState(rs.getString("state")); - res.add(data); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - rs.close(); - stat.close(); - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return res; - } - - /** - * Get the current ring thread object - * - * @param cpuData cpuData - * @return WakeupBean - */ - public Optional queryWakeupThread(final CpuData cpuData) { - WakeupBean wb = null; - String wakeTimeSql = String - .format(Locale.ENGLISH, getSql("QueryWakeUpThread_WakeTime"), cpuData.getId(), cpuData.getStartTime(), - cpuData.getId(), cpuData.getStartTime()); - Connection conn = getConn(); - try { - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery(wakeTimeSql); - while (rs.next()) { - long wakeupTs = rs.getLong("wakeTs"); - long startTs = rs.getLong("start_ts"); - long preRow = rs.getLong("preRow"); - if (wakeupTs < preRow) { - rs.close(); - statement.close(); - return Optional.ofNullable(wb); - } - String wakeThreadSql = String.format(Locale.ENGLISH, getSql("QueryWakeUpThread_WakeThread")); - wakeThreadSql = wakeThreadSql.replaceAll("wakeup_ts", wakeupTs + ""); - ResultSet rs1 = statement.executeQuery(wakeThreadSql); - while (rs1.next()) { - wb = new WakeupBean(); - wb.setWakeupTime(wakeupTs - startTs); - wb.setSchedulingLatency(cpuData.getStartTime() - wb.getWakeupTime()); - wb.setWakeupCpu(rs1.getInt("cpu")); - wb.setWakeupThread(rs1.getString("thread")); - wb.setWakeupProcess(rs1.getString("process")); - wb.setWakeupPid(rs1.getString("pid")); - wb.setWakeupTid(rs1.getString("tid")); - if (wb.getWakeupProcess() == null) { - wb.setWakeupProcess(wb.getWakeupThread()); - } - if (wb.getWakeupPid() == null) { - wb.setWakeupPid(wb.getWakeupTid()); - } - wb.setSchedulingDesc(getSql("QueryWakeUpThread_Desc")); - rs1.close(); - rs.close(); - statement.close(); - break; - } - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - free(conn); - } - return Optional.ofNullable(wb); - } - - /** - * Get cpu utilization - * - * @return ArrayList CpuRateBean - */ - public ArrayList getCpuUtilizationRate() { - ArrayList list = new ArrayList<>(); - String sql = getSql("GetCpuUtilizationRate"); - Connection conn = getConn(); - Statement st = null; - ResultSet rs = null; - try { - st = conn.createStatement(); - rs = st.executeQuery(sql); - while (rs.next()) { - CpuRateBean cpuRateBean = new CpuRateBean(); - cpuRateBean.setCpu(rs.getInt("cpu")); - cpuRateBean.setIndex(rs.getInt("ro")); - cpuRateBean.setRate(rs.getDouble("rate")); - list.add(cpuRateBean); - } - rs.close(); - st.close(); - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - free(conn); - } - return list; - } - - /** - * Get the memory information of the process - * - * @return List ProcessMem - */ - public List getProcessMem() { - ArrayList list = new ArrayList<>(); - String sql = "select\n" + " process_counter_track.id as trackId,\n" - + " process_counter_track.name as trackName,\n" + " upid,\n" + " process.pid,\n" - + " process.name as processName,\n" + " process.start_ts as startTs,\n" - + " process.end_ts as endTs\n" + " from process_counter_track\n" - + " join process using(upid) order by trackName"; - Connection conn = getConn(); - Statement st = null; - ResultSet rs = null; - try { - st = conn.createStatement(); - rs = st.executeQuery(sql); - while (rs.next()) { - ProcessMem bean = new ProcessMem(); - bean.setTrackId(rs.getInt("trackId")); - bean.setTrackName(rs.getString("trackName")); - bean.setUpid(rs.getInt("upid")); - bean.setPid(rs.getInt("pid")); - bean.setProcessName(rs.getString("processName")); - list.add(bean); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - if (st != null) { - st.close(); - } - if (rs != null) { - rs.close(); - } - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return list; - } - - /** - * Get memory data information occupied by a process - * - * @param trackId trackId - * @return List list - */ - public List getProcessMemData(final int trackId) { - ArrayList list = new ArrayList<>(); - String sql = "select c.*,c.ts-tb.start_ts startTime from counter c,trace_bounds tb where track_id=" + trackId; - Connection conn = getConn(); - Statement st = null; - ResultSet rs = null; - try { - st = conn.createStatement(); - rs = st.executeQuery(sql); - while (rs.next()) { - ProcessMemData bean = new ProcessMemData(); - bean.setTrackId(rs.getInt("track_id")); - bean.setValue(rs.getInt("value")); - bean.setStartTime(rs.getLong("startTime")); - bean.setType(rs.getString("type")); - list.add(bean); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - if (st != null) { - st.close(); - } - if (rs != null) { - rs.close(); - } - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return list; - } - - /** - * Get method call information according to tid - * - * @param tid tid - * @return ArrayList - */ - public ArrayList getFunDataByTid(final int tid) { - ArrayList list = new ArrayList<>(); - String sql = String.format(Locale.ENGLISH, getSql("GetFunDataByTid"), tid); - Connection conn = getConn(); - Statement st = null; - ResultSet rs = null; - try { - st = conn.createStatement(); - rs = st.executeQuery(sql); - while (rs.next()) { - FunctionBean bean = new FunctionBean(); - bean.setTid(rs.getInt("tid")); - bean.setIsMainThread(rs.getInt("is_main_thread")); - bean.setTrackId(rs.getInt("track_id")); - bean.setDepth(rs.getInt("depth")); - bean.setThreadName(rs.getString("threadName")); - bean.setFunName(rs.getString("funName")); - bean.setStartTime(rs.getLong("startTs")); - bean.setDuration(rs.getLong("dur")); - list.add(bean); - } - } catch (SQLException exception) { - exception.printStackTrace(); - } finally { - try { - if (st != null) { - st.close(); - } - if (rs != null) { - rs.close(); - } - free(conn); - } catch (SQLException exception) { - exception.printStackTrace(); - } - } - return list; - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import ohos.devtools.views.trace.DField; +import ohos.devtools.views.trace.Sql; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.Charset; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Database operation class class + * + * @date 2021/04/22 12:25 + */ +public final class Db { + private static boolean isLocal; + private static volatile Db db = new Db(); + private static String dbName = "trace.db"; + private final String[] units = new String[] {"", "K", "M", "G", "T", "E"}; + private LinkedBlockingQueue pool = new LinkedBlockingQueue(); + + private Db() { + } + + /** + * Gets the value of dbName . + * + * @return the value of java.lang.String + */ + public static String getDbName() { + return dbName; + } + + /** + * Sets the dbName . + *

You can use getDbName() to get the value of dbName

+ * + * @param dbName dbName + */ + public static void setDbName(final String dbName) { + Db.dbName = dbName; + } + + /** + * Load the database file according to the file location variable + * + * @param isLocal isLocal + */ + public static void load(final boolean isLocal) { + Db.isLocal = isLocal; + final int maxConnNum = 10; + try { + Class.forName("org.sqlite.JDBC"); + for (Connection connection : db.pool) { + connection.close(); + } + db.pool.clear(); + for (int size = 0; size < maxConnNum; size++) { + db.newConn().ifPresent(connection -> { + try { + db.pool.put(connection); + } catch (InterruptedException interruptedException) { + interruptedException.printStackTrace(); + } + }); + } + db.newConn().ifPresent(connection -> { + try { + Statement statement = connection.createStatement(); + String views = getSql("Views"); + String[] split = views.split(";"); + for (String str : split) { + statement.execute(str); + } + statement.close(); + connection.close(); + } catch (SQLException exception) { + exception.printStackTrace(); + } + }); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } catch (ClassNotFoundException classNotFoundException) { + classNotFoundException.printStackTrace(); + } + } + + /** + * Get the current current db object + * + * @return Db db + */ + public static Db getInstance() { + if (db == null) { + db = new Db(); + } + return db; + } + + /** + * Read the sql directory under resource + * + * @param sqlName sqlName + * @return String sql + */ + public static String getSql(String sqlName) { + String tmp = Final.OHOS ? "-self/" : "/"; + String path = "sql" + tmp + sqlName + ".txt"; + try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) { + return IOUtils.toString(STREAM, Charset.forName("UTF-8")); + } catch (UnsupportedEncodingException exception) { + exception.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + return ""; + } + + /** + * Get database connection + * + * @return Connection + */ + public Connection getConn() { + Connection connection = null; + try { + connection = pool.take(); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + return connection; + } + + /** + * Return the connection to the database connection pool after use + * + * @param conn conn + */ + public void free(final Connection conn) { + try { + pool.put(conn); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + } + + private Optional newConn() { + URL path = URLClassLoader.getSystemClassLoader().getResource(dbName); + Connection conn = null; + try { + if (isLocal) { + conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); + } else { + conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + return Optional.ofNullable(conn); + } + + /** + * Read the sql directory under resource + * + * @param em em + * @param res res + * @param args args + * @param return type + */ + public void query(Sql em, List res, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + query(sql, res); + } + + /** + * query sql count + * + * @param em em + * @param args args + * @return int int + */ + public int queryCount(Sql em, Object... args) { + String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args); + return queryCount(sql); + } + + /** + * query count from sql + * + * @param sql sql + * @return int int + */ + public int queryCount(String sql) { + Statement stat = null; + ResultSet rs = null; + int count = 0; + Connection conn = getConn(); + if (Objects.isNull(conn)) { + return 0; + } + try { + stat = conn.createStatement(); + String tSql = sql.trim(); + if (sql.trim().endsWith(";")) { + tSql = sql.trim().substring(0, sql.trim().length() - 1); + } + rs = stat.executeQuery("select count(1) as count from (" + tSql + ");"); + while (rs.next()) { + count = rs.getInt("count"); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + return count; + } + + /** + * Read the sql directory under resource + * + * @param sql sql + * @param res res + * @param T + */ + public void query(String sql, List res) { + Statement stat = null; + ResultSet rs = null; + Connection conn = getConn(); + if (Objects.isNull(conn)) { + return; + } + Type argument = getType(res); + try { + Class aClass = (Class) Class.forName(argument.getTypeName()); + stat = conn.createStatement(); + rs = stat.executeQuery(sql); + ArrayList columnList = new ArrayList<>(); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + for (int index = 1; index <= columnCount; index++) { + columnList.add(rsMeta.getColumnName(index)); + } + while (rs.next()) { + T data = aClass.getConstructor().newInstance(); + for (Field declaredField : aClass.getDeclaredFields()) { + declaredField.setAccessible(true); + DField annotation = declaredField.getAnnotation(DField.class); + if (Objects.nonNull(annotation) && columnList.contains(annotation.name())) { + setData(declaredField, data, rs, annotation); + } + } + res.add(data); + } + } catch (ClassNotFoundException | SQLException exception) { + exception.printStackTrace(); + } catch (InstantiationException exception) { + exception.printStackTrace(); + } catch (IllegalAccessException exception) { + exception.printStackTrace(); + } catch (InvocationTargetException exception) { + exception.printStackTrace(); + } catch (NoSuchMethodException exception) { + exception.printStackTrace(); + } finally { + release(rs, stat, conn); + } + } + + private void setData(Field declaredField, T data, ResultSet rs, DField annotation) + throws SQLException, IllegalAccessException { + if (declaredField.getType() == Long.class || declaredField.getType() == long.class) { + declaredField.set(data, rs.getLong(annotation.name())); + } else if (declaredField.getType() == Integer.class || declaredField.getType() == int.class) { + declaredField.set(data, rs.getInt(annotation.name())); + } else if (declaredField.getType() == Double.class || declaredField.getType() == double.class) { + declaredField.set(data, rs.getDouble(annotation.name())); + } else if (declaredField.getType() == Float.class || declaredField.getType() == float.class) { + declaredField.set(data, rs.getFloat(annotation.name())); + } else if (declaredField.getType() == Boolean.class || declaredField.getType() == boolean.class) { + declaredField.set(data, rs.getBoolean(annotation.name())); + } else if (declaredField.getType() == Blob.class) { + declaredField.set(data, rs.getBlob(annotation.name())); + } else { + declaredField.set(data, rs.getObject(annotation.name())); + } + } + + private Type getType(List res) { + Type clazz = res.getClass().getGenericSuperclass(); + ParameterizedType pt = null; + if (clazz instanceof ParameterizedType) { + pt = (ParameterizedType) clazz; + } + if (pt == null) { + return clazz; + } + Type argument = pt.getActualTypeArguments()[0]; + return argument; + } + + private void release(ResultSet rs, Statement stat, Connection conn) { + try { + if (Objects.nonNull(rs)) { + rs.close(); + } + if (Objects.nonNull(stat)) { + stat.close(); + } + if (Objects.nonNull(conn)) { + free(conn); + } + } catch (SQLException exception) { + exception.printStackTrace(); + } + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Final.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Final.java index 81e7e3616..ff16a5e67 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Final.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Final.java @@ -1,78 +1,104 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import java.awt.Font; - -/** - * Font color information tool - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class Final { - /** - * Font name - */ - public static final String FONT_NAME = "宋体"; - - /** - * Default font style - */ - public static final int PLAIN_STYLE = Font.PLAIN; - - /** - * Minimum font size - */ - public static final int SMALL_FONT_SIZE = 10; - - /** - * Normal font size - */ - public static final int NORMAL_FONT_SIZE = 11; - - /** - * Runtime color constants - */ - public static final int RUNNING_COLOR = 0x467b3b; - - /** - * R_COLOR - */ - public static final int R_COLOR = 0xa0b84d; - - /** - * UNINTERRUPTIBLE_SLEEP_COLOR - */ - public static final int UNINTERRUPTIBLE_SLEEP_COLOR = 0xf19d38; - - /** - * S_COLOR - */ - public static final int S_COLOR = 0xFBFBFB; - - /** - * NORMAL_FONT - */ - public static final Font NORMAL_FONT = new Font(FONT_NAME, PLAIN_STYLE, NORMAL_FONT_SIZE); - - /** - * NORMAL_FONT - */ - public static final Font SMALL_FONT = new Font(FONT_NAME, PLAIN_STYLE, SMALL_FONT_SIZE); - - private Final() { } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import java.awt.Font; + +/** + * Font color information tool + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public final class Final { + /** + * OHOS db file + */ + public static final boolean OHOS = true; + + /** + * Font name + */ + public static final String FONT_NAME = "宋体"; + + /** + * Default font style + */ + public static final int PLAIN_STYLE = Font.PLAIN; + + /** + * Minimum font size + */ + public static final int SMALL_FONT_SIZE = 10; + + /** + * litter font size + */ + public static final int LITTER_FONT_SIZE = 8; + + /** + * Normal font size + */ + public static final int NORMAL_FONT_SIZE = 11; + + /** + * Runtime color constants + */ + public static final int RUNNING_COLOR = 0x467b3b; + + /** + * R_COLOR + */ + public static final int R_COLOR = 0xa0b84d; + + /** + * UNINTERRUPTIBLE_SLEEP_COLOR + */ + public static final int UNINTERRUPTIBLE_SLEEP_COLOR = 0xf19d38; + + /** + * exit color + */ + public static final int EXIT_COLOR = 0x795649; + + /** + * S_COLOR + */ + public static final int S_COLOR = 0xFBFBFB; + + /** + * NORMAL_FONT + */ + public static final Font NORMAL_FONT = new Font(FONT_NAME, PLAIN_STYLE, NORMAL_FONT_SIZE); + + /** + * NORMAL_FONT + */ + public static final Font SMALL_FONT = new Font(FONT_NAME, PLAIN_STYLE, SMALL_FONT_SIZE); + + /** + * LITTER_FONT + */ + public static final Font LITTER_FONT = new Font(FONT_NAME, PLAIN_STYLE, LITTER_FONT_SIZE); + + /** + * db capacity ,if row number big then capacity use async load db data + */ + public static final long CAPACITY = 10000; + + private Final() { + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ImageUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ImageUtils.java index b624d3d98..b0f979a02 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ImageUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/ImageUtils.java @@ -1,227 +1,239 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import javax.imageio.ImageIO; -import java.awt.Image; -import java.io.IOException; - -/** - * Image processing tools - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class ImageUtils { - private static ImageUtils instance; - - private Image starFill; - - private Image star; - - private Image checkYes; - - private Image checkNo; - - private Image arrowDown; - - private Image arrowDownFocus; - - private Image arrowUp; - - private Image arrowUpFocus; - - - private ImageUtils() { - try { - starFill = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - star = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star.png")); - checkNo = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/check_box_1.png")); - checkYes = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/check_box_2.png")); - arrowUp = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-up.png")); - arrowUpFocus = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-up-2.png")); - arrowDown = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-down.png")); - arrowDownFocus = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-down-2.png")); - } catch (IOException exception) { - exception.printStackTrace(); - } - } - - /** - * Gets the value of starFill . - * - * @return the value of java.awt.Image - */ - public Image getStarFill() { - return starFill; - } - - /** - * Sets the starFill . - *

You can use getStarFill() to get the value of starFill

- * - * @param image image - */ - public void setStarFill(final Image image) { - this.starFill = image; - } - - /** - * Gets the value of star . - * - * @return the value of java.awt.Image - */ - public Image getStar() { - return star; - } - - /** - * Sets the star . - *

You can use getStar() to get the value of star

- * - * @param image image - */ - public void setStar(final Image image) { - this.star = image; - } - - /** - * Gets the value of checkYes . - * - * @return the value of java.awt.Image - */ - public Image getCheckYes() { - return checkYes; - } - - /** - * Sets the checkYes . - *

You can use getCheckYes() to get the value of checkYes

- * - * @param image image - */ - public void setCheckYes(final Image image) { - this.checkYes = image; - } - - /** - * Gets the value of checkNo . - * - * @return the value of java.awt.Image - */ - public Image getCheckNo() { - return checkNo; - } - - /** - * Sets the checkNo . - *

You can use getCheckNo() to get the value of checkNo

- * - * @param image image - */ - public void setCheckNo(final Image image) { - this.checkNo = image; - } - - /** - * Gets the value of arrowDown . - * - * @return the value of java.awt.Image - */ - public Image getArrowDown() { - return arrowDown; - } - - /** - * Sets the arrowDown . - *

You can use getArrowDown() to get the value of arrowDown

- * - * @param image image - */ - public void setArrowDown(final Image image) { - this.arrowDown = image; - } - - /** - * Gets the value of arrowDownFocus . - * - * @return the value of java.awt.Image - */ - public Image getArrowDownFocus() { - return arrowDownFocus; - } - - /** - * Sets the arrowDownFocus . - *

You can use getArrowDownFocus() to get the value of arrowDownFocus

- * - * @param image image - */ - public void setArrowDownFocus(final Image image) { - this.arrowDownFocus = image; - } - - /** - * Gets the value of arrowUp . - * - * @return the value of java.awt.Image - */ - public Image getArrowUp() { - return arrowUp; - } - - /** - * Sets the arrowUp . - *

You can use getArrowUp() to get the value of arrowUp

- * - * @param image image - */ - public void setArrowUp(final Image image) { - this.arrowUp = image; - } - - /** - * Gets the value of arrowUpFocus . - * - * @return the value of java.awt.Image - */ - public Image getArrowUpFocus() { - return arrowUpFocus; - } - - /** - * Sets the arrowUpFocus . - *

You can use getArrowUpFocus() to get the value of arrowUpFocus

- * - * @param image image - */ - public void setArrowUpFocus(final Image image) { - arrowUpFocus = image; - } - - - /** - * Get the current ImageUtils instantiation object - * - * @return ImageUtils - */ - public static ImageUtils getInstance() { - if (instance == null) { - instance = new ImageUtils(); - } - return instance; - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import javax.imageio.ImageIO; +import java.awt.Image; +import java.io.IOException; + +/** + * Image processing tools + * + * @version 1.0 + * @date 2021/04/22 12:25 + */ +public final class ImageUtils { + private static ImageUtils instance; + + private Image starFill; + + private Image star; + + private Image checkYes; + + private Image checkNo; + + private Image arrowDown; + + private Image arrowDownFocus; + + private Image arrowUp; + + private Image arrowUpFocus; + + private Image iconUsb; + + private Image iconWifi; + + private ImageUtils() { + try { + starFill = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + star = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star.png")); + checkNo = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/check_box_1.png")); + checkYes = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/check_box_2.png")); + arrowUp = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-up.png")); + arrowUpFocus = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-up-2.png")); + arrowDown = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-down.png")); + arrowDownFocus = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/arrow-down-2.png")); + iconUsb = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/icon_usb2.png")); + iconWifi = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/icon_wifi2.png")); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + /** + * Get the current ImageUtils instantiation object + * + * @return ImageUtils + */ + public static ImageUtils getInstance() { + if (instance == null) { + instance = new ImageUtils(); + } + return instance; + } + + /** + * Gets the value of starFill . + * + * @return the value of java.awt.Image + */ + public Image getStarFill() { + return starFill; + } + + /** + * Sets the starFill . + *

You can use getStarFill() to get the value of starFill

+ * + * @param image image + */ + public void setStarFill(final Image image) { + this.starFill = image; + } + + /** + * Gets the value of star . + * + * @return the value of java.awt.Image + */ + public Image getStar() { + return star; + } + + /** + * Sets the star . + *

You can use getStar() to get the value of star

+ * + * @param image image + */ + public void setStar(final Image image) { + this.star = image; + } + + /** + * Gets the value of checkYes . + * + * @return the value of java.awt.Image + */ + public Image getCheckYes() { + return checkYes; + } + + /** + * Sets the checkYes . + *

You can use getCheckYes() to get the value of checkYes

+ * + * @param image image + */ + public void setCheckYes(final Image image) { + this.checkYes = image; + } + + /** + * Gets the value of checkNo . + * + * @return the value of java.awt.Image + */ + public Image getCheckNo() { + return checkNo; + } + + /** + * Sets the checkNo . + *

You can use getCheckNo() to get the value of checkNo

+ * + * @param image image + */ + public void setCheckNo(final Image image) { + this.checkNo = image; + } + + /** + * Gets the value of arrowDown . + * + * @return the value of java.awt.Image + */ + public Image getArrowDown() { + return arrowDown; + } + + /** + * Sets the arrowDown . + *

You can use getArrowDown() to get the value of arrowDown

+ * + * @param image image + */ + public void setArrowDown(final Image image) { + this.arrowDown = image; + } + + /** + * Gets the value of arrowDownFocus . + * + * @return the value of java.awt.Image + */ + public Image getArrowDownFocus() { + return arrowDownFocus; + } + + /** + * Sets the arrowDownFocus . + *

You can use getArrowDownFocus() to get the value of arrowDownFocus

+ * + * @param image image + */ + public void setArrowDownFocus(final Image image) { + this.arrowDownFocus = image; + } + + /** + * Gets the value of arrowUp . + * + * @return the value of java.awt.Image + */ + public Image getArrowUp() { + return arrowUp; + } + + /** + * Sets the arrowUp . + *

You can use getArrowUp() to get the value of arrowUp

+ * + * @param image image + */ + public void setArrowUp(final Image image) { + this.arrowUp = image; + } + + /** + * Gets the value of arrowUpFocus . + * + * @return the value of java.awt.Image + */ + public Image getArrowUpFocus() { + return arrowUpFocus; + } + + /** + * Sets the arrowUpFocus . + *

You can use getArrowUpFocus() to get the value of arrowUpFocus

+ * + * @param image image + */ + public void setArrowUpFocus(final Image image) { + arrowUpFocus = image; + } + + public Image getIconUsb() { + return iconUsb; + } + + public Image getIconWifi() { + return iconWifi; + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/TimeUtils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/TimeUtils.java index 062ee2f9e..2932f4b36 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/TimeUtils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/TimeUtils.java @@ -1,101 +1,99 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -/** - * Time formatting tool - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class TimeUtils { - private TimeUtils() { - } - - private static DecimalFormat df = new DecimalFormat("#.0"); - - /** - * Convert to s according to ns - * - * @param ns ns - * @return String - */ - public static String getSecondFromNSecond(final long ns) { - final long second1 = 1_000_000_000L; // 1 second - final long millisecond1 = 1_000_000L; // 1 millisecond - final long microsecond1 = 1_000L; // 1 microsecond - final double nanosecond1 = 1000.0; - String res; - if (ns >= second1) { - res = df.format(TimeUnit.MILLISECONDS.convert(ns, TimeUnit.NANOSECONDS) / nanosecond1) + "s"; - } else if (ns >= millisecond1) { - res = df.format(TimeUnit.MICROSECONDS.convert(ns, TimeUnit.NANOSECONDS) / nanosecond1) + "ms"; - } else if (ns >= microsecond1) { - res = df.format(ns / nanosecond1) + "us"; - } else { - res = ns + "ns"; - } - return res; - } - - /** - * Get the current formatting time - * - * @param nsL nsL - * @return String - */ - public static String getTimeString(final long nsL) { - long ns = nsL; - long hours = TimeUnit.NANOSECONDS.toHours(ns); - ns = ns - TimeUnit.HOURS.toNanos(hours); - long minutes = TimeUnit.NANOSECONDS.toMinutes(ns); - ns = ns - TimeUnit.MINUTES.toNanos(minutes); - long second = TimeUnit.NANOSECONDS.toSeconds(ns); // second - ns = ns - TimeUnit.SECONDS.toNanos(second); - long millis = TimeUnit.NANOSECONDS.toMillis(ns); // millisecond - ns = ns - TimeUnit.MILLISECONDS.toNanos(millis); - long micros = TimeUnit.NANOSECONDS.toMicros(ns); // microsecond - ns = ns - TimeUnit.MICROSECONDS.toNanos(micros); - List list = new ArrayList<>(); - if (hours > 0) { - list.add(hours + "h"); - } - if (minutes > 0) { - list.add(minutes + "m"); - } - if (second > 0) { - list.add(second + "s"); - } - if (millis > 0) { - list.add(millis + "ms"); - } - if (micros > 0) { - list.add(micros + "us"); - } - long nanos = ns; - if (nanos > 0) { - list.add(nanos + "ns"); - } - return list.stream().collect(Collectors.joining(" ")); - } - -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * Time formatting tool + * + * @date 2021/04/22 12:25 + */ +public final class TimeUtils { + private static DecimalFormat df = new DecimalFormat("#.0"); + + private TimeUtils() { + } + + /** + * Convert to s according to ns + * + * @param ns ns + * @return String + */ + public static String getSecondFromNSecond(final long ns) { + final long second1 = 1_000_000_000L; // 1 second + final long millisecond1 = 1_000_000L; // 1 millisecond + final long microsecond1 = 1_000L; // 1 microsecond + final double nanosecond1 = 1000.0; + String res; + if (ns >= second1) { + res = df.format(TimeUnit.MILLISECONDS.convert(ns, TimeUnit.NANOSECONDS) / nanosecond1) + "s"; + } else if (ns >= millisecond1) { + res = df.format(TimeUnit.MICROSECONDS.convert(ns, TimeUnit.NANOSECONDS) / nanosecond1) + "ms"; + } else if (ns >= microsecond1) { + res = df.format(ns / nanosecond1) + "μs"; + } else { + res = ns + "ns"; + } + return res; + } + + /** + * Get the current formatting time + * + * @param nsL nsL + * @return String + */ + public static String getTimeString(final long nsL) { + long ns = nsL; + long hours = TimeUnit.NANOSECONDS.toHours(ns); + ns = ns - TimeUnit.HOURS.toNanos(hours); + long minutes = TimeUnit.NANOSECONDS.toMinutes(ns); + ns = ns - TimeUnit.MINUTES.toNanos(minutes); + long second = TimeUnit.NANOSECONDS.toSeconds(ns); // second + ns = ns - TimeUnit.SECONDS.toNanos(second); + long millis = TimeUnit.NANOSECONDS.toMillis(ns); // millisecond + ns = ns - TimeUnit.MILLISECONDS.toNanos(millis); + long micros = TimeUnit.NANOSECONDS.toMicros(ns); // microsecond + ns = ns - TimeUnit.MICROSECONDS.toNanos(micros); + List list = new ArrayList<>(); + if (hours > 0) { + list.add(hours + "h"); + } + if (minutes > 0) { + list.add(minutes + "m"); + } + if (second > 0) { + list.add(second + "s"); + } + if (millis > 0) { + list.add(millis + "ms"); + } + if (micros > 0) { + list.add(micros + "μs"); + } + long nanos = ns; + if (nanos > 0) { + list.add(nanos + "ns"); + } + return list.stream().collect(Collectors.joining(" ")); + } +} diff --git a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Utils.java b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Utils.java index 8b8485dcc..5acc8be46 100644 --- a/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Utils.java +++ b/host/ohosprofiler/src/main/java/ohos/devtools/views/trace/util/Utils.java @@ -1,100 +1,274 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import org.apache.commons.collections.map.HashedMap; - -import java.awt.Rectangle; -import java.util.Map; - -/** - * Tools - * - * @version 1.0 - * @date 2021/04/22 12:25 - **/ -public final class Utils { - private static Map statusMap = new HashedMap(); - private static Utils instance; - - private Utils() { - statusMap.put("D", "Uninterruptible Sleep"); - statusMap.put("S", "Sleeping"); - statusMap.put("R", "Runnable"); - statusMap.put("Running", "Running"); - statusMap.put("R+", "Runnable (Preempted)"); - statusMap.put("DK", "Uninterruptible Sleep + Wake Kill"); - statusMap.put("I", "Task Dead"); - statusMap.put("T", "Stopped"); - statusMap.put("t", "Traced"); - statusMap.put("X", "Exit (Dead)"); - statusMap.put("Z", "Exit (Zombie)"); - statusMap.put("K", "Wake Kill"); - statusMap.put("W", "Waking"); - statusMap.put("P", "Parked"); - statusMap.put("N", "No Load"); - } - - /** - * Gets the value of statusMap . - * - * @return Get state collection - */ - public Map getStatusMap() { - return statusMap; - } - - /** - * Get singleton object - * - * @return Utils - */ - public static Utils getInstance() { - if (instance == null) { - instance = new Utils(); - } - return instance; - } - - /** - * Calculate whether it is within the range of Rectangle according to the x and y coordinates - * - * @param rect rect - * @param xAxis xAxis - * @param yAxis yAxis - * @return boolean - */ - public static boolean pointInRect(final Rectangle rect, final int xAxis, final int yAxis) { - if (rect == null) { - return false; - } - return xAxis >= rect.x && xAxis <= rect.x + rect.width && yAxis >= rect.y && yAxis < rect.y + rect.height; - } - - /** - * Get the last status description - * - * @param state state - * @return String - */ - public static String getEndState(final String state) { - if (Utils.getInstance().getStatusMap().containsKey(state)) { - return Utils.getInstance().getStatusMap().get(state); - } else { - return "Unknown State"; - } - } -} +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import org.apache.commons.collections.map.HashedMap; + +import java.awt.Point; +import java.awt.Rectangle; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.DecimalFormat; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Tools + * + * @date 2021/04/22 12:25 + */ +public final class Utils { + private static Map statusMap = new HashedMap(); + private static Utils instance; + private static ExecutorService pool = Executors.newFixedThreadPool(8); + + private Utils() { + statusMap.put("D", "Uninterruptible Sleep"); + statusMap.put("S", "Sleeping"); + statusMap.put("R", "Runnable"); + statusMap.put("Running", "Running"); + statusMap.put("R+", "Runnable (Preempted)"); + statusMap.put("DK", "Uninterruptible Sleep + Wake Kill"); + statusMap.put("I", "Task Dead"); + statusMap.put("T", "Stopped"); + statusMap.put("t", "Traced"); + statusMap.put("X", "Exit (Dead)"); + statusMap.put("Z", "Exit (Zombie)"); + statusMap.put("K", "Wake Kill"); + statusMap.put("W", "Waking"); + statusMap.put("P", "Parked"); + statusMap.put("N", "No Load"); + } + + /** + * Get singleton object + * + * @return Utils + */ + public static Utils getInstance() { + if (instance == null) { + instance = new Utils(); + } + return instance; + } + + /** + * Calculate whether it is within the range of Rectangle according to the x and y coordinates + * + * @param rect rect + * @param xAxis xAxis + * @param yAxis yAxis + * @return boolean + */ + public static boolean pointInRect(final Rectangle rect, final int xAxis, final int yAxis) { + if (rect == null) { + return false; + } + return xAxis >= Utils.getX(rect) && xAxis <= Utils.getX(rect) + rect.width && yAxis >= Utils.getY(rect) + && yAxis < Utils.getY(rect) + rect.height; + } + + /** + * Calculate whether it is within the range of Rectangle according to the x and y coordinates + * + * @param rect rect + * @param point event point + * @return boolean + */ + public static boolean pointInRect(final Rectangle rect, final Point point) { + if (rect == null || point == null) { + return false; + } + int xAxis = Utils.getX(point); + int yAxis = Utils.getY(point); + return xAxis >= Utils.getX(rect) && xAxis <= Utils.getX(rect) + rect.width && yAxis >= Utils.getY(rect) + && yAxis < Utils.getY(rect) + rect.height; + } + + /** + * Get the last status description + * + * @param state state + * @return String + */ + public static String getEndState(final String state) { + if (Utils.getInstance().getStatusMap().containsKey(state)) { + return Utils.getInstance().getStatusMap().get(state); + } else { + if ("".equals(state) || state == null) { + return ""; + } + return "Unknown State"; + } + } + + /** + * transform time unit ns to ms + * + * @param data time + * @return String + */ + public static String transformTimeToMs(Number data) { + double ms; + if (data instanceof Long) { + ms = (Long) data / 1000000.0; + } else if (data instanceof Double) { + ms = (Double) data / 1000000.0; + } else { + ms = 0.0; + } + return new DecimalFormat("#.#######").format(ms); + } + + /** + * transform str to md5 + * + * @param str str + * @return String str to md5 string + */ + public static String md5String(String str) { + String result = ""; + try { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] digest = md5.digest(str.getBytes()); + StringBuilder builder = new StringBuilder(); + for (byte val : digest) { + builder.append(Integer.toHexString((0x000000FF & val) | 0xFFFFFF00).substring(6)); + } + result = builder.toString(); + } catch (NoSuchAlgorithmException exception) { + exception.printStackTrace(); + } + return result; + } + + /** + * get the db pool + * + * @return ExecutorService db pool + */ + public static ExecutorService getPool() { + return pool; + } + + /** + * reset the db pool + */ + public static void resetPool() { + pool.shutdownNow(); + pool = Executors.newFixedThreadPool(8); + } + + /** + * reset the db pool + * + * @param num pool size + */ + public static void resetPool(int num) { + pool.shutdownNow(); + pool = Executors.newFixedThreadPool(num); + } + + /** + * get rectangle x + * + * @param rectangle rectangle + * @return rectangleX + */ + public static int getX(Rectangle rectangle) { + return rectangle.x; + } + + /** + * get point x + * + * @param point point + * @return pointX + */ + public static int getX(Point point) { + return point.x; + } + + /** + * set rectangle x + * + * @param rectangle rectangle + * @param xVal xVal + */ + public static void setX(Rectangle rectangle, int xVal) { + rectangle.x = xVal; + } + + /** + * set point x + * + * @param point rectangle + * @param xVal xVal + */ + public static void setX(Point point, int xVal) { + point.x = xVal; + } + + /** + * set rectangle y + * + * @param rectangle rectangle + * @param yVal yVal + */ + public static void setY(Rectangle rectangle, int yVal) { + rectangle.y = yVal; + } + + /** + * set point y + * + * @param point point + * @param yVal yVal + */ + public static void setY(Point point, int yVal) { + point.y = yVal; + } + + /** + * get rectangle y + * + * @param rectangle rectangle + * @return rectangleY + */ + public static int getY(Rectangle rectangle) { + return rectangle.y; + } + + /** + * get point y + * + * @param point point + * @return rectangleY + */ + public static int getY(Point point) { + return point.y; + } + + /** + * Gets the value of statusMap . + * + * @return Get state collection + */ + public Map getStatusMap() { + return statusMap; + } +} diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_app_data.proto b/host/ohosprofiler/src/main/proto/agent_plugin_app_data.proto new file mode 100644 index 000000000..162d9ac93 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/agent_plugin_app_data.proto @@ -0,0 +1,52 @@ +// Copyright (c) 2021 Huawei Device Co., Ltd. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message AbilityStateInfo { + enum AbilityState { + UNSPECIFIED = 0; + START = 1; + INACTIVE = 2; + ACTIVE = 3; + BACKGROUND = 4; + FOREGROUND = 5; + STOP = 6; + } + int32 life_cycle_id = 1; + string ability_name = 2; + AbilityState state = 3; +} + +message KeyEvent { + int32 key_type = 1; + bool is_down = 2; +} + +message AgentAbilityEvent { + // timestamp obtained by CLOCK_REALTIME + uint64 tv_sec = 1; + uint64 tv_nsec = 2; + + oneof event { + AbilityStateInfo ability_state = 3; + KeyEvent key_event = 4; + } +} + +message BatchAgentAbilityEvent { + repeated AgentAbilityEvent events = 1; +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_config.proto b/host/ohosprofiler/src/main/proto/agent_plugin_config.proto index 2e6782a9f..049ffa4e6 100644 --- a/host/ohosprofiler/src/main/proto/agent_plugin_config.proto +++ b/host/ohosprofiler/src/main/proto/agent_plugin_config.proto @@ -10,6 +10,7 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_energy_data.proto b/host/ohosprofiler/src/main/proto/agent_plugin_energy_data.proto new file mode 100644 index 000000000..575dcfff6 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/agent_plugin_energy_data.proto @@ -0,0 +1,201 @@ +// 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. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message RunningLockBegin { + enum Type { + UNSPECIFIED = 0; + BACKGROUND = 1; + PROXIMITY_SCREEN_CONTROL = 2; + } + + int32 lock_id = 1; // 锁ID + Type type = 2; // 唤醒锁的类型 + string name = 3; // 唤醒锁名称 +} + +message RunningLockEnd { + int32 lock_id = 1; // 锁ID +} + +message PendingIntent { + string creator_package = 1; // 创建此PendingIntent的应用程序的程序包名称 + int32 creator_uid = 2; // 应用程序UID +} + +enum TimerType { + UNSPECIFIED = 0; + TIMER_TYPE_REALTIME = 1; + TIMER_TYPE_WAKEUP = 2; + TIMER_TYPE_EXACT = 4; + TIMER_TYPE_IDLE = 8; +} + +message OneShotStart { + PendingIntent intent = 1; + int64 oneshot_id = 2; + TimerType type = 3; + int64 triggertime_ns = 4; +} + +message RepeatStart { + PendingIntent intent = 1; + int64 repeat_id = 2; + TimerType type = 3; + int64 triggertime_ns = 4; + int64 interval_ns = 5; +} + +message TimerStop { + int64 stop_id = 1; +} + +message LocationRequest { + enum Priority { + UNSPECIFIED = 0; + PRIORITY_UNSET = 512; + PRIORITY_ACCURACY = 513; + PRIORITY_LOW_POWER = 514; + PRIORITY_FAST_FIRST_FIX = 515; + } + string provider = 1; // 提供位置的程序名称。通过LocationManager设置,则可以是“gps”、“network”、“passive”或空。通过FusedLocationProviderClient设置,则是“fused”。 + int64 interval_ms = 2; // 位置请求所需的间隔时间(ms),间隔时间越短越耗电 + int64 fastest_interval_ms = 3; // 位置请求的最快间隔时间(ms) + Priority priority = 4; // 位置请求精确度,精确度越高越耗电 +} + +message LocationUpdateRequested { + PendingIntent intent = 1; // 要为每个位置更新发送的挂起内容的元数据 + int32 location_id = 2; // 位置ID + LocationRequest request = 3; // 位置更新请求 +} + +message LocationReport { + int32 location_id = 1; // 位置ID + float accuracy_of_metre = 2; // 该位置的估计水平精度,径向,单位为米。 +} + +message LocationUpdateRemoved { + int32 location_id = 1; // 位置ID +} + +message WorkInfo { + enum BatteryLevel { + BATTERY_LEVEL_LOW = 0; + BATTERY_LEVEL_OKAY = 1; + BATTERY_LEVEL_LOW_OR_OKAY = 2; + } + enum ChargeType { + CHARGING_PLUGGED_ANY = 0; + CHARGING_PLUGGED_AC = 1; + CHARGING_PLUGGED_USB = 2; + CHARGING_PLUGGED_WIRELESS = 3; + } + enum NetworkType { + NETWORK_TYPE_ANY = 0; + NETWORK_TYPE_MOBILE = 1; + NETWORK_TYPE_WIFI = 2; + NETWORK_TYPE_BLUETOOTH = 3; + NETWORK_TYPE_WIFI_P2P = 4; + NETWORK_TYPE_ETHERNET = 5; + } + enum StorageType { + STORAGE_LEVEL_LOW = 0; + STORAGE_LEVEL_OKAY = 1; + STORAGE_LEVEL_LOW_OR_OKAY = 2; + } + + string ability_name = 1; // 运行作业的页面名称 + string bundle_name = 2; // 运行作业的程序名称 + int32 repeat_counter = 3; // 重复作业次数 + int64 repeat_cycle_time = 4; // 定期作业重复的间隔时间 + BatteryLevel battery_level = 5; // 作业设备的电池等级 + int32 battery_status = 6; // 作业设备的电池状态 + ChargeType charge_type = 7; // 作业设备的充电类型 + int32 wait_time = 8; // 非定期作业的延迟时间 + NetworkType network_type = 9; // 作业运行的网络类型 + StorageType storage_type = 10; // 作业设备的存储类型 + bool is_request_battery = 11; // 作业是否需要设备的电池电量不低于临界阈值 + bool is_request_charging = 12; // 作业是否需要充电 + bool is_request_deep_idle = 13; // 作业是否需要设备处于空闲维护窗口中 + bool is_request_delay = 14; // 作业是否需要延迟 + bool is_request_network = 15; // 作业是否需要网络 + bool is_request_persisted = 16; // 是否应跨设备重新引导持久化此作业 + bool is_request_repeat = 17; // 是否在给定时间内重复作业 + bool is_request_storage = 18; // 作业是否需要设备的存储空间不低 + bool is_work_info_valid = 19; // 作业是否有效 +} + +message WorkStart { + int64 work_id = 1; + WorkInfo work_info = 2; + bool start_now = 3; + bool is_start = 4; +} + +message WorkCancel { + int64 work_id = 1; + bool is_cancel = 2; +} + +message WorkStop { + int64 work_id = 1; + bool is_stop = 2; +} + +message BackgroundWork { + int64 work_id = 1; + int32 actual_delay_time = 2; + int32 request_id = 3; + string reason = 4; +} + +message OnStartWork { + int64 work_id = 1; + WorkInfo work_info = 2; +} + +message OnStopWork { + int64 work_id = 1; +} + +message AgentEnergyEvent { + // timestamp obtained by CLOCK_REALTIME + uint64 tv_sec = 1; + uint64 tv_nsec = 2; + string callstack = 3; // 生成此事件的调用堆栈 + oneof data { + RunningLockBegin runlock_begin = 4; // 获取唤醒锁(强制设备保持唤醒) + RunningLockEnd runlock_end = 5; // 释放唤醒锁 + OneShotStart oneshot_start = 6; // 闹钟 + RepeatStart repeat_start = 7; // 需要重复的闹钟 + TimerStop timer_stop = 8; + LocationUpdateRequested location_update_requested = 9; // 位置更新请求 + LocationReport location_report = 10; + LocationUpdateRemoved location_update_removed = 11; // 位置更新请求已删除 + WorkStart work_start = 12; + WorkCancel work_cancel = 13; + WorkStop work_stop = 14; + BackgroundWork back_work = 15; + OnStartWork on_start = 16; // 启动承载work的服务 + OnStopWork on_stop = 17; // 停止承载work的服务 + } +} + +message BatchAgentEnergyEvent { + repeated AgentEnergyEvent events = 1; +} diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_java_heap.proto b/host/ohosprofiler/src/main/proto/agent_plugin_java_heap.proto new file mode 100644 index 000000000..7b8930931 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/agent_plugin_java_heap.proto @@ -0,0 +1,62 @@ +// 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. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +// Java heap memory event from jvmti interface. +message ClassInfo { + int32 class_id = 1; + string class_name = 2; +} + +message AllocationInfo { + int32 object_id = 1; + int32 class_id = 2; + int32 object_size = 3; + int32 array_length = 4; + int32 heap_id = 5; + string thread_name = 6; + + message StackFrameInfo { + int32 frame_id = 1; + string class_name = 2; + string method_name = 3; + string file_name = 4; + int32 line_number = 5; + } + // First element means stack top. + repeated StackFrameInfo frame_info = 7; +} + +message DeallocationInfo { + int32 object_id = 1; +} + +message AgentMemoryEvent { + // timestamp obtained by CLOCK_REALTIME + uint64 tv_sec = 1; + uint64 tv_nsec = 2; + + oneof event { + ClassInfo class_data = 3; + AllocationInfo alloc_data = 4; + DeallocationInfo free_data = 5; + } +} + +message BatchAgentMemoryEvent { + repeated AgentMemoryEvent events = 1; +} diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_network_data.proto b/host/ohosprofiler/src/main/proto/agent_plugin_network_data.proto new file mode 100644 index 000000000..918af6320 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/agent_plugin_network_data.proto @@ -0,0 +1,64 @@ +// Copyright (c) 2021 Huawei Device Co., Ltd. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message HttpRequestHead { + string url = 1; + string method = 2; + string fields = 3; + string trace = 4; +} + +message HttpResponseHead { + string fields = 1; +} + +message HttpBody { + string payload_id = 1; + int32 payload_size = 2; + bytes payload_fields = 3; +} + +message HttpEndStatus { + bool aborted = 1; +} + +// thread +message AgentThread { + int64 id = 1; + string name = 2; +} + +message AgentNetworkEvent { + // timestamp obtained by CLOCK_REALTIME + uint64 tv_sec = 1; + uint64 tv_nsec = 2; + int64 event_id = 3; + + oneof event { + HttpRequestHead request_head = 4; + HttpResponseHead response_head = 5; + HttpBody request_body = 6; + HttpBody response_body = 7; + HttpEndStatus end_status = 8; + AgentThread agent_thread = 9; + } +} + +message BatchAgentNetworkEvent { + repeated AgentNetworkEvent events = 1; +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/agent_plugin_result.proto b/host/ohosprofiler/src/main/proto/agent_plugin_result.proto index 27639d6e5..ad9a3704a 100644 --- a/host/ohosprofiler/src/main/proto/agent_plugin_result.proto +++ b/host/ohosprofiler/src/main/proto/agent_plugin_result.proto @@ -10,49 +10,22 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; option optimize_for = LITE_RUNTIME; -message ClassInfo { - int32 class_id = 1; - string class_name = 2; -} +import "agent_plugin_java_heap.proto"; +import "agent_plugin_app_data.proto"; +import "agent_plugin_network_data.proto"; +import "agent_plugin_energy_data.proto"; -message AllocationInfo { - int32 object_id = 1; - int32 class_id = 2; - int32 object_size = 3; - int32 array_length = 4; - int32 heap_id = 5; - string thread_name = 6; - - message StackFrameInfo { - int32 frame_id = 1; - string class_name = 2; - string method_name = 3; - string file_name = 4; - int32 line_number = 5; - } - // First element means stack top. - repeated StackFrameInfo frame_info = 7; -} - -message DeallocationInfo { - int32 object_id = 1; -} - -message AgentMemoryEvent { - int64 timestamp = 1; - - oneof event { - ClassInfo class_data = 2; - AllocationInfo alloc_data = 3; - DeallocationInfo free_data = 4; +message AgentData { + oneof data { + BatchAgentMemoryEvent javaheap_data = 1; + BatchAgentAbilityEvent app_data = 2; + BatchAgentNetworkEvent network_data = 3; + BatchAgentEnergyEvent energy_data = 4; } } - -message BatchAgentMemoryEvent { - repeated AgentMemoryEvent events = 1; -} diff --git a/host/ohosprofiler/src/main/proto/bytrace_plugin_config.proto b/host/ohosprofiler/src/main/proto/bytrace_plugin_config.proto index c2106c3c8..82899c01e 100644 --- a/host/ohosprofiler/src/main/proto/bytrace_plugin_config.proto +++ b/host/ohosprofiler/src/main/proto/bytrace_plugin_config.proto @@ -1,4 +1,3 @@ - // 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. @@ -13,12 +12,14 @@ // limitations under the License. syntax = "proto3"; +option optimize_for = LITE_RUNTIME; option java_package = "ohos.devtools.datasources.transport.grpc.service"; message BytracePluginConfig { - uint32 buffe_size = 1; // size of the buffer (KB) for storing and reading traces. + uint32 buffe_size = 1; // Sets the size of the buffer (KB) for storing and reading traces. repeated string categories = 2; // Lists available bytrace categories. uint32 time = 3; // Sets the bytrace running duration in seconds (5s by default) - string clock = 4; // boot (default), global, mono, uptime, or perf. - string outfile_name = 5; // the name of the target file (stdout by default). -} + string clock = 4; // Sets the clock, which can be boot (default), global, mono, uptime, or perf. + string outfile_name = 5; // Sets the name of the target file (stdout by default). + bool is_root = 6; +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/common_types.proto b/host/ohosprofiler/src/main/proto/common_types.proto index eeab24f0c..fa67090ed 100644 --- a/host/ohosprofiler/src/main/proto/common_types.proto +++ b/host/ohosprofiler/src/main/proto/common_types.proto @@ -10,10 +10,12 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; +// Common message define for profiler tools, imported by profiler and plugin proto file. message ProfilerPluginConfig { string name = 1; string plugin_sha256 = 2; diff --git a/host/ohosprofiler/src/main/proto/cpu_plugin_config.proto b/host/ohosprofiler/src/main/proto/cpu_plugin_config.proto new file mode 100644 index 000000000..f3a730c98 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/cpu_plugin_config.proto @@ -0,0 +1,23 @@ +// 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. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + + +// Cpu plug-in configuration, passed to plug-in by plug-in service. +message CpuConfig { + int32 pid = 1; +} diff --git a/host/ohosprofiler/src/main/proto/cpu_plugin_result.proto b/host/ohosprofiler/src/main/proto/cpu_plugin_result.proto new file mode 100644 index 000000000..7b1896556 --- /dev/null +++ b/host/ohosprofiler/src/main/proto/cpu_plugin_result.proto @@ -0,0 +1,71 @@ +// Copyright (c) 2021 Huawei Device Co., Ltd. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message SampleTimeStamp { + uint64 tv_sec = 1; + uint64 tv_nsec = 2; +} + +message CpuCoreFrequency { + int32 min_frequency_khz = 1; + int32 max_frequency_khz = 2; + int32 cur_frequency_khz = 3; +} + +message CpuCoreUsageInfo { + int32 cpu_core = 1; + int64 prev_system_cpu_time_ms = 2; + int64 prev_system_boot_time_ms = 3; + int64 system_cpu_time_ms = 4; + int64 system_boot_time_ms = 5; + CpuCoreFrequency frequency = 6; + bool is_little_core = 7; +} + +message CpuUsageInfo { + int64 prev_process_cpu_time_ms = 1; + int64 prev_system_cpu_time_ms = 2; + int64 prev_system_boot_time_ms = 3; + int64 process_cpu_time_ms = 4; + int64 system_cpu_time_ms = 5; + int64 system_boot_time_ms = 6; + repeated CpuCoreUsageInfo cores = 7; + SampleTimeStamp timestamp = 8; +} + +enum ThreadState { + THREAD_UNSPECIFIED = 0; + THREAD_RUNNING = 1; + THREAD_SLEEPING = 2; + THREAD_STOPPED = 3; + THREAD_WAITING = 4; +} + +message ThreadInfo { + int32 tid = 1; + string thread_name = 2; + ThreadState thread_state = 3; + int64 prev_thread_cpu_time_ms = 4; + int64 thread_cpu_time_ms = 5; + SampleTimeStamp timestamp = 6; +} + +message CpuData { + CpuUsageInfo cpu_usage_info = 1; + repeated ThreadInfo thread_info = 2; +} diff --git a/host/ohosprofiler/src/main/proto/hiperf_call_plugin_config.proto b/host/ohosprofiler/src/main/proto/hiperf_call_plugin_config.proto new file mode 100644 index 000000000..1ee35a3ed --- /dev/null +++ b/host/ohosprofiler/src/main/proto/hiperf_call_plugin_config.proto @@ -0,0 +1,27 @@ +// 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. + +syntax = "proto3"; +option optimize_for = LITE_RUNTIME; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; + +message HiperfCallPluginConfig { + int32 pid = 1; // pid of app. + string app_name = 2; // app name. + string outfile = 4; // the name of the output target file. + + uint32 frequency = 3; // Set the counts of dumpping records per second, default 1000. + bool is_trace = 5; // Set if using --trace-offcpu, default true. + bool is_root = 6; // Set if using root privilege, default true. + bool is_emulator = 7; // Set if the device is emulator, default false. +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/memory_plugin_common.proto b/host/ohosprofiler/src/main/proto/memory_plugin_common.proto index ecf3a1794..afdf89e0f 100644 --- a/host/ohosprofiler/src/main/proto/memory_plugin_common.proto +++ b/host/ohosprofiler/src/main/proto/memory_plugin_common.proto @@ -10,11 +10,13 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; option optimize_for = LITE_RUNTIME; +// Common define for memory plug-in, imported by memory data and config proto file. enum SysMeminfoType { MEMINFO_UNSPECIFIED = 0; MEMINFO_MEM_TOTAL = 1; diff --git a/host/ohosprofiler/src/main/proto/memory_plugin_config.proto b/host/ohosprofiler/src/main/proto/memory_plugin_config.proto index 28689280f..72f824df4 100644 --- a/host/ohosprofiler/src/main/proto/memory_plugin_config.proto +++ b/host/ohosprofiler/src/main/proto/memory_plugin_config.proto @@ -10,6 +10,7 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; @@ -17,15 +18,25 @@ option optimize_for = LITE_RUNTIME; import "memory_plugin_common.proto"; +// Memory plug-in configuration, passed to plug-in by plug-in service. message MemoryConfig { // set true to report process list bool report_process_tree = 1; + // set true to report memory counter from /proc/meminfo bool report_sysmem_mem_info = 2; + // set required counter list of system meminfo, eg:MemTotal, MemFree, etc. repeated SysMeminfoType sys_meminfo_counters = 3; + // set true to report memory counter from /proc/vmstat bool report_sysmem_vmem_info = 4; + // set required counter list of virtual system meminfo, eg:nr_free_pages, nr_anon_pages, etc. repeated SysVMeminfoType sys_vmeminfo_counters = 5; + // set true to report process meminfo from /proc/${pid}/stat bool report_process_mem_info = 6; + // set true to report application memory usage summary, eg:java heap memory, native heap, stack memory, etc. bool report_app_mem_info = 7; + // set true to report application memory by dumpsys service, otherwise, + // application memory will count up by /proc/${pid}/smaps information bool report_app_mem_by_dumpsys = 8; + // set required pid list repeated int32 pid = 9; } diff --git a/host/ohosprofiler/src/main/proto/memory_plugin_result.proto b/host/ohosprofiler/src/main/proto/memory_plugin_result.proto index 3597c81aa..c0e622762 100644 --- a/host/ohosprofiler/src/main/proto/memory_plugin_result.proto +++ b/host/ohosprofiler/src/main/proto/memory_plugin_result.proto @@ -10,6 +10,7 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; @@ -17,6 +18,9 @@ option optimize_for = LITE_RUNTIME; import "memory_plugin_common.proto"; +// Data format of memory collect plug-in. +// Various memory data count, including system level and application level. +// Obtained from the proc file system or system service. message SysMeminfo { SysMeminfoType key = 1; uint64 value = 2; diff --git a/host/ohosprofiler/src/main/proto/profiler_service.proto b/host/ohosprofiler/src/main/proto/profiler_service.proto index f91bef805..35e1e1866 100644 --- a/host/ohosprofiler/src/main/proto/profiler_service.proto +++ b/host/ohosprofiler/src/main/proto/profiler_service.proto @@ -10,12 +10,16 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; import "profiler_service_types.proto"; +// RPC interface between profiler service and host service +// Use protobuf plug-ins to convert proto define to +// source and header files during the build process. service IProfilerService { // get all plugin infos and capabilities. rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse); @@ -35,6 +39,6 @@ service IProfilerService { // destroy tracing session. rpc DestroySession(DestroySessionRequest) returns (DestroySessionResponse); - // get device time 下一轮迭代再添加相关定义 - // rpc GetTime(GetTimeRequest) returns (GetTimeResponse); + // keep tracing session alive, call this interface will restart session expire count down task. + rpc KeepSession(KeepSessionRequest) returns (KeepSessionResponse); } diff --git a/host/ohosprofiler/src/main/proto/profiler_service_types.proto b/host/ohosprofiler/src/main/proto/profiler_service_types.proto index ec0b34ac0..a557e620a 100644 --- a/host/ohosprofiler/src/main/proto/profiler_service_types.proto +++ b/host/ohosprofiler/src/main/proto/profiler_service_types.proto @@ -10,12 +10,14 @@ // 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. + syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; import "common_types.proto"; +// Message define for profiler service, imported by profiler service proto file. // for GetCapabilities message GetCapabilitiesRequest { uint32 request_id = 1; @@ -51,7 +53,8 @@ message ProfilerSessionConfig { Mode session_mode = 2; string result_file = 3; // for OFFLINE mode, result file path uint32 result_max_size = 4; // for OFFLINE mode, result file max size in KB - uint32 sample_duration = 5; // for OFFLINE mode, smaple duration in ms + uint32 sample_duration = 5; // for OFFLINE mode, sample duration in ms + uint32 keep_alive_time = 6; // if set to non-zero value, session will auto-destroyed after CreateSession in ms } message CreateSessionRequest { @@ -114,4 +117,13 @@ message DestroySessionResponse { repeated ProfilerPluginState plugin_status = 3; } +// for KeepSession +message KeepSessionRequest { + uint32 request_id = 1; + uint32 session_id = 2; + uint32 keep_alive_time = 3; +} +message KeepSessionResponse { + uint32 status = 1; +} diff --git a/host/ohosprofiler/src/main/proto/stream_plugin_config.proto b/host/ohosprofiler/src/main/proto/stream_plugin_config.proto new file mode 100644 index 000000000..9d124a74c --- /dev/null +++ b/host/ohosprofiler/src/main/proto/stream_plugin_config.proto @@ -0,0 +1,19 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message StreamConfig { + int32 pid = 1; +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/stream_plugin_result.proto b/host/ohosprofiler/src/main/proto/stream_plugin_result.proto new file mode 100644 index 000000000..66d2a334e --- /dev/null +++ b/host/ohosprofiler/src/main/proto/stream_plugin_result.proto @@ -0,0 +1,20 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message StreamData { + uint64 intdata = 1; + string stringdata = 2; +} \ No newline at end of file diff --git a/host/ohosprofiler/src/main/proto/trace_plugin_config.proto b/host/ohosprofiler/src/main/proto/trace_plugin_config.proto index 74dfabfa5..079df5987 100644 --- a/host/ohosprofiler/src/main/proto/trace_plugin_config.proto +++ b/host/ohosprofiler/src/main/proto/trace_plugin_config.proto @@ -18,16 +18,9 @@ message TracePluginConfig { repeated string ftrace_events = 1; repeated string bytrace_categories = 2; repeated string bytrace_apps = 3; - uint32 buffer_size_kb = 4; /*cpu buffer_size*/ - uint32 trace_period_ms = 5; - bool symbolize_ksyms = 6; /*Enables symbol /proc/kallsyms.*/ - string clock = 7; - ExtractSchedConfig extract_sched = 8; - repeated string debug_outfile_name = 9; /*1: file 2:binary file*/ - bool debug_enable = 10; - string debug_fifo_path = 11; -} - -message ExtractSchedConfig { - bool enabled = 1; + uint32 buffer_size_kb = 4; // for ftrace procfs + uint32 flush_interval_ms = 5; + uint32 flush_threshold_kb = 6; + bool parse_ksyms = 7; // enable /proc/kallsyms parser + string clock = 8; } diff --git a/host/ohosprofiler/src/main/resources/LICENSE b/host/ohosprofiler/src/main/resources/LICENSE new file mode 100644 index 000000000..e454a5258 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/LICENSE @@ -0,0 +1,178 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + diff --git a/host/ohosprofiler/src/main/resources/META-INF/plugin.xml b/host/ohosprofiler/src/main/resources/META-INF/plugin.xml index 8bebb1a28..bc0ecc138 100644 --- a/host/ohosprofiler/src/main/resources/META-INF/plugin.xml +++ b/host/ohosprofiler/src/main/resources/META-INF/plugin.xml @@ -29,7 +29,7 @@ diff --git a/host/ohosprofiler/src/main/resources/assets/icon_usb2.png b/host/ohosprofiler/src/main/resources/assets/icon_usb2.png new file mode 100644 index 000000000..c445aa258 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/assets/icon_usb2.png differ diff --git a/host/ohosprofiler/src/main/resources/assets/icon_wifi2.png b/host/ohosprofiler/src/main/resources/assets/icon_wifi2.png new file mode 100644 index 000000000..bfc17fa18 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/assets/icon_wifi2.png differ diff --git a/host/ohosprofiler/src/main/resources/assets/top_star.png b/host/ohosprofiler/src/main/resources/assets/top_star.png index 4d4f1e0ba..e4f1fbe2c 100644 Binary files a/host/ohosprofiler/src/main/resources/assets/top_star.png and b/host/ohosprofiler/src/main/resources/assets/top_star.png differ diff --git a/host/ohosprofiler/src/main/resources/assets/top_star_fill.png b/host/ohosprofiler/src/main/resources/assets/top_star_fill.png index b688ea1e6..27d5810af 100644 Binary files a/host/ohosprofiler/src/main/resources/assets/top_star_fill.png and b/host/ohosprofiler/src/main/resources/assets/top_star_fill.png differ diff --git a/host/ohosprofiler/src/main/resources/hosprofiler.properties b/host/ohosprofiler/src/main/resources/hosprofiler.properties new file mode 100644 index 000000000..e3de8c5ed --- /dev/null +++ b/host/ohosprofiler/src/main/resources/hosprofiler.properties @@ -0,0 +1 @@ +version=%APP_VERSION% \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/images/attchLive.png b/host/ohosprofiler/src/main/resources/images/attchLive.png deleted file mode 100644 index cf46e2798..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/attchLive.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/backtrack.png b/host/ohosprofiler/src/main/resources/images/backtrack.png deleted file mode 100644 index ef6572be0..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/backtrack.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/breakpoint.png b/host/ohosprofiler/src/main/resources/images/breakpoint.png new file mode 100644 index 000000000..75a9a54f8 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/breakpoint.png differ diff --git a/host/ohosprofiler/src/main/resources/images/breakpoint_grey.png b/host/ohosprofiler/src/main/resources/images/breakpoint_grey.png new file mode 100644 index 000000000..ab12f0e03 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/breakpoint_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/button_add.png b/host/ohosprofiler/src/main/resources/images/button_add.png deleted file mode 100644 index dbf0af0c9..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_add.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_bottom_bar.png b/host/ohosprofiler/src/main/resources/images/button_bottom_bar.png deleted file mode 100644 index f4b4bb435..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_bottom_bar.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_bottom_bar_grey.png b/host/ohosprofiler/src/main/resources/images/button_bottom_bar_grey.png deleted file mode 100644 index 950ab62fe..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_bottom_bar_grey.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_delete.png b/host/ohosprofiler/src/main/resources/images/button_delete.png deleted file mode 100644 index f83499dca..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_delete.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_help.png b/host/ohosprofiler/src/main/resources/images/button_help.png deleted file mode 100644 index 019926110..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_help.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_left_bar.png b/host/ohosprofiler/src/main/resources/images/button_left_bar.png deleted file mode 100644 index 940314c6c..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_left_bar.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_record.png b/host/ohosprofiler/src/main/resources/images/button_record.png deleted file mode 100644 index 2d6e22ea6..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_record.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_save.png b/host/ohosprofiler/src/main/resources/images/button_save.png deleted file mode 100644 index f49475fb0..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_save.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/button_stop.png b/host/ohosprofiler/src/main/resources/images/button_stop.png deleted file mode 100644 index 9be654da0..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/button_stop.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/calculation.png b/host/ohosprofiler/src/main/resources/images/calculation.png new file mode 100644 index 000000000..c83111252 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/calculation.png differ diff --git a/host/ohosprofiler/src/main/resources/images/close.png b/host/ohosprofiler/src/main/resources/images/close.png index 69c6c6415..0cd7a0385 100644 Binary files a/host/ohosprofiler/src/main/resources/images/close.png and b/host/ohosprofiler/src/main/resources/images/close.png differ diff --git a/host/ohosprofiler/src/main/resources/images/copy.png b/host/ohosprofiler/src/main/resources/images/copy.png index 33790a449..3770f2f3f 100644 Binary files a/host/ohosprofiler/src/main/resources/images/copy.png and b/host/ohosprofiler/src/main/resources/images/copy.png differ diff --git a/host/ohosprofiler/src/main/resources/images/copyright.png b/host/ohosprofiler/src/main/resources/images/copyright.png new file mode 100644 index 000000000..255591a7e Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/copyright.png differ diff --git a/host/ohosprofiler/src/main/resources/images/cpu.png b/host/ohosprofiler/src/main/resources/images/cpu.png new file mode 100644 index 000000000..3e09b62e2 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/cpu.png differ diff --git a/host/ohosprofiler/src/main/resources/images/db_set_breakpoint_grey.png b/host/ohosprofiler/src/main/resources/images/db_set_breakpoint_grey.png new file mode 100644 index 000000000..1848a3956 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/db_set_breakpoint_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/gc.png b/host/ohosprofiler/src/main/resources/images/gc.png new file mode 100644 index 000000000..1dfbd1e85 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/gc.png differ diff --git a/host/ohosprofiler/src/main/resources/images/gc_grey.png b/host/ohosprofiler/src/main/resources/images/gc_grey.png new file mode 100644 index 000000000..353302088 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/gc_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/gpu_counter.png b/host/ohosprofiler/src/main/resources/images/gpu_counter.png new file mode 100644 index 000000000..b8410da51 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/gpu_counter.png differ diff --git a/host/ohosprofiler/src/main/resources/images/help.png b/host/ohosprofiler/src/main/resources/images/help.png new file mode 100644 index 000000000..05cc5d13c Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/help.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_dataselection_normal.png b/host/ohosprofiler/src/main/resources/images/icon_dataselection_normal.png new file mode 100644 index 000000000..9ff05609e Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/icon_dataselection_normal.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_heap_dump_grey.png b/host/ohosprofiler/src/main/resources/images/icon_heap_dump_grey.png new file mode 100644 index 000000000..3c390cb07 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/icon_heap_dump_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_heap_dump_normal.png b/host/ohosprofiler/src/main/resources/images/icon_heap_dump_normal.png new file mode 100644 index 000000000..e9d1f6870 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/icon_heap_dump_normal.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_time.png b/host/ohosprofiler/src/main/resources/images/icon_time.png new file mode 100644 index 000000000..77876bbdf Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/icon_time.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_usb.png b/host/ohosprofiler/src/main/resources/images/icon_usb.png index 1ee13268c..c445aa258 100644 Binary files a/host/ohosprofiler/src/main/resources/images/icon_usb.png and b/host/ohosprofiler/src/main/resources/images/icon_usb.png differ diff --git a/host/ohosprofiler/src/main/resources/images/icon_wifi.png b/host/ohosprofiler/src/main/resources/images/icon_wifi.png index 4dd7202b7..bfc17fa18 100644 Binary files a/host/ohosprofiler/src/main/resources/images/icon_wifi.png and b/host/ohosprofiler/src/main/resources/images/icon_wifi.png differ diff --git a/host/ohosprofiler/src/main/resources/images/left_grey.png b/host/ohosprofiler/src/main/resources/images/left_grey.png deleted file mode 100644 index 8d132173e..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/left_grey.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/loading.gif b/host/ohosprofiler/src/main/resources/images/loading.gif index ab88c5384..24fbdc131 100644 Binary files a/host/ohosprofiler/src/main/resources/images/loading.gif and b/host/ohosprofiler/src/main/resources/images/loading.gif differ diff --git a/host/ohosprofiler/src/main/resources/images/logo.png b/host/ohosprofiler/src/main/resources/images/logo.png deleted file mode 100644 index 7f76c492b..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/logo.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/menu-saveAll_grey.png b/host/ohosprofiler/src/main/resources/images/menu-saveAll_grey.png new file mode 100644 index 000000000..41dfef348 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/menu-saveAll_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/menu-saveall.png b/host/ohosprofiler/src/main/resources/images/menu-saveall.png new file mode 100644 index 000000000..80d2c5df4 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/menu-saveall.png differ diff --git a/host/ohosprofiler/src/main/resources/images/notificationInfo.png b/host/ohosprofiler/src/main/resources/images/notificationInfo.png new file mode 100644 index 000000000..b0a079162 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/notificationInfo.png differ diff --git a/host/ohosprofiler/src/main/resources/images/notificationInfo_normal.png b/host/ohosprofiler/src/main/resources/images/notificationInfo_normal.png new file mode 100644 index 000000000..f4ccf2e55 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/notificationInfo_normal.png differ diff --git a/host/ohosprofiler/src/main/resources/images/over.png b/host/ohosprofiler/src/main/resources/images/over.png deleted file mode 100644 index 024135416..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/over.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/overhead.png b/host/ohosprofiler/src/main/resources/images/overhead.png new file mode 100644 index 000000000..3a1be86f2 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/overhead.png differ diff --git a/host/ohosprofiler/src/main/resources/images/overhead_normal.png b/host/ohosprofiler/src/main/resources/images/overhead_normal.png new file mode 100644 index 000000000..ff5b6a5d6 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/overhead_normal.png differ diff --git a/host/ohosprofiler/src/main/resources/images/preview.png b/host/ohosprofiler/src/main/resources/images/preview.png new file mode 100644 index 000000000..9f7cd751a Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/preview.png differ diff --git a/host/ohosprofiler/src/main/resources/images/previewDetailsVertically_grey.png b/host/ohosprofiler/src/main/resources/images/previewDetailsVertically_grey.png new file mode 100644 index 000000000..b4594ab92 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/previewDetailsVertically_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/previewDetails_grey.png b/host/ohosprofiler/src/main/resources/images/previewDetails_grey.png new file mode 100644 index 000000000..5bbcda7a5 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/previewDetails_grey.png differ diff --git a/host/ohosprofiler/src/main/resources/images/preview_normal.png b/host/ohosprofiler/src/main/resources/images/preview_normal.png new file mode 100644 index 000000000..c05037f1e Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/preview_normal.png differ diff --git a/host/ohosprofiler/src/main/resources/images/right.png b/host/ohosprofiler/src/main/resources/images/right.png deleted file mode 100644 index 4f924f6ad..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/right.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/right_grey.png b/host/ohosprofiler/src/main/resources/images/right_grey.png deleted file mode 100644 index d4b700fc6..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/right_grey.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/rotation.png b/host/ohosprofiler/src/main/resources/images/rotation.png new file mode 100644 index 000000000..3b2c9dcb7 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/rotation.png differ diff --git a/host/ohosprofiler/src/main/resources/images/search.png b/host/ohosprofiler/src/main/resources/images/search.png deleted file mode 100644 index 6888a8820..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/search.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/selected.png b/host/ohosprofiler/src/main/resources/images/selected.png deleted file mode 100644 index 68516d124..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/selected.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/suspended.png b/host/ohosprofiler/src/main/resources/images/suspended.png deleted file mode 100644 index f17add8df..000000000 Binary files a/host/ohosprofiler/src/main/resources/images/suspended.png and /dev/null differ diff --git a/host/ohosprofiler/src/main/resources/images/tool_icon.png b/host/ohosprofiler/src/main/resources/images/tool_icon.png new file mode 100644 index 000000000..4294b39b3 Binary files /dev/null and b/host/ohosprofiler/src/main/resources/images/tool_icon.png differ diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/cpu_views.txt b/host/ohosprofiler/src/main/resources/metrics-sql/cpu_views.txt new file mode 100644 index 000000000..0c01d189d --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/cpu_views.txt @@ -0,0 +1,53 @@ +--metrics +DROP VIEW if exists cpu_frequency_view; +CREATE VIEW cpu_frequency_view AS +SELECT + B.cpu, + A.ts as start_ts, + LEAD(A.ts, 1, (SELECT end_ts from trace_range)) + OVER (PARTITION by A.filter_id ORDER BY ts) AS end_ts, + LEAD(A.ts, 1, (SELECT end_ts from trace_range)) + OVER (PARTITION by A.filter_id ORDER BY ts) - ts AS dur, + value as freq +FROM measure AS A, cpu_measure_filter AS B +WHERE B.name = 'cpu_frequency' and A.filter_id=B.id; + +DROP VIEW if exists cpu_thread_view; +CREATE VIEW cpu_thread_view AS +SELECT S.ts, + S.ts + S.dur as end_ts, + S.cpu, + T.ipid, + S.itid AS itid, + P.pid as pid, + T.name AS thread_name, + P.name AS process_name +FROM thread AS T, sched_slice AS S, process as P +where T.id = S.itid and T.ipid=P.id; + +DROP VIEW if exists tmp; +CREATE VIEW tmp AS +SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts; + +DROP VIEW if exists cpu_per_thread; +-- CPU info aggregated per CPU and thread. +CREATE VIEW cpu_per_thread AS +SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name +FROM tmp +GROUP BY itid, cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/distributed_term.txt b/host/ohosprofiler/src/main/resources/metrics-sql/distributed_term.txt new file mode 100644 index 000000000..04038d513 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/distributed_term.txt @@ -0,0 +1,18 @@ +select + group_concat(thread.id,",") as threadId, + group_concat(thread.name,",") as threadName, + group_concat(process.id,",") as processId, + group_concat(process.name,",") as processName, + group_concat(callstack.name,",") as funName, + group_concat(callstack.dur,",") as dur, + group_concat(callstack.ts,",") as ts, + cast(callstack.chainId as varchar) as chainId, + callstack.spanId, + callstack.parentSpanId, + group_concat(callstack.flag,",") as flag, + (select value from meta where name="source_name") as trace_name +from callstack +inner join thread on callstack.callid = thread.id +inner join process on process.id = thread.ipid +where (callstack.flag="S" or callstack.flag="C") +group by callstack.chainId,callstack.spanId,callstack.parentSpanId \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls.txt b/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls.txt new file mode 100644 index 000000000..5723561a3 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls.txt @@ -0,0 +1,9 @@ +select +count(*) as frequency, +min(dur) as minDur, +max(dur) as maxDur, +floor(avg(dur)) as avgDur, +name as funName +from callstack +group by name +order by frequency desc limit 100 \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls_top10.txt b/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls_top10.txt new file mode 100644 index 000000000..6400bd37e --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/sys_calls_top10.txt @@ -0,0 +1,46 @@ + select + cpu.tid as tid, + cpu.pid,cpu.process_name, + cpu.thread_name, + callstack.name as funName, + count(callstack.name) as frequency, + min(callstack.dur) as minDur, + max(callstack.dur) as maxDur, + floor(avg(callstack.dur)) as avgDur + from callstack inner join + ( select + itid as tid, + ipid as pid, + group_concat(cpu,",") as cpu, + group_concat(duration,",") as duration, + group_concat(min_freq,",") as min_freq, + group_concat(max_freq,",") as max_freq, + group_concat(avg_frequency,",") as avg_frequency, + sum(duration*avg_frequency) as sumNum, + process_name, + thread_name + from + ( + SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name + FROM (SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts + ) GROUP BY itid, cpu) GROUP BY ipid, itid order by sumNum desc limit 10 + ) + as cpu on + callstack.callid = cpu.tid + group by callstack.name order by frequency desc limit 10; diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu.txt new file mode 100644 index 000000000..e4e8a2d76 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu.txt @@ -0,0 +1,33 @@ + select + itid as tid, + ipid as pid, + group_concat(cpu,",") as cpu, + group_concat(duration,",") as duration, + group_concat(min_freq,",") as min_freq, + group_concat(max_freq,",") as max_freq, + group_concat(avg_frequency,",") as avg_frequency, + process_name, + thread_name + from + ( + SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name + FROM (SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts + ) GROUP BY itid, cpu + ) +GROUP BY ipid, itid order by ipid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu_top10.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu_top10.txt new file mode 100644 index 000000000..bd01a1bdc --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_cpu_top10.txt @@ -0,0 +1,34 @@ + select + itid as tid, + ipid as pid, + group_concat(cpu,",") as cpu, + group_concat(duration,",") as duration, + group_concat(min_freq,",") as min_freq, + group_concat(max_freq,",") as max_freq, + group_concat(avg_frequency,",") as avg_frequency, + sum(duration*avg_frequency) as sumNum, + process_name, + thread_name + from + ( + SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name + FROM (SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts + ) GROUP BY itid, cpu + ) +GROUP BY ipid, itid order by sumNum desc limit 10 \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem.txt new file mode 100644 index 000000000..8fead97b6 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem.txt @@ -0,0 +1,7 @@ +select max(value) as maxNum,min(value) as minNum,avg(value) avgNum,result.name,result.processName from measure inner join +( +select filter.id,filter.name,p.name as processName from process_measure_filter as filter +left join process as p +on filter.ipid=p.id where filter.name = "mem.rss.anon" +) as result on result.id = filter_id +where filter_id > 0 group by filter_id order by avgNum desc \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem_unagg.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem_unagg.txt new file mode 100644 index 000000000..806c82044 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_mem_unagg.txt @@ -0,0 +1,13 @@ +select +processName, +group_concat(name) as name, +cast(group_concat(value) as varchar) as value, +cast(group_concat(ts) as varchar) as ts +from measure inner join +( +select filter.ipid,filter.id,filter.name,p.name as processName from process_measure_filter as filter +left join process as p +on filter.ipid=p.id where filter.name = "mem.rss.anon" or filter.name = "mem.rss.file" or filter.name = "mem.swap" or filter.name = "oom_score_adj" +) as result +on result.id = filter_id +group by processName,ipid order by ipid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_metadata.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_metadata.txt new file mode 100644 index 000000000..372c4e044 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_metadata.txt @@ -0,0 +1,5 @@ +select cast(name as varchar) as name,cast(value as varchar) as value from meta +UNION +select 'start_ts',cast(start_ts as varchar) from trace_range +UNION +select 'end_ts',cast(end_ts as varchar) from trace_range \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_stats.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_stats.txt new file mode 100644 index 000000000..e103109cf --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_stats.txt @@ -0,0 +1 @@ +select event_name,stat_type,count,source,serverity from stat \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/metrics-sql/trace_task_names.txt b/host/ohosprofiler/src/main/resources/metrics-sql/trace_task_names.txt new file mode 100644 index 000000000..31dab8f4b --- /dev/null +++ b/host/ohosprofiler/src/main/resources/metrics-sql/trace_task_names.txt @@ -0,0 +1,6 @@ +select P.id, + P.pid, + P.name as process_name, + group_concat(T.name,",") as thread_name +from process as P left join thread as T where P.id = T.ipid +group by pid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/ohos/init.sql b/host/ohosprofiler/src/main/resources/ohos/init.sql index cfff13152..8aa55db16 100644 --- a/host/ohosprofiler/src/main/resources/ohos/init.sql +++ b/host/ohosprofiler/src/main/resources/ohos/init.sql @@ -13,56 +13,17 @@ * limitations under the License. */ -##设备详情信息表 -CREATE TABLE DeviceInfo -( - ID integer primary key autoincrement NOT NULL, - deviceID varchar(50) NOT NULL, - deviceName varchar(100) NOT NULL, - ramInfo varchar(100), - romInfo varchar(100) -); -##进程列表 -CREATE TABLE ProcessInfo -( - processId integer primary key not null, - deviceId varchar(50) not null, - processName varchar(100), - state integer(50), - startTime integer(50), - arch varchar(100), - agentStatus varchar(100) -); - ##设备实时动态表 CREATE TABLE DeviceIPPortInfo ( ID integer primary key autoincrement not null, deviceID varchar(100) not null, deviceName varchar(100) NOT NULL, - ip varchar(100) not null, + ip varchar(100) , deviceType varchar(100) not null, + connectType varchar(100) not null, + deviceStatus int not null, + retryNum int not null, port int not null, forwardPort int not null ); - -##监控项配置表 -CREATE TABLE MonitorInfo -( - localSessionId INT PRIMARY KEY NOT NULL, - monitorType varchar(64) NOT NULL, - parameter varchar(64) NOT NULL, - value varchar(256) DEFAULT '' -); -##自研插件表 -CREATE TABLE HiProfilerPlugin -( - deviceId INT PRIMARY KEY NOT NULL, - plugId INT NOT NULL, - name varchar(64) NOT NULL, - statue INT NOT NULL, - version INT NOT NULL, - plugSha256 varchar(256) NOT NULL, - sampleInterval INT NOT NULL, - configData varbinary(500) -); diff --git a/host/ohosprofiler/src/main/resources/ohos/ohosprofiler b/host/ohosprofiler/src/main/resources/ohos/ohosprofiler index af46dbb14..8394521ba 100644 --- a/host/ohosprofiler/src/main/resources/ohos/ohosprofiler +++ b/host/ohosprofiler/src/main/resources/ohos/ohosprofiler @@ -1,181 +1,214 @@ -#!/bin/bash - -# -# 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 -# -# https://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. -# - -WORK_DIR=/data/local/tmp -function error(){ - echo -e "\033[1;31m$1\033[0m" - exit 1 -} -process_name=$2 - -function start_daemon() { - echo "start Profiler Daemon Process" - cd $WORK_DIR/developtools - start_hiprofilerd - sleep 1 - start_plugins - echo "StartDaemonSuccess" - exit 0 -} - -function restart_daemon(){ - local pid=$(pgrep -l .|grep hiprofilerd |grep -v grep |sed 's/^¥s*//'|sed 's/[[:space:]].*//') - local plugPid=$(pgrep -l .|grep hiprofiler_plug |grep -v grep |sed 's/^¥s*//'|sed 's/[[:space:]].*//') - if [ !$pid ]; then - kill -9 $pid - fi - if [ !$plugPid ]; then - kill -9 $plugPid - fi - start_hiprofilerd - sleep 1 - start_plugins - echo "StartDaemonSuccess" - exit 0 -} - -function start_hiprofilerd() { - cd $WORK_DIR/developtools - if [ `ps -ef | grep hiprofilerd | grep -v grep | wc -l` == 0 ]; then - chmod +x $WORK_DIR/developtools/hiprofilerd - LD_LIBRARY_PATH=./ ./hiprofilerd & - fi -} - -function start_plugins() { - cd $WORK_DIR/developtools - if [ `ps -ef | grep hiprofiler_plugins | grep -v grep | wc -l` == 0 ]; then - chmod +x $WORK_DIR/developtools/hiprofiler_plugins - LD_LIBRARY_PATH=./ ./hiprofiler_plugins & - fi - -} - -function start_v7daemon(){ - echo "start Profiler Daemon V7 Process" - cd $WORK_DIR/developtools - if [ `ps -ef | grep hiprofilerd | grep -v grep | wc -l` == 0 ]; then - chmod +x $WORK_DIR/developtools/hiprofilerd - LD_LIBRARY_PATH=./ ./hiprofilerd & - fi - sleep 2 - if [ `ps -ef | grep hiprofiler_plugins | grep -v grep | wc -l` == 0 ]; then - chmod +x $WORK_DIR/developtools/hiprofiler_plugins - LD_LIBRARY_PATH=./ ./hiprofiler_plugins & - fi - echo "StartDaemonSuccess" - exit 0 -} - - -function uzip_file(){ - echo "uzip devtools file" - cd $WORK_DIR - if [ `ls $WORK_DIR | grep devtool | grep -v grep | wc -l` -eq 1 ]; then - tar -xf $WORK_DIR/devtool - chmod +x * - cp $WORK_DIR/developtools/libmemdataplugin.z.so $WORK_DIR - if [ `ls ${WORK_DIR}/developtools/ | grep libbytraceplugin.z.so | grep -v grep | wc -l` -eq 1 ]; then - cp $WORK_DIR/developtools/libbytraceplugin.z.so $WORK_DIR - fi - if [ `ls ${WORK_DIR}/developtools/ | grep libptrace_plugin.z.so | grep -v grep | wc -l` -eq 1 ]; then - cp $WORK_DIR/developtools/libptrace_plugin.z.so $WORK_DIR - fi - if [ `ls ${WORK_DIR}/developtools/ | grep libtraceplugin.z.so | grep -v grep | wc -l` -eq 1 ]; then - cp $WORK_DIR/developtools/libtraceplugin.z.so $WORK_DIR - fi - fi -} - - -function check_server(){ - chmod +x /data/local/tmp/developtools/hiprofiler_cmd - cd /data/local/tmp/developtools/ - if [ `ps -ef| grep hiprofiler_plugins | grep -v grep | wc -l` -eq 0 ];then - echo "FAIL" - fi - LD_LIBRARY_PATH=./ /data/local/tmp/developtools/hiprofiler_cmd -q -} - - -function unzip_start_daemon(){ - uzip_file - start_daemon - exit 0 -} - -function unzip_start_daemonV7(){ - uzip_file - start_v7daemon - exit 0 -} - -function check_file_exits(){ - echo "check daemon File " - if [ `ls $WORK_DIR | grep hiprofiler_cmd | wc -l` == 0 ]; then - echo "hiprofiler_cmd is not found" - exit 1 - fi - chmod +x $WORK_DIR/hiprofiler_cmd - - if [ `ls $WORK_DIR | grep hiprofilerd | wc -l` == 0 ]; then - echo "hiprofilerd is not found" - exit 2 - fi - chmod +x $WORK_DIR/hiprofilerd - - if [ `ls $WORK_DIR | grep hiprofiler_plugins | wc -l` == 0 ]; then - echo "hiprofilerd is not found" - exit 3 - fi - chmod +x $WORK_DIR/hiprofiler_plugins -} - -case $1 in - check) - echo "check file" - check_file_exits - ;; - start) - echo "start" - start_daemon - ;; - unzipStart) - echo "start" - unzip_start_daemon - ;; - startHeap) - echo "start Heap" - start_java_heap - ;; - check_server) - check_server - ;; - startV7) - start_v7daemon - ;; - restart) - restart_daemon - ;; - unzipStartV7) - unzip_start_daemonV7 - ;; - *) - echo "Ignorant" - ;; -esac +#!/bin/bash + +# +# 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 +# +# https://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. +# + +WORK_DIR=/data/local/tmp +function error(){ + echo -e "\033[1;31m$1\033[0m" + exit 1 +} +process_name=$2 + +function start_daemon() { + echo "start Profiler Daemon Process" + if [ $(getprop ro.product.cpu.abi) == "arm64-v8a" ]; then + echo "run as shell" + if [ `ps -ef | grep hiprofilerd | grep -v grep | wc -l` -ne 0 ]; then + killall hiprofilerd + fi + if [ `ps -ef | grep hiprofiler_plugins | grep -v grep | wc -l` -ne 0 ]; then + killall hiprofiler_plugins + fi + start_hiprofilerd + sleep 1 + start_plugins + else + su root <> /dev/null +} + +function start_plugins() { + cd $WORK_DIR/developtools + chmod +x $WORK_DIR/developtools/hiprofiler_plugins + LD_LIBRARY_PATH=./ ./hiprofiler_plugins & >> /dev/null +} + +function uzip_file(){ + echo "================= $1 " + string=$1 + array=(${string//,/ }) + echo "uzip devtools file" + cd $WORK_DIR + if [ `ls $WORK_DIR | grep developtools | grep -v grep | wc -l` -eq 1 ]; then + cd developtools + chmod + * + for pluginfile in ${array[@]} + do + echo "---------------- $pluginfile" + if [ `ls ${WORK_DIR}/developtools/ | grep $pluginfile | grep -v grep | wc -l` -eq 1 ]; then + cp $WORK_DIR/developtools/$pluginfile $WORK_DIR + fi + done + fi +} + + +function check_server(){ + chmod +x /data/local/tmp/developtools/hiprofiler_cmd + cd /data/local/tmp/developtools/ + if [ `ps -ef| grep hiprofiler_plugins | grep -v grep | wc -l` -eq 0 ];then + echo "FAIL" + fi + LD_LIBRARY_PATH=./ /data/local/tmp/developtools/hiprofiler_cmd -q +} + +function check_std_server(){ + if [ `ps -ef| grep hiprofiler_plugins | grep -v grep | wc -l` -eq 0 ];then + echo "FAIL" + fi + if [ `ps -ef| grep hiprofilerd | grep -v grep | wc -l` -eq 0 ];then + echo "FAIL" + fi + echo "OK"; +} + + +function unzip_start_daemon(){ + uzip_file $1 + start_daemon + exit 0 +} + +function untar_start_daemon(){ + untar + uzip_file $1 + start_std_daemon + exit 0 +} + +function untar(){ + cd /data/local/tmp/ + tar -vxf developtool.tar + return 0 +} + +case $1 in + check) + echo "check file" + check_file_exits + ;; + start) + echo "start" + start_daemon + ;; + unzipStart) + echo "start" + unzip_start_daemon $2 + ;; + untarStart) + echo "start" + untar_start_daemon $2 + ;; + check_server) + check_server + ;; + check_std_server) + check_std_server + ;; + restart) + restart_daemon + ;; + start_std_daemon) + start_std_daemon + ;; + start_hiprofilerd) + echo "ohosprofiler" + start_hiprofilerd + ;; + start_plugins) + echo "------------" + start_plugins + ;; + *) + echo "Ignorant" + ;; +esac diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/GetFunDataByTid.txt b/host/ohosprofiler/src/main/resources/sql-app-self/GetFunDataByTid.txt new file mode 100644 index 000000000..57b713634 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/GetFunDataByTid.txt @@ -0,0 +1,12 @@ +select tid, + A.name as threadName, + is_main_thread, + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.parent_id, + c.id, + c.depth +from thread A,trace_range D +left join callstack C on A.id = C.callid +where startTs not null and A.tid = %s \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/GetThreadFuncByName.txt b/host/ohosprofiler/src/main/resources/sql-app-self/GetThreadFuncByName.txt new file mode 100644 index 000000000..162ac4c3d --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/GetThreadFuncByName.txt @@ -0,0 +1,16 @@ +select tid, + A.start_ts, + A.end_ts, + A.name as threadName, + is_main_thread, + c.ts-D.start_ts as startTs, + c.ts + c.dur as endTs, + c.dur, + c.name as funName, + c.depth, + c.parent_id, + c.id +from thread A,trace_range D +left join callstack C on A.id = C.callid +left join process E on A.ipid = E.id +where startTs not null and A.name = 'RenderThread' and C.name = 'DrawFrame' and E.pid = %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpu.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpu.txt new file mode 100644 index 000000000..97ee3be52 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpu.txt @@ -0,0 +1 @@ +select cpu from cpu_measure_filter where name='cpuidle' order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuData.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuData.txt new file mode 100644 index 000000000..ad8074693 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuData.txt @@ -0,0 +1,18 @@ +SELECT IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name,C.id as schedId, + A.tid, + A.id, A.type, + B.dur, B.ts - TR.start_ts AS startTime, + C.priority, C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataCount.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataCount.txt new file mode 100644 index 000000000..4a252b307 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataCount.txt @@ -0,0 +1,24 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list; diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataLimit.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataLimit.txt new file mode 100644 index 000000000..7ea3d5c27 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuDataLimit.txt @@ -0,0 +1,24 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list order by random() limit %s; diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuFreqData.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuFreqData.txt new file mode 100644 index 000000000..d8d6a1440 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuFreqData.txt @@ -0,0 +1,4 @@ +select cpu,value,ts-tb.start_ts as startNS + from measure c ,trace_range tb + inner join cpu_measure_filter t on c.filter_id = t.id + where (name = 'cpufreq' or name='cpu_frequency') and cpu=%s order by ts ; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMax.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMax.txt new file mode 100644 index 000000000..c69cf243c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMax.txt @@ -0,0 +1 @@ +select cpu from sched_slice order by cpu desc limit 1; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMaxFreq.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMaxFreq.txt new file mode 100644 index 000000000..091b721cd --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuMaxFreq.txt @@ -0,0 +1,4 @@ +select max(value) as maxFreq + from measure c + inner join cpu_measure_filter t on c.filter_id = t.id + where (name = 'cpufreq' or name='cpu_frequency'); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuScale.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuScale.txt new file mode 100644 index 000000000..4087e55a8 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryCpuScale.txt @@ -0,0 +1 @@ +select id,session,sessionId,timeStamp,Data as data from processCpuInfo; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFiles.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFiles.txt new file mode 100644 index 000000000..a9e6f9b1d --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFiles.txt @@ -0,0 +1 @@ +select * from perf_files \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFunc.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFunc.txt new file mode 100644 index 000000000..04b2cce6b --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfFunc.txt @@ -0,0 +1,9 @@ +select perf_callchain.callchain_id, +sample.sample_id, +sample.thread_id, +sample.timestamp, +perf_callchain.file_id, +perf_callchain.symbol_id + ,perf_callchain.vaddr_in_file + from perf_callchain inner join (select * from perf_sample where thread_id = %s) as sample + on sample.sample_id = perf_callchain.sample_id order by sample.id,perf_callchain.callchain_id desc ; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfThread.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfThread.txt new file mode 100644 index 000000000..ef453d47a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPerfThread.txt @@ -0,0 +1,2 @@ +select T.thread_name as threadName,T.thread_id as tid,T.process_id as pid +from perf_thread T inner join (select count(*) as count,thread_id from perf_sample group by thread_id) S on T.thread_id = S.thread_id and S.count>0; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryPrefTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPrefTotalTime.txt new file mode 100644 index 000000000..9ca090c33 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryPrefTotalTime.txt @@ -0,0 +1 @@ +select max(timestamp) as endTime,min(timestamp) as startTime from perf_sample; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryProcess.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryProcess.txt new file mode 100644 index 000000000..e8b16d052 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryProcess.txt @@ -0,0 +1,16 @@ +select + distinct process_view.pid as pid, + process_view.name as processName + from ( + select ipid, itid from sched_slice join thread_view using(itid) group by itid + ) the_tracks + left join (select ipid, sum(dur) as total_dur + from sched_view join thread_view using(itid) + group by ipid + ) using(ipid) + left join process_view using(ipid) + order by + total_dur desc, + the_tracks.ipid, + processName, + the_tracks.itid; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadData.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadData.txt new file mode 100644 index 000000000..76e1ddcff --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadData.txt @@ -0,0 +1,6 @@ +select A.*,A.ipid as upid,B.itid as utid, B.cpu, B.ts-TR.start_ts AS startTime,B.dur,B.state,IP.pid,IP.name as processName + from thread_state AS B + left join thread as A + left join trace_range AS TR + left join process AS IP on IP.id=A.ipid + where A.id=B.itid and tid = %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadsByPid.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadsByPid.txt new file mode 100644 index 000000000..01933c480 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryThreadsByPid.txt @@ -0,0 +1,22 @@ +select + the_tracks.ipid as upid, + the_tracks.itid as utid, + total_dur as hasSched, + process_view.pid as pid, + thread_view.tid as tid, + process_view.name as processName, + thread_view.name as threadName + from ( + select ipid, itid from sched_view join thread_view using(itid) group by itid + ) the_tracks + left join (select ipid, sum(dur) as total_dur + from sched_view join thread_view using(itid) + group by ipid + ) using(ipid) + left join thread_view using(itid) + left join process_view using(ipid) + where pid = %s + order by + total_dur desc, + the_tracks.ipid, + the_tracks.itid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryTotalTime.txt new file mode 100644 index 000000000..2cd47e6d1 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryTotalTime.txt @@ -0,0 +1 @@ +select start_ts,end_ts,end_ts-start_ts as total from trace_range; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/QueryVSYNCAPP.txt b/host/ohosprofiler/src/main/resources/sql-app-self/QueryVSYNCAPP.txt new file mode 100644 index 000000000..69e2ac27a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/QueryVSYNCAPP.txt @@ -0,0 +1,10 @@ +with tracks as ( + select process_measure_filter.id as trackId, + process_measure_filter.name as trackName, ipid, process_view.pid, + process_view.name as processName, process_view.start_ts as startTs + from process_measure_filter + join process_view using(ipid) + where trackName='VSYNC-app' + order by trackName +) +select c.*,c.filter_id as track_id,c.ts-tb.start_ts startTime from measure c,trace_range tb where filter_id in (select tracks.trackId from tracks); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app-self/Views.txt b/host/ohosprofiler/src/main/resources/sql-app-self/Views.txt new file mode 100644 index 000000000..c6c932254 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app-self/Views.txt @@ -0,0 +1,4 @@ +CREATE VIEW IF NOT EXISTS thread_view AS SELECT id as itid, * FROM thread; +CREATE VIEW IF NOT EXISTS process_view AS SELECT id as ipid, * FROM process; +CREATE VIEW IF NOT EXISTS sched_view AS SELECT *, ts + dur as ts_end FROM sched_slice; +CREATE VIEW IF NOT EXISTS instants_view AS SELECT *, 0.0 as value FROM instant; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/GetFunDataByTid.txt b/host/ohosprofiler/src/main/resources/sql-app/GetFunDataByTid.txt new file mode 100644 index 000000000..dc523087c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/GetFunDataByTid.txt @@ -0,0 +1,17 @@ +select tid, + A.name as threadName, + is_main_thread, + c.track_id, + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.parent_id, + c.id, + c.stack_id, + c.parent_stack_id, + c.depth +-- ,(case when category isnull then 'N/A' else category end) as cat +from internal_thread A,trace_bounds D +left join thread_track B on A.id = B.utid +left join internal_slice C on B.id = C.track_id +where startTs not null and A.tid = %s \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/GetThreadFuncByName.txt b/host/ohosprofiler/src/main/resources/sql-app/GetThreadFuncByName.txt new file mode 100644 index 000000000..d1f7c7fa7 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/GetThreadFuncByName.txt @@ -0,0 +1,20 @@ +select tid, + A.start_ts, + A.end_ts, + A.name as threadName, + is_main_thread, + c.track_id, + c.ts-D.start_ts as startTs, + c.ts + c.dur as endTs, + c.dur, + c.name as funName, + c.depth, + c.parent_id, + c.stack_id, + c.parent_stack_id, + c.id +from internal_thread A,trace_bounds D +left join thread_track B on A.id = B.utid +left join internal_slice C on B.id = C.track_id +left join internal_process E on A.upid = E.id +where startTs not null and A.name = 'RenderThread' and C.name = 'DrawFrame' and E.pid = %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpu.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpu.txt new file mode 100644 index 000000000..c5d47ad60 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpu.txt @@ -0,0 +1 @@ +select cpu from cpu_counter_track where name='cpuidle' order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuData.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuData.txt new file mode 100644 index 000000000..b75607f3c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuData.txt @@ -0,0 +1,19 @@ +with list as (SELECT IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name,C.id as schedId, + A.tid, + A.id, A.type, + B.dur, B.ts - TR.start_ts AS startTime, + C.priority, C.end_state +from thread_state AS B + left join internal_thread as A + left join sched_slice AS C + left join trace_bounds AS TR + left join internal_process AS IP +where B.utid = A.id and B.cpu = %s + and B.utid = C.utid and B.ts = C.ts + and A.upid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataCount.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataCount.txt new file mode 100644 index 000000000..5d1456e55 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataCount.txt @@ -0,0 +1,25 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId, + B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join internal_thread as A + left join sched_slice AS C + left join trace_bounds AS TR + left join internal_process AS IP +where B.utid = A.id and B.cpu = %s + and B.utid = C.utid and B.ts = C.ts + and A.upid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataLimit.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataLimit.txt new file mode 100644 index 000000000..1fe7d3d2f --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuDataLimit.txt @@ -0,0 +1,25 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId, + B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join internal_thread as A + left join sched_slice AS C + left join trace_bounds AS TR + left join internal_process AS IP +where B.utid = A.id and B.cpu = %s + and B.utid = C.utid and B.ts = C.ts + and A.upid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list order by random() limit %s; diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuFreqData.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuFreqData.txt new file mode 100644 index 000000000..b29b686db --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuFreqData.txt @@ -0,0 +1,4 @@ +select cpu,value,ts-tb.start_ts as startNS + from counter c ,trace_bounds tb + inner join cpu_counter_track t on c.track_id = t.id + where (name = 'cpufreq' or name='cpu_frequency') and cpu=%s order by ts ; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMax.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMax.txt new file mode 100644 index 000000000..c69cf243c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMax.txt @@ -0,0 +1 @@ +select cpu from sched_slice order by cpu desc limit 1; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMaxFreq.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMaxFreq.txt new file mode 100644 index 000000000..fb0557a3a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuMaxFreq.txt @@ -0,0 +1,4 @@ +select max(value) as maxFreq + from counter c + inner join cpu_counter_track t on c.track_id = t.id + where (name = 'cpufreq' or name='cpu_frequency'); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryCpuScale.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuScale.txt new file mode 100644 index 000000000..4087e55a8 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryCpuScale.txt @@ -0,0 +1 @@ +select id,session,sessionId,timeStamp,Data as data from processCpuInfo; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFiles.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFiles.txt new file mode 100644 index 000000000..a9e6f9b1d --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFiles.txt @@ -0,0 +1 @@ +select * from perf_files \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFunc.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFunc.txt new file mode 100644 index 000000000..d45889e6e --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfFunc.txt @@ -0,0 +1,9 @@ +select perf_callchain.callchain_id, +sample.sample_id, +sample.thread_id, +sample.timestamp, +perf_callchain.file_id, +perf_callchain.symbol_id + ,perf_callchain.vaddr_in_file + from perf_callchain inner join (select * from perf_sample where thread_id = %s) as sample + on sample.sample_id = perf_callchain.sample_id order by sample.id,perf_callchain.callchain_id desc ; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryPerfThread.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfThread.txt new file mode 100644 index 000000000..ef453d47a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryPerfThread.txt @@ -0,0 +1,2 @@ +select T.thread_name as threadName,T.thread_id as tid,T.process_id as pid +from perf_thread T inner join (select count(*) as count,thread_id from perf_sample group by thread_id) S on T.thread_id = S.thread_id and S.count>0; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryPrefTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryPrefTotalTime.txt new file mode 100644 index 000000000..9ca090c33 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryPrefTotalTime.txt @@ -0,0 +1 @@ +select max(timestamp) as endTime,min(timestamp) as startTime from perf_sample; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryProcess.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryProcess.txt new file mode 100644 index 000000000..5b69f8d6a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryProcess.txt @@ -0,0 +1,45 @@ +select + distinct process.pid as pid, + process.name as processName + from ( +-- select upid, 0 as utid from process_track +-- union +-- select upid, 0 as utid from process_counter_track +-- union +-- select upid, utid from thread_counter_track join thread using(utid) +-- union +-- select upid, utid from thread_track join thread using(utid) +-- union + select upid, utid from sched_slice join thread using(utid) group by utid +-- union +-- select upid, utid from ( +-- select distinct(utid) from cpu_profile_stack_sample +-- ) join thread using(utid) +-- union +-- select distinct(upid) as upid, 0 as utid from heap_profile_allocation +-- union +-- select distinct(upid) as upid, 0 as utid from heap_graph_object + ) the_tracks + left join (select upid, sum(dur) as total_dur + from sched join thread using(utid) + group by upid + ) using(upid) +-- left join ( +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_profile_allocation +-- union +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_graph_object +-- ) using (upid) + left join process using(upid) + -- where pid is not null + order by +-- hasHeapProfiles, + total_dur desc, + the_tracks.upid, + processName, + the_tracks.utid; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryThreadData.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryThreadData.txt new file mode 100644 index 000000000..825d710f8 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryThreadData.txt @@ -0,0 +1,6 @@ +select A.*, B.cpu, B.ts-TR.start_ts AS startTime,B.dur,B.state,IP.pid,IP.name as processName + from thread_state AS B + left join internal_thread as A + left join trace_bounds AS TR + left join internal_process AS IP on IP.id=upid + where A.id=B.utid and tid = %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryThreadsByPid.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryThreadsByPid.txt new file mode 100644 index 000000000..62e080f94 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryThreadsByPid.txt @@ -0,0 +1,51 @@ +select + the_tracks.upid, + the_tracks.utid, + total_dur as hasSched, +-- hasHeapProfiles, + process.pid as pid, + thread.tid as tid, + process.name as processName, + thread.name as threadName + from ( +-- select upid, 0 as utid from process_track +-- union +-- select upid, 0 as utid from process_counter_track +-- union +-- select upid, utid from thread_counter_track join thread using(utid) +-- union +-- select upid, utid from thread_track join thread using(utid) +-- union + select upid, utid from sched join thread using(utid) group by utid +-- union +-- select upid, utid from ( +-- select distinct(utid) from cpu_profile_stack_sample +-- ) join thread using(utid) +-- union +-- select distinct(upid) as upid, 0 as utid from heap_profile_allocation +-- union +-- select distinct(upid) as upid, 0 as utid from heap_graph_object + ) the_tracks + left join (select upid, sum(dur) as total_dur + from sched join thread using(utid) + group by upid + ) using(upid) +-- left join ( +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_profile_allocation +-- union +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_graph_object +-- ) using (upid) + left join thread using(utid) + left join process using(upid) + where pid = %s + order by +-- hasHeapProfiles, + total_dur desc, + the_tracks.upid, + the_tracks.utid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryTotalTime.txt new file mode 100644 index 000000000..fdf913301 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryTotalTime.txt @@ -0,0 +1 @@ +select start_ts,end_ts,end_ts-start_ts as total from trace_bounds; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/QueryVSYNCAPP.txt b/host/ohosprofiler/src/main/resources/sql-app/QueryVSYNCAPP.txt new file mode 100644 index 000000000..588ad6b7c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/QueryVSYNCAPP.txt @@ -0,0 +1,11 @@ +with track as ( + select process_counter_track.id as trackId, + process_counter_track.name as trackName, upid, process.pid, + process.name as processName, process.start_ts as startTs + --,process.end_ts as endTs + from process_counter_track + join process using(upid) + where trackName='VSYNC-app' + order by trackName +) +select c.*,c.ts-tb.start_ts startTime from counter c,trace_bounds tb where track_id in (select track.trackId from track); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-app/Views.txt b/host/ohosprofiler/src/main/resources/sql-app/Views.txt new file mode 100644 index 000000000..c9418a2ef --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-app/Views.txt @@ -0,0 +1,4 @@ +CREATE VIEW IF NOT EXISTS thread AS SELECT id as utid, * FROM internal_thread; +CREATE VIEW IF NOT EXISTS process AS SELECT id as upid, * FROM internal_process; +CREATE VIEW IF NOT EXISTS sched AS SELECT *, ts + dur as ts_end FROM sched_slice; +CREATE VIEW IF NOT EXISTS instants AS SELECT *, 0.0 as value FROM instant; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedCpuViews.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedCpuViews.txt new file mode 100644 index 000000000..0c01d189d --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedCpuViews.txt @@ -0,0 +1,53 @@ +--metrics +DROP VIEW if exists cpu_frequency_view; +CREATE VIEW cpu_frequency_view AS +SELECT + B.cpu, + A.ts as start_ts, + LEAD(A.ts, 1, (SELECT end_ts from trace_range)) + OVER (PARTITION by A.filter_id ORDER BY ts) AS end_ts, + LEAD(A.ts, 1, (SELECT end_ts from trace_range)) + OVER (PARTITION by A.filter_id ORDER BY ts) - ts AS dur, + value as freq +FROM measure AS A, cpu_measure_filter AS B +WHERE B.name = 'cpu_frequency' and A.filter_id=B.id; + +DROP VIEW if exists cpu_thread_view; +CREATE VIEW cpu_thread_view AS +SELECT S.ts, + S.ts + S.dur as end_ts, + S.cpu, + T.ipid, + S.itid AS itid, + P.pid as pid, + T.name AS thread_name, + P.name AS process_name +FROM thread AS T, sched_slice AS S, process as P +where T.id = S.itid and T.ipid=P.id; + +DROP VIEW if exists tmp; +CREATE VIEW tmp AS +SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts; + +DROP VIEW if exists cpu_per_thread; +-- CPU info aggregated per CPU and thread. +CREATE VIEW cpu_per_thread AS +SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name +FROM tmp +GROUP BY itid, cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedGetFunDataByTid.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedGetFunDataByTid.txt new file mode 100644 index 000000000..e244c7708 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedGetFunDataByTid.txt @@ -0,0 +1,19 @@ +select tid, + A.name as threadName, + is_main_thread, + c.callid as track_id, + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.parent_id, + c.id, + c.depth, + c.chainId, + c.spanId, + c.parentSpanId, + c.flag, + c.args +-- ,(case when category isnull then 'N/A' else category end) as cat +from thread A,trace_range D +left join callstack C on A.id = C.callid +where startTs not null and A.tid = %s \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryThreadsByPid.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryThreadsByPid.txt new file mode 100644 index 000000000..d8f0da72c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryThreadsByPid.txt @@ -0,0 +1 @@ +select thread.*,p.pid from thread left join process p on thread.ipid = p.id where pid = %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryTotalTime.txt new file mode 100644 index 000000000..5630c0710 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedQueryTotalTime.txt @@ -0,0 +1 @@ +select end_ts-start_ts as total from trace_range; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedSetTraceRangeStartTime.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedSetTraceRangeStartTime.txt new file mode 100644 index 000000000..6b310655a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedSetTraceRangeStartTime.txt @@ -0,0 +1 @@ +update trace_range set start_ts=%s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceCpu.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceCpu.txt new file mode 100644 index 000000000..e4e8a2d76 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceCpu.txt @@ -0,0 +1,33 @@ + select + itid as tid, + ipid as pid, + group_concat(cpu,",") as cpu, + group_concat(duration,",") as duration, + group_concat(min_freq,",") as min_freq, + group_concat(max_freq,",") as max_freq, + group_concat(avg_frequency,",") as avg_frequency, + process_name, + thread_name + from + ( + SELECT itid, + ipid, + cpu, + CAST(SUM(duration) AS INT) AS duration, + CAST(MIN(freq) AS INT) AS min_freq, + CAST(MAX(freq) AS INT) AS max_freq, + CAST((SUM(duration * freq) / SUM(duration)) AS INT) AS avg_frequency, + process_name, + thread_name + FROM (SELECT (MIN(cpu_frequency_view.end_ts, cpu_thread_view.end_ts) - MAX(cpu_frequency_view.start_ts, cpu_thread_view.ts)) AS duration, + freq, + cpu_thread_view.cpu as cpu, + itid, + ipid, + process_name, + thread_name + FROM cpu_frequency_view JOIN cpu_thread_view ON(cpu_frequency_view.cpu = cpu_thread_view.cpu) + WHERE cpu_frequency_view.start_ts < cpu_thread_view.end_ts AND cpu_frequency_view.end_ts > cpu_thread_view.ts + ) GROUP BY itid, cpu + ) +GROUP BY ipid, itid order by ipid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMem.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMem.txt new file mode 100644 index 000000000..f77805c58 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMem.txt @@ -0,0 +1,7 @@ +select max(value) as maxNum,min(value) as minNum,result.name,result.processName from measure inner join +( +select filter.id,filter.name,p.name as processName from process_measure_filter as filter +left join process as p +on filter.ipid=p.id where filter.name = "mem.rss.anon" +) as result on result.id = filter_id +where filter_id > 0 group by filter_id \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMemUnagg.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMemUnagg.txt new file mode 100644 index 000000000..806c82044 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMemUnagg.txt @@ -0,0 +1,13 @@ +select +processName, +group_concat(name) as name, +cast(group_concat(value) as varchar) as value, +cast(group_concat(ts) as varchar) as ts +from measure inner join +( +select filter.ipid,filter.id,filter.name,p.name as processName from process_measure_filter as filter +left join process as p +on filter.ipid=p.id where filter.name = "mem.rss.anon" or filter.name = "mem.rss.file" or filter.name = "mem.swap" or filter.name = "oom_score_adj" +) as result +on result.id = filter_id +group by processName,ipid order by ipid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMetadata.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMetadata.txt new file mode 100644 index 000000000..372c4e044 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceMetadata.txt @@ -0,0 +1,5 @@ +select cast(name as varchar) as name,cast(value as varchar) as value from meta +UNION +select 'start_ts',cast(start_ts as varchar) from trace_range +UNION +select 'end_ts',cast(end_ts as varchar) from trace_range \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceStats.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceStats.txt new file mode 100644 index 000000000..e103109cf --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceStats.txt @@ -0,0 +1 @@ +select event_name,stat_type,count,source,serverity from stat \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceTaskNames.txt b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceTaskNames.txt new file mode 100644 index 000000000..31dab8f4b --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/DistributedTraceTaskNames.txt @@ -0,0 +1,6 @@ +select P.id, + P.pid, + P.name as process_name, + group_concat(T.name,",") as thread_name +from process as P left join thread as T where P.id = T.ipid +group by pid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetAsyncEvents.txt b/host/ohosprofiler/src/main/resources/sql-self/GetAsyncEvents.txt new file mode 100644 index 000000000..e15485910 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetAsyncEvents.txt @@ -0,0 +1,2 @@ +select *,p.pid as pid,c.ts - t.start_ts as "startTime" +from callstack c,trace_range t left join process p on c.callid = p.id where cookie is not null; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetCpuUtilizationRate.txt b/host/ohosprofiler/src/main/resources/sql-self/GetCpuUtilizationRate.txt new file mode 100644 index 000000000..fb9853c49 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetCpuUtilizationRate.txt @@ -0,0 +1,19 @@ +with cpu as ( + select cpu,ts,dur,(case when ro < 99 then ro else 99 end) as ro , + (case when ro < 99 then stime+ro*cell else stime + 99 * cell end) as st, + (case when ro < 99 then stime + (ro+1)*cell else etime end) as et + from ( + select cpu,ts,A.dur,((ts+A.dur)-D.start_ts)/((D.end_ts-D.start_ts)/100) as ro,D.start_ts as stime,D.end_ts etime,(D.end_ts-D.start_ts)/100 as cell + from sched_slice A + left join trace_range D + left join thread B on A.itid = B.id + left join process C on B.ipid = C.id + where tid != 0 )) +select cpu,ro, + sum(case + when ts <= st and ts + dur <= et then (ts + dur - st) + when ts <= st and ts + dur > et then et-st + when ts > st and ts + dur <= et then dur + when ts > st and ts + dur > et then et - ts end)/cast(et-st as float) as rate +from cpu +group by cpu,ro \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetFunDataByTid.txt b/host/ohosprofiler/src/main/resources/sql-self/GetFunDataByTid.txt new file mode 100644 index 000000000..0cb7fdce6 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetFunDataByTid.txt @@ -0,0 +1,14 @@ +select tid, + A.name as threadName, + is_main_thread, + c.callid as track_id, + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.parent_id, + c.id, + c.depth +-- ,(case when category isnull then 'N/A' else category end) as cat +from thread A,trace_range D +left join callstack C on A.id = C.callid +where startTs not null and A.tid = %s \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetTabCounters.txt b/host/ohosprofiler/src/main/resources/sql-self/GetTabCounters.txt new file mode 100644 index 000000000..e05822194 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetTabCounters.txt @@ -0,0 +1,6 @@ +select t1.filter_id as trackId,t2.name,value, t1.ts - t3.start_ts as startTime +from measure t1 +left join process_measure_filter t2 on t1.filter_id = t2.id +left join trace_range t3 where filter_id in (%s) +and startTime <= %d +order by startTime asc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByProcess.txt b/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByProcess.txt new file mode 100644 index 000000000..b54267862 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByProcess.txt @@ -0,0 +1,18 @@ +--参数 1 cpus 数组,框选范围中选中的 cpu +--参数 2 leftNs 框选范围左边的时间,单位 ns +--参数 3 rightNs 框选范围右边的时间 单位 ns +select IP.name as process, + IP.pid as pid, + sum(B.dur) as wallDuration, + avg(B.dur) as avgDuration, + count(A.tid) as occurrences +from thread_state AS B + left join thread as A + left join trace_range AS TR + left join process AS IP +where B.itid = A.id + and A.ipid = IP.id + and B.cpu in (%s) + and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) +group by IP.name, IP.pid +order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByThread.txt b/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByThread.txt new file mode 100644 index 000000000..e40060fb0 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetTabCpuByThread.txt @@ -0,0 +1,20 @@ +--参数 1 cpus 数组,框选范围中选中的 cpu +--参数 2 leftNs 框选范围左边的时间,单位 ns +--参数 3 rightNs 框选范围右边的时间 单位 ns +select IP.name as process, + IP.pid as pid, + A.name as thread, + A.tid as tid, + sum(B.dur) as wallDuration, + avg(B.dur) as avgDuration, + count(A.tid) as occurrences +from thread_state AS B + left join thread as A + left join trace_range AS TR + left join process AS IP +where B.itid = A.id + and A.ipid = IP.id + and B.cpu in (%s) + and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) +group by IP.name, IP.pid, A.name, A.tid +order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetTabSlices.txt b/host/ohosprofiler/src/main/resources/sql-self/GetTabSlices.txt new file mode 100644 index 000000000..8092c179f --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetTabSlices.txt @@ -0,0 +1,15 @@ +--参数 1 tids 数组,框选范围中选中的 thread id 集合 +--参数 2 leftNs 框选范围左边的时间,单位 ns +--参数 3 rightNs 框选范围右边的时间 单位 ns +select + c.name as funName, + sum(c.dur) as wallDuration, + avg(c.dur) as avgDuration, + count(c.name) as occurrences +from thread A,trace_range D +left join callstack C on A.id = C.callid +where C.ts not null + and A.tid in (%s) + and not ((C.ts - D.start_ts + C.dur < %d) or (C.ts - D.start_ts > %d)) +group by c.name +order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetTabThreadStates.txt b/host/ohosprofiler/src/main/resources/sql-self/GetTabThreadStates.txt new file mode 100644 index 000000000..ec8e8f530 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetTabThreadStates.txt @@ -0,0 +1,20 @@ +--参数 1 tids 数组,框选范围中选中的 thread id 集合 +--参数 2 leftNs 框选范围左边的时间,单位 ns +--参数 3 rightNs 框选范围右边的时间 单位 ns +select + IP.name as process, + IP.pid, + A.name as thread, + A.tid, + B.state, + sum(B.dur) as wallDuration, + avg(B.dur) as avgDuration, + count(A.tid) as occurrences +from thread_state AS B +left join thread as A on A.id = B.itid +left join trace_range AS TR +left join process AS IP on IP.id=ipid +where A.tid in (%s) +and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) +group by IP.name, IP.pid, A.name, A.tid, B.state +order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/GetThreadFuncData.txt b/host/ohosprofiler/src/main/resources/sql-self/GetThreadFuncData.txt new file mode 100644 index 000000000..0a7b871ce --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/GetThreadFuncData.txt @@ -0,0 +1,16 @@ +select tid, + A.start_ts, + A.end_ts, + A.name as threadName, + is_main_thread, + c.callid as track_id, + c.ts-D.start_ts as startTs, + c.ts + c.dur as endTs, + c.dur, + c.name as funName, + c.depth, + c.parent_id, + c.id +from thread A,trace_range D +left join callstack C on A.id = C.callid +where startTs not null and A.tid = ${tid}; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryClockFrequency.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryClockFrequency.txt new file mode 100644 index 000000000..ddf770bfb --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryClockFrequency.txt @@ -0,0 +1,5 @@ +with freq as ( select measure.filter_id, measure.ts, measure.type, measure.value from clock_event_filter +left join measure +where clock_event_filter.name = '%s' and clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id +order by measure.ts) +select freq.filter_id,freq.ts - r.start_ts as ts,freq.type,freq.value from freq,trace_range r; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryClockList.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryClockList.txt new file mode 100644 index 000000000..4c0118c5c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryClockList.txt @@ -0,0 +1,20 @@ +with list as ( + select distinct name from clock_event_filter + where clock_event_filter.type = 'clock_set_rate' order by name +),freq as( + select measure.filter_id, measure.ts, measure.type, measure.value , clock_event_filter.name from clock_event_filter + left join measure + where clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id + order by measure.ts +),state as ( + select filter_id, ts, endts, endts-ts as dur, type, value,name from + (select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value,clock_event_filter.name from clock_event_filter,trace_range + left join measure + where clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id + order by measure.ts) +),count_freq as ( + select COUNT(*) num,name srcname from freq group by name +),count_state as ( + select COUNT(*) num,name srcname from state group by name +) +select count_freq.srcname||' Frequency' as name,* from count_freq union select count_state.srcname||' State' as name,* from count_state order by name; diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryClockState.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryClockState.txt new file mode 100644 index 000000000..37e696ac3 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryClockState.txt @@ -0,0 +1,8 @@ +with state as ( +select filter_id, ts, endts, endts-ts as dur, type, value from +(select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value from clock_event_filter,trace_range +left join measure +where clock_event_filter.name = '%s' and clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id +order by measure.ts)) +-- select * from state; +select s.filter_id,s.ts-r.start_ts as ts,s.type,s.value,s.dur from state s,trace_range r; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpu.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpu.txt new file mode 100644 index 000000000..97ee3be52 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpu.txt @@ -0,0 +1 @@ +select cpu from cpu_measure_filter where name='cpuidle' order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuData.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuData.txt new file mode 100644 index 000000000..4a252b307 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuData.txt @@ -0,0 +1,24 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list; diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataCount.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataCount.txt new file mode 100644 index 000000000..4a252b307 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataCount.txt @@ -0,0 +1,24 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list; diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataLimit.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataLimit.txt new file mode 100644 index 000000000..7ea3d5c27 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuDataLimit.txt @@ -0,0 +1,24 @@ +with list as (SELECT + IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name, + C.id as schedId, + A.tid, + A.id, + A.type, + B.dur, + B.ts - TR.start_ts AS startTime, + C.priority, + C.end_state +from thread_state AS B + left join thread as A + left join sched_slice AS C + left join trace_range AS TR + left join process AS IP +where B.itid = A.id and B.cpu = %s + and B.itid = C.itid and B.ts = C.ts + and A.ipid = IP.id + and startTime between %s and %s +order by B.rowid) +select * from list order by random() limit %s; diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreq.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreq.txt new file mode 100644 index 000000000..bb7b999b3 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreq.txt @@ -0,0 +1 @@ +select cpu from cpu_measure_filter where (name='cpufreq' or name='cpu_frequency') order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreqData.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreqData.txt new file mode 100644 index 000000000..b86902060 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuFreqData.txt @@ -0,0 +1,5 @@ +select cpu,value,ts-tb.start_ts as startNS +from measure c ,trace_range tb +inner join cpu_measure_filter t on c.filter_id = t.id +where (name = 'cpufreq' or name='cpu_frequency') and cpu= %d +order by ts; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMax.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMax.txt new file mode 100644 index 000000000..4031f0abf --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMax.txt @@ -0,0 +1 @@ +select cpu from sched_slice order by cpu desc limit 1 \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMaxFreq.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMaxFreq.txt new file mode 100644 index 000000000..29b0e503c --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryCpuMaxFreq.txt @@ -0,0 +1,4 @@ +select max(value) as maxFreq +from measure c +inner join cpu_measure_filter t on c.filter_id = t.id +where (name = 'cpufreq' or name='cpu_frequency'); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcess.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcess.txt new file mode 100644 index 000000000..81d23d61e --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcess.txt @@ -0,0 +1,16 @@ +select + distinct process_view.pid as pid, + process_view.name as processName + from ( + select ipid, itid from sched_slice join thread_view using(itid) group by itid + ) the_tracks + left join (select ipid, sum(dur) as total_dur + from sched_view join thread_view using(itid) + group by ipid + ) using(ipid) + left join process_view using(ipid) + order by + total_dur desc, + the_tracks.ipid, + processName, + the_tracks.itid; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessData.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessData.txt new file mode 100644 index 000000000..48c28bfdc --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessData.txt @@ -0,0 +1,9 @@ +select ta.id,type, ts, dur, ta.cpu, itid as utid, state + ,ts-tb.start_ts as startTime,tc.tid,tc.pid,tc.process,tc.thread +from thread_state ta,trace_range tb +left join ( + select it.id,tid,pid,ip.name as process,it.name as thread from thread as it left join process ip on it.ipid = ip.id + ) tc on ta.itid = tc.id +where tc.pid = %d +and ta.cpu is not null +order by startTime; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMem.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMem.txt new file mode 100644 index 000000000..7764b5479 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMem.txt @@ -0,0 +1,7 @@ +select process_measure_filter.id as trackId, + process_measure_filter.name as trackName, + ipid as upid, + process_view.pid, + process_view.name as processName +from process_measure_filter join process_view using (ipid) +order by trackName; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMemData.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMemData.txt new file mode 100644 index 000000000..da6b8c6eb --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessMemData.txt @@ -0,0 +1,5 @@ +select c.type, + ts, value, + filter_id as track_id, + c.ts-tb.start_ts startTime +from measure c,trace_range tb where filter_id = %d; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessNOrder.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessNOrder.txt new file mode 100644 index 000000000..a330df5d6 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessNOrder.txt @@ -0,0 +1 @@ +select pid,name as processName from process; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreads.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreads.txt new file mode 100644 index 000000000..c3b45d3b0 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreads.txt @@ -0,0 +1,21 @@ +select + the_tracks.ipid as upid, + the_tracks.itid as utid, + total_dur as hasSched, + process_view.pid as pid, + thread_view.tid as tid, + process_view.name as processName, + thread_view.name as threadName +from ( + select ipid, itid from sched_view join thread_view using(itid) group by itid +) the_tracks +left join (select ipid, sum(dur) as total_dur + from sched_view join thread_view using(itid) + group by ipid +) using(ipid) +left join thread_view using(itid) +left join process_view using(ipid) +order by + total_dur desc, + the_tracks.ipid, + the_tracks.itid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreadsNOrder.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreadsNOrder.txt new file mode 100644 index 000000000..4de4dc9fc --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryProcessThreadsNOrder.txt @@ -0,0 +1,7 @@ +select p.id as upid, + t.id as utid, + p.pid, + t.tid, + p.name as processName, + t.name as threadName + from thread t left join process p on t.ipid = p.id; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryScreenState.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryScreenState.txt new file mode 100644 index 000000000..8d5f95b25 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryScreenState.txt @@ -0,0 +1 @@ +select m.type, m.ts-r.start_ts as ts, value, filter_id from measure m,trace_range r where filter_id in (select id from process_measure_filter where name = 'ScreenState'); diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryThreadData.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryThreadData.txt new file mode 100644 index 000000000..8b90faf00 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryThreadData.txt @@ -0,0 +1,7 @@ +select A.id, A.type, A.tid, A.name, A.start_ts, A.end_ts, A.ipid as upid, A.is_main_thread + , B.cpu, B.ts-TR.start_ts AS startTime,B.dur,B.state,IP.pid,IP.name as processName + from thread_state AS B + left join thread as A + left join trace_range AS TR + left join process AS IP on IP.id=ipid + where A.id=B.itid and tid = %s \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryThreadsByPid.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryThreadsByPid.txt new file mode 100644 index 000000000..01933c480 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryThreadsByPid.txt @@ -0,0 +1,22 @@ +select + the_tracks.ipid as upid, + the_tracks.itid as utid, + total_dur as hasSched, + process_view.pid as pid, + thread_view.tid as tid, + process_view.name as processName, + thread_view.name as threadName + from ( + select ipid, itid from sched_view join thread_view using(itid) group by itid + ) the_tracks + left join (select ipid, sum(dur) as total_dur + from sched_view join thread_view using(itid) + group by ipid + ) using(ipid) + left join thread_view using(itid) + left join process_view using(ipid) + where pid = %s + order by + total_dur desc, + the_tracks.ipid, + the_tracks.itid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryTotalTime.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryTotalTime.txt new file mode 100644 index 000000000..5630c0710 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryTotalTime.txt @@ -0,0 +1 @@ +select end_ts-start_ts as total from trace_range; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_Desc.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_Desc.txt new file mode 100644 index 000000000..d03d458c8 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_Desc.txt @@ -0,0 +1,2 @@ +This is the interval from when the task became eligible to run +(e.g.because of notifying a wait queue it was a suspended on) to when it started running. \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeThread.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeThread.txt new file mode 100644 index 000000000..524edc94f --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeThread.txt @@ -0,0 +1,7 @@ +select TB.tid,TB.name as thread,TA.cpu,TC.pid,TC.name as process +from sched_view TA +left join thread TB on TA.itid = TB.id +left join process TC on TB.ipid = TC.id +where itid = (select itid from raw where name = 'sched_waking' and ts = %d ) + and TA.ts < %d + and Ta.ts + Ta.dur >= %d \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeTime.txt b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeTime.txt new file mode 100644 index 000000000..6f520157e --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/QueryWakeUpThread_WakeTime.txt @@ -0,0 +1,11 @@ +select * from + ( select ts as wakeTs,start_ts from instants_view,trace_range + where name = 'sched_waking' + and ref = %s + and ts < start_ts + %s + order by ts desc limit 1) TA + left join + (select ts as preRow from sched_view,trace_range + where itid = %s + and ts < start_ts + %s + order by ts desc limit 1) TB \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql-self/Views.txt b/host/ohosprofiler/src/main/resources/sql-self/Views.txt new file mode 100644 index 000000000..c6c932254 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql-self/Views.txt @@ -0,0 +1,4 @@ +CREATE VIEW IF NOT EXISTS thread_view AS SELECT id as itid, * FROM thread; +CREATE VIEW IF NOT EXISTS process_view AS SELECT id as ipid, * FROM process; +CREATE VIEW IF NOT EXISTS sched_view AS SELECT *, ts + dur as ts_end FROM sched_slice; +CREATE VIEW IF NOT EXISTS instants_view AS SELECT *, 0.0 as value FROM instant; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetFunDataByTid.txt b/host/ohosprofiler/src/main/resources/sql/GetFunDataByTid.txt index efaf10a39..dc523087c 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetFunDataByTid.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetFunDataByTid.txt @@ -5,6 +5,10 @@ select tid, c.ts-D.start_ts as startTs, c.dur, c.name as funName, + c.parent_id, + c.id, + c.stack_id, + c.parent_stack_id, c.depth -- ,(case when category isnull then 'N/A' else category end) as cat from internal_thread A,trace_bounds D diff --git a/host/ohosprofiler/src/main/resources/sql/GetTabCounters.txt b/host/ohosprofiler/src/main/resources/sql/GetTabCounters.txt index 90bb37f3b..398eeae91 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetTabCounters.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetTabCounters.txt @@ -1,8 +1,6 @@ --- delta value 计算规则 框选范围内 last value - first value --- rate/s 计算规则 框选范围时间内 delta value / range time(单位换算成 s ) --- weight avg value 计算规则 以 value 在所选时间区域内 时间占比为权重,计算加权平均值 --- count 计算规则 计算选中范围内的 count 数量 --- first value 计算规则 框选区间内 first value --- last value 计算规则 框选区间内 last value --- min value 计算规则 框选区间内 min value --- max value 计算规则 框选区间内 max value \ No newline at end of file +select t1.track_id as trackId,t2.name,value, t1.ts - t3.start_ts as startTime +from counter t1 +left join process_counter_track t2 on t1.track_id = t2.id +left join trace_bounds t3 where track_id in (%s) +and startTime <= %d +order by startTime asc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetTabCpuByProcess.txt b/host/ohosprofiler/src/main/resources/sql/GetTabCpuByProcess.txt index 0af4bcb23..bc7be0d88 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetTabCpuByProcess.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetTabCpuByProcess.txt @@ -1,8 +1,8 @@ --参数 1 cpus 数组,框选范围中选中的 cpu --参数 2 leftNs 框选范围左边的时间,单位 ns --参数 3 rightNs 框选范围右边的时间 单位 ns -select IP.name as processName, - IP.pid as processId, +select IP.name as process, + IP.pid as pid, sum(B.dur) as wallDuration, avg(B.dur) as avgDuration, count(A.tid) as occurrences @@ -12,7 +12,7 @@ from thread_state AS B left join internal_process AS IP where B.utid = A.id and A.upid = IP.id - and B.cpu in (${cpus}) - and not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) + and B.cpu in (%s) + and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) group by IP.name, IP.pid order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetTabCpuByThread.txt b/host/ohosprofiler/src/main/resources/sql/GetTabCpuByThread.txt index 76652b682..5c5cd5442 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetTabCpuByThread.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetTabCpuByThread.txt @@ -1,10 +1,10 @@ --参数 1 cpus 数组,框选范围中选中的 cpu --参数 2 leftNs 框选范围左边的时间,单位 ns --参数 3 rightNs 框选范围右边的时间 单位 ns -select IP.name as processName, - IP.pid as processId, - A.name as threadName, - A.tid as threadId, +select IP.name as process, + IP.pid as pid, + A.name as thread, + A.tid as tid, sum(B.dur) as wallDuration, avg(B.dur) as avgDuration, count(A.tid) as occurrences @@ -14,7 +14,7 @@ from thread_state AS B left join internal_process AS IP where B.utid = A.id and A.upid = IP.id - and B.cpu in (${cpus}) - and not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) + and B.cpu in (%s) + and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) group by IP.name, IP.pid, A.name, A.tid order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetTabSlices.txt b/host/ohosprofiler/src/main/resources/sql/GetTabSlices.txt index c8fd2bc4e..c4c29b607 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetTabSlices.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetTabSlices.txt @@ -10,7 +10,7 @@ from internal_thread A,trace_bounds D left join thread_track B on A.id = B.utid left join internal_slice C on B.id = C.track_id where C.ts not null - and A.tid in (${tids}) - and not ((C.ts - D.start_ts + C.dur < ${leftNs}) or (C.ts - D.start_ts > ${rightNs})) + and A.tid in (%s) + and not ((C.ts - D.start_ts + C.dur < %d) or (C.ts - D.start_ts > %d)) group by c.name order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetTabThreadStates.txt b/host/ohosprofiler/src/main/resources/sql/GetTabThreadStates.txt index e6c9f0eae..46574b701 100644 --- a/host/ohosprofiler/src/main/resources/sql/GetTabThreadStates.txt +++ b/host/ohosprofiler/src/main/resources/sql/GetTabThreadStates.txt @@ -2,9 +2,9 @@ --参数 2 leftNs 框选范围左边的时间,单位 ns --参数 3 rightNs 框选范围右边的时间 单位 ns select - IP.name as processName, + IP.name as process, IP.pid, - A.name as threadName, + A.name as thread, A.tid, B.state, sum(B.dur) as wallDuration, @@ -14,7 +14,7 @@ from thread_state AS B left join internal_thread as A on A.id = B.utid left join trace_bounds AS TR left join internal_process AS IP on IP.id=upid -where A.tid in (${tids}) -and not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) +where A.tid in (%s) +and not ((B.ts - TR.start_ts + B.dur < %d) or (B.ts - TR.start_ts > %d)) group by IP.name, IP.pid, A.name, A.tid, B.state order by wallDuration desc; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/GetThreadFuncData.txt b/host/ohosprofiler/src/main/resources/sql/GetThreadFuncData.txt new file mode 100644 index 000000000..58c18848a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/GetThreadFuncData.txt @@ -0,0 +1,17 @@ +select tid, + A.start_ts, + A.end_ts, + A.name as threadName, + is_main_thread, + c.track_id, + c.ts-D.start_ts as startTs, + c.ts + c.dur as endTs, + c.dur, + c.name as funName, + c.depth, + c.parent_id, + c.id +from internal_thread A,trace_bounds D +left join thread_track B on A.id = B.utid +left join internal_slice C on B.id = C.track_id +where startTs not null and A.tid = ${tid}; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpu.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpu.txt new file mode 100644 index 000000000..c5d47ad60 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpu.txt @@ -0,0 +1 @@ +select cpu from cpu_counter_track where name='cpuidle' order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuData.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuData.txt index 8a4ee52b6..e8a3f11b8 100644 --- a/host/ohosprofiler/src/main/resources/sql/QueryCpuData.txt +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuData.txt @@ -1,4 +1,4 @@ -SELECT IP.name as processName, +with list as ( SELECT IP.name as processName, IP.name processCmdLine, IP.pid as processId,B.cpu, A.name,C.id as schedId, @@ -14,4 +14,6 @@ from thread_state AS B where B.utid = A.id and B.cpu = %s and B.utid = C.utid and B.ts = C.ts and A.upid = IP.id -order by B.rowid \ No newline at end of file + and startTime between %s and %s +order by B.rowid ) +select * from list; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuDataCount.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuDataCount.txt new file mode 100644 index 000000000..e8a3f11b8 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuDataCount.txt @@ -0,0 +1,19 @@ +with list as ( SELECT IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name,C.id as schedId, + A.tid, + A.id, A.type, + B.dur, B.ts - TR.start_ts AS startTime, + C.priority, C.end_state +from thread_state AS B + left join internal_thread as A + left join sched_slice AS C + left join trace_bounds AS TR + left join internal_process AS IP +where B.utid = A.id and B.cpu = %s + and B.utid = C.utid and B.ts = C.ts + and A.upid = IP.id + and startTime between %s and %s +order by B.rowid ) +select * from list; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuDataLimit.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuDataLimit.txt new file mode 100644 index 000000000..6281e8f3e --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuDataLimit.txt @@ -0,0 +1,19 @@ +with list as ( SELECT IP.name as processName, + IP.name processCmdLine, + IP.pid as processId,B.cpu, + A.name,C.id as schedId, + A.tid, + A.id, A.type, + B.dur, B.ts - TR.start_ts AS startTime, + C.priority, C.end_state +from thread_state AS B + left join internal_thread as A + left join sched_slice AS C + left join trace_bounds AS TR + left join internal_process AS IP +where B.utid = A.id and B.cpu = %s + and B.utid = C.utid and B.ts = C.ts + and A.upid = IP.id + and startTime between %s and %s +order by B.rowid ) +select * from list order by random() limit %s; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuFreq.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuFreq.txt new file mode 100644 index 000000000..a9414650b --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuFreq.txt @@ -0,0 +1 @@ +select cpu from cpu_counter_track where (name='cpufreq' or name='cpu_frequency') order by cpu; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuFreqData.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuFreqData.txt new file mode 100644 index 000000000..a904c154a --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuFreqData.txt @@ -0,0 +1,5 @@ +select cpu,value,ts-tb.start_ts as startNS +from counter c ,trace_bounds tb +inner join cpu_counter_track t on c.track_id = t.id +where (name = 'cpufreq' or name='cpu_frequency') and cpu= %d +order by ts; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuMax.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuMax.txt new file mode 100644 index 000000000..4031f0abf --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuMax.txt @@ -0,0 +1 @@ +select cpu from sched_slice order by cpu desc limit 1 \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryCpuMaxFreq.txt b/host/ohosprofiler/src/main/resources/sql/QueryCpuMaxFreq.txt new file mode 100644 index 000000000..3895682fc --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryCpuMaxFreq.txt @@ -0,0 +1,4 @@ +select max(value) as maxFreq +from counter c +inner join cpu_counter_track t on c.track_id = t.id +where (name = 'cpufreq' or name='cpu_frequency'); \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryProcessData.txt b/host/ohosprofiler/src/main/resources/sql/QueryProcessData.txt new file mode 100644 index 000000000..c83ab2f89 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryProcessData.txt @@ -0,0 +1,8 @@ +select ta.*,ts-tb.start_ts as startTime,tc.tid,tc.pid,tc.process,tc.thread +from thread_state ta,trace_bounds tb +left join ( + select it.id,tid,pid,ip.name as process,it.name as thread from thread as it left join process ip on it.upid = ip.id + ) tc on ta.utid = tc.id +where tc.pid = %d +and ta.cpu is not null +order by startTime \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryProcessMem.txt b/host/ohosprofiler/src/main/resources/sql/QueryProcessMem.txt new file mode 100644 index 000000000..1e666eded --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryProcessMem.txt @@ -0,0 +1,7 @@ +select process_counter_track.id as trackId, + process_counter_track.name as trackName, + upid, + process.pid, + process.name as processName +from process_counter_track join process using (upid) +order by trackName; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryProcessMemData.txt b/host/ohosprofiler/src/main/resources/sql/QueryProcessMemData.txt new file mode 100644 index 000000000..23884eb5f --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryProcessMemData.txt @@ -0,0 +1 @@ +select c.*,c.ts-tb.start_ts startTime from counter c,trace_bounds tb where track_id = %d; \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryProcessThreads.txt b/host/ohosprofiler/src/main/resources/sql/QueryProcessThreads.txt index 616943926..026a9cf4a 100644 --- a/host/ohosprofiler/src/main/resources/sql/QueryProcessThreads.txt +++ b/host/ohosprofiler/src/main/resources/sql/QueryProcessThreads.txt @@ -20,7 +20,8 @@ select -- union -- select upid, utid from ( -- select distinct(utid) from cpu_profile_stack_sample --- ) join thread using(utid) + "-- union +-- ) join thread using(utid) +-- union -- select distinct(upid) as upid, 0 as utid from heap_profile_allocation -- union -- select distinct(upid) as upid, 0 as utid from heap_graph_object diff --git a/host/ohosprofiler/src/main/resources/sql/QueryThreadsByPid.txt b/host/ohosprofiler/src/main/resources/sql/QueryThreadsByPid.txt new file mode 100644 index 000000000..62e080f94 --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/QueryThreadsByPid.txt @@ -0,0 +1,51 @@ +select + the_tracks.upid, + the_tracks.utid, + total_dur as hasSched, +-- hasHeapProfiles, + process.pid as pid, + thread.tid as tid, + process.name as processName, + thread.name as threadName + from ( +-- select upid, 0 as utid from process_track +-- union +-- select upid, 0 as utid from process_counter_track +-- union +-- select upid, utid from thread_counter_track join thread using(utid) +-- union +-- select upid, utid from thread_track join thread using(utid) +-- union + select upid, utid from sched join thread using(utid) group by utid +-- union +-- select upid, utid from ( +-- select distinct(utid) from cpu_profile_stack_sample +-- ) join thread using(utid) +-- union +-- select distinct(upid) as upid, 0 as utid from heap_profile_allocation +-- union +-- select distinct(upid) as upid, 0 as utid from heap_graph_object + ) the_tracks + left join (select upid, sum(dur) as total_dur + from sched join thread using(utid) + group by upid + ) using(upid) +-- left join ( +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_profile_allocation +-- union +-- select +-- distinct(upid) as upid, +-- true as hasHeapProfiles +-- from heap_graph_object +-- ) using (upid) + left join thread using(utid) + left join process using(upid) + where pid = %s + order by +-- hasHeapProfiles, + total_dur desc, + the_tracks.upid, + the_tracks.utid \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/QueryWakeUpThread_WakeThread.txt b/host/ohosprofiler/src/main/resources/sql/QueryWakeUpThread_WakeThread.txt index 660b60d1a..75fbc956a 100644 --- a/host/ohosprofiler/src/main/resources/sql/QueryWakeUpThread_WakeThread.txt +++ b/host/ohosprofiler/src/main/resources/sql/QueryWakeUpThread_WakeThread.txt @@ -2,6 +2,6 @@ select TB.tid,TB.name as thread ,TA.cpu,TC.pid,TC.name as process from sched TA left join internal_thread TB on TA.utid = TB.id left join internal_process TC on TB.upid = TC.id -where utid = (select utid from raw where name = 'sched_waking' and ts = wakeup_ts ) - and TA.ts < wakeup_ts - and Ta.ts + Ta.dur >= wakeup_ts \ No newline at end of file +where utid = (select utid from raw where name = 'sched_waking' and ts = %d ) + and TA.ts < %d + and Ta.ts + Ta.dur >= %d \ No newline at end of file diff --git a/host/ohosprofiler/src/main/resources/sql/Views.txt b/host/ohosprofiler/src/main/resources/sql/Views.txt new file mode 100644 index 000000000..c9418a2ef --- /dev/null +++ b/host/ohosprofiler/src/main/resources/sql/Views.txt @@ -0,0 +1,4 @@ +CREATE VIEW IF NOT EXISTS thread AS SELECT id as utid, * FROM internal_thread; +CREATE VIEW IF NOT EXISTS process AS SELECT id as upid, * FROM internal_process; +CREATE VIEW IF NOT EXISTS sched AS SELECT *, ts + dur as ts_end FROM sched_slice; +CREATE VIEW IF NOT EXISTS instants AS SELECT *, 0.0 as value FROM instant; \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/Config.java b/host/ohosprofiler/src/test/java/ohos/devtools/Config.java new file mode 100644 index 000000000..650a75ab9 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/Config.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools; + +/** + * Config + * + * @date 2021/09/03 11:25 + */ +public class Config { + /** + * TRACE SYS + */ + public static final String TRACE_SYS = "/Users/fangzhen/Downloads/trace_db/trace_sys.db"; + + /** + * TRACE APP + */ + public static final String TRACE_APP = "/Users/fangzhen/Downloads/trace_db/trace_app.db"; + + /** + * TRACE CPU + */ + public static final String TRACE_CPU = "/Users/fangzhen/Downloads/trace_db/trace_cpu.db"; + + /** + * TRACE PREF + */ + public static final String TRACE_PREF = "/Users/fangzhen/Downloads/trace_db/trace_pref.db"; + + /** + * TRACE DISTRIBUTED A + */ + public static final String TRACE_DISTRIBUTED_A = "/Users/fangzhen/Downloads/trace_db/trace_distributed_deviceA.db"; + + /** + * TRACE DISTRIBUTED B + */ + public static final String TRACE_DISTRIBUTED_B = "/Users/fangzhen/Downloads/trace_db/trace_distributed_deviceB.db"; +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApiTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApiTest.java index be8c7c085..fec0ec612 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApiTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databaseapi/DataBaseApiTest.java @@ -1,980 +1,1062 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databaseapi; - -import com.alibaba.druid.pool.DruidDataSource; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * @version 1.0 - * @date 2021/03/22 16:07 - **/ -public class DataBaseApiTest { - private List processMemInfo; - private List processMemInfoIndex; - - /** - * functional testing init - * - * @tc.name: setUp - * @tc.number: OHOS_JAVA_database_DataBaseApi_setUp_0001 - * @tc.desc: setUp - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Before - public void setUp() { - processMemInfo = new ArrayList() { - { - add("id INTEGER primary key autoincrement not null"); - add("sessionId INTEGER NOT NULL"); - add("session INTEGER NOT NULL"); - add("timeStamp Long NOT NULL"); - add("Data BLOB NOT NULL"); - } - }; - processMemInfoIndex = new ArrayList() { - { - add("id"); - add("sessionId"); - add("timeStamp"); - } - }; - SessionManager.getInstance().setDevelopMode(true); - } - - /** - * functional testing init - * - * @tc.name: init DataSourceManager - * @tc.number: OHOS_JAVA_database_DataBaseApi_initDataSourceManager_0001 - * @tc.desc: init DataSourceManager - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDataSourceManager() { - try { - DataBaseApi.getInstance().initDataSourceManager(); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing init - * - * @tc.name: init DataSourceManager - * @tc.number: OHOS_JAVA_database_DataBaseApi_initDataSourceManager_0002 - * @tc.desc: init DataSourceManager - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDataSourceManager02() { - try { - DataBaseApi.getInstance().initDataSourceManager(); - DataBaseApi.getInstance().initDataSourceManager(); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get DefaultDataBase Connect - * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0001 - * @tc.desc: get DefaultDataBase Connect - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getDefaultDataBaseConnect01() { - Optional res = null; - try { - DataBaseApi.getInstance().initDataSourceManager(); - res = DataBaseApi.getInstance().getDefaultDataBaseConnect(); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get DefaultDataBase Connect - * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0002 - * @tc.desc: get DefaultDataBase Connect - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getDefaultDataBaseConnect02() { - Optional res = null; - try { - DataBaseApi.getInstance().initDataSourceManager(); - res = DataBaseApi.getInstance().getDefaultDataBaseConnect(); - Assert.assertTrue(res.isPresent()); - Connection conn = res.get(); - Assert.assertNotNull(conn); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get DefaultDataBase Connect - * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0003 - * @tc.desc: get DefaultDataBase Connect - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getDefaultDataBaseConnect03() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getDefaultDataBaseConnect(); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get DefaultDataBase Connect - * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0004 - * @tc.desc: get DefaultDataBase Connect - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getDefaultDataBaseConnect04() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getDefaultDataBaseConnect(); - Assert.assertTrue(res.isPresent()); - Connection cc = res.get(); - Assert.assertNotNull(cc); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By Table - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0001 - * @tc.desc: get Connect By Table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectByTableTest01() { - Optional res = null; - try { - DataBaseApi.getInstance().initDataSourceManager(); - res = DataBaseApi.getInstance().getConnectByTable("DeviceInfo"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By Table - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0002 - * @tc.desc: get Connect By Table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectByTableTest02() { - Optional res = null; - try { - DataBaseApi.getInstance().initDataSourceManager(); - res = DataBaseApi.getInstance().getConnectByTable(""); - Assert.assertFalse(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By Table - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0003 - * @tc.desc: get Connect By Table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectByTableTest03() { - Optional res = null; - try { - DataBaseApi.getInstance().initDataSourceManager(); - res = DataBaseApi.getInstance().getConnectByTable(null); - Assert.assertFalse(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By Table - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0004 - * @tc.desc: get Connect By Table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectByTableTest04() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectByTable("DeviceInfo"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By Table - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0005 - * @tc.desc: get Connect By Table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectByTableTest05() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectByTable(""); - Assert.assertFalse(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By dbname - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0001 - * @tc.desc: get Connect By dbname - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectBydbnameTest01() { - Optional res = DataBaseApi.getInstance().getConnectBydbname("defaultDB"); - Assert.assertTrue(res.isPresent()); - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By dbname - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0002 - * @tc.desc: get Connect By dbname - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectBydbnameTest02() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectBydbname("defaultDB"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By dbname - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0003 - * @tc.desc: get Connect By dbname - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectBydbnameTest03() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectBydbname("test"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By dbname - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0004 - * @tc.desc: get Connect By dbname - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectBydbnameTest04() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectBydbname("test"); - Assert.assertTrue(res.isPresent()); - res = DataBaseApi.getInstance().getConnectBydbname("test"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get Connect - * - * @tc.name: get Connect By dbname - * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0005 - * @tc.desc: get Connect By dbname - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getConnectBydbnameTest05() { - Optional res = null; - try { - res = DataBaseApi.getInstance().getConnectBydbname("defaultDB"); - Assert.assertTrue(res.isPresent()); - res = DataBaseApi.getInstance().getConnectBydbname("test"); - Assert.assertTrue(res.isPresent()); - } catch (Exception exception) { - Assert.assertTrue(res.isPresent()); - } - } - - /** - * functional testing get DataBaseName - * - * @tc.name: get Pool By DataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0001 - * @tc.desc: get Pool By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getPoolByDataBaseNameTest01() { - DataSource res = null; - try { - res = DataBaseApi.getInstance().getPoolByDataBaseName(""); - Assert.assertNotNull(res); - } catch (Exception exception) { - Assert.assertNotNull(res); - } - } - - /** - * functional testing get DataBaseName - * - * @tc.name: get Pool By DataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0002 - * @tc.desc: get Pool By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getPoolByDataBaseNameTest02() { - DataSource res = null; - try { - res = DataBaseApi.getInstance().getPoolByDataBaseName(null); - Assert.assertNotNull(res); - } catch (Exception exception) { - Assert.assertNotNull(res); - } - } - - /** - * functional testing get DataBaseName - * - * @tc.name: get Pool By DataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0003 - * @tc.desc: get Pool By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getPoolByDataBaseNameTest03() { - DataSource res = null; - try { - res = DataBaseApi.getInstance().getPoolByDataBaseName("test"); - Assert.assertNotNull(res); - } catch (Exception exception) { - Assert.assertNotNull(res); - } - } - - /** - * functional testing get DataBaseName - * - * @tc.name: get Pool By DataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0004 - * @tc.desc: get Pool By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getPoolByDataBaseNameTest04() { - DataSource res = null; - try { - res = DataBaseApi.getInstance().getPoolByDataBaseName("test"); - Assert.assertNotNull(res); - res = DataBaseApi.getInstance().getPoolByDataBaseName("test"); - Assert.assertNotNull(res); - } catch (Exception exception) { - Assert.assertNotNull(res); - } - } - - /** - * functional testing get DataBaseName - * - * @tc.name: get Pool By DataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0005 - * @tc.desc: get Pool By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getPoolByDataBaseNameTest05() { - DataSource res = null; - try { - res = DataBaseApi.getInstance().getPoolByDataBaseName(null); - Assert.assertNotNull(res); - res = DataBaseApi.getInstance().getPoolByDataBaseName("test"); - Assert.assertNotNull(res); - } catch (Exception exception) { - Assert.assertNotNull(res); - } - } - - /** - * functional testing register table - * - * @tc.name: register table - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0001 - * @tc.desc: register table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerTableTest01() { - try { - DataBaseApi.getInstance().registerTable("test", "ttest"); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register table - * - * @tc.name: register table - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0002 - * @tc.desc: register table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerTableTest02() { - try { - DataBaseApi.getInstance().registerTable("", "ttest"); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register table - * - * @tc.name: register table - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0003 - * @tc.desc: register table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerTableTest03() { - try { - DataBaseApi.getInstance().registerTable("test", ""); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register table - * - * @tc.name: register table - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0004 - * @tc.desc: register table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerTableTest04() { - try { - DataBaseApi.getInstance().registerTable(null, null); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register table - * - * @tc.name: register table - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0005 - * @tc.desc: register table - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerTableTest05() { - try { - DataBaseApi.getInstance().registerTable("test", "ttest"); - Assert.assertTrue(true); - DataBaseApi.getInstance().registerTable("test", "ttest"); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register DataSource - * - * @tc.name: register DataSource - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0001 - * @tc.desc: register DataSource - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerDataSourceTest01() { - try { - DataBaseApi.getInstance().registerDataSource(null, null); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register DataSource - * - * @tc.name: register DataSource - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0002 - * @tc.desc: register DataSource - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerDataSourceTest02() { - try { - DataBaseApi.getInstance().registerDataSource("dataBase", null); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register DataSource - * - * @tc.name: register DataSource - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0003 - * @tc.desc: register DataSource - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerDataSourceTest03() { - try { - DataBaseApi.getInstance().registerDataSource("dataBase", new DruidDataSource()); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register DataSource - * - * @tc.name: register DataSource - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0004 - * @tc.desc: register DataSource - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerDataSourceTest04() { - try { - DataBaseApi.getInstance().registerDataSource(null, new DruidDataSource()); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing register DataSource - * - * @tc.name: register DataSource - * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0005 - * @tc.desc: register DataSource - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void registerDataSourceTest05() { - try { - DataBaseApi.getInstance().registerDataSource("dataBase", new DruidDataSource()); - Assert.assertTrue(true); - DataBaseApi.getInstance().registerDataSource(null, new DruidDataSource()); - Assert.assertTrue(true); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing Database creation - * - * @tc.name: Database creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0001 - * @tc.desc: Database creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest01() { - try { - boolean res = DataBaseApi.getInstance().createDataBase(null); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing Database creation - * - * @tc.name: Database creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0002 - * @tc.desc: Database creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest02() { - try { - boolean res = DataBaseApi.getInstance().createDataBase("testaa"); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing Database creation - * - * @tc.name: Database creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0003 - * @tc.desc: Database creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest03() { - try { - boolean res = DataBaseApi.getInstance().createDataBase("testaa"); - Assert.assertTrue(res); - boolean res0 = DataBaseApi.getInstance().createDataBase("testaa"); - Assert.assertTrue(res0); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing Database creation - * - * @tc.name: Database creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0005 - * @tc.desc: Database creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest05() { - try { - boolean res = DataBaseApi.getInstance().createDataBase(null); - Assert.assertFalse(res); - boolean res0 = DataBaseApi.getInstance().createDataBase("testaa"); - Assert.assertTrue(res0); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing table creation - * - * @tc.name: Database table creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0001 - * @tc.desc: Database table creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createTableTest01() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing table creation - * - * @tc.name: Database table creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0002 - * @tc.desc: Database table creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createTableTest02() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, null, processMemInfo); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing table creation - * - * @tc.name: Database table creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0003 - * @tc.desc: Database table creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createTableTest03() { - try { - boolean res = DataBaseApi.getInstance().createTable("", null, processMemInfo); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing table creation - * - * @tc.name: Database table creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0004 - * @tc.desc: Database table creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createTableTest04() { - try { - boolean res = DataBaseApi.getInstance().createTable(null, null, processMemInfo); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing table creation - * - * @tc.name: Database table creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0005 - * @tc.desc: Database table creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createTableTest05() { - try { - boolean res = DataBaseApi.getInstance().createTable(null, null, processMemInfo); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing index creation - * - * @tc.name: Database index creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0001 - * @tc.desc: Database index creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createIndexTest01() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - boolean result = DataBaseApi.getInstance().createIndex("testTable", "testIndex", processMemInfoIndex); - Assert.assertTrue(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing index creation - * - * @tc.name: Database index creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0002 - * @tc.desc: Database index creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createIndexTest02() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - boolean result = DataBaseApi.getInstance().createIndex("testTable", null, processMemInfoIndex); - Assert.assertFalse(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing index creation - * - * @tc.name: Database index creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0003 - * @tc.desc: Database index creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createIndexTest03() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - boolean result = DataBaseApi.getInstance().createIndex(null, "aaa", processMemInfoIndex); - Assert.assertFalse(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing index creation - * - * @tc.name: Database index creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0004 - * @tc.desc: Database index creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createIndexTest04() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - - boolean result = DataBaseApi.getInstance().createIndex(null, null, processMemInfoIndex); - Assert.assertFalse(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing index creation - * - * @tc.name: Database index creation - * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0005 - * @tc.desc: Database index creation - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createIndexTest05() { - try { - boolean res = - DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", processMemInfo); - Assert.assertTrue(res); - boolean result = DataBaseApi.getInstance().createIndex(null, null, null); - Assert.assertFalse(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databaseapi; + +import com.alibaba.druid.pool.DruidDataSource; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Data Base Api Test + */ +public class DataBaseApiTest { + private List processMemInfo; + private List processMemInfoIndex; + + /** + * functional testing init + * + * @tc.name: setUp + * @tc.number: OHOS_JAVA_database_DataBaseApi_setUp_0001 + * @tc.desc: setUp + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Before + public void setUp() { + processMemInfo = new ArrayList() { + { + add("id INTEGER primary key autoincrement not null"); + add("sessionId INTEGER NOT NULL"); + add("session INTEGER NOT NULL"); + add("timeStamp Long NOT NULL"); + add("Data BLOB NOT NULL"); + } + }; + processMemInfoIndex = new ArrayList() { + { + add("id"); + add("sessionId"); + add("timeStamp"); + } + }; + SessionManager.getInstance().setDevelopMode(true); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_database_DataBaseApi_getInstanceTest_0001 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest01() { + DataBaseApi dataBaseApi = DataBaseApi.getInstance(); + Assert.assertNotNull(dataBaseApi); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_database_DataBaseApi_getInstanceTest_0002 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest02() { + DataBaseApi dataBaseApi1 = DataBaseApi.getInstance(); + DataBaseApi dataBaseApi2 = DataBaseApi.getInstance(); + Assert.assertEquals(dataBaseApi1, dataBaseApi2); + } + + /** + * functional testing init + * + * @tc.name: init DataSourceManager + * @tc.number: OHOS_JAVA_database_DataBaseApi_initDataSourceManager_0001 + * @tc.desc: init DataSourceManager + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDataSourceManager() { + boolean flag = DataBaseApi.getInstance().initDataSourceManager(); + Assert.assertTrue(flag); + } + + /** + * functional testing init + * + * @tc.name: init DataSourceManager + * @tc.number: OHOS_JAVA_database_DataBaseApi_initDataSourceManager_0002 + * @tc.desc: init DataSourceManager + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDataSourceManager02() { + boolean flag1 = DataBaseApi.getInstance().initDataSourceManager(); + boolean flag2 = DataBaseApi.getInstance().initDataSourceManager(); + Assert.assertEquals(flag1, flag2); + } + + /** + * functional testing get Connect + * + * @tc.name: get DefaultDataBase Connect + * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0001 + * @tc.desc: get DefaultDataBase Connect + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getDefaultDataBaseConnect01() { + Optional res = DataBaseApi.getInstance().getDefaultDataBaseConnect(); + Assert.assertTrue(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get DefaultDataBase Connect + * @tc.number: OHOS_JAVA_database_DataBaseApi_getDefaultDataBaseConnect_0002 + * @tc.desc: get DefaultDataBase Connect + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getDefaultDataBaseConnect02() { + Optional res1 = DataBaseApi.getInstance().getDefaultDataBaseConnect(); + Optional res2 = DataBaseApi.getInstance().getDefaultDataBaseConnect(); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By Table + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0001 + * @tc.desc: get Connect By Table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectByTableTest01() { + boolean flag = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "DeviceInfo", + processMemInfo); + Optional res = DataBaseApi.getInstance().getConnectByTable("DeviceInfo"); + Assert.assertTrue(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By Table + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0002 + * @tc.desc: get Connect By Table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectByTableTest02() { + Optional res = DataBaseApi.getInstance().getConnectByTable(""); + Assert.assertFalse(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By Table + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0003 + * @tc.desc: get Connect By Table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectByTableTest03() { + Optional res = DataBaseApi.getInstance().getConnectByTable(null); + Assert.assertFalse(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By Table + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0004 + * @tc.desc: get Connect By Table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectByTableTest04() { + boolean flag1 = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "DeviceInfo1", + processMemInfo); + Optional res1 = DataBaseApi.getInstance().getConnectByTable("DeviceInfo1"); + boolean flag2 = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "DeviceInfo2", + processMemInfo); + Optional res2 = DataBaseApi.getInstance().getConnectByTable("DeviceInfo2"); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By Table + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectByTable_0005 + * @tc.desc: get Connect By Table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectByTableTest05() { + boolean flag1 = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "DeviceInfo", + processMemInfo); + Optional res1 = DataBaseApi.getInstance().getConnectByTable("DeviceInfo"); + Optional res2 = DataBaseApi.getInstance().getConnectByTable("DeviceInfo"); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By dbname + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0001 + * @tc.desc: get Connect By dbname + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectBydbnameTest01() { + Optional res = DataBaseApi.getInstance().getConnectBydbname("defaultDB"); + Assert.assertTrue(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By dbname + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0002 + * @tc.desc: get Connect By dbname + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectBydbnameTest02() { + Optional res = DataBaseApi.getInstance().getConnectBydbname(null); + Assert.assertTrue(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By dbname + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0003 + * @tc.desc: get Connect By dbname + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectBydbnameTest03() { + Optional res = DataBaseApi.getInstance().getConnectBydbname(""); + Assert.assertTrue(res.isPresent()); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By dbname + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0004 + * @tc.desc: get Connect By dbname + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectBydbnameTest04() { + Optional res1 = DataBaseApi.getInstance().getConnectBydbname("test"); + Optional res2 = DataBaseApi.getInstance().getConnectBydbname("test"); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing get Connect + * + * @tc.name: get Connect By dbname + * @tc.number: OHOS_JAVA_database_DataBaseApi_getConnectBydbname_0005 + * @tc.desc: get Connect By dbname + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getConnectBydbnameTest05() { + Optional res1 = DataBaseApi.getInstance().getConnectBydbname("defaultDB"); + Optional res2 = DataBaseApi.getInstance().getConnectBydbname("test"); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing get DataBaseName + * + * @tc.name: get Pool By DataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0001 + * @tc.desc: get Pool By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getPoolByDataBaseNameTest01() { + DataSource res = DataBaseApi.getInstance().getPoolByDataBaseName(""); + Assert.assertNotNull(res); + } + + /** + * functional testing get DataBaseName + * + * @tc.name: get Pool By DataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0002 + * @tc.desc: get Pool By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getPoolByDataBaseNameTest02() { + DataSource res = DataBaseApi.getInstance().getPoolByDataBaseName(null); + Assert.assertNotNull(res); + } + + /** + * functional testing get DataBaseName + * + * @tc.name: get Pool By DataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0003 + * @tc.desc: get Pool By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getPoolByDataBaseNameTest03() { + DataSource res = DataBaseApi.getInstance().getPoolByDataBaseName("test"); + Assert.assertNotNull(res); + } + + /** + * functional testing get DataBaseName + * + * @tc.name: get Pool By DataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0004 + * @tc.desc: get Pool By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getPoolByDataBaseNameTest04() { + DataSource res1 = DataBaseApi.getInstance().getPoolByDataBaseName(null); + DataSource res2 = DataBaseApi.getInstance().getPoolByDataBaseName(""); + Assert.assertEquals(res1, res2); + } + + /** + * functional testing get DataBaseName + * + * @tc.name: get Pool By DataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseApi_getPoolByDataBaseName_0005 + * @tc.desc: get Pool By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getPoolByDataBaseNameTest05() { + DataSource res1 = DataBaseApi.getInstance().getPoolByDataBaseName("test1"); + DataSource res2 = DataBaseApi.getInstance().getPoolByDataBaseName("test"); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing register table + * + * @tc.name: register table + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0001 + * @tc.desc: register table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerTableTest01() { + DataBaseApi.getInstance().registerTable("test", "ttest"); + Assert.assertTrue(true); + } + + /** + * functional testing register table + * + * @tc.name: register table + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0002 + * @tc.desc: register table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerTableTest02() { + DataBaseApi.getInstance().registerTable("", "ttest"); + Assert.assertTrue(true); + } + + /** + * functional testing register table + * + * @tc.name: register table + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0003 + * @tc.desc: register table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerTableTest03() { + DataBaseApi.getInstance().registerTable("test", ""); + Assert.assertTrue(true); + } + + /** + * functional testing register table + * + * @tc.name: register table + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0004 + * @tc.desc: register table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerTableTest04() { + DataBaseApi.getInstance().registerTable(null, null); + Assert.assertTrue(true); + } + + /** + * functional testing register table + * + * @tc.name: register table + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerTable_0005 + * @tc.desc: register table + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerTableTest05() { + DataBaseApi.getInstance().registerTable("", ""); + Assert.assertTrue(true); + } + + /** + * functional testing register DataSource + * + * @tc.name: register DataSource + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0001 + * @tc.desc: register DataSource + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerDataSourceTest01() { + DataBaseApi.getInstance().registerDataSource(null, null); + Assert.assertTrue(true); + } + + /** + * functional testing register DataSource + * + * @tc.name: register DataSource + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0002 + * @tc.desc: register DataSource + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerDataSourceTest02() { + DataBaseApi.getInstance().registerDataSource("dataBase", null); + Assert.assertTrue(true); + } + + /** + * functional testing register DataSource + * + * @tc.name: register DataSource + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0003 + * @tc.desc: register DataSource + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerDataSourceTest03() { + DataBaseApi.getInstance().registerDataSource("dataBase", new DruidDataSource()); + Assert.assertTrue(true); + } + + /** + * functional testing register DataSource + * + * @tc.name: register DataSource + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0004 + * @tc.desc: register DataSource + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerDataSourceTest04() { + DataBaseApi.getInstance().registerDataSource(null, new DruidDataSource()); + Assert.assertTrue(true); + } + + /** + * functional testing register DataSource + * + * @tc.name: register DataSource + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerDataSource_0005 + * @tc.desc: register DataSource + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerDataSourceTest05() { + DataBaseApi.getInstance().registerDataSource("", null); + Assert.assertTrue(true); + } + + /** + * functional testing Database creation + * + * @tc.name: Database creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0001 + * @tc.desc: Database creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest01() { + boolean res = DataBaseApi.getInstance().createDataBase(null); + Assert.assertFalse(res); + } + + /** + * functional testing Database creation + * + * @tc.name: Database creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0002 + * @tc.desc: Database creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest02() { + boolean res = DataBaseApi.getInstance().createDataBase("testaa"); + Assert.assertTrue(res); + } + + /** + * functional testing Database creation + * + * @tc.name: Database creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0003 + * @tc.desc: Database creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest03() { + boolean res = DataBaseApi.getInstance().createDataBase("test01"); + boolean res0 = DataBaseApi.getInstance().createDataBase(""); + Assert.assertNotEquals(res, res0); + } + + /** + * functional testing Database creation + * + * @tc.name: Database creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0004 + * @tc.desc: Database creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest04() { + boolean res = DataBaseApi.getInstance().createDataBase(""); + Assert.assertFalse(res); + } + + /** + * functional testing Database creation + * + * @tc.name: Database creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createDataBase_0005 + * @tc.desc: Database creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest05() { + boolean res = DataBaseApi.getInstance().createDataBase(null); + boolean res0 = DataBaseApi.getInstance().createDataBase(""); + Assert.assertEquals(res, res0); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0001 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableTest01() { + boolean res = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", + processMemInfo); + Assert.assertTrue(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0002 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableTest02() { + boolean res = DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, null, + processMemInfo); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0003 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableTest03() { + boolean res = DataBaseApi.getInstance().createTable("", null, processMemInfo); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0004 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableTest04() { + boolean res = DataBaseApi.getInstance().createTable(null, null, processMemInfo); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTable_0005 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableTest05() { + boolean res = DataBaseApi.getInstance().createTable("", "", processMemInfo); + Assert.assertFalse(res); + } + + /** + * functional testing index creation + * + * @tc.name: Database index creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0001 + * @tc.desc: Database index creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createIndexTest01() { + boolean res = + DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", + processMemInfo); + Assert.assertTrue(res); + } + + /** + * functional testing index creation + * + * @tc.name: Database index creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0002 + * @tc.desc: Database index creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createIndexTest02() { + boolean result = DataBaseApi.getInstance().createIndex("testTable", null, + processMemInfoIndex); + Assert.assertFalse(result); + } + + /** + * functional testing index creation + * + * @tc.name: Database index creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0003 + * @tc.desc: Database index creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createIndexTest03() { + boolean result = DataBaseApi.getInstance().createIndex(null, "", processMemInfoIndex); + Assert.assertFalse(result); + } + + /** + * functional testing index creation + * + * @tc.name: Database index creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0004 + * @tc.desc: Database index creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createIndexTest04() { + boolean result = DataBaseApi.getInstance().createIndex(null, null, processMemInfoIndex); + Assert.assertFalse(result); + } + + /** + * functional testing index creation + * + * @tc.name: Database index creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createIndex_0005 + * @tc.desc: Database index creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createIndexTest05() { + boolean result = DataBaseApi.getInstance().createIndex(null, null, null); + Assert.assertFalse(result); + } + + /** + * functional testing table check + * + * @tc.name: Check Table Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkTableRegister_0001 + * @tc.desc: Check Table Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkTableRegisterTest01() { + String res = DataBaseApi.getInstance().checkTableRegister(""); + Assert.assertFalse(StringUtils.isNotBlank(res)); + } + + /** + * functional testing table check + * + * @tc.name: Check Table Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkTableRegister_0002 + * @tc.desc: Check Table Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkTableRegisterTest02() { + String res = DataBaseApi.getInstance().checkTableRegister(null); + Assert.assertFalse(StringUtils.isNotBlank(res)); + } + + /** + * functional testing table check + * + * @tc.name: Check Table Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkTableRegister_0003 + * @tc.desc: Check Table Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkTableRegisterTest03() { + String res = DataBaseApi.getInstance().checkTableRegister("testTable"); + Assert.assertNotNull(res); + } + + /** + * functional testing table check + * + * @tc.name: Check Table Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkTableRegister_0004 + * @tc.desc: Check Table Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkTableRegisterTest04() { + String res1 = DataBaseApi.getInstance().checkTableRegister("tableName"); + String res2 = DataBaseApi.getInstance().checkTableRegister(""); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing table check + * + * @tc.name: Check Table Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkTableRegister_0005 + * @tc.desc: Check Table Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkTableRegisterTest05() { + String res1 = DataBaseApi.getInstance().checkTableRegister(null); + String res2 = DataBaseApi.getInstance().checkTableRegister(""); + Assert.assertEquals(res1, res2); + } + + /** + * functional testing index check + * + * @tc.name: Check Index Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkIndexRegister_0001 + * @tc.desc: Check Index Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkIndexRegisterTest01() { + boolean res = DataBaseApi.getInstance().checkIndexRegister(""); + Assert.assertFalse(res); + } + + /** + * functional testing index check + * + * @tc.name: Check Index Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkIndexRegister_0002 + * @tc.desc: Check Index Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkIndexRegisterTest02() { + boolean res = DataBaseApi.getInstance().checkIndexRegister(null); + Assert.assertFalse(res); + } + + /** + * functional testing index check + * + * @tc.name: Check Index Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkIndexRegister_0003 + * @tc.desc: Check Index Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkIndexRegisterTest03() { + boolean res = DataBaseApi.getInstance().checkIndexRegister("testTable"); + Assert.assertFalse(res); + } + + /** + * functional testing index check + * + * @tc.name: Check Index Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkIndexRegister_0004 + * @tc.desc: Check Index Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkIndexRegisterTest04() { + boolean res1 = DataBaseApi.getInstance().checkIndexRegister("tableName"); + boolean res2 = DataBaseApi.getInstance().checkIndexRegister(""); + Assert.assertEquals(res1, res2); + } + + /** + * functional testing index check + * + * @tc.name: Check Index Register + * @tc.number: OHOS_JAVA_database_DataBaseApi_checkIndexRegister_0005 + * @tc.desc: Check Index Register + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkIndexRegisterTest05() { + boolean res1 = DataBaseApi.getInstance().checkIndexRegister(null); + boolean res2 = DataBaseApi.getInstance().checkIndexRegister(""); + Assert.assertEquals(res1, res2); + } + + /** + * functional testing index check + * + * @tc.name: Register Create Index + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerCreateIndex_0001 + * @tc.desc: Register Create Index + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerCreateIndexTest01() { + DataBaseApi.getInstance().registerCreateIndex(""); + Assert.assertTrue(true); + } + + /** + * functional testing index check + * + * @tc.name: Register Create Index + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerCreateIndex_0002 + * @tc.desc: Register Create Index + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerCreateIndexTest02() { + DataBaseApi.getInstance().registerCreateIndex(null); + Assert.assertTrue(true); + } + + /** + * functional testing index check + * + * @tc.name: Register Create Index + * @tc.number: OHOS_JAVA_database_DataBaseApi_registerCreateIndex_0003 + * @tc.desc: Register Create Index + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void registerCreateIndexTest03() { + DataBaseApi.getInstance().registerCreateIndex("testTable"); + Assert.assertTrue(true); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTableSql_0001 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableSqlTest01() { + boolean res = DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, "testTable", + "sql"); + Assert.assertTrue(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTableSql_0002 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableSqlTest02() { + boolean res = DataBaseApi.getInstance().createTable(DataBaseApi.DEFAULT_DATABASE_DBNAME, null, + ""); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTableSql_0003 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableSqlTest03() { + boolean res = DataBaseApi.getInstance().createTable("", null, ""); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTableSql_0004 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableSqlTest04() { + boolean res = DataBaseApi.getInstance().createTable(null, null, ""); + Assert.assertFalse(res); + } + + /** + * functional testing table creation + * + * @tc.name: Database table creation + * @tc.number: OHOS_JAVA_database_DataBaseApi_createTableSql_0005 + * @tc.desc: Database table creation + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createTableSqlTest05() { + boolean res = DataBaseApi.getInstance().createTable(null, null, "sql"); + Assert.assertFalse(res); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManagerTest.java index 8dd7c21dd..b7ee2c720 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasemanager/DataBaseManagerTest.java @@ -1,284 +1,398 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasemanager; - -import ohos.devtools.datasources.databases.databasepool.DataBase; -import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import javax.sql.DataSource; -import static ohos.devtools.datasources.databases.databaseapi.DataBaseApi.DEFAULT_DATABASE_DBNAME; -import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; - -/** - * @version 1.0 - * @date 2021/03/26 11:06 - **/ -public class DataBaseManagerTest { - /** - * functional testing init - * - * @tc.name: setUp - * @tc.number: OHOS_JAVA_database_DataBaseManager_setUp_0001 - * @tc.desc: setUp - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Before - public void setUp() { - SessionManager.getInstance().setDevelopMode(true); - } - - /** - * functional testing DefaultDataBase - * - * @tc.name: init DefaultDataBase - * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0001 - * @tc.desc: init DefaultDataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDefaultDataBaseTest01() { - try { - DataBase dataBase = DataBaseHelper.createDefaultDataBase(); - dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); - boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing DefaultDataBase - * - * @tc.name: init DefaultDataBase - * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0002 - * @tc.desc: init DefaultDataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDefaultDataBaseTest02() { - try { - DataBase dataBase = DataBaseHelper.createDefaultDataBase(); - dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); - boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); - Assert.assertTrue(res); - boolean res01 = DataBaseManager.getInstance().initDefaultDataBase(dataBase); - Assert.assertTrue(res01); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing initDefaultSql - * - * @tc.name: init DefaultSql - * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0001 - * @tc.desc: init DefaultSql - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDefaultSqlTest01() { - try { - DataBase dataBase = DataBaseHelper.createDefaultDataBase(); - dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); - boolean result = DataBaseManager.getInstance().initDefaultSql(dataBase); - Assert.assertTrue(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing initDefaultSql - * - * @tc.name: init DefaultSql - * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0002 - * @tc.desc: init DefaultSql - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void initDefaultSqlTest02() { - try { - DataBase dataBase = DataBaseHelper.createDefaultDataBase(); - dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); - boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); - Assert.assertTrue(res); - boolean result = DataBaseManager.getInstance().initDefaultSql(dataBase); - Assert.assertTrue(result); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing createDataBase - * - * @tc.name: create DataBase - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0001 - * @tc.desc: create DataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest01() { - try { - boolean res = DataBaseManager.getInstance().createDataBase("test01"); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing createDataBase - * - * @tc.name: create DataBase - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0002 - * @tc.desc: create DataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest02() { - try { - boolean res = DataBaseManager.getInstance().createDataBase(null); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing createDataBase - * - * @tc.name: create DataBase - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0003 - * @tc.desc: create DataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest03() { - try { - boolean res = DataBaseManager.getInstance().createDataBase(""); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing createDruidConnectionPool - * - * @tc.name: create DruidConnection Pool - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0001 - * @tc.desc: create DruidConnection Pool - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDruidConnectionPoolTest01() { - DataSource result = null; - try { - boolean res = DataBaseManager.getInstance().createDataBase("test01"); - Assert.assertTrue(res); - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName("test01")); - result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - Assert.assertNotNull(result); - } catch (Exception exception) { - Assert.assertNotNull(result); - } - } - - /** - * functional testing createDruidConnectionPool - * - * @tc.name: create DruidConnection Pool - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0002 - * @tc.desc: create DruidConnection Pool - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDruidConnectionPoolTest02() { - DataSource result = null; - try { - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName("test02")); - result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - Assert.assertNotNull(result); - } catch (Exception exception) { - Assert.assertNotNull(result); - } - } - - /** - * functional testing createDruidConnectionPool - * - * @tc.name: create DruidConnection Pool - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0003 - * @tc.desc: create DruidConnection Pool - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDruidConnectionPoolTest03() { - DataSource result = null; - try { - result = DataBaseManager.getInstance().createDruidConnectionPool(null); - Assert.assertNull(result); - } catch (Exception exception) { - Assert.assertNull(result); - } - } - - /** - * functional testing createDruidConnectionPool - * - * @tc.name: create DruidConnection Pool - * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0004 - * @tc.desc: create DruidConnection Pool - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDruidConnectionPoolTest04() { - DataSource result = null; - try { - boolean res = DataBaseManager.getInstance().createDataBase("test01"); - Assert.assertTrue(res); - DataBase dataBase = DataBaseHelper.createDataBase(); - dataBase.setUrl(getUrlByDataBaseName("test01")); - result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - DataBase dataBas2 = DataBaseHelper.createDataBase(); - dataBas2.setUrl(getUrlByDataBaseName("test01")); - result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); - Assert.assertNotNull(result); - } catch (Exception exception) { - Assert.assertNotNull(result); - } - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasemanager; + +import ohos.devtools.datasources.databases.databasepool.DataBase; +import ohos.devtools.datasources.databases.databasepool.DataBaseHelper; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import javax.sql.DataSource; +import static ohos.devtools.datasources.databases.databaseapi.DataBaseApi.DEFAULT_DATABASE_DBNAME; +import static ohos.devtools.datasources.databases.databasepool.DataBaseHelper.getUrlByDataBaseName; + +/** + * Data Base Manager Test + */ +public class DataBaseManagerTest { + /** + * functional testing init + * + * @tc.name: setUp + * @tc.number: OHOS_JAVA_database_DataBaseManager_setUp_0001 + * @tc.desc: setUp + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Before + public void setUp() { + SessionManager.getInstance().setDevelopMode(true); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_database_DataBaseManager_getInstanceTest_0001 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest01() { + DataBaseManager dataBaseManager = DataBaseManager.getInstance(); + Assert.assertNotNull(dataBaseManager); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_database_DataBaseManager_getInstanceTest_0002 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest02() { + DataBaseManager dataBaseManager1 = DataBaseManager.getInstance(); + DataBaseManager dataBaseManager2 = DataBaseManager.getInstance(); + Assert.assertEquals(dataBaseManager1, dataBaseManager2); + } + + /** + * functional testing DefaultDataBase + * + * @tc.name: init DefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0001 + * @tc.desc: init DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultDataBaseTest01() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); + boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); + Assert.assertTrue(res); + } + + /** + * functional testing DefaultDataBase + * + * @tc.name: init DefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0002 + * @tc.desc: init DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultDataBaseTest02() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName(null)); + boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); + Assert.assertTrue(res); + } + + /** + * functional testing DefaultDataBase + * + * @tc.name: init DefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0003 + * @tc.desc: init DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultDataBaseTest03() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); + Assert.assertFalse(res); + } + + /** + * functional testing DefaultDataBase + * + * @tc.name: init DefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0004 + * @tc.desc: init DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultDataBaseTest04() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName("defaultDB2")); + boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); + Assert.assertTrue(res); + } + + /** + * functional testing DefaultDataBase + * + * @tc.name: init DefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultDataBase_0005 + * @tc.desc: init DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultDataBaseTest05() { + boolean res = DataBaseManager.getInstance().initDefaultDataBase(null); + Assert.assertFalse(res); + } + + /** + * functional testing initDefaultSql + * + * @tc.name: init DefaultSql + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0001 + * @tc.desc: init DefaultSql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultSqlTest01() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); + boolean result = DataBaseManager.getInstance().initDefaultSql(dataBase); + Assert.assertTrue(result); + } + + /** + * functional testing initDefaultSql + * + * @tc.name: init DefaultSql + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0002 + * @tc.desc: init DefaultSql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultSqlTest02() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName(null)); + boolean res = DataBaseManager.getInstance().initDefaultDataBase(dataBase); + Assert.assertTrue(res); + } + + /** + * functional testing initDefaultSql + * + * @tc.name: init DefaultSql + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0003 + * @tc.desc: init DefaultSql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultSqlTest03() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + boolean result = DataBaseManager.getInstance().initDefaultSql(dataBase); + Assert.assertFalse(result); + } + + /** + * functional testing initDefaultSql + * + * @tc.name: init DefaultSql + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0004 + * @tc.desc: init DefaultSql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultSqlTest04() { + boolean result = DataBaseManager.getInstance().initDefaultSql(null); + Assert.assertFalse(result); + } + + /** + * functional testing initDefaultSql + * + * @tc.name: init DefaultSql + * @tc.number: OHOS_JAVA_database_DataBaseManager_initDefaultSql_0005 + * @tc.desc: init DefaultSql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void initDefaultSqlTest05() { + DataBase dataBase = DataBaseHelper.createDefaultDataBase(); + dataBase.setUrl(getUrlByDataBaseName("defaultDB2")); + boolean result = DataBaseManager.getInstance().initDefaultSql(dataBase); + Assert.assertTrue(result); + } + + /** + * functional testing createDataBase + * + * @tc.name: create DataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0001 + * @tc.desc: create DataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest01() { + boolean res = DataBaseManager.getInstance().createDataBase("test01"); + Assert.assertTrue(res); + } + + /** + * functional testing createDataBase + * + * @tc.name: create DataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0002 + * @tc.desc: create DataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest02() { + boolean res = DataBaseManager.getInstance().createDataBase(null); + Assert.assertTrue(res); + } + + /** + * functional testing createDataBase + * + * @tc.name: create DataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0003 + * @tc.desc: create DataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest03() { + boolean res = DataBaseManager.getInstance().createDataBase(""); + Assert.assertTrue(res); + } + + /** + * functional testing createDataBase + * + * @tc.name: create DataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0004 + * @tc.desc: create DataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest04() { + boolean res1 = DataBaseManager.getInstance().createDataBase("test11"); + boolean res2 = DataBaseManager.getInstance().createDataBase("test01"); + Assert.assertEquals(res1, res2); + } + + /** + * functional testing createDataBase + * + * @tc.name: create DataBase + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDataBase_0005 + * @tc.desc: create DataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest05() { + boolean res1 = DataBaseManager.getInstance().createDataBase("defaultDB"); + Assert.assertTrue(res1); + } + + /** + * functional testing createDruidConnectionPool + * + * @tc.name: create DruidConnection Pool + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0001 + * @tc.desc: create DruidConnection Pool + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDruidConnectionPoolTest01() { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName(DEFAULT_DATABASE_DBNAME)); + DataSource result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + Assert.assertNotNull(result); + } + + /** + * functional testing createDruidConnectionPool + * + * @tc.name: create DruidConnection Pool + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0002 + * @tc.desc: create DruidConnection Pool + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDruidConnectionPoolTest02() { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName(null)); + DataSource result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + Assert.assertNotNull(result); + } + + /** + * functional testing createDruidConnectionPool + * + * @tc.name: create DruidConnection Pool + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0003 + * @tc.desc: create DruidConnection Pool + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDruidConnectionPoolTest03() { + DataBase dataBase = DataBaseHelper.createDataBase(); + dataBase.setUrl(getUrlByDataBaseName("")); + DataSource result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + Assert.assertNotNull(result); + } + + /** + * functional testing createDruidConnectionPool + * + * @tc.name: create DruidConnection Pool + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0004 + * @tc.desc: create DruidConnection Pool + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDruidConnectionPoolTest04() { + DataSource result = DataBaseManager.getInstance().createDruidConnectionPool(null); + Assert.assertNull(result); + } + + /** + * functional testing createDruidConnectionPool + * + * @tc.name: create DruidConnection Pool + * @tc.number: OHOS_JAVA_database_DataBaseManager_createDruidConnectionPool_0005 + * @tc.desc: create DruidConnection Pool + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDruidConnectionPoolTest05() { + DataBase dataBase = DataBaseHelper.createDataBase(); + DataSource result = DataBaseManager.getInstance().createDruidConnectionPool(dataBase); + Assert.assertNull(result); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelperTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelperTest.java index 4bd9d1691..a5846f80a 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelperTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataBaseHelperTest.java @@ -1,130 +1,126 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -/** - * DataBaseHelperTest - * - * @version 1.0 - * @date 2021/04/12 18:38 - **/ -public class DataBaseHelperTest { - private static String url = "jdbc:sqlite://localhost:1521"; - - /** - * functional testing checkDataBaseExists - * - * @tc.name: checkDataBaseExists - * @tc.number: OHOS_JAVA_database_DataBaseHelper_checkDataBaseExists_0001 - * @tc.desc: checkDataBaseExists - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void checkDataBaseExistsTest() { - boolean flag = DataBaseHelper.checkDataBaseExists(url); - if (flag) { - Assert.assertTrue(true); - } - } - - /** - * functional testing loadSqlFileToList - * - * @tc.name: loadSqlFileToList - * @tc.number: OHOS_JAVA_database_DataBaseHelper_loadSqlFileToList_0001 - * @tc.desc: loadSqlFileToList - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void loadSqlFileToListTest() { - List list = null; - try { - list = DataBaseHelper.loadSqlFileToList("d://"); - Assert.assertNotNull(list); - } catch (IOException ioException) { - Assert.assertNotNull(list); - } - } - - /** - * functional testing getFilePath - * - * @tc.name: getFilePath - * @tc.number: OHOS_JAVA_database_DataBaseHelper_getFilePath_0001 - * @tc.desc: get FilePath - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getFilePathTest() { - String fileStr = DataBaseHelper.getFilePath(url); - Assert.assertNotNull(fileStr); - } - - /** - * functional testing getUrlByDataBaseName - * - * @tc.name: getUrlByDataBaseName - * @tc.number: OHOS_JAVA_database_DataBaseHelper_getUrlByDataBaseName_0001 - * @tc.desc: get Url By DataBaseName - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getUrlByDataBaseNameTest() { - String dataBaseStr = DataBaseHelper.getUrlByDataBaseName("defaultDB"); - Assert.assertNotNull(dataBaseStr); - } - - /** - * functional testing createDataBase - * - * @tc.name: createDataBase - * @tc.number: OHOS_JAVA_database_DataBaseHelper_createDataBase_0001 - * @tc.desc: createDataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDataBaseTest() { - DataBase dataBase = DataBaseHelper.createDataBase(); - Assert.assertNotNull(dataBase); - } - - /** - * functional testing createDefaultDataBase - * - * @tc.name: createDefaultDataBase - * @tc.number: OHOS_JAVA_database_DataBaseHelper_createDefaultDataBase_0001 - * @tc.desc: create DefaultDataBase - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void createDefaultDataBaseTest() { - DataBase dataBaseDefault = DataBaseHelper.createDefaultDataBase(); - Assert.assertNotNull(dataBaseDefault); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +/** + * Data Base Helper Test + */ +public class DataBaseHelperTest { + private static String url = "jdbc:sqlite://localhost:1521"; + + /** + * functional testing checkDataBaseExists + * + * @tc.name: checkDataBaseExists + * @tc.number: OHOS_JAVA_database_DataBaseHelper_checkDataBaseExists_0001 + * @tc.desc: checkDataBaseExists + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void checkDataBaseExistsTest() { + boolean flag = DataBaseHelper.checkDataBaseExists(url); + if (flag) { + Assert.assertTrue(true); + } + } + + /** + * functional testing loadSqlFileToList + * + * @tc.name: loadSqlFileToList + * @tc.number: OHOS_JAVA_database_DataBaseHelper_loadSqlFileToList_0001 + * @tc.desc: loadSqlFileToList + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void loadSqlFileToListTest() { + List list = null; + try { + list = DataBaseHelper.loadSqlFileToList("d://"); + Assert.assertNotNull(list); + } catch (IOException ioException) { + Assert.assertNotNull(list); + } + } + + /** + * functional testing getFilePath + * + * @tc.name: getFilePath + * @tc.number: OHOS_JAVA_database_DataBaseHelper_getFilePath_0001 + * @tc.desc: get FilePath + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getFilePathTest() { + String fileStr = DataBaseHelper.getFilePath(url); + Assert.assertNotNull(fileStr); + } + + /** + * functional testing getUrlByDataBaseName + * + * @tc.name: getUrlByDataBaseName + * @tc.number: OHOS_JAVA_database_DataBaseHelper_getUrlByDataBaseName_0001 + * @tc.desc: get Url By DataBaseName + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getUrlByDataBaseNameTest() { + String dataBaseStr = DataBaseHelper.getUrlByDataBaseName("defaultDB"); + Assert.assertNotNull(dataBaseStr); + } + + /** + * functional testing createDataBase + * + * @tc.name: createDataBase + * @tc.number: OHOS_JAVA_database_DataBaseHelper_createDataBase_0001 + * @tc.desc: createDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDataBaseTest() { + DataBase dataBase = DataBaseHelper.createDataBase(); + Assert.assertNotNull(dataBase); + } + + /** + * functional testing createDefaultDataBase + * + * @tc.name: createDefaultDataBase + * @tc.number: OHOS_JAVA_database_DataBaseHelper_createDefaultDataBase_0001 + * @tc.desc: create DefaultDataBase + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void createDefaultDataBaseTest() { + DataBase dataBaseDefault = DataBaseHelper.createDefaultDataBase(); + Assert.assertNotNull(dataBaseDefault); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataTableHelperTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataTableHelperTest.java index 5994c510e..e693c7449 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataTableHelperTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/databasepool/DataTableHelperTest.java @@ -1,88 +1,102 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.databases.databasepool; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; - -/** - * @Description DataTableHelperTest - * @Date 2021/04/12 17:33 - **/ -public class DataTableHelperTest { - /** - * functional testing getTableNameBySql - * - * @tc.name: getTableNameBySql - * @tc.number: OHOS_JAVA_database_DataBaseHelper_getTableNameBySql_0001 - * @tc.desc: getTableNameBySql - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getTableNameBySqlTest() { - String str = DataTableHelper.getTableNameBySql("("); - Assert.assertNotNull(str); - } - - /** - * functional testing sqlPlaceholder - * - * @tc.name: sqlPlaceholder - * @tc.number: OHOS_JAVA_database_DataTableHelper_sqlPlaceholder_0001 - * @tc.desc: sqlPlaceholder - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void sqlPlaceholderTest() { - String sqlStr = DataTableHelper.sqlPlaceholder(10); - Assert.assertNotNull(sqlStr); - } - - /** - * functional testing getDeleteCondition - * - * @tc.name: getDeleteCondition - * @tc.number: OHOS_JAVA_database_DataTableHelper_getDeleteCondition_0001 - * @tc.desc: getDeleteCondition - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void getDeleteConditionTest() { - String deleteStr = DataTableHelper.getDeleteCondition(new HashMap<>()); - Assert.assertNotNull(deleteStr); - } - - /** - * functional testing mapToString - * - * @tc.name: mapToString - * @tc.number: OHOS_JAVA_database_DataTableHelper_mapToString_0001 - * @tc.desc: mapToString - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void mapToStringTest() { - String mapStr = DataTableHelper.mapToString(new HashMap<>()); - Assert.assertNotNull(mapStr); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.databases.databasepool; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; + +/** + * Data Table Helper Test + */ +public class DataTableHelperTest { + /** + * functional testing getTableNameBySql + * + * @tc.name: getTableNameBySql + * @tc.number: OHOS_JAVA_database_DataBaseHelper_getTableNameBySql_0001 + * @tc.desc: getTableNameBySql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getTableNameBySqlTest01() { + String str = DataTableHelper.getTableNameBySql("("); + Assert.assertNotNull(str); + } + + /** + * functional testing getTableNameBySql + * + * @tc.name: getTableNameBySql + * @tc.number: OHOS_JAVA_database_DataBaseHelper_getTableNameBySql_0002 + * @tc.desc: getTableNameBySql + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getTableNameBySqlTest02() { + String sqlStr = DataTableHelper.getTableNameBySql("("); + String str = DataTableHelper.getTableNameBySql("("); + Assert.assertEquals(sqlStr, str); + } + + /** + * functional testing sqlPlaceholder + * + * @tc.name: sqlPlaceholder + * @tc.number: OHOS_JAVA_database_DataTableHelper_sqlPlaceholder_0001 + * @tc.desc: sqlPlaceholder + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void sqlPlaceholderTest() { + String sqlStr = DataTableHelper.sqlPlaceholder(10); + Assert.assertNotNull(sqlStr); + } + + /** + * functional testing getDeleteCondition + * + * @tc.name: getDeleteCondition + * @tc.number: OHOS_JAVA_database_DataTableHelper_getDeleteCondition_0001 + * @tc.desc: getDeleteCondition + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getDeleteConditionTest() { + String deleteStr = DataTableHelper.getDeleteCondition(new HashMap<>()); + Assert.assertNotNull(deleteStr); + } + + /** + * functional testing mapToString + * + * @tc.name: mapToString + * @tc.number: OHOS_JAVA_database_DataTableHelper_mapToString_0001 + * @tc.desc: mapToString + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void mapToStringTest() { + String mapStr = DataTableHelper.mapToString(new HashMap<>()); + Assert.assertNotNull(mapStr); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryDataTest.java deleted file mode 100644 index b689a0d41..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryDataTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package ohos.devtools.datasources.databases.datatable; - -import ohos.devtools.datasources.databases.datatable.enties.MemoryData; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description MemoryDataTest - * @Date 2021/4/23 11:30 - **/ -public class MemoryDataTest { - /** - * 时间戳 - */ - private long timeStamp = 2006 - 07 - 11; - - /** - * sessionId数字3243 - */ - private int sessionId = 3243; - - /** - * localSessionId - */ - private long localSessionId = 1619147859561L; - - /** - * memoryData 实例 - */ - private MemoryData memoryData = new MemoryData(); - - /** - * object 数据实例 - */ - private Object object = new Object(); - - /** - * functional testing init - * - * @tc.name: initObj - * @tc.number: OHOS_JAVA_database_MemoryData_initObj_0001 - * @tc.desc: initObj - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Before - public void initObj() { - memoryData.setSession(localSessionId); - memoryData.setSessionId(sessionId); - memoryData.setTimeStamp(timeStamp); - memoryData.setData(object); - } - - /** - * functional testing getSession - * - * @tc.name: getSession - * @tc.number: OHOS_JAVA_database_MemoryData_getSession_0001 - * @tc.desc: getSession - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getSessionTest() { - long session = memoryData.getSession(); - Assert.assertEquals(session, 1619147859561L); - } - - /** - * functional testing getSessionId - * - * @tc.name: getSessionId - * @tc.number: OHOS_JAVA_database_MemoryData_getSessionId_0001 - * @tc.desc: getSessionId - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getSessionIdTest() { - int session = memoryData.getSessionId(); - Assert.assertEquals(session, 3243); - } - - /** - * functional testing getlocalSessionId - * - * @tc.name: getlocalSessionId - * @tc.number: OHOS_JAVA_database_MemoryData_getlocalSessionId_0001 - * @tc.desc: getlocalSessionId - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getlocalSessionIdTest() { - long session = memoryData.getLocalSessionId(); - Assert.assertEquals(session, 1619147859561L); - } - - /** - * functional testing getTimeStamp - * - * @tc.name: getTimeStamp - * @tc.number: OHOS_JAVA_database_MemoryData_getTimeStamp_0001 - * @tc.desc: getTimeStamp - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getTimeStampTest() { - long session = memoryData.getTimeStamp(); - Assert.assertEquals(session, 2006 - 07 - 11); - } - - /** - * functional testing getData - * - * @tc.name: getData - * @tc.number: OHOS_JAVA_database_MemoryData_getData_0001 - * @tc.desc: getData - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getDataTest() { - Object obj = memoryData.getData(); - Assert.assertNotNull(obj); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryTableTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryTableTest.java new file mode 100644 index 000000000..d34b0a8db --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/databases/datatable/MemoryTableTest.java @@ -0,0 +1,162 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.databases.datatable; + +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory Table Test + */ +public class MemoryTableTest { + private MemoryTable memoryTable; + private List list; + + /** + * functional testing + * + * @tc.name: init + * @tc.number: OHOS_JAVA_views_devtools_init_0001 + * @tc.desc: init + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Before + public void init() { + memoryTable = new MemoryTable(); + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(1L); + processMemInfo.setSessionId(1); + processMemInfo.setTimeStamp(1L); + MemoryPluginResult.AppSummary appSummary = MemoryPluginResult.AppSummary.newBuilder().setCode(1L).build(); + processMemInfo.setData(appSummary); + list = new ArrayList<>(); + list.add(processMemInfo); + } + + /** + * functional testing + * + * @tc.name: memoryTableTest + * @tc.number: OHOS_JAVA_views_devtools_memoryTableTest_0001 + * @tc.desc: memory Table Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void memoryTableTest() { + MemoryTable table = new MemoryTable(); + Assert.assertNotNull(table); + } + + /** + * functional testing + * + * @tc.name: insertProcessMemInfoTest + * @tc.number: OHOS_JAVA_views_devtools_insertProcessMemInfoTest_0001 + * @tc.desc: insert ProcessMem Info Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void insertProcessMemInfoTest() { + boolean res = memoryTable.insertProcessMemInfo(list); + Assert.assertTrue(res); + } + + /** + * functional testing + * + * @tc.name: insertProcessMemInfoTest + * @tc.number: OHOS_JAVA_views_devtools_insertProcessMemInfoTest_0002 + * @tc.desc: insert ProcessMem Info Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void insertProcessMemInfoTest02() { + boolean res = memoryTable.insertProcessMemInfo(null); + Assert.assertFalse(res); + } + + /** + * functional testing + * + * @tc.name: insertProcessMemInfoTest + * @tc.number: OHOS_JAVA_views_devtools_insertProcessMemInfoTest_0003 + * @tc.desc: insert ProcessMem Info Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void insertProcessMemInfoTest03() { + boolean res1 = memoryTable.insertProcessMemInfo(list); + boolean res2 = memoryTable.insertProcessMemInfo(null); + Assert.assertNotEquals(res1, res2); + } + + /** + * functional testing + * + * @tc.name: insertProcessMemInfoTest + * @tc.number: OHOS_JAVA_views_devtools_insertProcessMemInfoTest_0004 + * @tc.desc: insert ProcessMem Info Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void insertProcessMemInfoTest04() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(1L); + processMemInfo.setSessionId(1); + processMemInfo.setTimeStamp(1L); + processMemInfo.setData(null); + list.add(processMemInfo); + boolean res = memoryTable.insertProcessMemInfo(list); + Assert.assertTrue(res); + } + + /** + * functional testing + * + * @tc.name: insertProcessMemInfoTest + * @tc.number: OHOS_JAVA_views_devtools_insertProcessMemInfoTest_0005 + * @tc.desc: insert ProcessMem Info Test + * @tc.type: profiler scrollbar test + * @tc.require: SR-002-AR-001 + */ + @Test + public void insertProcessMemInfoTest05() { + for (int i = 0; i < 1000; i++) { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(1L); + processMemInfo.setSessionId(10); + processMemInfo.setTimeStamp(1L); + MemoryPluginResult.AppSummary appSummary = MemoryPluginResult.AppSummary.newBuilder().setCode(1L).build(); + processMemInfo.setData(appSummary); + list.add(processMemInfo); + } + boolean res = memoryTable.insertProcessMemInfo(list); + Assert.assertTrue(res); + } + +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/HiprofilerClientTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/HiprofilerClientTest.java index 4790a6c6c..0455eb438 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/HiprofilerClientTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/HiprofilerClientTest.java @@ -1,1263 +1,1551 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.transport.grpc; - -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import io.grpc.util.MutableHandlerRegistry; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -/** - * 测试Hiprofiler模块 - * - * @version 1.0 - * @date 2021/02/02 10:11 - **/ -public class HiprofilerClientTest { - private static volatile int requestId = 1; - private String IP; - private int firstPort; - private int secondPort; - private int thirPort; - private String serverName; - private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); - - /** - * grpcCleanup - */ - private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - - /** - * functional testing init - * - * @tc.name: setUp - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_setUp_0001 - * @tc.desc: setUp - * @tc.type: functional testing - * @tc.require: SR-005 - * @throws IOException throw IOException - */ - @Before - public void setUp() throws IOException { - IP = ""; - firstPort = 5001; - secondPort = 5002; - thirPort = 5003; - serverName = InProcessServerBuilder.generateName(); - grpcCleanup.register( - InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() - .start()); - } - - /** - * functional testing getProfilerClient normal get Single - * - * @tc.name: getProfilerClient - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0001 - * @tc.desc: getProfilerClient - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void getProfilerClientTest01() { - ProfilerClient profierlClient = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort); - Assert.assertNotNull(profierlClient); - } - - /** - * functional testing getProfilerClient normal get instance diffrent port is not equals - * - * @tc.name: getProfilerClient - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0002 - * @tc.desc: getProfilerClient - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void getProfilerClientTest02() { - ProfilerClient profierlClientOne = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort); - ProfilerClient profilerClientTWo = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); - Assert.assertNotEquals(profierlClientOne, profilerClientTWo); - } - - /** - * functional testing getProfilerClient normal get instance same port is equals - * - * @tc.name: getProfilerClient - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0003 - * @tc.desc: getProfilerClient - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void getProfilerClientTest03() { - ProfilerClient profierlClientOne = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); - ProfilerClient profilerClientTWo = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); - Assert.assertEquals(profierlClientOne, profilerClientTWo); - } - - /** - * functional testing getProfilerClient abnormal port is -1 - * - * @tc.name: getProfilerClient - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0004 - * @tc.desc: getProfilerClient - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void getProfilerClientTest04() { - ProfilerClient profierlClient = HiProfilerClient.getInstance().getProfilerClient(IP, -1); - Assert.assertNull(profierlClient); - } - - /** - * functional testing getProfilerClient abnormal port is 0 - * - * @tc.name: getProfilerClient - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0005 - * @tc.desc: getProfilerClient - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void getProfilerClientTest05() { - ProfilerClient profierlClient = HiProfilerClient.getInstance().getProfilerClient(IP, 0); - Assert.assertNull(profierlClient); - } - - /** - * functional testing destroyProfiler normal - * - * @tc.name: destroyProfiler - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0001 - * @tc.desc: destroyProfiler - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void destroyProfilerTest01() { - ProfilerClient profierlClient = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); - Assert.assertNotNull(profierlClient); - boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, secondPort); - Assert.assertTrue(res); - } - - /** - * functional testing destroyProfiler normal different port - * - * @tc.name: destroyProfiler - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0002 - * @tc.desc: destroyProfiler - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void destroyProfilerTest02() { - boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, firstPort); - Assert.assertTrue(res); - } - - /** - * functional testing destroyProfiler abnormal port is 0 - * - * @tc.name: destroyProfiler - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0003 - * @tc.desc: destroyProfiler - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void destroyProfilerTest03() { - boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, 0); - Assert.assertFalse(res); - } - - /** - * functional testing destroyProfiler abnormal port is 65536 - * - * @tc.name: destroyProfiler - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0004 - * @tc.desc: destroyProfiler - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void destroyProfilerTest04() { - boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, 65536); - Assert.assertFalse(res); - } - - /** - * functional testing destroyProfiler abnormal port is -1 - * - * @tc.name: destroyProfiler - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0005 - * @tc.desc: destroyProfiler - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void destroyProfilerTest05() { - boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, -1); - Assert.assertFalse(res); - } - - /** - * functional testing getCapabilities normal based on port and Status - * - * @tc.name: getCapabilities - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0001 - * @tc.desc: getCapabilities - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getCapabilitiesTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") - .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, thirPort, channel); - ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, thirPort); - List caps = res.getCapabilitiesList(); - caps.forEach(profilerPluginCapability -> { - Assert.assertEquals(profilerPluginCapability.getName(), "test0"); - }); - Assert.assertEquals(caps.size(), 1); - } - - /** - * functional testing getCapabilities abnormal based on port is 0 - * - * @tc.name: getCapabilities - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0002 - * @tc.desc: getCapabilities - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getCapabilitiesTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") - .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); - ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 0); - Assert.assertNull(res); - } - - /** - * functional testing getCapabilities abnormal based on port and Status is -1 - * - * @tc.name: getCapabilities - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0003 - * @tc.desc: getCapabilities - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getCapabilitiesTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") - .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10001, channel); - ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 10001); - Assert.assertEquals(res.getStatus(), -1); - } - - /** - * functional testing getCapabilities abnormal based on port is -1 - * - * @tc.name: getCapabilities - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0004 - * @tc.desc: getCapabilities - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getCapabilitiesTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") - .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); - ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, -1); - Assert.assertNull(res); - } - - /** - * functional testing getCapabilities 2 normal based on port and Status - * - * @tc.name: getCapabilities - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0005 - * @tc.desc: getCapabilities - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getCapabilitiesTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libbytraceplugin.z.so") - .setPath("/data/local/tmp/libbytraceplugin.z.so").build()).build(); - - ProfilerServiceTypes.ProfilerPluginCapability pluginCapabilityPtrace = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libptrace_plugin.z.so") - .setPath("/data/local/tmp/libptrace_plugin.z.so").build()).build(); - - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .addCapabilities(pluginCapabilityPtrace).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11004, channel); - ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 11004); - List caps = res.getCapabilitiesList(); - Assert.assertEquals(caps.size(), 2); - } - - /** - * functional testing requestCreateSession Normal based on reportprocesstree is true - * - * @tc.name: requestCreateSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0001 - * @tc.desc: requestCreateSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestCreateSessionTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - HiProfilerClient.getInstance().getProfilerClient(IP, 10002, channel); - int res = HiProfilerClient.getInstance() - .requestCreateSession(10002, "/data/local/tmp/libmemdata.z.so", 212, true, ""); - Assert.assertEquals(res, 0); - } - - /** - * functional testing requestCreateSession Normal based on reportprocesstree is false - * - * @tc.name: requestCreateSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0002 - * @tc.desc: requestCreateSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestCreateSessionTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - HiProfilerClient.getInstance().getProfilerClient(IP, 10002, channel); - int res = HiProfilerClient.getInstance() - .requestCreateSession(10002, "/data/local/tmp/libmemdata.z.so", 212, false, ""); - Assert.assertEquals(res, 0); - } - - /** - * functional testing requestCreateSession abNormal based on SessionId is -1 and reportprocesstree is true - * - * @tc.name: requestCreateSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0003 - * @tc.desc: requestCreateSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestCreateSessionTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - HiProfilerClient.getInstance().getProfilerClient(IP, 10003, channel); - int res = HiProfilerClient.getInstance() - .requestCreateSession(10003, "/data/local/tmp/libmemdata.z.so", 212, true, ""); - - Assert.assertEquals(res, -1); - } - - /** - * functional testing requestCreateSession abNormal based on port is 0 - * - * @tc.name: requestCreateSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0004 - * @tc.desc: requestCreateSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestCreateSessionTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); - int res = - HiProfilerClient.getInstance().requestCreateSession(0, "/data/local/tmp/libmemdata.z.so", 212, false, ""); - Assert.assertEquals(res, -1); - } - - /** - * functional testing requestCreateSession abNormal based on port is -1 - * - * @tc.name: requestCreateSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0005 - * @tc.desc: requestCreateSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestCreateSessionTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(-1).setStatus(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); - int res = - HiProfilerClient.getInstance().requestCreateSession(-1, "/data/local/tmp/libmemdata.z.so", 212, true, ""); - Assert.assertEquals(res, -1); - } - - /** - * functional testing requestStartSession normal based on status is 0 - * - * @tc.name: requestStartSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0001 - * @tc.desc: requestStartSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestStartSessionTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10003, channel); - boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 10003, 1); - Assert.assertTrue(res); - } - - /** - * functional testing requestStartSession abnormal based on status is -1 - * - * @tc.name: requestStartSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0002 - * @tc.desc: requestStartSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestStartSessionTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(-1) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11103, channel); - boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 11103, 1); - Assert.assertFalse(res); - } - - /** - * functional testing requestStartSession normal based on status is 0 and port different - * - * @tc.name: requestStartSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0003 - * @tc.desc: requestStartSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestStartSessionTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10004, channel); - boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 10004, 2); - Assert.assertTrue(res); - } - - /** - * functional testing requestStartSession abnormal based on port is 0 - * - * @tc.name: requestStartSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0004 - * @tc.desc: requestStartSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestStartSessionTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); - boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 0, 2); - Assert.assertFalse(res); - } - - /** - * functional testing requestStartSession abnormal based on port is -1 - * - * @tc.name: requestStartSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0005 - * @tc.desc: requestStartSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-001 - */ - @Test - public void requestStartSessionTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); - boolean res = HiProfilerClient.getInstance().requestStartSession(IP, -1, 2); - Assert.assertFalse(res); - } - - /** - * functional testing requestStopSession normal based on status is 0 - * - * @tc.name: requestStopSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0001 - * @tc.desc: requestStopSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-002 - */ - @Test - public void requestStopSessionTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10004, channel); - - boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 10004, 111, false); - Assert.assertTrue(res); - } - - /** - * functional testing requestStopSession normal based on status is -1 - * - * @tc.name: requestStopSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0002 - * @tc.desc: requestStopSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-002 - */ - @Test - public void requestStopSessionTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10104, channel); - - boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 10104, 111, false); - Assert.assertFalse(res); - } - - /** - * functional testing requestStopSession normal based on port - * - * @tc.name: requestStopSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0003 - * @tc.desc: requestStopSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-002 - */ - @Test - public void requestStopSessionTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 12004, channel); - - boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 12004, 111, false); - Assert.assertTrue(res); - } - - /** - * functional testing requestStopSession abnormal based on port is 0 - * - * @tc.name: requestStopSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0004 - * @tc.desc: requestStopSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-002 - */ - @Test - public void requestStopSessionTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); - - boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 0, 111, false); - Assert.assertFalse(res); - } - - /** - * functional testing requestStopSession abnormal based on port is -1 - * - * @tc.name: requestStopSession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0005 - * @tc.desc: requestStopSession - * @tc.type: functional testing - * @tc.require: SR-005-AR-002 - */ - @Test - public void requestStopSessionTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); - - boolean res = HiProfilerClient.getInstance().requestStopSession(IP, -1, 111, true); - Assert.assertFalse(res); - } - - /** - * functional testing requestdestorySession normal based on status is 0 - * - * @tc.name: requestdestorySession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0001 - * @tc.desc: requestdestorySession - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void requestdestorySessionTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10005, channel); - boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10005, 222); - Assert.assertTrue(res); - } - - /** - * functional testing requestdestorySession abnormal based on status is -1 - * - * @tc.name: requestdestorySession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0002 - * @tc.desc: requestdestorySession - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void requestdestorySessionTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(-1).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10006, channel); - boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10006, 222); - Assert.assertFalse(res); - } - - /** - * functional testing requestdestorySession normal based on status is 0 and diffrent port - * - * @tc.name: requestdestorySession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0003 - * @tc.desc: requestdestorySession - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void requestdestorySessionTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10016, channel); - boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10016, 222); - Assert.assertTrue(res); - } - - /** - * functional testing requestdestorySession abnormal based on port is 0 - * - * @tc.name: requestdestorySession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0004 - * @tc.desc: requestdestorySession - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void requestdestorySessionTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); - boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 0, 222); - Assert.assertFalse(res); - } - - /** - * functional testing requestdestorySession abnormal based on port is -1 - * - * @tc.name: requestdestorySession - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0005 - * @tc.desc: requestdestorySession - * @tc.type: functional testing - * @tc.require: SR-005-AR-004 - */ - @Test - public void requestdestorySessionTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); - boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, -1, 222); - Assert.assertFalse(res); - } - - /** - * functional testing fetchProcessData normal Single get 3 - * - * @tc.name: fetchProcessData - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0001 - * @tc.desc: fetchProcessData - * @tc.type: functional testing - * @tc.require: SR-005-AR-005 - */ - @Test - public void fetchProcessDataTest01() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) - .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("com.eg.and.AlipayGphone") - .setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoThree = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) - .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoOne) - .addProcessesinfo(processesInfoTwo).addProcessesinfo(processesInfoThree).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10007, channel); - List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10007, 11111); - Assert.assertEquals(res.size(), 3); - } - - /** - * functional testing fetchProcessData normal Repeated get 3 and 2 - * - * @tc.name: fetchProcessData - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0002 - * @tc.desc: fetchProcessData - * @tc.type: functional testing - * @tc.require: SR-005-AR-005 - */ - @Test - public void fetchProcessDataTest02() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - int sessionId = request.getSessionId(); - if (sessionId == 1) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoZero = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) - .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142) - .setName("com.eg.and.AlipayGphone").setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) - .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) - .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } else { - MemoryPluginResult.AppSummary appSummary = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoZero = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) - .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(appSummary).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31143) - .setName("com.eg.and.AlipayGphone").setRssShmemKb(1111).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) - .addProcessesinfo(processesInfoOne).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(222).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10008, channel); - List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10008, 1); - Assert.assertEquals(res.size(), 3); - List ress = HiProfilerClient.getInstance().fetchProcessData(IP, 10008, 22); - Assert.assertEquals(ress.size(), 2); - } - - /** - * functional testing fetchProcessData normal get no response data base on status is 0 - * - * @tc.name: fetchProcessData - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0003 - * @tc.desc: fetchProcessData - * @tc.type: functional testing - * @tc.require: SR-005-AR-005 - */ - @Test - public void fetchProcessDataTest03() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10009, channel); - List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10009, 2222); - Assert.assertEquals(res.size(), 0); - } - - /** - * functional testing fetchProcessData normal get no response data base on status is 0 - * - * @tc.name: fetchProcessData - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0004 - * @tc.desc: fetchProcessData - * @tc.type: functional testing - * @tc.require: SR-005-AR-005 - */ - @Test - public void fetchProcessDataTest04() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(1).setStatus(-1).setHasMore(false) - .build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11009, channel); - List res = HiProfilerClient.getInstance().fetchProcessData(IP, 11009, 2222); - Assert.assertEquals(res.size(), 0); - } - - /** - * functional testing fetchProcessData - * - * @tc.name: fetchProcessData - * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0005 - * @tc.desc: fetchProcessData - * @tc.type: functional testing - * @tc.require: SR-005-AR-005 - */ - @Test - public void fetchProcessDataTest05() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoZero = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(3114) - .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(3114).setName("com.eg.and.AlipayGphone") - .setRssShmemKb(2222).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) - .addProcessesinfo(processesInfoOne).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(12345).setStatus(-1) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11007, channel); - List res = HiProfilerClient.getInstance().fetchProcessData(IP, 11007, 11111); - Assert.assertEquals(res.size(), 0); - } - - /** - * get Int Data - * - * @return int - */ - private int getIntData() { - requestId++; - if (requestId == Integer.MAX_VALUE) { - requestId = 0; - } - return requestId; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * test hiprofiler module + */ +public class HiprofilerClientTest { + private static volatile int requestId = 1; + private String IP; + private int firstPort; + private int secondPort; + private int thirdPort; + private String serverName; + private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + /** + * functional testing init + * + * @tc.name: setUp + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_setUp_0001 + * @tc.desc: setUp + * @tc.type: functional testing + * @tc.require: SR-005 + * @throws IOException throw IOException + */ + @Before + public void setUp() throws IOException { + IP = ""; + firstPort = 5001; + secondPort = 5002; + thirdPort = 5003; + serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() + .start()); + } + + /** + * get Instance + * + * @tc.name: getInstanceTest01 + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getInstanceTest_0001 + * @tc.desc: get Instance + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getInstanceTest() { + HiProfilerClient instance = HiProfilerClient.getInstance(); + Assert.assertNotNull(instance); + } + + /** + * functional testing getProfilerClient normal get Single + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0001 + * @tc.desc: getProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientTest01() { + ProfilerClient profilerClient = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort); + Assert.assertNotNull(profilerClient); + } + + /** + * functional testing getProfilerClient normal get instance diffrent port is not equals + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0002 + * @tc.desc: getProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientTest02() { + ProfilerClient profilerClient = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); + Assert.assertNotEquals(profilerClient, client); + } + + /** + * functional testing getProfilerClient normal get instance same port is equals + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0003 + * @tc.desc: getProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientTest03() { + ProfilerClient profilerClient = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort); + Assert.assertEquals(profilerClient, client); + } + + /** + * functional testing getProfilerClient abnormal port is -1 + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0004 + * @tc.desc: getProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientTest04() { + ProfilerClient profilerClient = HiProfilerClient.getInstance().getProfilerClient(IP, -1); + Assert.assertNull(profilerClient); + } + + /** + * functional testing getProfilerClient abnormal port is 0 + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClient_0005 + * @tc.desc: getProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientTest05() { + ProfilerClient profilerClient = HiProfilerClient.getInstance().getProfilerClient(IP, 0); + Assert.assertNull(profilerClient); + } + + /** + * get ProfilerClient + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClientMultiParam_0001 + * @tc.desc: get ProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientMultiParam01() { + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 65536, channel); + Assert.assertNull(client); + } + + /** + * get ProfilerClient + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClientMultiParam_0002 + * @tc.desc: get ProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientMultiParam02() { + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort, channel); + ProfilerClient getClient = HiProfilerClient.getInstance().getProfilerClient(IP, secondPort, channel); + Assert.assertNotEquals(client, getClient); + } + + /** + * get ProfilerClient + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClientMultiParam_0003 + * @tc.desc: get ProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientMultiParam03() { + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort, channel); + ProfilerClient getClient = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort, channel); + Assert.assertEquals(client, getClient); + } + + /** + * get ProfilerClient + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClientMultiParam_0004 + * @tc.desc: get ProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientMultiParam04() { + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + Assert.assertNull(client); + } + + /** + * get ProfilerClient + * + * @tc.name: getProfilerClient + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getProfilerClientMultiParam_0005 + * @tc.desc: get ProfilerClient + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getProfilerClientMultiParam05() { + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + Assert.assertNull(client); + } + + /** + * functional testing destroyProfiler normal + * + * @tc.name: destroyProfiler + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0001 + * @tc.desc: destroyProfiler + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void destroyProfilerTest01() { + boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, secondPort); + Assert.assertTrue(res); + } + + /** + * functional testing destroyProfiler normal different port + * + * @tc.name: destroyProfiler + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0002 + * @tc.desc: destroyProfiler + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void destroyProfilerTest02() { + boolean res = HiProfilerClient.getInstance().destroyProfiler(null, firstPort); + Assert.assertTrue(res); + } + + /** + * functional testing destroyProfiler abnormal port is 0 + * + * @tc.name: destroyProfiler + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0003 + * @tc.desc: destroyProfiler + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void destroyProfilerTest03() { + boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, 0); + Assert.assertFalse(res); + } + + /** + * functional testing destroyProfiler abnormal port is 65536 + * + * @tc.name: destroyProfiler + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0004 + * @tc.desc: destroyProfiler + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void destroyProfilerTest04() { + boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, 65536); + Assert.assertFalse(res); + } + + /** + * functional testing destroyProfiler abnormal port is -1 + * + * @tc.name: destroyProfiler + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_destroyProfiler_0005 + * @tc.desc: destroyProfiler + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void destroyProfilerTest05() { + boolean res = HiProfilerClient.getInstance().destroyProfiler(IP, -1); + Assert.assertFalse(res); + } + + /** + * functional testing getCapabilities normal based on port and Status + * + * @tc.name: getCapabilities + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0001 + * @tc.desc: getCapabilities + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getCapabilitiesTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, thirdPort, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = + HiProfilerClient.getInstance().getCapabilities(IP, thirdPort); + List caps = res.getCapabilitiesList(); + caps.forEach(profilerPluginCapability -> { + Assert.assertEquals(profilerPluginCapability.getName(), "test0"); + }); + Assert.assertEquals(caps.size(), 1); + } + + /** + * functional testing getCapabilities abnormal based on port is 0 + * + * @tc.name: getCapabilities + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0002 + * @tc.desc: getCapabilities + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getCapabilitiesTest02() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 0); + Assert.assertNull(res); + } + + /** + * functional testing getCapabilities abnormal based on port and Status is -1 + * + * @tc.name: getCapabilities + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0003 + * @tc.desc: getCapabilities + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getCapabilitiesTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(-1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10001, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 10001); + Assert.assertEquals(res.getStatus(), -1); + } + + /** + * functional testing getCapabilities abnormal based on port is -1 + * + * @tc.name: getCapabilities + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0004 + * @tc.desc: getCapabilities + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getCapabilitiesTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, -1); + Assert.assertNull(res); + } + + /** + * functional testing getCapabilities 2 normal based on port and Status + * + * @tc.name: getCapabilities + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilities_0005 + * @tc.desc: getCapabilities + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getCapabilitiesTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libbytraceplugin.z.so") + .setPath("/data/local/tmp/libbytraceplugin.z.so").build()).build(); + + ProfilerServiceTypes.ProfilerPluginCapability pluginCapabilityPtrace = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libptrace_plugin.z.so") + .setPath("/data/local/tmp/libptrace_plugin.z.so").build()).build(); + + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .addCapabilities(pluginCapabilityPtrace).setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11004, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 11004); + List caps = res.getCapabilitiesList(); + Assert.assertEquals(caps.size(), 2); + } + + /** + * get Capabilities Overtime Test + * + * @tc.name: getCapabilitiesOvertimeTest06 + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_getCapabilitiesOvertimeTest_0006 + * @tc.desc: get Capabilities Overtime Test + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void getCapabilitiesOvertimeTest06() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + try { + TimeUnit.SECONDS.sleep(6); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, thirdPort, channel); + ProfilerServiceTypes.GetCapabilitiesResponse res = HiProfilerClient.getInstance().getCapabilities(IP, 5004); + List caps = res.getCapabilitiesList(); + Assert.assertEquals(caps.size(), 0); + } + + /** + * functional testing requestCreateSession Normal based on reportprocesstree is true + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0001 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, 10002, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(10002, "/data/local/tmp/libmemdata.z.so", 212, true, DeviceType.FULL_HOS_DEVICE); + Assert.assertEquals(res, 0); + } + + /** + * functional testing requestCreateSession Normal based on reportprocesstree is false + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0002 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionTest02() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, 10002, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(10002, "/data/local/tmp/libmemdata.z.so", 212, false, DeviceType.FULL_HOS_DEVICE); + Assert.assertEquals(res, 0); + } + + /** + * functional testing requestCreateSession abNormal based on SessionId is -1 and reportprocesstree is true + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0003 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(-1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, 10003, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(10003, "/data/local/tmp/libmemdata.z.so", 212, true, DeviceType.FULL_HOS_DEVICE); + + Assert.assertEquals(res, -1); + } + + /** + * functional testing requestCreateSession abNormal based on port is 0 + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0004 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(0, "/data/local/tmp/libmemdata.z.so", 212, false, DeviceType.FULL_HOS_DEVICE); + Assert.assertEquals(res, -1); + } + + /** + * functional testing requestCreateSession abNormal based on port is -1 + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0005 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(-1).setStatus(-1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(-1, "/data/local/tmp/libmemdata.z.so", 212, true, DeviceType.FULL_HOS_DEVICE); + Assert.assertEquals(res, -1); + } + + /** + * functional testing requestCreateSession abNormal based on port is -1 + * + * @tc.name: requestCreateSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestCreateSession_0006 + * @tc.desc: requestCreateSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestCreateSessionOvertimeTest06() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); + try { + TimeUnit.SECONDS.sleep(6); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + HiProfilerClient.getInstance().getProfilerClient(IP, 10004, channel); + int res = HiProfilerClient.getInstance() + .requestCreateSession(10004, "/data/local/tmp/libmemdata.z.so", 212, true, DeviceType.FULL_HOS_DEVICE); + Assert.assertEquals(res, -1); + } + + /** + * functional testing requestStartSession normal based on status is 0 + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0001 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10003, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 10003, 1); + Assert.assertTrue(res); + } + + /** + * functional testing requestStartSession abnormal based on status is -1 + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0002 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionTest02() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(-1) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11103, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 11103, 1); + Assert.assertFalse(res); + } + + /** + * functional testing requestStartSession normal based on status is 0 and port different + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0003 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 65536, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 65536, 2); + Assert.assertFalse(res); + } + + /** + * functional testing requestStartSession abnormal based on port is 0 + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0004 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 0, 2); + Assert.assertFalse(res); + } + + /** + * functional testing requestStartSession abnormal based on port is -1 + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0005 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, -1, 2); + Assert.assertFalse(res); + } + + /** + * functional testing requestStartSession abnormal based on port is -1 + * + * @tc.name: requestStartSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStartSession_0006 + * @tc.desc: requestStartSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-001 + */ + @Test + public void requestStartSessionOvertimeTest06() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + try { + TimeUnit.SECONDS.sleep(4); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10003, channel); + boolean res = HiProfilerClient.getInstance().requestStartSession(IP, 10003, 1); + Assert.assertTrue(res); + } + + /** + * functional testing requestStopSession normal based on status is 0 + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0001 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10004, channel); + + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 10004, 111, false); + Assert.assertTrue(res); + } + + /** + * functional testing requestStopSession normal based on status is -1 + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0002 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionTest02() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(-1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10104, channel); + + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 10104, 111, false); + Assert.assertFalse(res); + } + + /** + * functional testing requestStopSession normal based on port + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0003 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 65536, channel); + + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 65536, 111, false); + Assert.assertFalse(res); + } + + /** + * functional testing requestStopSession abnormal based on port is 0 + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0004 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 0, 111, false); + Assert.assertFalse(res); + } + + /** + * functional testing requestStopSession abnormal based on port is -1 + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0005 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, -1, 111, true); + Assert.assertFalse(res); + } + + /** + * functional testing requestStopSession abnormal based on port is -1 + * + * @tc.name: requestStopSession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestStopSession_0006 + * @tc.desc: requestStopSession + * @tc.type: functional testing + * @tc.require: SR-005-AR-002 + */ + @Test + public void requestStopSessionOvertimeTest06() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + try { + TimeUnit.SECONDS.sleep(4); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10004, channel); + boolean res = HiProfilerClient.getInstance().requestStopSession(IP, 10004, 111, false); + Assert.assertTrue(res); + } + + /** + * functional testing requestdestorySession normal based on status is 0 + * + * @tc.name: requestdestorySession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0001 + * @tc.desc: requestdestorySession + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10005, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10005, 222); + Assert.assertTrue(res); + } + + /** + * functional testing requestdestorySession abnormal based on status is -1 + * + * @tc.name: requestdestorySession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0002 + * @tc.desc: requestdestorySession + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionTest02() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(-1).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10006, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10006, 222); + Assert.assertFalse(res); + } + + /** + * functional testing requestdestorySession normal based on status is 0 and diffrent port + * + * @tc.name: requestdestorySession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0003 + * @tc.desc: requestdestorySession + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 65536, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 65536, 222); + Assert.assertFalse(res); + } + + /** + * functional testing requestdestorySession abnormal based on port is 0 + * + * @tc.name: requestdestorySession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0004 + * @tc.desc: requestdestorySession + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 0, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 0, 222); + Assert.assertFalse(res); + } + + /** + * functional testing requestdestorySession abnormal based on port is -1 + * + * @tc.name: requestdestorySession + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestdestorySession_0005 + * @tc.desc: requestdestorySession + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, -1, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, -1, 222); + Assert.assertFalse(res); + } + + /** + * functional testing requestdestory + * + * @tc.name: requestDestroySessionOvertimeTest06 + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_requestDestroySessionOvertimeTest_0006 + * @tc.desc: request Destroy Session Overtime Test + * @tc.type: functional testing + * @tc.require: SR-005-AR-004 + */ + @Test + public void requestDestroySessionOvertimeTest06() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + try { + TimeUnit.SECONDS.sleep(2); + } catch (InterruptedException exception) { + exception.printStackTrace(); + } + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10005, channel); + boolean res = HiProfilerClient.getInstance().requestDestroySession(IP, 10005, 222); + Assert.assertTrue(res); + } + + /** + * functional testing fetchProcessData normal Single get 3 + * + * @tc.name: fetchProcessData + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0001 + * @tc.desc: fetchProcessData + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void fetchProcessDataTest01() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) + .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("com.eg.and.AlipayGphone") + .setRssShmemKb(2222222).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoThree = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) + .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoOne) + .addProcessesinfo(processesInfoTwo).addProcessesinfo(processesInfoThree).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10007, channel); + List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10007, 11111); + Assert.assertEquals(res.size(), 3); + } + + /** + * functional testing fetchProcessData normal Repeated get 3 and 2 + * + * @tc.name: fetchProcessData + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0002 + * @tc.desc: fetchProcessData + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void fetchProcessDataTest02() { + MockProfilerServiceImplBase getFeatureImpl = getMockProfilerServiceImplBase(); + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10008, channel); + List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10008, 1); + Assert.assertEquals(res.size(), 3); + List ress = HiProfilerClient.getInstance().fetchProcessData(IP, 10008, 22); + Assert.assertEquals(ress.size(), 2); + } + + @NotNull + private MockProfilerServiceImplBase getMockProfilerServiceImplBase() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + int sessionId = request.getSessionId(); + if (sessionId == 1) { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = getFetchDataResponse(sss); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } else { + MemoryPluginResult.AppSummary appSummary = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoZero = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) + .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(appSummary).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31143) + .setName("com.eg.and.AlipayGphone").setRssShmemKb(1111).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) + .addProcessesinfo(processesInfoOne).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(222).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + } + }; + return getFeatureImpl; + } + + private ProfilerServiceTypes.FetchDataResponse getFetchDataResponse(MemoryPluginResult.AppSummary sss) { + MemoryPluginResult.ProcessMemoryInfo processesInfoZero = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary( + sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142) + .setName("com.eg.and.AlipayGphone").setRssShmemKb(2222222).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) + .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) + .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + return fetchDataResponse; + } + + /** + * functional testing fetchProcessData normal get no response data base on status is 0 + * + * @tc.name: fetchProcessData + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0003 + * @tc.desc: fetchProcessData + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void fetchProcessDataTest03() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 10009, channel); + List res = HiProfilerClient.getInstance().fetchProcessData(IP, 10009, 2222); + Assert.assertEquals(res.size(), 0); + } + + /** + * functional testing fetchProcessData normal get no response data base on status is 0 + * + * @tc.name: fetchProcessData + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0004 + * @tc.desc: fetchProcessData + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void fetchProcessDataTest04() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(1).setStatus(-1).setHasMore(false) + .build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11009, channel); + List res = HiProfilerClient.getInstance().fetchProcessData(IP, 11009, 2222); + Assert.assertEquals(res.size(), 0); + } + + /** + * functional testing fetchProcessData + * + * @tc.name: fetchProcessData + * @tc.number: OHOS_JAVA_grpc_HiProfilerClient_fetchProcessData_0005 + * @tc.desc: fetchProcessData + * @tc.type: functional testing + * @tc.require: SR-005-AR-005 + */ + @Test + public void fetchProcessDataTest05() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoZero = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(3114) + .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(3114).setName("com.eg.and.AlipayGphone") + .setRssShmemKb(2222).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) + .addProcessesinfo(processesInfoOne).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(12345).setStatus(-1) + .setHasMore(false).addPluginData(data).build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, 11007, channel); + List res = HiProfilerClient.getInstance().fetchProcessData(IP, 11007, 11111); + Assert.assertEquals(res.size(), 0); + } + + /** + * get Int Data + * + * @return int + */ + private int getIntData() { + requestId++; + if (requestId == Integer.MAX_VALUE) { + requestId = 0; + } + return requestId; + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/MockProfilerServiceImplBase.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/MockProfilerServiceImplBase.java index a77c1416a..c011b0e9a 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/MockProfilerServiceImplBase.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/MockProfilerServiceImplBase.java @@ -1,25 +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. - */ - -package ohos.devtools.datasources.transport.grpc; - -import ohos.devtools.datasources.transport.grpc.service.IProfilerServiceGrpc; - -/** - * @version 1.0 - * @date 2021/03/22 13:52 - **/ -public class MockProfilerServiceImplBase extends IProfilerServiceGrpc.IProfilerServiceImplBase { -} +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import ohos.devtools.datasources.transport.grpc.service.IProfilerServiceGrpc; + +/** + * Mock Profiler ServiceImpl Base + */ +public class MockProfilerServiceImplBase extends IProfilerServiceGrpc.IProfilerServiceImplBase { +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/ProfilerClientTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/ProfilerClientTest.java new file mode 100644 index 000000000..8127f908b --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/transport/grpc/ProfilerClientTest.java @@ -0,0 +1,723 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.transport.grpc; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.common.util.BeanUtil; +import ohos.devtools.datasources.utils.common.util.CommonUtil; +import ohos.devtools.views.common.LayoutConstants; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + +/** + * Profiler Client Test + */ +public class ProfilerClientTest { + private String ip; + private int port; + private String serverName; + private ManagedChannel channel; + private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + + /** + * functional testing init + * + * @tc.name: setUp + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_setUp_0001 + * @tc.desc: setUp + * @tc.type: functional testing + * @tc.require: SR-005 + * @throws IOException throw IOException + */ + @Before + public void setUp() throws IOException { + ip = ""; + port = 5001; + serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() + .start()); + MockProfilerServiceImplBase getFeatureImpl = getMockProfilerServiceImplBase(); + channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + } + + @NotNull + private MockProfilerServiceImplBase getMockProfilerServiceImplBase() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.GetCapabilitiesResponse reply = getGetCapabilitiesResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = getCreateSessionResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StartSessionResponse reply = getStartSessionResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(1).setStatus(-1).setHasMore(false) + .build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + return getFeatureImpl; + } + + private ProfilerServiceTypes.StartSessionResponse getStartSessionResponse() { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + return reply; + } + + private ProfilerServiceTypes.CreateSessionResponse getCreateSessionResponse() { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.getDefaultInstance(); + return reply; + } + + private ProfilerServiceTypes.GetCapabilitiesResponse getGetCapabilitiesResponse() { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + return reply; + } + + /** + * functional testing + * + * @tc.name: getCapabilitiesTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_getCapabilitiesTest_0001 + * @tc.desc: get Capabilities Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getCapabilitiesTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.GetCapabilitiesResponse capabilities = profilerClient.getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()).build()); + Assert.assertNotNull(capabilities); + } + + /** + * functional testing + * + * @tc.name: getCapabilitiesTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_getCapabilitiesTest_0002 + * @tc.desc: get Capabilities Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getCapabilitiesTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.GetCapabilitiesResponse capabilities = profilerClient.getCapabilities(null); + Assert.assertNotNull(capabilities); + } + + /** + * functional testing + * + * @tc.name: getCapabilitiesTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_getCapabilitiesTest_0003 + * @tc.desc: get Capabilities Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getCapabilitiesTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, 0, channel); + ProfilerServiceTypes.GetCapabilitiesResponse capabilities = profilerClient.getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()).build()); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: getCapabilitiesTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_getCapabilitiesTest_0004 + * @tc.desc: get Capabilities Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getCapabilitiesTest04() { + ProfilerClient profilerClient = new ProfilerClient(null, -1, channel); + ProfilerServiceTypes.GetCapabilitiesResponse capabilities = profilerClient.getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()).build()); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: getCapabilitiesTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_getCapabilitiesTest_0005 + * @tc.desc: get Capabilities Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void getCapabilitiesTest05() { + ProfilerClient profilerClient = new ProfilerClient(null, port, channel); + ProfilerServiceTypes.GetCapabilitiesResponse capabilities = profilerClient.getCapabilities( + ProfilerServiceTypes.GetCapabilitiesRequest.newBuilder().setRequestId(CommonUtil.getRequestId()).build()); + Assert.assertNotNull(capabilities); + } + + /** + * functional testing + * + * @tc.name: createSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_createSessionTest_0001 + * @tc.desc: create Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void createSessionTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = + BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); + BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf).build(); + CommonTypes.ProfilerPluginConfig plugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setName("pluginName") + .setConfigData(ByteString.copyFrom(configByte)).build(); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) + .addPluginConfigs(plugConfig).build(); + ProfilerServiceTypes.CreateSessionResponse session = profilerClient.createSession(request); + Assert.assertNotNull(session); + } + + /** + * functional testing + * + * @tc.name: createSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_createSessionTest_0002 + * @tc.desc: create Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void createSessionTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.CreateSessionResponse session = profilerClient.createSession(null); + Assert.assertNotNull(session); + } + + /** + * functional testing + * + * @tc.name: createSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_createSessionTest_0003 + * @tc.desc: create Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void createSessionTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, -1, channel); + BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = + BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); + BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf).build(); + CommonTypes.ProfilerPluginConfig plugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setName("pluginName") + .setConfigData(ByteString.copyFrom(configByte)).build(); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) + .addPluginConfigs(plugConfig).build(); + ProfilerServiceTypes.CreateSessionResponse response = profilerClient.createSession(request); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: createSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_createSessionTest_0004 + * @tc.desc: create Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void createSessionTest04() { + ProfilerClient profilerClient = new ProfilerClient(null, port, channel); + ProfilerServiceTypes.CreateSessionResponse session = profilerClient.createSession(null); + Assert.assertNotNull(session); + } + + /** + * functional testing + * + * @tc.name: createSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_createSessionTest_0005 + * @tc.desc: create Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void createSessionTest05() { + ProfilerClient profilerClient = new ProfilerClient(ip, 0, channel); + BytracePluginConfigOuterClass.BytracePluginConfig.Builder build = + BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder(); + BytracePluginConfigOuterClass.BytracePluginConfig config = build.build(); + byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config); + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf = + ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD) + .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build(); + ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = + ProfilerServiceTypes.ProfilerSessionConfig.newBuilder() + .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf).build(); + CommonTypes.ProfilerPluginConfig plugConfig = + CommonTypes.ProfilerPluginConfig.newBuilder().setName("pluginName") + .setConfigData(ByteString.copyFrom(configByte)).build(); + ProfilerServiceTypes.CreateSessionRequest request = + ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(1).setSessionConfig(sessionConfig) + .addPluginConfigs(plugConfig).build(); + ProfilerServiceTypes.CreateSessionResponse session = profilerClient.createSession(request); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: startSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_startSessionTest_0001 + * @tc.desc: start Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void startSessionTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StartSessionRequest requestStartSession = + ProfilerServiceHelper.startSessionRequest(CommonUtil.getRequestId(), 1, new ArrayList<>()); + ProfilerServiceTypes.StartSessionResponse startSessionResponse = + profilerClient.startSession(requestStartSession); + Assert.assertNotNull(startSessionResponse); + } + + /** + * functional testing + * + * @tc.name: startSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_startSessionTest_0002 + * @tc.desc: start Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void startSessionTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StartSessionRequest requestStartSession = + ProfilerServiceHelper.startSessionRequest(CommonUtil.getRequestId(), 1, null); + ProfilerServiceTypes.StartSessionResponse startSessionResponse = + profilerClient.startSession(requestStartSession); + Assert.assertNotNull(startSessionResponse); + } + + /** + * functional testing + * + * @tc.name: startSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_startSessionTest_0003 + * @tc.desc: start Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void startSessionTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StartSessionRequest requestStartSession = + ProfilerServiceHelper.startSessionRequest(CommonUtil.getRequestId(), -1, new ArrayList<>()); + ProfilerServiceTypes.StartSessionResponse startSessionResponse = + profilerClient.startSession(requestStartSession); + Assert.assertNotNull(startSessionResponse); + } + + /** + * functional testing + * + * @tc.name: startSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_startSessionTest_0004 + * @tc.desc: start Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void startSessionTest04() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StartSessionRequest requestStartSession = + ProfilerServiceHelper.startSessionRequest(-1, 0, new ArrayList<>()); + ProfilerServiceTypes.StartSessionResponse startSessionResponse = + profilerClient.startSession(requestStartSession); + Assert.assertNotNull(startSessionResponse); + } + + /** + * functional testing + * + * @tc.name: startSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_startSessionTest_0005 + * @tc.desc: start Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void startSessionTest05() { + ProfilerClient profilerClient = new ProfilerClient(null, 0, channel); + ProfilerServiceTypes.StartSessionResponse startSessionResponse = profilerClient.startSession(null); + Assert.assertNotNull(startSessionResponse); + } + + /** + * functional testing + * + * @tc.name: fetchDataTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_fetchDataTest_0001 + * @tc.desc: fetch Data Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void fetchDataTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.FetchDataRequest fetchDataRequest = + ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), 1, null); + Iterator fetchDataResponseIterator = + profilerClient.fetchData(fetchDataRequest); + Assert.assertNotNull(fetchDataResponseIterator); + } + + /** + * functional testing + * + * @tc.name: fetchDataTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_fetchDataTest_0002 + * @tc.desc: fetch Data Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void fetchDataTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + Iterator fetchDataResponseIterator = profilerClient.fetchData(null); + Assert.assertNotNull(fetchDataResponseIterator); + } + + /** + * functional testing + * + * @tc.name: fetchDataTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_fetchDataTest_0003 + * @tc.desc: fetch Data Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void fetchDataTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.FetchDataRequest fetchDataRequest = + ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), -1, null); + Iterator fetchDataResponseIterator = + profilerClient.fetchData(fetchDataRequest); + Assert.assertNotNull(fetchDataResponseIterator); + } + + /** + * functional testing + * + * @tc.name: fetchDataTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_fetchDataTest_0004 + * @tc.desc: fetch Data Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void fetchDataTest04() { + ProfilerClient profilerClient = new ProfilerClient(null, -1, channel); + ProfilerServiceTypes.FetchDataRequest fetchDataRequest = + ProfilerServiceHelper.fetchDataRequest(CommonUtil.getRequestId(), 0, null); + Iterator fetchDataResponseIterator = + profilerClient.fetchData(fetchDataRequest); + Assert.assertNotNull(fetchDataResponseIterator); + } + + /** + * functional testing + * + * @tc.name: fetchDataTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_fetchDataTest_0005 + * @tc.desc: fetch Data Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void fetchDataTest05() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.FetchDataRequest fetchDataRequest = ProfilerServiceHelper.fetchDataRequest(-1, -1, null); + Iterator fetchDataResponseIterator = + profilerClient.fetchData(fetchDataRequest); + Assert.assertNotNull(fetchDataResponseIterator); + } + + /** + * functional testing + * + * @tc.name: stopSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_stopSessionTest_0001 + * @tc.desc: stop Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void stopSessionTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), 1); + ProfilerServiceTypes.StopSessionResponse stopSessionResponse = profilerClient.stopSession(stopSession); + Assert.assertNotNull(stopSessionResponse); + } + + /** + * functional testing + * + * @tc.name: stopSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_stopSessionTest_0002 + * @tc.desc: stop Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void stopSessionTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StopSessionResponse stopSessionResponse = profilerClient.stopSession(null); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: stopSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_stopSessionTest_0003 + * @tc.desc: stop Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void stopSessionTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), -1); + ProfilerServiceTypes.StopSessionResponse stopSessionResponse = profilerClient.stopSession(stopSession); + Assert.assertNotNull(stopSessionResponse); + } + + /** + * functional testing + * + * @tc.name: stopSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_stopSessionTest_0004 + * @tc.desc: stop Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void stopSessionTest04() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(-1, 1); + ProfilerServiceTypes.StopSessionResponse stopSessionResponse = profilerClient.stopSession(stopSession); + Assert.assertNotNull(stopSessionResponse); + } + + /** + * functional testing + * + * @tc.name: stopSessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_stopSessionTest_0005 + * @tc.desc: stop Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void stopSessionTest05() { + ProfilerClient profilerClient = new ProfilerClient(null, -1, channel); + ProfilerServiceTypes.StopSessionRequest stopSession = + ProfilerServiceHelper.stopSessionRequest(-1, -1); + ProfilerServiceTypes.StopSessionResponse stopSessionResponse = profilerClient.stopSession(stopSession); + Assert.assertTrue(true); + } + + /** + * functional testing + * + * @tc.name: destroySessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_destroySessionTest_0001 + * @tc.desc: destroy Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void destroySessionTest01() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), 1); + ProfilerServiceTypes.DestroySessionResponse destroySessionResponse = profilerClient.destroySession(req); + Assert.assertEquals(destroySessionResponse.getStatus(), 0); + } + + /** + * functional testing + * + * @tc.name: destroySessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_destroySessionTest_0002 + * @tc.desc: destroy Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void destroySessionTest02() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.DestroySessionResponse destroySessionResponse = profilerClient.destroySession(null); + Assert.assertNotNull(destroySessionResponse); + } + + /** + * functional testing + * + * @tc.name: destroySessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_destroySessionTest_0003 + * @tc.desc: destroy Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void destroySessionTest03() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), -1); + ProfilerServiceTypes.DestroySessionResponse destroySessionResponse = profilerClient.destroySession(req); + Assert.assertNotNull(destroySessionResponse); + } + + /** + * functional testing + * + * @tc.name: destroySessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_destroySessionTest_0004 + * @tc.desc: destroy Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void destroySessionTest04() { + ProfilerClient profilerClient = new ProfilerClient(ip, port, channel); + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(-1, 1); + ProfilerServiceTypes.DestroySessionResponse destroySessionResponse = profilerClient.destroySession(req); + Assert.assertNotNull(destroySessionResponse); + } + + /** + * functional testing + * + * @tc.name: destroySessionTest01 + * @tc.number: OHOS_JAVA_grpc_ProfilerClient_destroySessionTest_0005 + * @tc.desc: destroy Session Test + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void destroySessionTest05() { + ProfilerClient profilerClient = new ProfilerClient(null, -1, channel); + ProfilerServiceTypes.DestroySessionRequest req = + ProfilerServiceHelper.destroySessionRequest(CommonUtil.getRequestId(), -1); + ProfilerServiceTypes.DestroySessionResponse destroySessionResponse = profilerClient.destroySession(req); + Assert.assertNotNull(destroySessionResponse); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/ConstantTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/ConstantTest.java deleted file mode 100644 index b2e3f08d9..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/ConstantTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.common; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @Description ConstantTest - * @Date 2021/4/3 20:47 - **/ -public class ConstantTest { - /** - * functional testing init - * - * @tc.name: constant test - * @tc.number: OHOS_JAVA_utils_Constant_0001 - * @tc.desc: constant test - * @tc.type: functional testing - * @tc.require: SR-010 - */ - @Test - public void test01() { - Long abnormal = Constant.ABNORMAL; - int normalStatus = Constant.NORMAL_STATUS; - int fileImportScene = Constant.FILE_IMPORT_SCENE; - String memoryPlug = Constant.MEMORY_PLUG; - String cpuPlugName = Constant.CPU_PLUG_NAME; - String destPath = Constant.DEST_PATH; - String deviceSataStatPushed = Constant.DEVICE_SATA_STAT_PUSHED; - String deviceStatClosed = Constant.DEVICE_STAT_CLOSED; - String deviceStatError = Constant.DEVICE_STAT_ERROR; - String deviceStatFail = Constant.DEVICE_STAT_FAIL; - String deviceStatNotFound = Constant.DEVICE_STAT_NOT_FOUND; - String deviceStatOffline = Constant.DEVICE_STAT_OFFLINE; - String deviceStatOnline = Constant.DEVICE_STAT_ONLINE; - String deviceStstUnauthorized = Constant.DEVICE_STST_UNAUTHORIZED; - String fileName = Constant.FILE_NAME; - String fileSuffix = Constant.FILE_SUFFIX; - String targetPlugPath = Constant.TARGET_PLUG_PATH; - String sourceFilepath = Constant.SOURCE_FILEPATH; - int realtimeScene = Constant.REALTIME_SCENE; - int radix = Constant.RADIX; - Assert.assertNotNull(radix); - Assert.assertNotNull(realtimeScene); - Assert.assertNotNull(sourceFilepath); - Assert.assertNotNull(targetPlugPath); - Assert.assertNotNull(fileSuffix); - Assert.assertNotNull(fileName); - Assert.assertNotNull(deviceStstUnauthorized); - Assert.assertNotNull(deviceStatOnline); - Assert.assertNotNull(deviceStatOffline); - Assert.assertNotNull(deviceStatNotFound); - Assert.assertNotNull(deviceStatFail); - Assert.assertNotNull(deviceStatError); - Assert.assertNotNull(deviceStatClosed); - Assert.assertNotNull(deviceSataStatPushed); - Assert.assertNotNull(destPath); - Assert.assertNotNull(cpuPlugName); - Assert.assertNotNull(abnormal); - Assert.assertNotNull(normalStatus); - Assert.assertNotNull(fileImportScene); - Assert.assertNotNull(memoryPlug); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/BeanUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/BeanUtilTest.java index ffed8b51e..55cd3041c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/BeanUtilTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/BeanUtilTest.java @@ -1,181 +1,173 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; -import java.util.Map; - -/** - * @Description BeanUtilTest - * @Date 2021/4/8 13:15 - **/ -public class BeanUtilTest { - /** - * DeviceIPPortInfo - */ - private DeviceIPPortInfo deviceIPPortInfo; - - /** - * serializes - */ - private byte[] serializes; - - /** - * functional testing init - * - * @tc.name: init - * @tc.number: OHOS_JAVA_common_BeanUtil_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void init() { - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setPort(1); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setDeviceName(""); - deviceIPPortInfo.setDeviceID(""); - deviceIPPortInfo.setDeviceType(""); - serializes = BeanUtil.serialize(deviceIPPortInfo); - } - - /** - * functional testing serialize - * - * @tc.name: serialize - * @tc.number: OHOS_JAVA_common_BeanUtil_serialize_0001 - * @tc.desc: serialize - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testserialize() { - byte[] serialize = BeanUtil.serialize(deviceIPPortInfo); - Assert.assertNotNull(serialize); - } - - /** - * functional testing deserialize - * - * @tc.name: deserialize - * @tc.number: OHOS_JAVA_common_BeanUtil_deserialize_0001 - * @tc.desc: deserialize - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testdeserialize() { - Object obj = new BeanUtil().deserialize(serializes); - Assert.assertNotNull(obj); - } - - /** - * functional testing getFiledsInfo - * - * @tc.name: getFiledsInfo - * @tc.number: OHOS_JAVA_common_BeanUtil_getFiledsInfo_0001 - * @tc.desc: getFiledsInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetFiledsInfo() { - List fieldsInfo = BeanUtil.getFieldsInfo(deviceIPPortInfo); - Assert.assertNotNull(fieldsInfo); - } - - /** - * functional testing getFileds - * - * @tc.name: getFileds - * @tc.number: OHOS_JAVA_common_BeanUtil_getFileds_0001 - * @tc.desc: getFileds - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetFiled() { - List> fields = BeanUtil.getFields(deviceIPPortInfo); - Assert.assertNotNull(fields); - } - - /** - * functional testing getFiledsInfo - * - * @tc.name: getFiledsInfo - * @tc.number: OHOS_JAVA_common_BeanUtil_getFiledsInfo_0001 - * @tc.desc: getFiledsInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetFiledsInfos() { - Map fieldsInfoInfos = BeanUtil.getFiledsInfos(deviceIPPortInfo); - Assert.assertNotNull(fieldsInfoInfos); - } - - /** - * functional testing getObjectAttributeNames - * - * @tc.name: getObjectAttributeNames - * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectAttributeNames_0001 - * @tc.desc: getObjectAttributeNames - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetObjectAttributeNames() { - List objectAttributeNames = BeanUtil.getObjectAttributeNames(deviceIPPortInfo); - Assert.assertNotNull(objectAttributeNames); - } - - /** - * functional testing getObjectValue - * - * @tc.name: getObjectValue - * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectValue_0001 - * @tc.desc: getObjectValue - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetObjectValue() { - List objectValue = BeanUtil.getObjectValue(deviceIPPortInfo); - Assert.assertNotNull(objectValue); - } - - /** - * functional testing getObjectName - * - * @tc.name: getObjectName - * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectName_0001 - * @tc.desc: getObjectName - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetObjectName() { - String objectName = BeanUtil.getObjectName(deviceIPPortInfo); - Assert.assertNotNull(objectName); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +/** + * Bean Util + */ +public class BeanUtilTest { + private DeviceIPPortInfo deviceIPPortInfo; + private byte[] serializes; + + /** + * functional testing init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_common_BeanUtil_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Before + public void init() { + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setPort(1); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setDeviceName(""); + deviceIPPortInfo.setDeviceID(""); + deviceIPPortInfo.setDeviceType(DeviceType.FULL_HOS_DEVICE); + serializes = BeanUtil.serialize(deviceIPPortInfo); + } + + /** + * functional testing serialize + * + * @tc.name: serialize + * @tc.number: OHOS_JAVA_common_BeanUtil_serialize_0001 + * @tc.desc: serialize + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testserialize() { + byte[] serialize = BeanUtil.serialize(deviceIPPortInfo); + Assert.assertNotNull(serialize); + } + + /** + * functional testing deserialize + * + * @tc.name: deserialize + * @tc.number: OHOS_JAVA_common_BeanUtil_deserialize_0001 + * @tc.desc: deserialize + * @tc.type: functional testing + * @tc.require: AR000FK61M + */ + @Test + public void testdeserialize() { + Object obj = new BeanUtil().deserialize(serializes); + Assert.assertNotNull(obj); + } + + /** + * functional testing getFiledsInfo + * + * @tc.name: getFiledsInfo + * @tc.number: OHOS_JAVA_common_BeanUtil_getFiledsInfo_0001 + * @tc.desc: getFiledsInfo + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetFiledsInfo() { + List fieldsInfo = BeanUtil.getFieldsInfo(deviceIPPortInfo); + Assert.assertNotNull(fieldsInfo); + } + + /** + * functional testing getFileds + * + * @tc.name: getFileds + * @tc.number: OHOS_JAVA_common_BeanUtil_getFileds_0001 + * @tc.desc: getFileds + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetFiled() { + List> fields = BeanUtil.getFields(deviceIPPortInfo); + Assert.assertNotNull(fields); + } + + /** + * functional testing getFiledsInfo + * + * @tc.name: getFiledsInfo + * @tc.number: OHOS_JAVA_common_BeanUtil_getFiledsInfo_0001 + * @tc.desc: getFiledsInfo + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetFiledsInfos() { + Map fieldsInfoInfos = BeanUtil.getFiledsInfos(deviceIPPortInfo); + Assert.assertNotNull(fieldsInfoInfos); + } + + /** + * functional testing getObjectAttributeNames + * + * @tc.name: getObjectAttributeNames + * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectAttributeNames_0001 + * @tc.desc: getObjectAttributeNames + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetObjectAttributeNames() { + List objectAttributeNames = BeanUtil.getObjectAttributeNames(deviceIPPortInfo); + Assert.assertNotNull(objectAttributeNames); + } + + /** + * functional testing getObjectValue + * + * @tc.name: getObjectValue + * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectValue_0001 + * @tc.desc: getObjectValue + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetObjectValue() { + List objectValue = BeanUtil.getObjectValue(deviceIPPortInfo); + Assert.assertNotNull(objectValue); + } + + /** + * functional testing getObjectName + * + * @tc.name: getObjectName + * @tc.number: OHOS_JAVA_common_BeanUtil_getObjectName_0001 + * @tc.desc: getObjectName + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetObjectName() { + String objectName = BeanUtil.getObjectName(deviceIPPortInfo); + Assert.assertNotNull(objectName); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CharsetUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CharsetUtilTest.java index 481a5a641..e3bb50e68 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CharsetUtilTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CharsetUtilTest.java @@ -1,129 +1,119 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.nio.charset.Charset; - -/** - * CharsetUtilTest测试类 - * - * @version 1.0 - * @date 2021/04/08 16:42 - **/ -public class CharsetUtilTest { - /** - * GBK - */ - private String GBK = "GBK"; - - /** - * UTF-8 - */ - private String UTF_8 = "UTF-8"; - - /** - * functional testing parse - * - * @tc.name: parse - * @tc.number: OHOS_JAVA_common_CharsetUtil_parse_0001 - * @tc.desc: 解析字符串编码为Charset对象,解析失败返回系统默认编码 - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void parseTest() { - Charset charset = CharsetUtil.parse(UTF_8); - Assert.assertNotNull(charset); - } - - /** - * functional testing parse - * - * @tc.name: parse - * @tc.number: OHOS_JAVA_common_CharsetUtil_parse_0002 - * @tc.desc: 解析字符串编码为Charset对象,解析失败返回系统默认编码 - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void parseTest01() { - Charset charset = CharsetUtil.parse(UTF_8, Charset.forName(GBK)); - Assert.assertNotNull(charset); - } - - /** - * functional testing convert - * - * @tc.name: convert - * @tc.number: OHOS_JAVA_common_CharsetUtil_convert_0001 - * @tc.desc: 转换字符串的字符集编码 - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void convertTest() { - String str = CharsetUtil.convert("convertTest", GBK, UTF_8); - Assert.assertNotNull(str); - } - - /** - * functional testing convert - * - * @tc.name: convert - * @tc.number: OHOS_JAVA_common_CharsetUtil_convert_0002 - * @tc.desc: 转换字符串的字符集编码 - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void convertTest01() { - String str = CharsetUtil.convert("convertTest", Charset.forName(GBK), Charset.forName(UTF_8)); - Assert.assertNotNull(str); - } - - /** - * functional testing defaultCharsetName - * - * @tc.name: defaultCharsetName - * @tc.number: OHOS_JAVA_common_CharsetUtil_defaultCharsetName_0001 - * @tc.desc: 系统默认Charset - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void defaultCharsetNameTest() { - String str = CharsetUtil.defaultCharsetName(); - Assert.assertNotNull(str); - } - - /** - * functional testing defaultCharset - * - * @tc.name: defaultCharset - * @tc.number: OHOS_JAVA_common_CharsetUtil_defaultCharset_0001 - * @tc.desc: 系统默认Charset - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void defaultCharsetTest() { - Charset charset = CharsetUtil.defaultCharset(); - Assert.assertNotNull(charset); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import org.junit.Assert; +import org.junit.Test; + +import java.nio.charset.Charset; + +/** + * Charset Util Test + */ +public class CharsetUtilTest { + private String GBK = "GBK"; + private String UTF_8 = "UTF-8"; + + /** + * functional testing parse + * + * @tc.name: parse + * @tc.number: OHOS_JAVA_common_CharsetUtil_parse_0001 + * @tc.desc: 解析字符串编码为Charset对象,解析失败返回系统默认编码 + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void parseTest() { + Charset charset = CharsetUtil.parse(UTF_8); + Assert.assertNotNull(charset); + } + + /** + * functional testing parse + * + * @tc.name: parse + * @tc.number: OHOS_JAVA_common_CharsetUtil_parse_0002 + * @tc.desc: 解析字符串编码为Charset对象,解析失败返回系统默认编码 + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void parseTest01() { + Charset charset = CharsetUtil.parse(UTF_8, Charset.forName(GBK)); + Assert.assertNotNull(charset); + } + + /** + * functional testing convert + * + * @tc.name: convert + * @tc.number: OHOS_JAVA_common_CharsetUtil_convert_0001 + * @tc.desc: 转换字符串的字符集编码 + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void convertTest() { + String str = CharsetUtil.convert("convertTest", GBK, UTF_8); + Assert.assertNotNull(str); + } + + /** + * functional testing convert + * + * @tc.name: convert + * @tc.number: OHOS_JAVA_common_CharsetUtil_convert_0002 + * @tc.desc: 转换字符串的字符集编码 + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void convertTest01() { + String str = CharsetUtil.convert("convertTest", Charset.forName(GBK), Charset.forName(UTF_8)); + Assert.assertNotNull(str); + } + + /** + * functional testing defaultCharsetName + * + * @tc.name: defaultCharsetName + * @tc.number: OHOS_JAVA_common_CharsetUtil_defaultCharsetName_0001 + * @tc.desc: 系统默认Charset + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void defaultCharsetNameTest() { + String str = CharsetUtil.defaultCharsetName(); + Assert.assertNotNull(str); + } + + /** + * functional testing defaultCharset + * + * @tc.name: defaultCharset + * @tc.number: OHOS_JAVA_common_CharsetUtil_defaultCharset_0001 + * @tc.desc: 系统默认Charset + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void defaultCharsetTest() { + Charset charset = CharsetUtil.defaultCharset(); + Assert.assertNotNull(charset); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CommonUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CommonUtilTest.java deleted file mode 100644 index c7ff5de3c..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/CommonUtilTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.common.util; - -import ohos.devtools.views.common.LayoutConstants; -import org.junit.Assert; -import org.junit.Test; - -/** - * @Description CommonUtilTest - * @Date 2021/4/9 13:15 - **/ -public class CommonUtilTest { - /** - * functional testing collectionSize - * - * @tc.name: collectionSize - * @tc.number: OHOS_JAVA_common_CommonUtil_collectionSize_0001 - * @tc.desc: collectionSize - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testcollectionSizeOne() { - int num = CommonUtil.collectionSize(0); - Assert.assertEquals(num, LayoutConstants.SIXTEEN); - } - - /** - * functional testing collectionSize - * - * @tc.name: collectionSize - * @tc.number: OHOS_JAVA_common_CommonUtil_collectionSize_0002 - * @tc.desc: collectionSize - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testcollectionSizeTwo() { - int num = CommonUtil.collectionSize(1); - Assert.assertNotNull(num); - } - - /** - * functional testing getRequestId - * - * @tc.name: getRequestId - * @tc.number: OHOS_JAVA_common_CommonUtil_getRequestId_0001 - * @tc.desc: getRequestId - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetRequestId() { - int num = CommonUtil.getRequestId(); - Assert.assertNotNull(num); - } - - /** - * functional testing generateSessionName - * - * @tc.name: generateSessionName - * @tc.number: OHOS_JAVA_common_CommonUtil_generateSessionName_0001 - * @tc.desc: generateSessionName - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgenerateSessionName() { - String sessionName = CommonUtil.generateSessionName("", 1); - Assert.assertNotNull(sessionName); - } - - /** - * functional testing getLocalSessionId - * - * @tc.name: getLocalSessionId - * @tc.number: OHOS_JAVA_common_CommonUtil_getLocalSessionId_0001 - * @tc.desc: getLocalSessionId - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetLocalSessionId() { - long num = CommonUtil.getLocalSessionId(); - Assert.assertNotNull(num); - } -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/DateTimeUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/DateTimeUtilTest.java index 91bd70c30..2f3d96469 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/DateTimeUtilTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/DateTimeUtilTest.java @@ -1,168 +1,164 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -/** - * @Description DateTimeUtilTest - * @Date 2021/2/7 15:00 - **/ -public class DateTimeUtilTest { - /** - * yyyy-MM-dd HH:mm:ss - */ - private static DateTimeFormatter COMMON_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - /** - * functional testing dateToString - * - * @tc.name: dateToString - * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToString_0001 - * @tc.desc: dateToString - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void dateToStringTest() { - String str = DateTimeUtil.dateToString(LocalDateTime.now()); - Assert.assertNotNull(str); - } - - /** - * functional testing stringToDate - * - * @tc.name: stringToDate - * @tc.number: OHOS_JAVA_common_DateTimeUtil_stringToDate_0001 - * @tc.desc: stringToDate - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void stringToDateTest() { - LocalDateTime localDateTime = DateTimeUtil.stringToDate("2021-04-09 10:14:48"); - Assert.assertNotNull(localDateTime); - } - - /** - * functional testing getNowTime - * - * @tc.name: getNowTime - * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTime_0001 - * @tc.desc: getNowTime - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getNowTimeTest() { - LocalDateTime localDateTime = DateTimeUtil.getNowTime(); - Assert.assertNotNull(localDateTime); - } - - /** - * functional testing dateToString - * - * @tc.name: dateToString - * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToString_0001 - * @tc.desc: dateToString - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testDateToString() { - String str = DateTimeUtil.dateToString(LocalDateTime.now(), COMMON_FORMATTER); - Assert.assertNotNull(str); - } - - /** - * functional testing stringToDate - * - * @tc.name: stringToDate - * @tc.number: OHOS_JAVA_common_DateTimeUtil_stringToDate_0001 - * @tc.desc: stringToDate - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testStringToDate() { - LocalDateTime localDateTime = DateTimeUtil.stringToDate("2021-04-09 10:14:48", COMMON_FORMATTER); - Assert.assertNotNull(localDateTime); - } - - /** - * functional testing dateToTimeMillis - * - * @tc.name: dateToTimeMillis - * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToTimeMillis_0001 - * @tc.desc: dateToTimeMillis - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void dateToTimeMillisTest() { - long timeMillis = DateTimeUtil.dateToTimeMillis(LocalDateTime.now()); - Assert.assertNotNull(timeMillis); - } - - /** - * functional testing timeMillisToDate - * - * @tc.name: timeMillisToDate - * @tc.number: OHOS_JAVA_common_DateTimeUtil_timeMillisToDate_0001 - * @tc.desc: timeMillisToDate - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void timeMillisToDateTest() { - LocalDateTime localDateTime = DateTimeUtil.timeMillisToDate(System.currentTimeMillis()); - Assert.assertNotNull(localDateTime); - } - - /** - * functional testing getNowTimeString - * - * @tc.name: getNowTimeString - * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTimeString_0001 - * @tc.desc: getNowTimeString - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getNowTimeStringTest() { - String str = DateTimeUtil.getNowTimeString("yyyy-MM-dd HH:mm:ss"); - Assert.assertNotNull(str); - } - - /** - * functional testing getNowTimeLong - * - * @tc.name: getNowTimeLong - * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTimeLong_0001 - * @tc.desc: getNowTimeLong - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getNowTimeLongTest() { - Long timeLong = DateTimeUtil.getNowTimeLong(); - Assert.assertNotNull(timeLong); - } +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Date Time Util Test + */ +public class DateTimeUtilTest { + private static DateTimeFormatter COMMON_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** + * functional testing dateToString + * + * @tc.name: dateToString + * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToString_0001 + * @tc.desc: dateToString + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void dateToStringTest() { + String str = DateTimeUtil.dateToString(LocalDateTime.now()); + Assert.assertNotNull(str); + } + + /** + * functional testing stringToDate + * + * @tc.name: stringToDate + * @tc.number: OHOS_JAVA_common_DateTimeUtil_stringToDate_0001 + * @tc.desc: stringToDate + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void stringToDateTest() { + LocalDateTime localDateTime = DateTimeUtil.stringToDate("2021-04-09 10:14:48"); + Assert.assertNotNull(localDateTime); + } + + /** + * functional testing getNowTime + * + * @tc.name: getNowTime + * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTime_0001 + * @tc.desc: getNowTime + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getNowTimeTest() { + LocalDateTime localDateTime = DateTimeUtil.getNowTime(); + Assert.assertNotNull(localDateTime); + } + + /** + * functional testing dateToString + * + * @tc.name: dateToString + * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToString_0001 + * @tc.desc: dateToString + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testDateToString() { + String str = DateTimeUtil.dateToString(LocalDateTime.now(), COMMON_FORMATTER); + Assert.assertNotNull(str); + } + + /** + * functional testing stringToDate + * + * @tc.name: stringToDate + * @tc.number: OHOS_JAVA_common_DateTimeUtil_stringToDate_0001 + * @tc.desc: stringToDate + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testStringToDate() { + LocalDateTime localDateTime = DateTimeUtil.stringToDate("2021-04-09 10:14:48", COMMON_FORMATTER); + Assert.assertNotNull(localDateTime); + } + + /** + * functional testing dateToTimeMillis + * + * @tc.name: dateToTimeMillis + * @tc.number: OHOS_JAVA_common_DateTimeUtil_dateToTimeMillis_0001 + * @tc.desc: dateToTimeMillis + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void dateToTimeMillisTest() { + long timeMillis = DateTimeUtil.dateToTimeMillis(LocalDateTime.now()); + Assert.assertNotNull(timeMillis); + } + + /** + * functional testing timeMillisToDate + * + * @tc.name: timeMillisToDate + * @tc.number: OHOS_JAVA_common_DateTimeUtil_timeMillisToDate_0001 + * @tc.desc: timeMillisToDate + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void timeMillisToDateTest() { + LocalDateTime localDateTime = DateTimeUtil.timeMillisToDate(System.currentTimeMillis()); + Assert.assertNotNull(localDateTime); + } + + /** + * functional testing getNowTimeString + * + * @tc.name: getNowTimeString + * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTimeString_0001 + * @tc.desc: getNowTimeString + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getNowTimeStringTest() { + String str = DateTimeUtil.getNowTimeString("yyyy-MM-dd HH:mm:ss"); + Assert.assertNotNull(str); + } + + /** + * functional testing getNowTimeLong + * + * @tc.name: getNowTimeLong + * @tc.number: OHOS_JAVA_common_DateTimeUtil_getNowTimeLong_0001 + * @tc.desc: getNowTimeLong + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getNowTimeLongTest() { + Long timeLong = DateTimeUtil.getNowTimeLong(); + Assert.assertNotNull(timeLong); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/FileSafeUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/FileSafeUtilsTest.java index b53a3639e..e6644f1f0 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/FileSafeUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/common/util/FileSafeUtilsTest.java @@ -1,114 +1,109 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.common.util; - -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; - -/** - * FileSafeUtilsTest - * - * @version 1.0 - * @date 2021/04/06 13:18 - **/ -public class FileSafeUtilsTest { - private String filepath; - - private String sha; - - private File file; - - /** - * functional testing setFile - * - * @tc.name: setFile - * @tc.number: OHOS_JAVA_common_FileSafeUtils_setFile_0001 - * @tc.desc: setFile - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void setFile() { - filepath = SessionManager.getInstance().getPluginPath() + "libmemdataplugin.z.so"; - sha = "SHA-256"; - file = new File(filepath); - } - - /** - * functional testing getFileSha - * - * @tc.name: getFileSha - * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0001 - * @tc.desc: getFileSha - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getFileSha01() { - String fileSha = FileSafeUtils.getFileSha(file, sha); - Assert.assertNotNull(fileSha); - } - - /** - * functional testing getFileSha - * - * @tc.name: getFileSha - * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0002 - * @tc.desc: getFileSha - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getFileSha02() { - String fileSha = FileSafeUtils.getFileSha(file, null); - Assert.assertNotNull(fileSha); - } - - /** - * functional testing getFileSha - * - * @tc.name: getFileSha - * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0003 - * @tc.desc: getFileSha - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getFileSha03() { - String fileSha = FileSafeUtils.getFileSha(null, sha); - Assert.assertNotNull(fileSha); - } - - /** - * functional testing getFileSha - * - * @tc.name: getFileSha - * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0004 - * @tc.desc: getFileSha - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void getFileSha04() { - String fileSha01 = FileSafeUtils.getFileSha(file, sha); - String fileSha02 = FileSafeUtils.getFileSha(file, sha); - Assert.assertEquals(fileSha01, fileSha02); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.common.util; + +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; + +/** + * File Safe Utils Test + */ +public class FileSafeUtilsTest { + private String filepath; + private String sha; + private File file; + + /** + * functional testing setFile + * + * @tc.name: setFile + * @tc.number: OHOS_JAVA_common_FileSafeUtils_setFile_0001 + * @tc.desc: setFile + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Before + public void setFile() { + filepath = SessionManager.getInstance().getPluginPath() + "libmemdataplugin.z.so"; + sha = "SHA-256"; + file = new File(filepath); + } + + /** + * functional testing getFileSha + * + * @tc.name: getFileSha + * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0001 + * @tc.desc: getFileSha + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getFileSha01() { + String fileSha = FileSafeUtils.getFileSha(file, sha); + Assert.assertNotNull(fileSha); + } + + /** + * functional testing getFileSha + * + * @tc.name: getFileSha + * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0002 + * @tc.desc: getFileSha + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getFileSha02() { + String fileSha = FileSafeUtils.getFileSha(file, null); + Assert.assertNotNull(fileSha); + } + + /** + * functional testing getFileSha + * + * @tc.name: getFileSha + * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0003 + * @tc.desc: getFileSha + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getFileSha03() { + String fileSha = FileSafeUtils.getFileSha(null, sha); + Assert.assertNotNull(fileSha); + } + + /** + * functional testing getFileSha + * + * @tc.name: getFileSha + * @tc.number: OHOS_JAVA_common_FileSafeUtils_getFileSha_0004 + * @tc.desc: getFileSha + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void getFileSha04() { + String fileSha01 = FileSafeUtils.getFileSha(file, sha); + String fileSha02 = FileSafeUtils.getFileSha(file, sha); + Assert.assertEquals(fileSha01, fileSha02); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumerTest.java similarity index 73% rename from host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumerTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumerTest.java index 379e802a9..cdb5ad4fa 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryHeapDataConsumerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/AgentDataConsumerTest.java @@ -1,99 +1,88 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.services.memory.ClassInfoDao; -import ohos.devtools.services.memory.MemoryHeapDao; -import ohos.devtools.services.memory.MemoryInstanceDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsDao; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; - -/** - * @Description MemoryHeapDataConsumerTest - * @Date 2021/4/23 15:02 - **/ -public class MemoryHeapDataConsumerTest { - private long localSessionId; - private Queue queue; - private ClassInfoDao classInfoDao; - private MemoryInstanceDetailsDao memoryInstanceDetailsDao; - private MemoryInstanceDao memoryInstanceDao; - private MemoryHeapDao memoryHeapDao; - private Long countTime; - - /** - * functional testing init - * - * @tc.name: MemoryHeapData initialization configuration - * @tc.number: OHOS_JAVA_datahandler_MemoryHeapHandle_init_0001 - * @tc.desc: MemoryHeapData initialization configuration - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Before - public void init() { - this.localSessionId = 3274894L; - queue = new LinkedBlockingQueue(); - HashMap tableService = new HashMap<>(); - tableService.put(MEMORY_PLUG, new MemoryTable()); - tableService.put(JVMTI_AGENT_PLUG, new ClassInfoDao()); - tableService.put("jvmtiagentDetails", new MemoryInstanceDetailsDao()); - tableService.put("jvmtiagentInstance", new MemoryInstanceDao()); - tableService.put("jvmtiagentMemoryHeap", new MemoryHeapDao()); - if (tableService.get(JVMTI_AGENT_PLUG) instanceof ClassInfoDao) { - classInfoDao = (ClassInfoDao) tableService.get(JVMTI_AGENT_PLUG); - } - if (tableService.get("jvmtiagentDetails") instanceof MemoryInstanceDetailsDao) { - memoryInstanceDetailsDao = (MemoryInstanceDetailsDao) tableService.get("jvmtiagentDetails"); - } - if (tableService.get("jvmtiagentInstance") instanceof MemoryInstanceDao) { - memoryInstanceDao = (MemoryInstanceDao) tableService.get("jvmtiagentInstance"); - } - - if (tableService.get("jvmtiagentMemoryHeap") instanceof MemoryHeapDao) { - memoryHeapDao = (MemoryHeapDao) tableService.get("jvmtiagentMemoryHeap"); - } - countTime = DateTimeUtil.getNowTimeLong(); - } - - /** - * functional testing MemoryHeapHandle - * - * @tc.name: MemoryHeapHandle - * @tc.number: OHOS_JAVA_datahandler_MemoryHeapHandle_constructor_0001 - * @tc.desc: MemoryHeapHandle - * @tc.type: functional testing - * @tc.require: SR000FK61J - */ - @Test - public void handleMemoryHeapHandleTest() { - MemoryHeapDataConsumer memoryHeapDataConsumer = - new MemoryHeapDataConsumer(queue, localSessionId, classInfoDao, memoryInstanceDetailsDao, memoryInstanceDao, - memoryHeapDao); - memoryHeapDataConsumer.start(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; + +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; + +/** + * Memory Heap Data Consumer Test + */ +public class AgentDataConsumerTest { + private long localSessionId; + private Queue queue; + private ClassInfoDao classInfoDao; + private MemoryInstanceDetailsDao memoryInstanceDetailsDao; + private MemoryInstanceDao memoryInstanceDao; + private MemoryHeapDao memoryHeapDao; + private Long countTime; + + /** + * functional testing init + */ + @Before + public void init() { + this.localSessionId = 3274894L; + queue = new LinkedBlockingQueue(); + HashMap tableService = new HashMap<>(); + tableService.put(MEMORY_PLUG, new MemoryTable()); + tableService.put(JVMTI_AGENT_PLUG, new ClassInfoDao()); + tableService.put("jvmtiagentDetails", new MemoryInstanceDetailsDao()); + tableService.put("jvmtiagentInstance", new MemoryInstanceDao()); + tableService.put("jvmtiagentMemoryHeap", new MemoryHeapDao()); + if (tableService.get(JVMTI_AGENT_PLUG) instanceof ClassInfoDao) { + classInfoDao = (ClassInfoDao) tableService.get(JVMTI_AGENT_PLUG); + } + if (tableService.get("jvmtiagentDetails") instanceof MemoryInstanceDetailsDao) { + memoryInstanceDetailsDao = (MemoryInstanceDetailsDao) tableService.get("jvmtiagentDetails"); + } + if (tableService.get("jvmtiagentInstance") instanceof MemoryInstanceDao) { + memoryInstanceDao = (MemoryInstanceDao) tableService.get("jvmtiagentInstance"); + } + + if (tableService.get("jvmtiagentMemoryHeap") instanceof MemoryHeapDao) { + memoryHeapDao = (MemoryHeapDao) tableService.get("jvmtiagentMemoryHeap"); + } + countTime = DateTimeUtil.getNowTimeLong(); + } + + /** + * functional testing MemoryHeapHandle + */ + @Test + public void handleMemoryHeapHandleTest() { + AgentDataConsumer agentDataConsumer = new AgentDataConsumer(); + agentDataConsumer.init(queue, 1, localSessionId); + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService.execute(agentDataConsumer); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPollerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPollerTest.java index 36aefd0df..97497bdb9 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPollerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/DataPollerTest.java @@ -1,234 +1,222 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import io.grpc.util.MutableHandlerRegistry; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.Constant; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.HashMap; - -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; - -/** - * DataPollerTest - * - * @Description DataPollerTest - * @Date 2021/4/3 15:02 - **/ -public class DataPollerTest { - /** - * requestId - */ - private static volatile Integer requestId = 1; - - /** - * grpcCleanup - */ - public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - - /** - * serverName - */ - private String serverName; - - /** - * SessionManager - */ - private SessionManager session; - - /** - * DeviceIPPortInfo - */ - private DeviceIPPortInfo device; - - /** - * ProcessInfo - */ - private ProcessInfo process; - - /** - * JSONObject - */ - private JSONObject jsonObject; - - private MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); - - /** - * init - * - * @throws IOException IOException - */ - @Before - public void init() throws IOException { - session = SessionManager.getInstance(); - session.setDevelopMode(true); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - jsonObject = new JSONObject(); - JSONObject memoryObject = new JSONObject(); - memoryObject.put("Select All", true); - memoryObject.put("Java", true); - memoryObject.put("Native", true); - memoryObject.put("Graphics", true); - memoryObject.put("Stack", true); - memoryObject.put("Code", true); - memoryObject.put("Others", true); - jsonObject.put("Memory", memoryObject); - device = new DeviceIPPortInfo(); - device.setIp(""); - device.setPort(11007); - device.setForwardPort(11007); - process = new ProcessInfo(); - process.setProcessId(111); - process.setProcessName("process"); - serverName = InProcessServerBuilder.generateName(); - grpcCleanup.register( - InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() - .start()); - } - - /** - * functional testing dataPoller - * - * @tc.name: dataPoller - * @tc.number: OHOS_JAVA_utils_DataPoller_dataPoller_0001 - * @tc.desc: dataPoller - * @tc.type: functional testing - * @tc.require: SR000FK61J - */ - @Test - public void dataPollerTest() { - MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { - /** - * init createSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init getCapabilities - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libmemdataplugin.z.so") - .setPath("/data/local/tmp/libmemdataplugin.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init fetchData - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) - .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("com.eg.and.AlipayGphone") - .setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoThree = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) - .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoOne) - .addProcessesinfo(processesInfoTwo).addProcessesinfo(processesInfoThree).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - }; - ManagedChannel channel = - grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - SessionManager.getInstance(); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 11007, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - HashMap map = new HashMap(); - map.put(MEMORY_PLUG, new MemoryTable()); - DataPoller dataPoller = new DataPoller(num, 111, client, map); - dataPoller.run(); - Assert.assertNotNull(dataPoller); - } - - /** - * get Int Data - * - * @return int - */ - private int getIntData() { - requestId++; - if (requestId == Integer.MAX_VALUE) { - requestId = 0; - } - return requestId; - } - +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import com.alibaba.fastjson.JSONObject; +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; +import ohos.devtools.datasources.transport.grpc.ProfilerClient; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.HashMap; + +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; + +/** + * Data Poller Test + */ +public class DataPollerTest { + private static volatile Integer requestId = 1; + + /** + * grpcCleanup + */ + public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + private String serverName; + private SessionManager session; + private DeviceIPPortInfo device; + private ProcessInfo process; + private JSONObject jsonObject; + private MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + + /** + * init + * + * @throws IOException IOException + */ + @Before + public void init() throws IOException { + session = SessionManager.getInstance(); + session.setDevelopMode(true); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + jsonObject = new JSONObject(); + JSONObject memoryObject = new JSONObject(); + memoryObject.put("Select All", true); + memoryObject.put("Java", true); + memoryObject.put("Native", true); + memoryObject.put("Graphics", true); + memoryObject.put("Stack", true); + memoryObject.put("Code", true); + memoryObject.put("Others", true); + jsonObject.put("Memory", memoryObject); + device = new DeviceIPPortInfo(); + device.setIp(""); + device.setPort(11007); + device.setForwardPort(11007); + process = new ProcessInfo(); + process.setProcessId(111); + process.setProcessName("process"); + serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() + .start()); + } + + /** + * functional testing dataPoller + * + * @tc.name: dataPoller + * @tc.number: OHOS_JAVA_utils_DataPoller_dataPoller_0001 + * @tc.desc: dataPoller + * @tc.type: functional testing + * @tc.require: SR000FK61J + */ + @Test + public void dataPollerTest() { + MockProfilerServiceImplBase getFeatureImpl = getMockProfilerServiceImplBase(); + ManagedChannel channel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + SessionManager.getInstance(); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 11007, channel); + long num = session.createSession(device, process); + HashMap map = new HashMap(); + map.put(MEMORY_PLUG, new MemoryTable()); + DataPoller dataPoller = new DataPoller(num, 111, client); + dataPoller.run(); + Assert.assertNotNull(dataPoller); + } + + @NotNull + private MockProfilerServiceImplBase getMockProfilerServiceImplBase() { + MockProfilerServiceImplBase getFeatureImpl = new MockProfilerServiceImplBase() { + /** + * init createSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init getCapabilities + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.GetCapabilitiesResponse reply = getGetCapabilitiesResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init fetchData + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = getFetchDataResponse(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + }; + return getFeatureImpl; + } + + private ProfilerServiceTypes.GetCapabilitiesResponse getGetCapabilitiesResponse() { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libmemdataplugin.z.so") + .setPath("/data/local/tmp/libmemdataplugin.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + return reply; + } + + private ProfilerServiceTypes.FetchDataResponse getFetchDataResponse() { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141) + .setName("com.eg.and.AlipayGphone:push").setRssShmemKb(1).setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("com.eg.and.AlipayGphone") + .setRssShmemKb(2222222).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoThree = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144) + .setName("com.hisunflytone.and:pushservice").setRssShmemKb(3333333).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoOne) + .addProcessesinfo(processesInfoTwo).addProcessesinfo(processesInfoThree).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + return fetchDataResponse; + } + + /** + * get Int Data + * + * @return int + */ + private int getIntData() { + requestId++; + if (requestId == Integer.MAX_VALUE) { + requestId = 0; + } + return requestId; + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumerTest.java index 9992369f6..f340c9248 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/datapoller/MemoryDataConsumerTest.java @@ -1,81 +1,84 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.datahandler.datapoller; - -import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; -import ohos.devtools.datasources.databases.datatable.MemoryTable; -import ohos.devtools.services.memory.ClassInfoDao; -import ohos.devtools.services.memory.MemoryHeapDao; -import ohos.devtools.services.memory.MemoryInstanceDao; -import ohos.devtools.services.memory.MemoryInstanceDetailsDao; -import org.junit.Before; -import org.junit.Test; -import java.util.HashMap; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; -import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; -import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; - -/** - * @Description MemoryDataConsumerTest - * @Date 2021/4/23 15:02 - **/ -public class MemoryDataConsumerTest { - private long localSessionId; - private int sessionId; - private Queue queue; - private MemoryTable memoryTable; - - /** - * functional testing init - * - * @tc.name: Memory initialization configuration - * @tc.number: OHOS_JAVA_datahandler_MemoryDataConsumer_init_0001 - * @tc.desc: Memory initialization configuration - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Before - public void init() { - this.localSessionId = 3274894L; - this.sessionId = 3247; - queue = new LinkedBlockingQueue(); - HashMap tableService = new HashMap<>(); - tableService.put(MEMORY_PLUG, new MemoryTable()); - tableService.put(JVMTI_AGENT_PLUG, new ClassInfoDao()); - tableService.put("jvmtiagentDetails", new MemoryInstanceDetailsDao()); - tableService.put("jvmtiagentInstance", new MemoryInstanceDao()); - tableService.put("jvmtiagentMemoryHeap", new MemoryHeapDao()); - if (tableService.get(MEMORY_PLUG) instanceof MemoryTable) { - memoryTable = (MemoryTable) tableService.get(MEMORY_PLUG); - } - } - - /** - * functional testing MemoryDataConsumer - * - * @tc.name: MemoryDataConsumer - * @tc.number: OHOS_JAVA_datahandler_MemoryDataConsumer_constructor_0001 - * @tc.desc: MemoryDataConsumer - * @tc.type: functional testing - * @tc.require: SR000FK61J - */ - @Test - public void handleMemoryDataTest() { - MemoryDataConsumer consumer = new MemoryDataConsumer(queue, memoryTable, sessionId, localSessionId); - consumer.start(); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.datahandler.datapoller; + +import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import org.junit.Before; +import org.junit.Test; +import java.util.HashMap; +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import static ohos.devtools.datasources.utils.common.Constant.JVMTI_AGENT_PLUG; +import static ohos.devtools.datasources.utils.common.Constant.MEMORY_PLUG; + +/** + * Memory Data Consumer Test + */ +public class MemoryDataConsumerTest { + private long localSessionId; + private int sessionId; + private Queue queue; + private MemoryTable memoryTable; + + /** + * functional testing init + * + * @tc.name: Memory initialization configuration + * @tc.number: OHOS_JAVA_datahandler_MemoryDataConsumer_init_0001 + * @tc.desc: Memory initialization configuration + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Before + public void init() { + this.localSessionId = 3274894L; + this.sessionId = 3247; + queue = new LinkedBlockingQueue(); + HashMap tableService = new HashMap<>(); + tableService.put(MEMORY_PLUG, new MemoryTable()); + tableService.put(JVMTI_AGENT_PLUG, new ClassInfoDao()); + tableService.put("jvmtiagentDetails", new MemoryInstanceDetailsDao()); + tableService.put("jvmtiagentInstance", new MemoryInstanceDao()); + tableService.put("jvmtiagentMemoryHeap", new MemoryHeapDao()); + if (tableService.get(MEMORY_PLUG) instanceof MemoryTable) { + memoryTable = (MemoryTable) tableService.get(MEMORY_PLUG); + } + } + + /** + * functional testing MemoryDataConsumer + * + * @tc.name: MemoryDataConsumer + * @tc.number: OHOS_JAVA_datahandler_MemoryDataConsumer_constructor_0001 + * @tc.desc: MemoryDataConsumer + * @tc.type: functional testing + * @tc.require: SR000FK61J + */ + @Test + public void handleMemoryDataTest() { + MemoryDataConsumer consumer = new MemoryDataConsumer(); + consumer.init(queue, sessionId, localSessionId); + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService.execute(consumer); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/timesync/DeviceTimeStampSnapshootTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/timesync/DeviceTimeStampSnapshootTest.java deleted file mode 100644 index 62df7977c..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/datahandler/timesync/DeviceTimeStampSnapshootTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.datahandler.timesync; - -/** - * @Description DeviceTimeStampSnapshootTest - * @Date 2021/4/3 17:44 - **/ -public class DeviceTimeStampSnapshootTest { -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceDaoTest.java new file mode 100644 index 000000000..a381bd90a --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceDaoTest.java @@ -0,0 +1,147 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.dao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Device Util Test + */ +public class DeviceDaoTest { + private ProcessInfo processInfo; + private DeviceIPPortInfo deviceIPPortInfo; + private ArrayList deviceIPPortList; + private DeviceDao deviceDao; + + /** + * functional testing init + * + * @tc.name: DeviceUtil init + * @tc.number: OHOS_JAVA_device_DeviceUtil_init_0001 + * @tc.desc: DeviceUtil init + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Before + public void init() { + SessionManager.getInstance().setDevelopMode(true); + // 应用初始化 Step1 初始化数据中心 + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + deviceDao = new DeviceDao(); + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setDeviceID("1"); + deviceIPPortInfo.setPort(5001); + deviceIPPortInfo.setForwardPort(5001); + deviceIPPortInfo.setDeviceName(""); + deviceIPPortInfo.setDeviceType(DeviceType.FULL_HOS_DEVICE); + deviceIPPortList = new ArrayList<>(); + deviceIPPortList.add(deviceIPPortInfo); + processInfo = new ProcessInfo(); + processInfo.setDeviceId("1"); + processInfo.setProcessId(1); + processInfo.setProcessName("com.go.maps"); + } + + /** + * functional testing init + * + * @tc.name: deleteExceptDeviceIPPortTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_deleteExceptDeviceIPPortTest_0001 + * @tc.desc: delete Except Device IP Port Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void deleteExceptDeviceIPPortTest001() { + deviceDao.deleteExceptDeviceIPPort(deviceIPPortList); + Assert.assertTrue(true); + } + + /** + * functional testing init + * + * @tc.name: deleteAllDeviceIPPortInfoTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_deleteAllDeviceIPPortInfoTest_0001 + * @tc.desc: delete All Device IP Port Info Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void deleteAllDeviceIPPortInfoTest001() { + deviceDao.deleteAllDeviceIPPortInfo(); + Assert.assertTrue(true); + } + + /** + * functional testing init + * + * @tc.name: hasDeviceTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_hasDeviceTest_0001 + * @tc.desc: has Device Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void hasDeviceTest001() { + boolean res = deviceDao.hasDeviceIPPort("123"); + Assert.assertFalse(res); + } + + /** + * functional testing init + * + * @tc.name: hasDeviceTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_hasDeviceIPPortTest_0001 + * @tc.desc: has Device IP Port Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void hasDeviceIPPortTest001() { + boolean res = deviceDao.hasDeviceIPPort("123"); + Assert.assertFalse(res); + } + + /** + * functional testing init + * + * @tc.name: getAllDeviceIPPortInfosTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_getAllDeviceIPPortInfosTest_0001 + * @tc.desc: get All Device IP Port Infos Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getAllDeviceIPPortInfosTest001() { + List allDeviceIPPortInfos = deviceDao.getAllDeviceIPPortInfos(); + Assert.assertNotNull(allDeviceIPPortInfos); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceUtilTest.java new file mode 100644 index 000000000..c84cc441f --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/dao/DeviceUtilTest.java @@ -0,0 +1,147 @@ +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.dao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Device Util Test + */ +public class DeviceUtilTest { + private ProcessInfo processInfo; + private DeviceIPPortInfo deviceIPPortInfo; + private ArrayList deviceIPPortList; + private DeviceDao deviceUtil; + + /** + * functional testing init + * + * @tc.name: DeviceUtil init + * @tc.number: OHOS_JAVA_device_DeviceUtil_init_0001 + * @tc.desc: DeviceUtil init + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Before + public void init() { + SessionManager.getInstance().setDevelopMode(true); + // 应用初始化 Step1 初始化数据中心 + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + deviceUtil = new DeviceDao(); + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setDeviceID("1"); + deviceIPPortInfo.setPort(5001); + deviceIPPortInfo.setForwardPort(5001); + deviceIPPortInfo.setDeviceName(""); + deviceIPPortInfo.setDeviceType(DeviceType.FULL_HOS_DEVICE); + deviceIPPortList = new ArrayList<>(); + deviceIPPortList.add(deviceIPPortInfo); + processInfo = new ProcessInfo(); + processInfo.setDeviceId("1"); + processInfo.setProcessId(1); + processInfo.setProcessName("com.go.maps"); + } + + /** + * functional testing init + * + * @tc.name: deleteExceptDeviceIPPortTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_deleteExceptDeviceIPPortTest_0001 + * @tc.desc: delete Except Device IP Port Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void deleteExceptDeviceIPPortTest001() { + deviceUtil.deleteExceptDeviceIPPort(deviceIPPortList); + Assert.assertTrue(true); + } + + /** + * functional testing init + * + * @tc.name: deleteAllDeviceIPPortInfoTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_deleteAllDeviceIPPortInfoTest_0001 + * @tc.desc: delete All Device IP Port Info Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void deleteAllDeviceIPPortInfoTest001() { + deviceUtil.deleteAllDeviceIPPortInfo(); + Assert.assertTrue(true); + } + + /** + * functional testing init + * + * @tc.name: hasDeviceTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_hasDeviceTest_0001 + * @tc.desc: has Device Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void hasDeviceTest001() { + boolean res = deviceUtil.hasDeviceIPPort("123"); + Assert.assertFalse(res); + } + + /** + * functional testing init + * + * @tc.name: hasDeviceTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_hasDeviceIPPortTest_0001 + * @tc.desc: has Device IP Port Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void hasDeviceIPPortTest001() { + boolean res = deviceUtil.hasDeviceIPPort("123"); + Assert.assertFalse(res); + } + + /** + * functional testing init + * + * @tc.name: getAllDeviceIPPortInfosTest + * @tc.number: OHOS_JAVA_device_DeviceUtil_getAllDeviceIPPortInfosTest_0001 + * @tc.desc: get All Device IP Port Infos Test + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getAllDeviceIPPortInfosTest001() { + List allDeviceIPPortInfos = deviceUtil.getAllDeviceIPPortInfos(); + Assert.assertNotNull(allDeviceIPPortInfos); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfoTest.java deleted file mode 100644 index cb4b531c5..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/DeviceProcessInfoTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.entity; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @Description DeviceProcessInfoTest - * @Date 2021/4/3 19:50 - **/ -public class DeviceProcessInfoTest { - /** - * functional testing init - * - * @tc.name: DeviceProcessInfo initialization configuration - * @tc.number: OHOS_JAVA_device_DeviceProcessInfo_init_0001 - * @tc.desc: DeviceProcessInfo initialization configuration - * @tc.type: functional testing - * @tc.require: SR-004-AR-001 - */ - @Test - public void getTraceFileInfo() { - DeviceProcessInfo deviceProcessInfo = new DeviceProcessInfo(); - deviceProcessInfo.setDeviceName("test"); - deviceProcessInfo.setDeviceType("test"); - deviceProcessInfo.setProcessName("test"); - deviceProcessInfo.setEndTime(23472L); - deviceProcessInfo.setLocalSessionId(24367L); - deviceProcessInfo.setStartTime(24379L); - deviceProcessInfo.getDeviceName(); - deviceProcessInfo.getDeviceType(); - deviceProcessInfo.getProcessName(); - deviceProcessInfo.getEndTime(); - deviceProcessInfo.getLocalSessionId(); - deviceProcessInfo.getStartTime(); - Assert.assertNotNull(deviceProcessInfo); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfoTest.java deleted file mode 100644 index 87f4b594c..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/entity/TraceFileInfoTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.entity; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @Description TraceFileInfoTest - * @Date 2021/4/3 19:46 - **/ -public class TraceFileInfoTest { - /** - * functional testing TraceFileInfo initialization configuration - * - * @tc.name: TraceFileInfo initialization configuration - * @tc.number: OHOS_JAVA_device_TraceFileInfo_init_0001 - * @tc.desc: TraceFileInfo initialization configuration - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getTraceFileInfo() { - TraceFileInfo traceFileInfo = new TraceFileInfo(); - traceFileInfo.setCreateTime(2342L); - traceFileInfo.setRecordNum(73829L); - traceFileInfo.setVersion("test"); - traceFileInfo.getCreateTime(); - traceFileInfo.getRecordNum(); - traceFileInfo.getVersion(); - Assert.assertNotNull(traceFileInfo); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPortTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPortTest.java index 6e3bcb425..9836c67e1 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPortTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceForwardPortTest.java @@ -1,99 +1,122 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description 设备转发端口类 - * @Date 2021/4/9 19:02 - **/ -public class DeviceForwardPortTest { - /** - * DeviceForwardPort - */ - private DeviceForwardPort deviceForwardPort; - - /** - * DeviceIPPortInfo类 - */ - private DeviceIPPortInfo deviceIPPortInfo; - - /** - * functional testing init - * - * @tc.name: DeviceForwardPort initialization configuration - * @tc.number: OHOS_JAVA_device_DeviceForwardPort_init_0001 - * @tc.desc: DeviceForwardPort initialization configuration - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Before - public void initObj() { - deviceForwardPort = DeviceForwardPort.getInstance(); - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setPort(5001); - } - - /** - * functional testing getInstance - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_device_DeviceForwardPort_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getInstanceTest() { - DeviceForwardPort deviceForwardPorts = DeviceForwardPort.getInstance(); - Assert.assertNotNull(deviceForwardPorts); - } - - /** - * functional testing setDeviceIPPortInfo - * - * @tc.name: setDeviceIPPortInfo - * @tc.number: OHOS_JAVA_device_DeviceForwardPort_setDeviceIPPortInfo_0001 - * @tc.desc: setDeviceIPPortInfo - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void setDeviceIPPortInfoTest() { - DeviceIPPortInfo deviceIPPortInfoNew = deviceForwardPort.setDeviceIPPortInfo(deviceIPPortInfo); - Assert.assertNotNull(deviceIPPortInfoNew); - } - - /** - * functional testing configuration - * - * @tc.name: DeviceForwardPort initialization configuration - * @tc.number: OHOS_JAVA_device_DeviceForwardPort_getForwardPort_0001 - * @tc.desc: DeviceForwardPort initialization configuration - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getForwardPortTest() { - int anInt = deviceForwardPort.getForwardPort(); - Assert.assertNotNull(anInt); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.service; + +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Device forwarding port class + */ +public class DeviceForwardPortTest { + private DeviceForwardPort deviceForwardPort; + private DeviceIPPortInfo deviceIPPortInfo; + + /** + * functional testing init + * + * @tc.name: DeviceForwardPort initialization configuration + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_init_0001 + * @tc.desc: DeviceForwardPort initialization configuration + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Before + public void initObj() { + deviceForwardPort = DeviceForwardPort.getInstance(); + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setPort(5001); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getInstanceTest01() { + DeviceForwardPort deviceForwardPorts = DeviceForwardPort.getInstance(); + Assert.assertNotNull(deviceForwardPorts); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_getInstance_0002 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getInstanceTest02() { + DeviceForwardPort deviceForwardPorts = DeviceForwardPort.getInstance(); + DeviceForwardPort deviceForward = DeviceForwardPort.getInstance(); + Assert.assertEquals(deviceForward, deviceForwardPorts); + } + + /** + * functional testing setDeviceIPPortInfo + * + * @tc.name: setDeviceIPPortInfo + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_setDeviceIPPortInfo_0001 + * @tc.desc: setDeviceIPPortInfo + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void setDeviceIPPortInfoTest01() { + int deviceIPPortInfoNew = deviceForwardPort.forwardDevicePort(deviceIPPortInfo); + Assert.assertNotNull(deviceIPPortInfoNew); + } + + /** + * functional testing setDeviceIPPortInfo + * + * @tc.name: setDeviceIPPortInfo + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_setDeviceIPPortInfo_0002 + * @tc.desc: setDeviceIPPortInfo + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void setDeviceIPPortInfoTest02() { + int deviceIPPortInfoNew = deviceForwardPort.forwardDevicePort(deviceIPPortInfo); + Assert.assertNotEquals(5001, deviceIPPortInfoNew); + } + + /** + * functional testing configuration + * + * @tc.name: DeviceForwardPort initialization configuration + * @tc.number: OHOS_JAVA_device_DeviceForwardPort_getForwardPort_0001 + * @tc.desc: DeviceForwardPort initialization configuration + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getForwardPortTest() { + int anInt = deviceForwardPort.getForwardPort(); + Assert.assertNotNull(anInt); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThreadTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThreadTest.java deleted file mode 100644 index cc6f8330a..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceGrpcThreadTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * DeviceGrpcThreadTest - * - * @version 1.0 - * @date 2021/04/05 17:12 - **/ -public class DeviceGrpcThreadTest { - private DeviceGrpcThread deviceGrpcThread; - private DeviceIPPortInfo deviceIPPortInfo; - - /** - * functional testing getDeviceGrpcThread - * - * @tc.name: getDeviceGrpcThread - * @tc.number: OHOS_JAVA_device_DeviceGrpcThread_getDeviceGrpcThread_0001 - * @tc.desc: getDeviceGrpcThread - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Before - public void getDeviceGrpcThread() { - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setPort(1); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setDeviceName(""); - deviceIPPortInfo.setDeviceID(""); - deviceIPPortInfo.setDeviceType(""); - deviceGrpcThread = new DeviceGrpcThread(deviceIPPortInfo); - } - - /** - * functional testing run - * - * @tc.name: DeviceGrpcThread run - * @tc.number: OHOS_JAVA_device_DeviceGrpcThread_run_0001 - * @tc.desc: DeviceGrpcThread run - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void run() { - deviceGrpcThread.run(); - Assert.assertTrue(true); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceInstallThreadTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceInstallThreadTest.java deleted file mode 100644 index 781fab41c..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/DeviceInstallThreadTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.junit.Before; - -/** - * DeviceInstallThreadTest - * - * @version 1.0 - * @date 2021/04/09 11:30 - **/ -public class DeviceInstallThreadTest { - /** - * DeviceIPPortInfo类 - */ - private DeviceIPPortInfo deviceIPPortInfo; - - /** - * functional testing init - * - * @tc.name: DeviceIPPortInfo initialization configuration - * @tc.number: OHOS_JAVA_device_DeviceIPPortInfo_init_0001 - * @tc.desc: DeviceIPPortInfo initialization configuration - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Before - public void initObj() { - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setPort(5001); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManagerTest.java index dbfea4eb6..7b84de013 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/device/service/MultiDeviceManagerTest.java @@ -1,143 +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. - */ - -package ohos.devtools.datasources.utils.device.service; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * 多设备管理测试类 - * - * @version 1.0 - * @date 2021/2/2 19:02 - **/ -public class MultiDeviceManagerTest { - private String serialNumber; - - /** - * functional testing init - * - * @tc.name: MultiDeviceManager setup - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_init_0001 - * @tc.desc: MultiDeviceManager setup - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Before - public void setUp() { - serialNumber = "emulator-5554"; - DataBaseApi.getInstance().initDataSourceManager(); - MultiDeviceManager.getInstance().run(); - } - - /** - * functional testing pushDevToolsShell - * - * @tc.name: pushDevToolsShell - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_pushDevToolsShell_0001 - * @tc.desc: pushDevToolsShell - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void pushHiprofilerCliTest1() { - boolean cli = MultiDeviceManager.getInstance().pushDevToolsShell(serialNumber); - Assert.assertTrue(cli); - } - - /** - * functional testing pushDevToolsShell - * - * @tc.name: pushDevToolsShell - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_pushDevToolsShell_0002 - * @tc.desc: pushDevToolsShell - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void pushHiprofilerCliTest2() { - boolean cli = MultiDeviceManager.getInstance().pushDevToolsShell(serialNumber); - Assert.assertTrue(cli); - } - - /** - * functional testing getDeviceIPPort - * - * @tc.name: getDeviceIPPort - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getDeviceIPPort_0001 - * @tc.desc: getDeviceIPPort - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getDeviceIPPortTest() { - ArrayList> deviceIPPortList = MultiDeviceManager.getInstance().getDeviceIPPort(serialNumber); - Assert.assertNotNull(deviceIPPortList); - } - - /** - * functional testing getDevicesInfo - * - * @tc.name: getDevicesInfo - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getDevicesInfo_0001 - * @tc.desc: getDevicesInfo - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getDevicesInfoTest() { - List devicesInfo = MultiDeviceManager.getInstance().getDevicesInfo(); - Assert.assertNotNull(devicesInfo); - } - - /** - * functional testing getAllDeviceIPPortInfos - * - * @tc.name: getAllDeviceIPPortInfos - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getAllDeviceIPPortInfos_0001 - * @tc.desc: getAllDeviceIPPortInfos - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getAllDeviceIPPortInfosTest() { - List list = MultiDeviceManager.getInstance().getAllDeviceIPPortInfos(); - Assert.assertNotNull(list); - } - - /** - * functional testing getInstance - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: SR-004-AR-002 - */ - @Test - public void getInstanceTest() { - MultiDeviceManager multiDeviceManager = MultiDeviceManager.getInstance(); - Assert.assertNotNull(multiDeviceManager); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.device.service; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +/** + * Multi-device management test class + */ +public class MultiDeviceManagerTest { + private String serialNumber; + private DeviceIPPortInfo deviceIPPortInfo; + + /** + * functional testing init + * + * @tc.name: MultiDeviceManager setup + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_init_0001 + * @tc.desc: MultiDeviceManager setup + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Before + public void setUp() { + serialNumber = "emulator-5554"; + DataBaseApi.getInstance().initDataSourceManager(); + MultiDeviceManager.getInstance().start(); + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setDeviceID("1"); + deviceIPPortInfo.setDeviceType(DeviceType.FULL_HOS_DEVICE); + } + + /** + * functional testing pushDevToolsShell + * + * @tc.name: pushDevToolsShell + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_pushDevToolsShell_0001 + * @tc.desc: pushDevToolsShell + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void pushHiprofilerCliTest1() { + boolean cli = MultiDeviceManager.getInstance().pushDevToolsShell(deviceIPPortInfo); + Assert.assertFalse(cli); + } + + /** + * functional testing pushDevToolsShell + * + * @tc.name: pushDevToolsShell + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_pushDevToolsShell_0002 + * @tc.desc: pushDevToolsShell + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void pushHiprofilerCliTest2() { + boolean cli = MultiDeviceManager.getInstance().pushDevToolsShell(deviceIPPortInfo); + Assert.assertFalse(cli); + } + + /** + * functional testing getAllDeviceIPPortInfos + * + * @tc.name: getAllDeviceIPPortInfos + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getAllDeviceIPPortInfos_0001 + * @tc.desc: getAllDeviceIPPortInfos + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getAllDeviceIPPortInfosTest() { + List list = MultiDeviceManager.getInstance().getOnlineDeviceInfoList(); + Assert.assertNotNull(list); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void getInstanceTest() { + MultiDeviceManager multiDeviceManager = MultiDeviceManager.getInstance(); + Assert.assertNotNull(multiDeviceManager); + } + + /** + * functional testing getInstance + * + * @tc.name: pushHiprofilerToolsTest + * @tc.number: OHOS_JAVA_device_MultiDeviceManager_pushHiprofilerToolsTest_0001 + * @tc.desc: push Hiprofiler Tools Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-002 + */ + @Test + public void pushHiprofilerToolsTest() { + MultiDeviceManager.getInstance().pushHiProfilerTools(deviceIPPortInfo); + Assert.assertTrue(true); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDaoTest.java index 76b82e95f..efcc6d84c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDaoTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/dao/MonitorConfigDaoTest.java @@ -1,98 +1,110 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.monitorconfig.dao; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * 监控项配置数据的dao层测试类 - * - * @version 1.0 - * @date 2021/04/12 14:13 - **/ -public class MonitorConfigDaoTest { - private MonitorConfigDao monitorConfigDao; - - /** - * init - */ - @Before - public void init() { - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - } - - /** - * functional testing getInstance - * - * @tc.name: MonitorConfigDao initialization configuration - * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_getInstance_0001 - * @tc.desc: MonitorConfigDao getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void getInstanceTest() { - monitorConfigDao = MonitorConfigDao.getInstance(); - Assert.assertNotNull(monitorConfigDao); - } - - /** - * functional testing insertMonitorInfo - * - * @tc.name: MonitorConfigDao insertMonitorInfo - * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_insertMonitorInfo_0001 - * @tc.desc: MonitorConfigDao insertMonitorInfo - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void testInsert() { - MonitorInfo monitorInfo = - MonitorInfo.builder().monitorType("type").localSessionId(1L).parameter("name").value("value").build(); - monitorConfigDao = MonitorConfigDao.getInstance(); - boolean flag = monitorConfigDao.insertMonitorInfo(monitorInfo); - Assert.assertTrue(flag); - } - - /** - * functional testing insertMonitorInfos - * - * @tc.name: MonitorConfigDao insertMonitorInfos - * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_insertMonitorInfos_0001 - * @tc.desc: MonitorConfigDao insertMonitorInfos - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void testInsertList() { - List list = new ArrayList<>(); - MonitorInfo monitorInfo = - MonitorInfo.builder().monitorType("type").localSessionId(1L).parameter("name").value("value").build(); - list.add(monitorInfo); - monitorConfigDao = MonitorConfigDao.getInstance(); - boolean flag = monitorConfigDao.insertMonitorInfos(list); - Assert.assertTrue(flag); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.monitorconfig.dao; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * DAO layer test class of monitoring item configuration data + */ +public class MonitorConfigDaoTest { + private MonitorConfigDao monitorConfigDao; + + /** + * init + */ + @Before + public void init() { + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + } + + /** + * functional testing getInstance + * + * @tc.name: MonitorConfigDao initialization configuration + * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_getInstance_0001 + * @tc.desc: MonitorConfigDao getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void getInstanceTest01() { + monitorConfigDao = MonitorConfigDao.getInstance(); + Assert.assertNotNull(monitorConfigDao); + } + + /** + * functional testing getInstance + * + * @tc.name: MonitorConfigDao initialization configuration + * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_getInstance_0002 + * @tc.desc: MonitorConfigDao getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void getInstanceTest02() { + monitorConfigDao = MonitorConfigDao.getInstance(); + MonitorConfigDao configDao = MonitorConfigDao.getInstance(); + Assert.assertEquals(monitorConfigDao, configDao); + } + + /** + * functional testing insertMonitorInfo + * + * @tc.name: MonitorConfigDao insertMonitorInfo + * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_insertMonitorInfo_0001 + * @tc.desc: MonitorConfigDao insertMonitorInfo + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void testInsert() { + MonitorInfo monitorInfo = + MonitorInfo.builder().monitorType("type").localSessionId(1L).parameter("name").value("value").build(); + monitorConfigDao = MonitorConfigDao.getInstance(); + boolean flag = monitorConfigDao.insertMonitorInfo(monitorInfo); + Assert.assertTrue(flag); + } + + /** + * functional testing insertMonitorInfos + * + * @tc.name: MonitorConfigDao insertMonitorInfos + * @tc.number: OHOS_JAVA_monitor_MonitorConfigDao_insertMonitorInfos_0001 + * @tc.desc: MonitorConfigDao insertMonitorInfos + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void testInsertList() { + List list = new ArrayList<>(); + MonitorInfo monitorInfo = + MonitorInfo.builder().monitorType("type").localSessionId(1L).parameter("name").value("value").build(); + list.add(monitorInfo); + monitorConfigDao = MonitorConfigDao.getInstance(); + boolean flag = monitorConfigDao.insertMonitorInfos(list); + Assert.assertTrue(flag); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfoTest.java deleted file mode 100644 index b4f5c038f..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/entity/MonitorInfoTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.monitorconfig.entity; - -import org.junit.Assert; -import org.junit.Test; - -/** - * MonitorInfoTest - * - * @version 1.0 - * @date 2021/04/14 10:52 - **/ -public class MonitorInfoTest { - private Long sessionId = 0L; - - /** - * functional testing set localSessionId - * - * @tc.name: MonitorInfo localSessionId - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_localSessionId_0001 - * @tc.desc: MonitorInfo localSessionId - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void localSessionIdTest() { - MonitorInfo.Builder builder = MonitorInfo.builder().localSessionId(sessionId); - Assert.assertNotNull(builder); - } - - /** - * functional testing set monitorType - * - * @tc.name: MonitorInfo monitorType - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_monitorType_0001 - * @tc.desc: MonitorInfo monitorType - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void monitorTypeTest() { - MonitorInfo.Builder builder = MonitorInfo.builder().monitorType(""); - Assert.assertNotNull(builder); - } - - /** - * functional testing set parameter - * - * @tc.name: MonitorInfo parameter - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_parameter_0001 - * @tc.desc: MonitorInfo parameter - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void parameterTest() { - MonitorInfo.Builder builder = MonitorInfo.builder().parameter(""); - Assert.assertNotNull(builder); - } - - /** - * functional testing set value - * - * @tc.name: MonitorInfo value - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_value_0001 - * @tc.desc: MonitorInfo value - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void valueTest() { - MonitorInfo.Builder builder = MonitorInfo.builder().value(""); - Assert.assertNotNull(builder); - } - - /** - * functional testing set build - * - * @tc.name: MonitorInfo build - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_build_0001 - * @tc.desc: MonitorInfo build - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void buildTest() { - MonitorInfo monitorInfo = MonitorInfo.builder().build(); - Assert.assertNotNull(monitorInfo); - } - - /** - * functional testing equals - * - * @tc.name: MonitorInfo equals - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_equals_0001 - * @tc.desc: MonitorInfo equals - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void equalsTest() { - boolean flag = MonitorInfo.builder().build().equals(Object.class); - Assert.assertFalse(flag); - } - - /** - * functional testing toString - * - * @tc.name: MonitorInfo toString - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_toString_0001 - * @tc.desc: MonitorInfo toString - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void toStringTest() { - String str = MonitorInfo.builder().build().toString(); - Assert.assertNotNull(str); - } - - /** - * functional testing hashCode - * - * @tc.name: MonitorInfo hashCode - * @tc.number: OHOS_JAVA_monitor_MonitorInfo_hashCode_0001 - * @tc.desc: MonitorInfo hashCode - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void hashCodeTest() { - int number = MonitorInfo.builder().build().hashCode(); - Assert.assertNotNull(number); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManagerTest.java index ad5f2aafc..08b30d051 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/monitorconfig/service/MonitorConfigManagerTest.java @@ -1,150 +1,147 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.monitorconfig.service; - -import com.alibaba.fastjson.JSONObject; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * MonitorConfigManagerTest - * - * @version 1.0 - * @date 2021/03/31 10:10 - **/ -public class MonitorConfigManagerTest { - private long localSessionId = 0; - private JSONObject jsonObject; - private DeviceIPPortInfo device; - private ProcessInfo processInfo; - private MonitorConfigManager monitorConfigManager; - private LinkedList monitorInfo; - - /** - * functional testing setAnalyzeJson - * - * @tc.name: MonitorConfigManager setAnalyzeJson - * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_setAnalyzeJson_0001 - * @tc.desc: MonitorConfigManager setAnalyzeJson - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Before - public void setAnalyzeJson() { - SessionManager.getInstance().setDevelopMode(true); - localSessionId = 1000L; - jsonObject = new JSONObject(); - JSONObject memoryObject = new JSONObject(); - memoryObject.put("Select All", true); - memoryObject.put("Java", true); - memoryObject.put("Native", true); - memoryObject.put("Graphics", true); - memoryObject.put("Stack", true); - memoryObject.put("Code", true); - memoryObject.put("Others", true); - JSONObject cPUObject = new JSONObject(); - cPUObject.put("Select All1", true); - cPUObject.put("System Memory1", true); - cPUObject.put("Gpu Memory1", true); - cPUObject.put("BandWidth1", true); - jsonObject.put("Memory", memoryObject); - jsonObject.put("CPU", cPUObject); - device = new DeviceIPPortInfo(); - device.setIp(""); - device.setForwardPort(5001); - processInfo = new ProcessInfo(); - processInfo.setProcessId(1); - processInfo.setProcessName("process"); - monitorConfigManager = MonitorConfigManager.getInstance(); - DataBaseApi.getInstance().initDataSourceManager(); - ConcurrentHashMap>> dataMap = monitorConfigManager.dataMap; - } - - /** - * functional testing getInstance - * - * @tc.name: MonitorConfigManager getInstance - * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_getInstance_0001 - * @tc.desc: MonitorConfigManager getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void getInstance01() { - MonitorConfigManager configManager = MonitorConfigManager.getInstance(); - Assert.assertNotNull(configManager); - } - - /** - * functional testing getInstance - * - * @tc.name: MonitorConfigManager getInstance - * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_getInstance_0002 - * @tc.desc: MonitorConfigManager getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void getInstance02() { - MonitorConfigManager configManager01 = MonitorConfigManager.getInstance(); - MonitorConfigManager configManager02 = MonitorConfigManager.getInstance(); - Assert.assertEquals(configManager01, configManager02); - } - - /** - * functional testing analyzeCharTarget - * - * @tc.name: MonitorConfigManager analyzeCharTarget - * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_analyzeCharTarget_0001 - * @tc.desc: MonitorConfigManager analyzeCharTarget - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void analyzeCharTargetTest1() { - Map> stringLinkedListMap = - MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); - Assert.assertNotNull(stringLinkedListMap); - } - - /** - * functional testing analyzeCharTarget - * - * @tc.name: MonitorConfigManager analyzeCharTarget - * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_analyzeCharTarget_0002 - * @tc.desc: MonitorConfigManager analyzeCharTarget - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void analyzeCharTargetTest3() { - Map> stringLinkedListMap = - MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); - Map> stringLinkedListMap1 = - MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); - Assert.assertEquals(stringLinkedListMap, stringLinkedListMap1); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.monitorconfig.service; + +import com.alibaba.fastjson.JSONObject; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.monitorconfig.entity.MonitorInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.LinkedList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Monitor Config Manager Test + */ +public class MonitorConfigManagerTest { + private long localSessionId = 0; + private JSONObject jsonObject; + private DeviceIPPortInfo device; + private ProcessInfo processInfo; + private MonitorConfigManager monitorConfigManager; + private LinkedList monitorInfo; + + /** + * functional testing setAnalyzeJson + * + * @tc.name: MonitorConfigManager setAnalyzeJson + * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_setAnalyzeJson_0001 + * @tc.desc: MonitorConfigManager setAnalyzeJson + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Before + public void setAnalyzeJson() { + SessionManager.getInstance().setDevelopMode(true); + localSessionId = 1000L; + jsonObject = new JSONObject(); + JSONObject memoryObject = new JSONObject(); + memoryObject.put("Select All", true); + memoryObject.put("Java", true); + memoryObject.put("Native", true); + memoryObject.put("Graphics", true); + memoryObject.put("Stack", true); + memoryObject.put("Code", true); + memoryObject.put("Others", true); + JSONObject cPUObject = new JSONObject(); + cPUObject.put("Select All1", true); + cPUObject.put("System Memory1", true); + cPUObject.put("Gpu Memory1", true); + cPUObject.put("BandWidth1", true); + jsonObject.put("Memory", memoryObject); + jsonObject.put("CPU", cPUObject); + device = new DeviceIPPortInfo(); + device.setIp(""); + device.setForwardPort(5001); + processInfo = new ProcessInfo(); + processInfo.setProcessId(1); + processInfo.setProcessName("process"); + monitorConfigManager = MonitorConfigManager.getInstance(); + DataBaseApi.getInstance().initDataSourceManager(); + ConcurrentHashMap>> dataMap = monitorConfigManager.dataMap; + } + + /** + * functional testing getInstance + * + * @tc.name: MonitorConfigManager getInstance + * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_getInstance_0001 + * @tc.desc: MonitorConfigManager getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void getInstance01() { + MonitorConfigManager configManager = MonitorConfigManager.getInstance(); + Assert.assertNotNull(configManager); + } + + /** + * functional testing getInstance + * + * @tc.name: MonitorConfigManager getInstance + * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_getInstance_0002 + * @tc.desc: MonitorConfigManager getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void getInstance02() { + MonitorConfigManager configManager01 = MonitorConfigManager.getInstance(); + MonitorConfigManager configManager02 = MonitorConfigManager.getInstance(); + Assert.assertEquals(configManager01, configManager02); + } + + /** + * functional testing analyzeCharTarget + * + * @tc.name: MonitorConfigManager analyzeCharTarget + * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_analyzeCharTarget_0001 + * @tc.desc: MonitorConfigManager analyzeCharTarget + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void analyzeCharTargetTest1() { + Map> stringLinkedListMap = + MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); + Assert.assertNotNull(stringLinkedListMap); + } + + /** + * functional testing analyzeCharTarget + * + * @tc.name: MonitorConfigManager analyzeCharTarget + * @tc.number: OHOS_JAVA_monitor_MonitorConfigManager_analyzeCharTarget_0002 + * @tc.desc: MonitorConfigManager analyzeCharTarget + * @tc.type: functional testing + * @tc.require: AR000FK61R + */ + @Test + public void analyzeCharTargetTest3() { + Map> stringLinkedListMap = + MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); + Map> stringLinkedListMap1 = + MonitorConfigManager.getInstance().analyzeCharTarget(localSessionId, jsonObject); + Assert.assertEquals(stringLinkedListMap, stringLinkedListMap1); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/dao/PlugDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/dao/PlugDaoTest.java deleted file mode 100644 index 0bf32eb3a..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/dao/PlugDaoTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.plugin.dao; - -import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPlugin; -import org.junit.Assert; -import org.junit.Test; - -import java.util.List; - -/** - * 插件dao层(与sqlite交互)测试类 - * - * @version 1.0 - * @date 2021/04/12 11:11 - **/ -public class PlugDaoTest { - /** - * functional testing getInstance - * - * @tc.name: PlugDao getInstance - * @tc.number: OHOS_JAVA_plugin_PlugDao_getInstance_0001 - * @tc.desc: PlugDao getInstance - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void getInstanceTest() { - PlugDao plugDao = PlugDao.getInstance(); - Assert.assertNotNull(plugDao); - } - - /** - * functional testing selectPlugConfig - * - * @tc.name: PlugDao selectPlugConfig - * @tc.number: OHOS_JAVA_plugin_PlugDao_selectPlugConfig_0001 - * @tc.desc: PlugDao selectPlugConfig - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void selectPlugConfigTest() { - List list = null; - list = PlugDao.getInstance().selectPlugConfig("1"); - if (list != null) { - Assert.assertTrue(true); - } - } -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/service/PlugManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/service/PlugManagerTest.java index 6b2da0cec..07fd33c2b 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/service/PlugManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/plugin/service/PlugManagerTest.java @@ -1,120 +1,913 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.plugin.service; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPlugin; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -/** - * PlugManagerTest - * - * @version 1.0 - * @date 2021/03/31 10:10 - **/ -public class PlugManagerTest { - private DeviceIPPortInfo deviceInfo; - - /** - * functional testing init - * - * @tc.name: PlugManager init - * @tc.number: OHOS_JAVA_plugin_PlugManager_init_0001 - * @tc.desc: PlugManager init - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Before - public void setDeviceInfo() { - SessionManager.getInstance().setDevelopMode(true); - String serialNumber = "emulator-5554"; - deviceInfo = new DeviceIPPortInfo(); - deviceInfo.setDeviceID(serialNumber); - DataBaseApi.getInstance().initDataSourceManager(); - } - - /** - * functional testing getInstance - * - * @tc.name: PlugManager getInstance - * @tc.number: OHOS_JAVA_plugin_PlugManager_getInstance_0001 - * @tc.desc: PlugManager getInstance - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void getInstance01() { - PlugManager plugManager = PlugManager.getInstance(); - Assert.assertNotNull(plugManager); - } - - /** - * functional testing getInstance - * - * @tc.name: PlugManager getInstance - * @tc.number: OHOS_JAVA_plugin_PlugManager_getInstance_0002 - * @tc.desc: PlugManager getInstance - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void getInstance02() { - PlugManager plugManager01 = PlugManager.getInstance(); - PlugManager plugManager02 = PlugManager.getInstance(); - Assert.assertEquals(plugManager01, plugManager02); - } - - /** - * functional testing insertPlugInfo - * - * @tc.name: PlugManager insertPlugInfo - * @tc.number: OHOS_JAVA_plugin_PlugManager_insertPlugInfo_0001 - * @tc.desc: PlugManager insertPlugInfo - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void insertPlugInfoTest() { - HiProfilerPlugin hiProfilerPlugin = - HiProfilerPlugin.builder().deviceId("dsf").version("dsfaf").sampleInterval(3).plugSha256("dshfjka") - .status(1).id(3).name("tst").build(); - hiProfilerPlugin.setPath("C:\\ohoslibmemdataplugin.z.so"); - hiProfilerPlugin.toString(); - PlugManager.getInstance().insertPlugInfo(hiProfilerPlugin); - } - - /** - * functional testing selectPlugConfig - * - * @tc.name: PlugManager selectPlugConfig - * @tc.number: OHOS_JAVA_plugin_PlugManager_selectPlugConfig_0001 - * @tc.desc: PlugManager selectPlugConfig - * @tc.type: functional testing - * @tc.require: AR000FK5SH - */ - @Test - public void selectPlugConfigTest() { - List list = PlugManager.getInstance().selectPlugConfig(deviceInfo.getDeviceID()); - Assert.assertNotNull(list); - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.plugin.service; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.plugin.IPluginConfig; +import ohos.devtools.datasources.utils.plugin.entity.PluginConf; +import ohos.devtools.datasources.utils.plugin.entity.PluginMode; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.pluginconfig.CpuConfig; +import ohos.devtools.pluginconfig.MemoryConfig; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.memory.MemoryItemView; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * PlugManagerTest + */ +public class PlugManagerTest { + private DeviceIPPortInfo deviceInfo; + private PluginConf pluginConf; + + /** + * functional testing init + * + * @tc.name: PlugManager init + * @tc.number: OHOS_JAVA_plugin_PlugManager_init_0001 + * @tc.desc: PlugManager init + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Before + public void setDeviceInfo() { + pluginConf = new PluginConf("", "", null, false, null); + SessionManager.getInstance().setDevelopMode(true); + String serialNumber = "emulator-5554"; + deviceInfo = new DeviceIPPortInfo(); + deviceInfo.setDeviceID(serialNumber); + DataBaseApi.getInstance().initDataSourceManager(); + } + + /** + * functional testing getInstance + * + * @tc.name: PlugManager getInstance + * @tc.number: OHOS_JAVA_plugin_PlugManager_getInstance_0001 + * @tc.desc: PlugManager getInstance + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getInstance01() { + PlugManager plugManager = PlugManager.getInstance(); + Assert.assertNotNull(plugManager); + } + + /** + * functional testing getInstance + * + * @tc.name: PlugManager getInstance + * @tc.number: OHOS_JAVA_plugin_PlugManager_getInstance_0002 + * @tc.desc: PlugManager getInstance + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getInstance02() { + PlugManager plugManager01 = PlugManager.getInstance(); + PlugManager plugManager02 = PlugManager.getInstance(); + Assert.assertEquals(plugManager01, plugManager02); + } + + /** + * functional testing getPluginConfigTest + * + * @tc.name: PlugManager getPluginConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getPluginConfigTest_0001 + * @tc.desc: PlugManager getPluginConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getPluginConfigTest01() { + List list = PlugManager.getInstance().getPluginConfig(null, null); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getPluginConfigTest + * + * @tc.name: PlugManager getPluginConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getPluginConfigTest_0002 + * @tc.desc: PlugManager getPluginConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getPluginConfigTest02() { + List list = PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, null); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getPluginConfigTest + * + * @tc.name: PlugManager getPluginConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getPluginConfigTest_0003 + * @tc.desc: PlugManager getPluginConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getPluginConfigTest03() { + List list = PlugManager.getInstance().getPluginConfig(null, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getPluginConfigTest + * + * @tc.name: PlugManager getPluginConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getPluginConfigTest_0004 + * @tc.desc: PlugManager getPluginConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getPluginConfigTest04() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing getPluginConfigTest + * + * @tc.name: PlugManager getPluginConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getPluginConfigTest_0005 + * @tc.desc: PlugManager getPluginConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getPluginConfigTest05() { + PlugManager.getInstance().clearPluginConfList(); + pluginConf.setPluginMode(PluginMode.OFFLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing loadingPlugsTest + * + * @tc.name: PlugManager loadingPlugsTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugsTest_0001 + * @tc.desc: PlugManager loadingPlugsTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugsTest01() { + PlugManager.getInstance().loadingPlugs(null); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugsTest + * + * @tc.name: PlugManager loadingPlugsTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugsTest_0002 + * @tc.desc: PlugManager loadingPlugsTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugsTest02() { + List> pluginConfigs = new ArrayList<>(); + PlugManager.getInstance().loadingPlugs(pluginConfigs); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugsTest + * + * @tc.name: PlugManager loadingPlugsTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugsTest_0003 + * @tc.desc: PlugManager loadingPlugsTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugsTest03() { + List> plugConfigList = new ArrayList(); + plugConfigList.add(CpuConfig.class); + plugConfigList.add(MemoryConfig.class); + PlugManager.getInstance().loadingPlugs(plugConfigList); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugsTest + * + * @tc.name: PlugManager loadingPlugsTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugsTest_0004 + * @tc.desc: PlugManager loadingPlugsTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugsTest04() { + List> plugConfigList = new ArrayList(); + plugConfigList.add(null); + PlugManager.getInstance().loadingPlugs(plugConfigList); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugsTest + * + * @tc.name: PlugManager loadingPlugsTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugsTest_0005 + * @tc.desc: PlugManager loadingPlugsTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugsTest05() { + List> plugConfigList = new ArrayList(); + plugConfigList.add(null); + PlugManager.getInstance().loadingPlugs(plugConfigList); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugTest + * + * @tc.name: PlugManager loadingPlugTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugTest_0001 + * @tc.desc: PlugManager loadingPlugTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugTest01() { + PlugManager.getInstance().loadingPlug(null); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugTest + * + * @tc.name: PlugManager loadingPlugTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugTest_0002 + * @tc.desc: PlugManager loadingPlugTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugTest02() { + PlugManager.getInstance().loadingPlug(MemoryConfig.class); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugTest + * + * @tc.name: PlugManager loadingPlugTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugTest_0003 + * @tc.desc: PlugManager loadingPlugTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugTest03() { + PlugManager.getInstance().loadingPlug(IPluginConfig.class); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugTest + * + * @tc.name: PlugManager loadingPlugTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugTest_0004 + * @tc.desc: PlugManager loadingPlugTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugTest04() { + PlugManager.getInstance().loadingPlug(new CpuConfig().getClass()); + Assert.assertTrue(true); + } + + /** + * functional testing loadingPlugTest + * + * @tc.name: PlugManager loadingPlugTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_loadingPlugTest_0005 + * @tc.desc: PlugManager loadingPlugTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void loadingPlugTest05() { + List> plugConfigList = new ArrayList(); + plugConfigList.add(null); + PlugManager.getInstance().loadingPlug(plugConfigList.get(1)); + Assert.assertTrue(true); + } + + /** + * functional testing registerPluginTest + * + * @tc.name: PlugManager registerPluginTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_registerPluginTest_0001 + * @tc.desc: PlugManager registerPluginTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void registerPluginTest01() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing registerPluginTest + * + * @tc.name: PlugManager registerPluginTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_registerPluginTest_0002 + * @tc.desc: PlugManager registerPluginTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void registerPluginTest02() { + PlugManager.getInstance().clearPluginConfList(); + pluginConf.setPluginMode(PluginMode.OFFLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing registerPluginTest + * + * @tc.name: PlugManager registerPluginTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_registerPluginTest_0003 + * @tc.desc: PlugManager registerPluginTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void registerPluginTest03() { + PlugManager.getInstance().registerPlugin(null); + Assert.assertTrue(true); + } + + /** + * functional testing registerPluginTest + * + * @tc.name: PlugManager registerPluginTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_registerPluginTest_0004 + * @tc.desc: PlugManager registerPluginTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void registerPluginTest04() { + PlugManager.getInstance().clearPluginConfList(); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing registerPluginTest + * + * @tc.name: PlugManager registerPluginTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_registerPluginTest_0005 + * @tc.desc: PlugManager registerPluginTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void registerPluginTest05() { + PlugManager.getInstance().clearPluginConfList(); + PlugManager.getInstance().registerPlugin(new PluginConf("pluginFileName", "", null, true, null)); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing addPluginStartSuccessTest + * + * @tc.name: PlugManager addPluginStartSuccessTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_addPluginStartSuccessTest_0001 + * @tc.desc: PlugManager addPluginStartSuccessTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void addPluginStartSuccessTest01() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(1L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing addPluginStartSuccessTest + * + * @tc.name: PlugManager addPluginStartSuccessTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_addPluginStartSuccessTest_0002 + * @tc.desc: PlugManager addPluginStartSuccessTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void addPluginStartSuccessTest02() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + PlugManager.getInstance().addPluginStartSuccess(1L, null); + List list = PlugManager.getInstance().getProfilerPlugConfig(1L); + PluginConf pluginConfParam = list.get(0); + Assert.assertNull(pluginConfParam); + } + + /** + * functional testing addPluginStartSuccessTest + * + * @tc.name: PlugManager addPluginStartSuccessTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_addPluginStartSuccessTest_0003 + * @tc.desc: PlugManager addPluginStartSuccessTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void addPluginStartSuccessTest03() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(0L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing addPluginStartSuccessTest + * + * @tc.name: PlugManager addPluginStartSuccessTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_addPluginStartSuccessTest_0004 + * @tc.desc: PlugManager addPluginStartSuccessTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void addPluginStartSuccessTest04() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(Long.MAX_VALUE, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(Long.MAX_VALUE); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing addPluginStartSuccessTest + * + * @tc.name: PlugManager addPluginStartSuccessTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_addPluginStartSuccessTest_0005 + * @tc.desc: PlugManager addPluginStartSuccessTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void addPluginStartSuccessTest05() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(1L); + int num = list.size(); + Assert.assertEquals(2, num); + } + + /** + * functional testing getProfilerPlugConfigTest + * + * @tc.name: PlugManager getProfilerPlugConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerPlugConfigTest_0001 + * @tc.desc: PlugManager getProfilerPlugConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerPlugConfigTest01() { + List list = PlugManager.getInstance().getProfilerPlugConfig(0L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getProfilerPlugConfigTest + * + * @tc.name: PlugManager getProfilerPlugConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerPlugConfigTest_0002 + * @tc.desc: PlugManager getProfilerPlugConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerPlugConfigTest02() { + List list = PlugManager.getInstance().getProfilerPlugConfig(Long.MAX_VALUE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getProfilerPlugConfigTest + * + * @tc.name: PlugManager getProfilerPlugConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerPlugConfigTest_0003 + * @tc.desc: PlugManager getProfilerPlugConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerPlugConfigTest03() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing getProfilerPlugConfigTest + * + * @tc.name: PlugManager getProfilerPlugConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerPlugConfigTest_0004 + * @tc.desc: PlugManager getProfilerPlugConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerPlugConfigTest04() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + PlugManager.getInstance().addPluginStartSuccess(10L, null); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + PluginConf pluginConfParam = list.get(0); + Assert.assertNull(pluginConfParam); + } + + /** + * functional testing getProfilerPlugConfigTest + * + * @tc.name: PlugManager getProfilerPlugConfigTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerPlugConfigTest_0005 + * @tc.desc: PlugManager getProfilerPlugConfigTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerPlugConfigTest05() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + PlugManager.getInstance().addPluginStartSuccess(10L, new PluginConf("pluginFileName", "", null, true, null)); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + PluginConf pluginConfParam = list.get(0); + Assert.assertNotNull(pluginConfParam); + } + + /** + * functional testing getProfilerMonitorItemListTest + * + * @tc.name: PlugManager getProfilerMonitorItemListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerMonitorItemListTest_0001 + * @tc.desc: PlugManager getProfilerMonitorItemListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerMonitorItemListTest01() { + List list = PlugManager.getInstance().getProfilerMonitorItemList(0L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getProfilerMonitorItemListTest + * + * @tc.name: PlugManager getProfilerMonitorItemListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerMonitorItemListTest_0002 + * @tc.desc: PlugManager getProfilerMonitorItemListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerMonitorItemListTest02() { + List list = PlugManager.getInstance().getProfilerMonitorItemList(Long.MAX_VALUE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getProfilerMonitorItemListTest + * + * @tc.name: PlugManager getProfilerMonitorItemListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerMonitorItemListTest_0003 + * @tc.desc: PlugManager getProfilerMonitorItemListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerMonitorItemListTest03() { + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + pluginConf.setMonitorItem(memoryItem); + pluginConf.setChartPlugin(true); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerMonitorItemList(10L); + ProfilerMonitorItem profilerMonitorItem = list.get(0); + Assert.assertNotNull(profilerMonitorItem); + } + + /** + * functional testing getProfilerMonitorItemListTest + * + * @tc.name: PlugManager getProfilerMonitorItemListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerMonitorItemListTest_0004 + * @tc.desc: PlugManager getProfilerMonitorItemListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerMonitorItemListTest04() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + pluginConf.setChartPlugin(true); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerMonitorItemList(10L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing getProfilerMonitorItemListTest + * + * @tc.name: PlugManager getProfilerMonitorItemListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_getProfilerMonitorItemListTest_0005 + * @tc.desc: PlugManager getProfilerMonitorItemListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void getProfilerMonitorItemListTest05() { + PlugManager.getInstance().clearProfilerMonitorItemMap(); + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + pluginConf.setMonitorItem(memoryItem); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + ProfilerMonitorItem memoryItem2 = new ProfilerMonitorItem(10, "Memory", MemoryItemView.class); + pluginConf.setMonitorItem(memoryItem2); + pluginConf.setChartPlugin(true); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerMonitorItemList(10L); + int num = list.size(); + Assert.assertEquals(2, num); + } + + /** + * functional testing clearProfilerMonitorItemMapTest + * + * @tc.name: PlugManager clearProfilerMonitorItemMapTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearProfilerMonitorItemMapTest_0001 + * @tc.desc: PlugManager clearProfilerMonitorItemMapTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearProfilerMonitorItemMapTest01() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearProfilerMonitorItemMapTest + * + * @tc.name: PlugManager clearProfilerMonitorItemMapTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearProfilerMonitorItemMapTest_0002 + * @tc.desc: PlugManager clearProfilerMonitorItemMapTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearProfilerMonitorItemMapTest02() { + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing clearProfilerMonitorItemMapTest + * + * @tc.name: PlugManager clearProfilerMonitorItemMapTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearProfilerMonitorItemMapTest_0003 + * @tc.desc: PlugManager clearProfilerMonitorItemMapTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearProfilerMonitorItemMapTest03() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + List list = PlugManager.getInstance().getProfilerPlugConfig(10L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearProfilerMonitorItemMapTest + * + * @tc.name: PlugManager clearProfilerMonitorItemMapTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearProfilerMonitorItemMapTest_0004 + * @tc.desc: PlugManager clearProfilerMonitorItemMapTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearProfilerMonitorItemMapTest04() { + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + pluginConf.setMonitorItem(memoryItem); + pluginConf.setChartPlugin(true); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + List list = PlugManager.getInstance().getProfilerMonitorItemList(10L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearProfilerMonitorItemMapTest + * + * @tc.name: PlugManager clearProfilerMonitorItemMapTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearProfilerMonitorItemMapTest_0005 + * @tc.desc: PlugManager clearProfilerMonitorItemMapTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearProfilerMonitorItemMapTest05() { + pluginConf.setChartPlugin(true); + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + pluginConf.setMonitorItem(memoryItem); + PlugManager.getInstance().addPluginStartSuccess(1L, pluginConf); + PlugManager.getInstance().clearProfilerMonitorItemMap(); + pluginConf.setMonitorItem(memoryItem); + PlugManager.getInstance().addPluginStartSuccess(10L, pluginConf); + List list = PlugManager.getInstance().getProfilerMonitorItemList(1L); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearPluginConfListTest + * + * @tc.name: PlugManager clearPluginConfListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearPluginConfListTest_0001 + * @tc.desc: PlugManager clearPluginConfListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearPluginConfListTest01() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + PlugManager.getInstance().clearPluginConfList(); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearPluginConfListTest + * + * @tc.name: PlugManager clearPluginConfListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearPluginConfListTest_0002 + * @tc.desc: PlugManager clearPluginConfListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearPluginConfListTest02() { + PlugManager.getInstance().registerPlugin(pluginConf); + PlugManager.getInstance().clearPluginConfList(); + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * functional testing clearPluginConfListTest + * + * @tc.name: PlugManager clearPluginConfListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearPluginConfListTest_0003 + * @tc.desc: PlugManager clearPluginConfListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearPluginConfListTest03() { + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + PlugManager.getInstance().registerPlugin(pluginConf); + PlugManager.getInstance().clearPluginConfList(); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearPluginConfListTest + * + * @tc.name: PlugManager clearPluginConfListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearPluginConfListTest_0004 + * @tc.desc: PlugManager clearPluginConfListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearPluginConfListTest04() { + PluginConf pluginConfNew = new PluginConf("pluginFileName", "", null, true, null); + pluginConfNew.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConfNew); + PlugManager.getInstance().clearPluginConfList(); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.ONLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } + + /** + * functional testing clearPluginConfListTest + * + * @tc.name: PlugManager clearPluginConfListTest + * @tc.number: OHOS_JAVA_plugin_PlugManager_clearPluginConfListTest_0005 + * @tc.desc: PlugManager clearPluginConfListTest + * @tc.type: functional testing + * @tc.require: AR000FK5SH + */ + @Test + public void clearPluginConfListTest05() { + pluginConf.setPluginMode(PluginMode.OFFLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + PlugManager.getInstance().clearPluginConfList(); + pluginConf.setPluginMode(PluginMode.ONLINE); + PlugManager.getInstance().registerPlugin(pluginConf); + List list = + PlugManager.getInstance().getPluginConfig(DeviceType.FULL_HOS_DEVICE, PluginMode.OFFLINE); + int num = list.size(); + Assert.assertEquals(0, num); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/ProcessManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/ProcessManagerTest.java index 4e65e0755..138fa9d1c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/ProcessManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/ProcessManagerTest.java @@ -1,308 +1,374 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.process.service; - -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import io.grpc.util.MutableHandlerRegistry; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.utils.device.dao.DeviceUtil; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -/** - * process Unit Test - * - * @version 1.0 - * @date 2021/02/25 14:22 - **/ -public class ProcessManagerTest { - private static volatile Integer requestId = 1; - private ProcessInfo processInfo; - private String processName; - private DeviceInfo deviceInfo; - private DeviceIPPortInfo deviceIPPortInfo; - private String deviceId; - private String serverName; - private String IP; - private int firstPort; - private MockProfilerServiceImplBase getFeatureImpl; - private ManagedChannel channel; - private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); - - /** - * grpcCleanup - */ - private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - - /** - * functional testing init - * - * @tc.name: ProcessManager init - * @tc.number: OHOS_JAVA_process_ProcessManager_init_0001 - * @tc.desc: ProcessManager init - * @tc.type: functional testing - * @tc.require: SR-004 - * @throws IOException throw IOException - */ - @Before - public void initObj() throws IOException { - SessionManager.getInstance().setDevelopMode(true); - // 应用初始化 Step1 初始化数据中心 - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceID("1"); - deviceInfo.setDeviceName("华为p40"); - deviceInfo.setRamInfo("zz"); - deviceInfo.setRomInfo("vv"); - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setDeviceID("1"); - deviceIPPortInfo.setPort(5001); - deviceIPPortInfo.setForwardPort(5001); - deviceIPPortInfo.setDeviceName(""); - deviceIPPortInfo.setDeviceType(""); - deviceId = "1"; - processInfo = new ProcessInfo(); - processInfo.setDeviceId("1"); - processInfo.setProcessId(1); - processInfo.setProcessName("com.go.maps"); - processName = "goo"; - IP = ""; - firstPort = 5001; - serverName = InProcessServerBuilder.generateName(); - getFeatureImpl = new MockProfilerServiceImplBase() { - /** - * init getCapabilities - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") - .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init createSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init startSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init fetchData - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoZero = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) - .setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh") - .setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns") - .setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) - .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - - /** - * init stopSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init destroySession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - }; - grpcCleanup.register( - InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() - .start()); - channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - } - - /** - * functional testing getInstance - * - * @tc.name: ProcessManager getInstance - * @tc.number: OHOS_JAVA_process_ProcessManager_getInstance_0001 - * @tc.desc: ProcessManager getInstance - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getProcessManager01() { - ProcessManager processManager = ProcessManager.getInstance(); - Assert.assertNotNull(processManager); - } - - /** - * functional testing getInstance - * - * @tc.name: ProcessManager getInstance - * @tc.number: OHOS_JAVA_process_ProcessManager_getInstance_0002 - * @tc.desc: ProcessManager getInstance - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getProcessManager02() { - ProcessManager processManagerOne = ProcessManager.getInstance(); - ProcessManager processManagerTwo = ProcessManager.getInstance(); - Assert.assertEquals(processManagerOne, processManagerTwo); - } - - /** - * functional testing getProcessList - * - * @tc.name: ProcessManager getProcessList - * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0001 - * @tc.desc: ProcessManager getProcessList - * @tc.type: functional testing - * @tc.require: SR-004-AR-003 - */ - @Test - public void getProcessList() { - List processList = ProcessManager.getInstance().getProcessList(null); - int size = processList.size(); - Assert.assertEquals(0, size); - } - - /** - * functional testing getProcessList - * - * @tc.name: ProcessManager getProcessList - * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0002 - * @tc.desc: ProcessManager getProcessList - * @tc.type: functional testing - * @tc.require: SR-004-AR-003 - */ - @Test - public void getProcessList1() { - new DeviceUtil().insertDeviceIPPortInfo(deviceIPPortInfo); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient(IP, firstPort, channel); - List processList = ProcessManager.getInstance().getProcessList(deviceIPPortInfo); - int size = processList.size(); - Assert.assertEquals(0, size); - } - - private int getIntData() { - requestId++; - if (requestId == Integer.MAX_VALUE) { - requestId = 0; - } - return requestId; - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.process.service; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.device.dao.DeviceDao; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceType; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +/** + * process Unit Test + */ +public class ProcessManagerTest { + private static volatile Integer requestId = 1; + private ProcessInfo processInfo; + private String processName; + private DeviceIPPortInfo deviceIPPortInfo; + private String deviceId; + private String serverName; + private String IP; + private int firstPort; + private MockProfilerServiceImplBase getFeatureImpl; + private ManagedChannel channel; + private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + /** + * functional testing init + * + * @tc.name: ProcessManager init + * @tc.number: OHOS_JAVA_process_ProcessManager_init_0001 + * @tc.desc: ProcessManager init + * @tc.type: functional testing + * @tc.require: SR-004 + * @throws IOException throw IOException + */ + @Before + public void initObj() throws IOException { + SessionManager.getInstance().setDevelopMode(true); + // 应用初始化 Step1 初始化数据中心 + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setDeviceID("1"); + deviceIPPortInfo.setPort(5001); + deviceIPPortInfo.setForwardPort(5001); + deviceIPPortInfo.setDeviceName(""); + deviceIPPortInfo.setDeviceType(DeviceType.FULL_HOS_DEVICE); + deviceId = "1"; + processInfo = new ProcessInfo(); + processInfo.setDeviceId("1"); + processInfo.setProcessId(1); + processInfo.setProcessName("com.go.maps"); + processName = "goo"; + IP = ""; + firstPort = 5001; + serverName = InProcessServerBuilder.generateName(); + getFeatureImpl = new GrpcMockServer(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() + .start()); + channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + } + + /** + * GrpcMockServer + */ + private class GrpcMockServer extends MockProfilerServiceImplBase { + /** + * init getCapabilities + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.GetCapabilitiesResponse reply = getGetCapabilitiesResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init createSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = getCreateSessionResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init startSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StartSessionResponse reply = getStartSessionResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init fetchData + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = getFetchDataResponse(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + + /** + * init stopSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init destroySession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = getDestroySessionResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + } + private ProfilerServiceTypes.DestroySessionResponse getDestroySessionResponse() { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + return reply; + } + + private ProfilerServiceTypes.StartSessionResponse getStartSessionResponse() { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + return reply; + } + + private ProfilerServiceTypes.CreateSessionResponse getCreateSessionResponse() { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); + return reply; + } + + private ProfilerServiceTypes.GetCapabilitiesResponse getGetCapabilitiesResponse() { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().setName("test0") + .setPath("/data/local/tmp/libmemdata.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + return reply; + } + + private ProfilerServiceTypes.FetchDataResponse getFetchDataResponse() { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoZero = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) + .setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh") + .setRssShmemKb(2222222).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns") + .setRssShmemKb(3333333).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) + .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + return fetchDataResponse; + } + + /** + * functional testing getInstance + * + * @tc.name: ProcessManager getInstance + * @tc.number: OHOS_JAVA_process_ProcessManager_getInstance_0001 + * @tc.desc: ProcessManager getInstance + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getProcessManager01() { + ProcessManager processManager = ProcessManager.getInstance(); + Assert.assertNotNull(processManager); + } + /** + * functional testing getInstance + * + * @tc.name: ProcessManager getInstance + * @tc.number: OHOS_JAVA_process_ProcessManager_getInstance_0002 + * @tc.desc: ProcessManager getInstance + * @tc.type: functional testing + * @tc.require: SR-004 + */ + @Test + public void getProcessManager02() { + ProcessManager processManagerOne = ProcessManager.getInstance(); + ProcessManager processManagerTwo = ProcessManager.getInstance(); + Assert.assertEquals(processManagerOne, processManagerTwo); + } + + /** + * functional testing getProcessList + * + * @tc.name: ProcessManager getProcessList + * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0001 + * @tc.desc: ProcessManager getProcessList + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getProcessList() { + List processList = ProcessManager.getInstance().getProcessList(null); + int size = processList.size(); + Assert.assertEquals(0, size); + } + + /** + * functional testing getProcessList + * + * @tc.name: ProcessManager getProcessList + * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0002 + * @tc.desc: ProcessManager getProcessList + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getProcessList1() { + List processList = ProcessManager.getInstance().getProcessList(deviceIPPortInfo); + int size = processList.size(); + Assert.assertEquals(0, size); + } + + /** + * functional testing getProcessList + * + * @tc.name: ProcessManager getProcessList + * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0002 + * @tc.desc: ProcessManager getProcessList + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getProcessList2() { + deviceIPPortInfo.setIp("10"); + deviceIPPortInfo.setPort(Integer.MAX_VALUE); + new DeviceDao().insertDeviceIPPortInfo(deviceIPPortInfo); + List processList1 = ProcessManager.getInstance().getProcessList(deviceIPPortInfo); + List processList2 = ProcessManager.getInstance().getProcessList(null); + Assert.assertEquals(processList1, processList2); + } + + /** + * functional testing getProcessList + * + * @tc.name: ProcessManager getProcessList + * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0003 + * @tc.desc: ProcessManager getProcessList + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getProcessList3() { + deviceIPPortInfo.setIp("10"); + deviceIPPortInfo.setPort(-1); + new DeviceDao().insertDeviceIPPortInfo(deviceIPPortInfo); + List processList = ProcessManager.getInstance().getProcessList(deviceIPPortInfo); + int size = processList.size(); + Assert.assertEquals(0, size); + } + + /** + * functional testing getProcessList + * + * @tc.name: ProcessManager getProcessList + * @tc.number: OHOS_JAVA_process_ProcessManager_getProcessList_0004 + * @tc.desc: ProcessManager getProcessList + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getProcessList4() { + deviceIPPortInfo.setIp("10"); + deviceIPPortInfo.setDeviceID(""); + new DeviceDao().insertDeviceIPPortInfo(deviceIPPortInfo); + List processList = ProcessManager.getInstance().getProcessList(deviceIPPortInfo); + int size = processList.size(); + Assert.assertEquals(0, size); + } + + private int getIntData() { + requestId++; + if (requestId == Integer.MAX_VALUE) { + requestId = 0; + } + return requestId; + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/entity/ProcessInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/entity/ProcessInfoTest.java deleted file mode 100644 index 88f3af580..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/process/service/entity/ProcessInfoTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.process.service.entity; - -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * 进程实体测试类 - * - * @version 1.0 - * @date 2021/04/09 15:14 - **/ -public class ProcessInfoTest { - /** - * ProcessInfo类 - */ - private ProcessInfo processInfo; - - /** - * functional testing init - * - * @tc.name: ProcessInfo init - * @tc.number: OHOS_JAVA_process_ProcessInfo_init_0001 - * @tc.desc: ProcessInfo init - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Before - public void initObj() { - processInfo = new ProcessInfo(); - } - - /** - * functional testing getDeviceId - * - * @tc.name: ProcessInfo getDeviceId - * @tc.number: OHOS_JAVA_process_ProcessInfo_getDeviceId_0001 - * @tc.desc: ProcessInfo getDeviceId - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getDeviceIdTest() { - try { - if (new ProcessInfo().getDeviceId() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getProcessId - * - * @tc.name: ProcessInfo getProcessId - * @tc.number: OHOS_JAVA_process_ProcessInfo_getProcessId_0001 - * @tc.desc: ProcessInfo getProcessId - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getProcessIdTest() { - try { - if (new ProcessInfo().getProcessId() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getProcessName - * - * @tc.name: ProcessInfo getProcessName - * @tc.number: OHOS_JAVA_process_ProcessInfo_getProcessName_0001 - * @tc.desc: ProcessInfo getProcessName - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getProcessNameTest() { - try { - if (new ProcessInfo().getProcessName() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getState - * - * @tc.name: ProcessInfo getState - * @tc.number: OHOS_JAVA_process_ProcessInfo_getState_0001 - * @tc.desc: ProcessInfo getState - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getStateTest() { - try { - if (new ProcessInfo().getState() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getStartTime - * - * @tc.name: ProcessInfo getStartTime - * @tc.number: OHOS_JAVA_process_ProcessInfo_getStartTime_0001 - * @tc.desc: ProcessInfo getStartTime - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getStartTimeTest() { - try { - if (new ProcessInfo().getStartTime() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getArch - * - * @tc.name: ProcessInfo getArch - * @tc.number: OHOS_JAVA_process_ProcessInfo_getArch_0001 - * @tc.desc: ProcessInfo getArch - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getArchTest() { - try { - if (new ProcessInfo().getArch() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing getAgentStatus - * - * @tc.name: ProcessInfo getAgentStatus - * @tc.number: OHOS_JAVA_process_ProcessInfo_getAgentStatus_0001 - * @tc.desc: ProcessInfo getAgentStatus - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void getAgentStatusTest() { - try { - if (new ProcessInfo().getAgentStatus() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } - - /** - * functional testing toString - * - * @tc.name: ProcessInfo toString - * @tc.number: OHOS_JAVA_process_ProcessInfo_toString_0001 - * @tc.desc: ProcessInfo toString - * @tc.type: functional testing - * @tc.require: SR-004 - */ - @Test - public void toStringTest() { - try { - if (new ProcessInfo().toString() != null) { - Assert.assertTrue(true); - } - } catch (Exception exception) { - Assert.assertTrue(false); - } - } -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManagerTest.java index bcd77c764..43c2742e8 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/profilerlog/ProfilerLogManagerTest.java @@ -1,87 +1,70 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.profilerlog; - -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Test; - -/** - * @version 1.0 - * @date 2021/03/27 15:34 - **/ -public class ProfilerLogManagerTest { - /** - * functional testing updateLogLevel - * - * @tc.name: ProfilerLogManager updateLogLevel - * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0001 - * @tc.desc: ProfilerLogManager updateLogLevel - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void updateLogLevelTest01() { - boolean res = false; - try { - res = ProfilerLogManager.getSingleton().updateLogLevel(null); - Assert.assertFalse(res); - } catch (Exception exception) { - Assert.assertFalse(res); - } - } - - /** - * functional testing updateLogLevel - * - * @tc.name: ProfilerLogManager updateLogLevel - * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0002 - * @tc.desc: ProfilerLogManager updateLogLevel - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void updateLogLevelTest02() { - boolean res = false; - try { - res = ProfilerLogManager.getSingleton().updateLogLevel(Level.OFF); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(res); - } - } - - /** - * functional testing updateLogLevel - * - * @tc.name: ProfilerLogManager updateLogLevel - * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0003 - * @tc.desc: ProfilerLogManager updateLogLevel - * @tc.type: functional testing - * @tc.require: SR-005 - */ - @Test - public void updateLogLevelTest03() { - boolean res = false; - try { - res = ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - Assert.assertTrue(res); - } catch (Exception exception) { - Assert.assertTrue(res); - } - } - -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.profilerlog; + +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Test; + +/** + * Profiler Log Manager Test + */ +public class ProfilerLogManagerTest { + /** + * functional testing updateLogLevel + * + * @tc.name: ProfilerLogManager updateLogLevel + * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0001 + * @tc.desc: ProfilerLogManager updateLogLevel + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void updateLogLevelTest01() { + boolean res = ProfilerLogManager.getSingleton().updateLogLevel(null); + Assert.assertFalse(res); + } + + /** + * functional testing updateLogLevel + * + * @tc.name: ProfilerLogManager updateLogLevel + * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0002 + * @tc.desc: ProfilerLogManager updateLogLevel + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void updateLogLevelTest02() { + boolean res = ProfilerLogManager.getSingleton().updateLogLevel(Level.OFF); + Assert.assertTrue(res); + } + + /** + * functional testing updateLogLevel + * + * @tc.name: ProfilerLogManager updateLogLevel + * @tc.number: OHOS_JAVA_profiler_ProfilerLogManager_updateLogLevel_0003 + * @tc.desc: ProfilerLogManager updateLogLevel + * @tc.type: functional testing + * @tc.require: SR-005 + */ + @Test + public void updateLogLevelTest03() { + boolean res = ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + Assert.assertTrue(res); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManagerTest.java index e9c895232..300edf888 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/quartzmanager/QuartzManagerTest.java @@ -1,42 +1,39 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.quartzmanager; - -import org.junit.Assert; -import org.junit.Test; - -/** - * 定时任务管理类 - * - * @version 1.0 - * @date 2021/04/12 10:29 - **/ -public class QuartzManagerTest { - /** - * functional testing getInstance - * - * @tc.name: QuartzManager getInstance - * @tc.number: OHOS_JAVA_quartz_QuartzManager_getInstance_0001 - * @tc.desc: QuartzManager getInstance - * @tc.type: functional testing - * @tc.require: SR-011 - */ - @Test - public void getInstanceTest() { - QuartzManager quartzManager = QuartzManager.getInstance(); - Assert.assertNotNull(quartzManager); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.quartzmanager; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Timed task management + */ +public class QuartzManagerTest { + /** + * functional testing getInstance + * + * @tc.name: QuartzManager getInstance + * @tc.number: OHOS_JAVA_quartz_QuartzManager_getInstance_0001 + * @tc.desc: QuartzManager getInstance + * @tc.type: functional testing + * @tc.require: SR-011 + */ + @Test + public void getInstanceTest() { + QuartzManager quartzManager = QuartzManager.getInstance(); + Assert.assertNotNull(quartzManager); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/entity/SessionInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/entity/SessionInfoTest.java deleted file mode 100644 index a817b74dc..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/entity/SessionInfoTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.datasources.utils.session.entity; - -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * SessionInfoTest测试类 - * - * @version 1.0 - * @date 2021/04/09 14:06 - **/ -public class SessionInfoTest { - /** - * 时间戳 - */ - private long longParam = 2006 - 07 - 11; - - /** - * sessionId数字3243 - */ - private int sessionId = 3243; - - /** - * DeviceIPPortInfo类 - */ - private DeviceIPPortInfo deviceIPPortInfo; - - /** - * functional testing init - * - * @tc.name: SessionInfo init - * @tc.number: OHOS_JAVA_session_SessionInfo_init_0001 - * @tc.desc: SessionInfo init - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Before - public void initObj() { - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setPort(5001); - } - - /** - * functional testing getInstance - * - * @tc.name: SessionInfo getDefaultInstance - * @tc.number: OHOS_JAVA_session_SessionInfo_getDefaultInstance_0001 - * @tc.desc: SessionInfo getDefaultInstance - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void getDefaultInstanceTest() { - SessionInfo sessionInfo = SessionInfo.getDefaultInstance(); - Assert.assertNotNull(sessionInfo); - } - - /** - * functional testing set sessionName - * - * @tc.name: SessionInfo sessionName - * @tc.number: OHOS_JAVA_session_SessionInfo_sessionName_0001 - * @tc.desc: SessionInfo sessionName - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void sessionNameTest() { - SessionInfo.Builder builder = SessionInfo.builder().sessionName(Object.class.toString()); - Assert.assertNotNull(builder); - } - - /** - * functional testing set sessionId - * - * @tc.name: SessionInfo sessionId - * @tc.number: OHOS_JAVA_session_SessionInfo_sessionId_0001 - * @tc.desc: SessionInfo sessionId - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void sessionIdTest() { - SessionInfo.Builder builder = SessionInfo.builder().sessionId(sessionId); - Assert.assertNotNull(builder); - } - - /** - * functional testing set startTimestamp - * - * @tc.name: SessionInfo startTimestamp - * @tc.number: OHOS_JAVA_session_SessionInfo_startTimestamp_0001 - * @tc.desc: SessionInfo startTimestamp - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void startTimestampTest() { - SessionInfo.Builder builder = SessionInfo.builder().startTimestamp(longParam); - Assert.assertNotNull(builder); - } - - /** - * functional testing set endTimestamp - * - * @tc.name: SessionInfo endTimestamp - * @tc.number: OHOS_JAVA_session_SessionInfo_endTimestamp_0001 - * @tc.desc: SessionInfo endTimestamp - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void endTimestampTest() { - SessionInfo.Builder builder = SessionInfo.builder().endTimestamp(longParam); - Assert.assertNotNull(builder); - } - - /** - * functional testing set streamId - * - * @tc.name: SessionInfo streamId - * @tc.number: OHOS_JAVA_session_SessionInfo_streamId_0001 - * @tc.desc: SessionInfo streamId - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void streamIdTest() { - SessionInfo.Builder builder = SessionInfo.builder().streamId(longParam); - Assert.assertNotNull(builder); - } - - /** - * functional testing set pid - * - * @tc.name: SessionInfo pid - * @tc.number: OHOS_JAVA_session_SessionInfo_pid_0001 - * @tc.desc: SessionInfo pid - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void pidTest() { - SessionInfo.Builder builder = SessionInfo.builder().pid(longParam); - Assert.assertNotNull(builder); - } - - /** - * functional testing set deviceIPPortInfo - * - * @tc.name: SessionInfo deviceIPPortInfo - * @tc.number: OHOS_JAVA_session_SessionInfo_deviceIPPortInfo_0001 - * @tc.desc: SessionInfo deviceIPPortInfo - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void deviceIPPortInfoTest() { - SessionInfo.Builder builder = SessionInfo.builder().deviceIPPortInfo(deviceIPPortInfo); - Assert.assertNotNull(builder); - } - - /** - * functional testing build - * - * @tc.name: SessionInfo build - * @tc.number: OHOS_JAVA_session_SessionInfo_build_0001 - * @tc.desc: SessionInfo build - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void buildTest() { - SessionInfo sessionInfo = SessionInfo.builder().build(); - Assert.assertNotNull(sessionInfo); - } - - /** - * functional testing hashCode - * - * @tc.name: SessionInfo hashCode - * @tc.number: OHOS_JAVA_session_SessionInfo_hashCode_0001 - * @tc.desc: SessionInfo hashCode - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void hashCodeTest() { - int number = SessionInfo.getDefaultInstance().hashCode(); - Assert.assertNotNull(number); - } - - /** - * functional testing equals - * - * @tc.name: SessionInfo equals - * @tc.number: OHOS_JAVA_session_SessionInfo_equals_0001 - * @tc.desc: SessionInfo equals - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void equalsTest() { - boolean flag = SessionInfo.getDefaultInstance().equals(Object.class); - Assert.assertFalse(flag); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/service/SessionManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/service/SessionManagerTest.java index a29412992..f0f386555 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/service/SessionManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/session/service/SessionManagerTest.java @@ -1,1011 +1,910 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.session.service; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import io.grpc.util.MutableHandlerRegistry; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.Constant; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.services.memory.MemoryHeapInfo; -import ohos.devtools.services.memory.MemoryHeapManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JProgressBar; -import java.io.File; -import java.io.IOException; -import java.util.Optional; - -/** - * @version 1.0 - * @date 2021/03/23 19:40 - **/ -public class SessionManagerTest { - private static volatile Integer requestId = 1; - private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); - /** - * grpcCleanup - */ - private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - private SessionManager session; - private DeviceIPPortInfo device; - private ProcessInfo process; - private JSONObject jsonObject; - private DeviceProcessInfo deviceProcessInfo; - private String serverName; - private MemoryHeapInfo memoryHeapInfo; - private MemoryHeapManager memoryHeapManager; - private MockProfilerServiceImplBase getFeatureImpl; - private ManagedChannel channel; - - /** - * functional testing init - * - * @tc.name: init - * @tc.number: OHOS_JAVA_session_SessionManager_init - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Before - public void init() { - session = SessionManager.getInstance(); - session.setDevelopMode(true); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - jsonObject = new JSONObject(); - JSONObject memoryObject = new JSONObject(); - memoryObject.put("Select All", true); - memoryObject.put("Java", true); - memoryObject.put("Native", true); - memoryObject.put("Graphics", true); - memoryObject.put("Stack", true); - memoryObject.put("Code", true); - memoryObject.put("Others", true); - jsonObject.put("Memory", memoryObject); - device = new DeviceIPPortInfo(); - device.setIp(""); - device.setPort(3333); - device.setForwardPort(3333); - device.setDeviceID("1"); - process = new ProcessInfo(); - process.setProcessId(1); - process.setProcessName("process"); - deviceProcessInfo = new DeviceProcessInfo(); - serverName = InProcessServerBuilder.generateName(); - memoryHeapManager = new MemoryHeapManager(); - memoryHeapInfo = new MemoryHeapInfo(); - memoryHeapInfo.setcId(1); - memoryHeapInfo.setHeapId(1); - memoryHeapInfo.setSessionId(1L); - memoryHeapInfo.setArrangeStyle("name"); - memoryHeapInfo.setAllocations(10); - memoryHeapInfo.setDeallocations(0); - memoryHeapInfo.setTotalCount(79); - memoryHeapInfo.setShallowSize(348L); - memoryHeapInfo.setCreateTime(20210406L); - try { - grpcCleanup.register( - InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor() - .build().start()); - } catch (IOException exception) { - exception.printStackTrace(); - } - getFeatureImpl = new MockProfilerServiceImplBase() { - /** - * init getCapabilities - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libmemdataplugin.z.so") - .setPath("/data/local/tmp/libmemdataplugin.z.so").build()).build(); - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init createSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init startSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init fetchData - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoZero = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) - .setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoOne = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh") - .setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns") - .setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) - .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - - /** - * init stopSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init destroySession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - }; - channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - } - - /** - * functional testing Instance - * - * @tc.name: get Instance - * @tc.number: OHOS_JAVA_session_SessionManager_getInstance_0001 - * @tc.desc: get Instance - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getInstance01() { - SessionManager sessionInstance = SessionManager.getInstance(); - Assert.assertNotNull(sessionInstance); - } - - /** - * functional testing Instance - * - * @tc.name: get Instance - * @tc.number: OHOS_JAVA_session_SessionManager_getInstance_0002 - * @tc.desc: get Instance - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getInstance02() { - SessionManager sessionOne = SessionManager.getInstance(); - SessionManager sessionTwo = SessionManager.getInstance(); - Assert.assertEquals(sessionOne, sessionTwo); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0001 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionREALTIME_SCENE() { - long num = session.createSession(null, process, Constant.REALTIME_SCENE, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0002 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionREALTIME_SCENE01() { - long num = session.createSession(device, null, Constant.REALTIME_SCENE, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0003 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionREALTIME_SCENE02() { - long num = session.createSession(device, process, Constant.REALTIME_SCENE, null); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0004 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionREALTIME_SCENE03() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0005 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionFILE_IMPORT_SCENE() { - long num = session.createSession(null, process, Constant.FILE_IMPORT_SCENE, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0006 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionFILE_IMPORT_SCENE01() { - long num = session.createSession(device, null, Constant.FILE_IMPORT_SCENE, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0007 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionFILE_IMPORT_SCENE02() { - long num = session.createSession(device, process, Constant.FILE_IMPORT_SCENE, null); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0008 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionOFFLINE() { - long num = session.createSession(null, process, 3, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0009 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionOFFLINE01() { - long num = session.createSession(device, null, 3, jsonObject); - Assert.assertNotNull(num); - } - - /** - * functional testing create Session - * - * @tc.name: create Session - * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0010 - * @tc.desc: create Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testCreateSessionOFFLINE02() { - long num = session.createSession(device, process, 3, null); - Assert.assertNotNull(num); - } - - /** - * functional testing start Session - * - * @tc.name: start Session - * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0001 - * @tc.desc: start Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testStart01() { - boolean flag = session.startSession(null, false); - Assert.assertFalse(flag); - } - - /** - * functional testing start Session - * - * @tc.name: start Session - * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0002 - * @tc.desc: start Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testStart02() { - boolean flag = session.startSession(null, true); - Assert.assertFalse(flag); - } - - /** - * functional testing start Session - * - * @tc.name: start Session - * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0003 - * @tc.desc: start Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testStart03() { - boolean flag = session.startSession(2L, false); - Assert.assertTrue(flag); - } - - /** - * functional testing start Session - * - * @tc.name: start Session - * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0004 - * @tc.desc: start Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testStart04() { - boolean flag = session.startSession(2L, true); - Assert.assertTrue(flag); - } - - /** - * functional testing start Session - * - * @tc.name: start Session - * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0005 - * @tc.desc: start Session - * @tc.type: functional testing - * @tc.require: AR000FK5S7 - */ - @Test - public void testStart05() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - boolean flag = session.startSession(num, false); - Assert.assertTrue(flag); - } - - /** - * functional testing fetchData - * - * @tc.name: fetchData - * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0001 - * @tc.desc: fetchData - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testFetchData01() { - boolean flag = session.fetchData(null); - Assert.assertFalse(flag); - } - - /** - * functional testing fetchData - * - * @tc.name: fetchData - * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0002 - * @tc.desc: fetchData - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testFetchData02() { - boolean flag = session.fetchData(1L); - Assert.assertTrue(flag); - } - - /** - * functional testing fetchData - * - * @tc.name: fetchData - * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0003 - * @tc.desc: fetchData - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testFetchData03() { - boolean flag = session.fetchData(0L); - Assert.assertFalse(flag); - } - - /** - * functional testing fetchData - * - * @tc.name: fetchData - * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0004 - * @tc.desc: fetchData - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testFetchData04() { - boolean flag = session.fetchData(-1L); - Assert.assertFalse(flag); - } - - /** - * functional testing fetchData - * - * @tc.name: fetchData - * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0005 - * @tc.desc: fetchData - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testFetchData05() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - session.startSession(num, false); - boolean flag = session.fetchData(num); - Assert.assertTrue(flag); - } - - /** - * functional testing end Session - * - * @tc.name: end Session - * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0001 - * @tc.desc: end Session - * @tc.type: functional testing - * @tc.require: AR000FK5S8 - */ - @Test - public void testEndSession01() { - boolean flag = session.endSession(null); - Assert.assertFalse(flag); - } - - /** - * functional testing end Session - * - * @tc.name: end Session - * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0002 - * @tc.desc: end Session - * @tc.type: functional testing - * @tc.require: AR000FK5S8 - */ - @Test - public void testEndSession02() { - boolean flag = session.endSession(1L); - Assert.assertTrue(flag); - } - - /** - * functional testing end Session - * - * @tc.name: end Session - * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0003 - * @tc.desc: end Session - * @tc.type: functional testing - * @tc.require: AR000FK5S8 - */ - @Test - public void testEndSession03() { - boolean flag = session.endSession(0L); - Assert.assertFalse(flag); - } - - /** - * functional testing end Session - * - * @tc.name: end Session - * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0004 - * @tc.desc: end Session - * @tc.type: functional testing - * @tc.require: AR000FK5S8 - */ - @Test - public void testEndSession04() { - boolean flag = session.endSession(-1L); - Assert.assertFalse(flag); - } - - /** - * functional testing end Session - * - * @tc.name: end Session - * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0005 - * @tc.desc: end Session - * @tc.type: functional testing - * @tc.require: AR000FK5S8 - */ - @Test - public void testEndSession05() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - boolean flag = session.endSession(num); - Assert.assertTrue(flag); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0001 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDeleteSession01() { - boolean flag = session.deleteSession(null); - Assert.assertFalse(flag); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0002 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDeleteSession02() { - boolean flag = session.deleteSession(1L); - Assert.assertFalse(flag); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0003 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDeleteSession03() { - boolean flag = session.deleteSession(0L); - Assert.assertFalse(flag); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0004 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDeleteSession04() { - boolean flag = session.deleteSession(-1L); - Assert.assertFalse(flag); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0005 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDeleteSession05() { - boolean flag1 = session.deleteSession(-1L); - boolean flag2 = session.deleteSession(0L); - Assert.assertEquals(flag1, flag2); - } - - /** - * functional testing delete Session - * - * @tc.name: delete Session - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0006 - * @tc.desc: delete Session - * @tc.type: functional testing - * @tc.require: AR000FK5SA - */ - @Test - public void testDelete05() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - session.fetchData(num); - boolean flag = session.deleteSession(num); - Assert.assertTrue(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0001 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile01() { - boolean flag = session.saveSessionDataToFile(0L, deviceProcessInfo, ""); - Assert.assertFalse(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0002 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile02() { - boolean flag = session.saveSessionDataToFile(-1L, deviceProcessInfo, ""); - Assert.assertFalse(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0003 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile03() { - boolean flag = session.saveSessionDataToFile(1L, deviceProcessInfo, ""); - Assert.assertFalse(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0004 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile04() { - boolean flag = session.saveSessionDataToFile(1L, null, ""); - Assert.assertFalse(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0005 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile05() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - session.fetchData(num); - boolean flag = session.saveSessionDataToFile(num, deviceProcessInfo, "/"); - Assert.assertFalse(flag); - } - - /** - * functional testing saveSessionDataToFile - * - * @tc.name: saveSessionDataToFile - * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0006 - * @tc.desc: save SessionData To File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testSaveSessionDataToFile06() { - boolean flag = session.saveSessionDataToFile(1L, deviceProcessInfo, null); - Assert.assertFalse(flag); - } - - /** - * functional testing localSessionDataFromFile - * - * @tc.name: localSessionDataFromFile - * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0001 - * @tc.desc: local SessionData From File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testlocalSessionDataFromFile01() { - JProgressBar jProgressBar = new JProgressBar(); - Optional optional = session.localSessionDataFromFile(jProgressBar, null); - Assert.assertFalse(optional.isPresent()); - } - - /** - * functional testing localSessionDataFromFile - * - * @tc.name: localSessionDataFromFile - * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0002 - * @tc.desc: local SessionData From File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testlocalSessionDataFromFile02() { - File file = new File(""); - Optional optional = session.localSessionDataFromFile(null, file); - Assert.assertFalse(optional.isPresent()); - } - - /** - * functional testing localSessionDataFromFile - * - * @tc.name: localSessionDataFromFile - * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0003 - * @tc.desc: local SessionData From File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testlocalSessionDataFromFile03() { - Optional optional = session.localSessionDataFromFile(null, null); - Assert.assertFalse(optional.isPresent()); - } - - /** - * functional testing localSessionDataFromFile - * - * @tc.name: localSessionDataFromFile - * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0004 - * @tc.desc: local SessionData From File - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testlocalSessionDataFromFile05() { - JProgressBar jProgressBar = new JProgressBar(); - File rootPath = new File(this.getClass().getResource("/Demo.trace").getFile().toString()); - Optional deviceProcessInfoNew = session.localSessionDataFromFile(jProgressBar, rootPath); - Assert.assertNotNull(deviceProcessInfoNew); - } - - /** - * functional testing deleteSessionByOffLineDivece - * - * @tc.name: deleteSessionByOffLineDivece - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSessionByOffLineDivece_0001 - * @tc.desc: delete Session By OffLineDivece - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testdeleteSessionByOffLineDivece() { - session.deleteSessionByOffLineDivece(device); - } - - /** - * functional testing deleteSessionByOffLineDivece - * - * @tc.name: deleteSessionByOffLineDivece - * @tc.number: OHOS_JAVA_session_SessionManager_deleteSessionByOffLineDivece_0002 - * @tc.desc: delete Session By OffLineDivece - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testdeleteSessionByOffLineDivece01() { - session.deleteSessionByOffLineDivece(null); - } - - /** - * functional testing deleteLocalSession - * - * @tc.name: deleteLocalSession - * @tc.number: OHOS_JAVA_session_SessionManager_deleteLocalSession_0001 - * @tc.desc: delete LocalSession - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testdeleteLocalSession() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - session.deleteLocalSession(num); - } - - /** - * functional testing stop AllSession - * - * @tc.name: stop AllSession - * @tc.number: OHOS_JAVA_session_SessionManager_stopAllSession_0001 - * @tc.desc: stop AllSession - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void teststopAllSession() { - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); - long num = session.createSession(device, process, Constant.REALTIME_SCENE, jsonObject); - session.startSession(num, false); - session.stopAllSession(); - } - - /** - * functional testing getPluginPath - * - * @tc.name: getPluginPath - * @tc.number: OHOS_JAVA_session_SessionManager_getPluginPath_0001 - * @tc.desc: getPluginPath - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testgetPluginPath() { - String pluginPath = session.getPluginPath(); - Assert.assertNotNull(pluginPath); - } - - /** - * functional testing getPluginPath - * - * @tc.name: getPluginPath - * @tc.number: OHOS_JAVA_session_SessionManager_getPluginPath_0002 - * @tc.desc: getPluginPath - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testgetPluginPathFalse() { - session.setDevelopMode(false); - String pluginPath = session.getPluginPath(); - Assert.assertNotNull(pluginPath); - } - - private int getIntData() { - requestId++; - if (requestId == Integer.MAX_VALUE) { - requestId = 0; - } - return requestId; - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.session.service; + +import com.alibaba.fastjson.JSONObject; +import io.grpc.BindableService; +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; +import ohos.devtools.datasources.transport.grpc.ProfilerClient; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentdao.MemoryHeapManager; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import javax.swing.JProgressBar; +import java.io.File; +import java.io.IOException; +import java.util.Optional; + +/** + * Session Manager Test + */ +public class SessionManagerTest { + private static volatile Integer requestId = 1; + private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + private SessionManager session; + private DeviceIPPortInfo device; + private ProcessInfo process; + private JSONObject jsonObject; + private DeviceProcessInfo deviceProcessInfo; + private String serverName; + private MemoryHeapInfo memoryHeapInfo; + private MemoryHeapManager memoryHeapManager; + private MockProfilerServiceImplBase getFeatureImpl; + private ManagedChannel channel; + + /** + * functional testing init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_session_SessionManager_init + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Before + public void init() { + session = SessionManager.getInstance(); + session.setDevelopMode(true); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + jsonObject = new JSONObject(); + JSONObject memoryObject = new JSONObject(); + memoryObject.put("Select All", true); + memoryObject.put("Java", true); + memoryObject.put("Native", true); + memoryObject.put("Graphics", true); + memoryObject.put("Stack", true); + memoryObject.put("Code", true); + memoryObject.put("Others", true); + jsonObject.put("Memory", memoryObject); + device = new DeviceIPPortInfo(); + device.setIp(""); + device.setPort(3333); + device.setForwardPort(3333); + device.setDeviceID("1"); + process = new ProcessInfo(); + process.setProcessId(1); + process.setProcessName("process"); + deviceProcessInfo = new DeviceProcessInfo(); + serverName = InProcessServerBuilder.generateName(); + memoryHeapManager = new MemoryHeapManager(); + memoryHeapInfo = new MemoryHeapInfo(); + memoryHeapInfo.setcId(1); + memoryHeapInfo.setHeapId(1); + memoryHeapInfo.setSessionId(1L); + memoryHeapInfo.setAllocations(10); + memoryHeapInfo.setDeallocations(0); + memoryHeapInfo.setTotalCount(79); + memoryHeapInfo.setShallowSize(348L); + memoryHeapInfo.setCreateTime(20210406L); + try { + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor() + .build().start()); + } catch (IOException exception) { + exception.printStackTrace(); + } + createServer(); + channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService((BindableService) getFeatureImpl); + } + + private void createServer () { + getFeatureImpl = new MockProfilerServiceImplBase() { + /** + * init getCapabilities + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libmemdataplugin.z.so") + .setPath("/data/local/tmp/libmemdataplugin.z.so").build()).build(); + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init createSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init startSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = + CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) + .addPluginStatus(profilerPluginState).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init fetchData + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) + .setPrivateOther(getIntData()).setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoZero = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) + .setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoOne = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh") + .setRssShmemKb(2222222).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfoTwo = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns") + .setRssShmemKb(3333333).build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfoZero) + .addProcessesinfo(processesInfoOne).addProcessesinfo(processesInfoTwo).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) + .setHasMore(false).addPluginData(data).build(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + + /** + * init stopSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init destroySession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + }; + } + /** + * functional testing Instance + * + * @tc.name: get Instance + * @tc.number: OHOS_JAVA_session_SessionManager_getInstance_0001 + * @tc.desc: get Instance + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void getInstance() { + SessionManager sessionInstance = SessionManager.getInstance(); + Assert.assertNotNull(sessionInstance); + } + + /** + * functional testing create Session + * + * @tc.name: create Session + * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0001 + * @tc.desc: create Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testCreateSessionRealTime01() { + long num = session.createSession(null, process); + Assert.assertNotNull(num); + } + + /** + * functional testing create Session + * + * @tc.name: create Session + * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0002 + * @tc.desc: create Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testCreateSessionRealTime02() { + long num = session.createSession(device, null); + Assert.assertEquals(-1L, num); + } + + /** + * functional testing create Session + * + * @tc.name: create Session + * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0003 + * @tc.desc: create Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testCreateSessionRealTime03() { + long num = session.createSession(device, process); + Assert.assertNotNull(num); + } + + /** + * functional testing create Session + * + * @tc.name: create Session + * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0004 + * @tc.desc: create Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testCreateSession04() { + long num = session.createSession(null, null); + Assert.assertEquals(-1L, num); + } + + /** + * functional testing create Session + * + * @tc.name: create Session + * @tc.number: OHOS_JAVA_session_SessionManager_createSession_0005 + * @tc.desc: create Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testCreateSession05() { + long num = session.createSession(null, process); + Assert.assertEquals(num, -1L); + } + + /** + * functional testing start Session + * + * @tc.name: start Session + * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0001 + * @tc.desc: start Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testStart01() { + boolean flag = session.startSession(null, false); + Assert.assertFalse(flag); + } + + /** + * functional testing start Session + * + * @tc.name: start Session + * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0002 + * @tc.desc: start Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testStart02() { + boolean flag = session.startSession(null, true); + Assert.assertFalse(flag); + } + + /** + * functional testing start Session + * + * @tc.name: start Session + * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0003 + * @tc.desc: start Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testStart03() { + boolean flag = session.startSession(2L, false); + Assert.assertTrue(flag); + } + + /** + * functional testing start Session + * + * @tc.name: start Session + * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0004 + * @tc.desc: start Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testStart04() { + boolean flag = session.startSession(2L, true); + Assert.assertTrue(flag); + } + + /** + * functional testing start Session + * + * @tc.name: start Session + * @tc.number: OHOS_JAVA_session_SessionManager_startSession_0005 + * @tc.desc: start Session + * @tc.type: functional testing + * @tc.require: AR000FK5S7 + */ + @Test + public void testStart05() { + long num = session.createSession(device, process); + boolean flag = session.startSession(num, false); + Assert.assertTrue(flag); + } + + /** + * functional testing fetchData + * + * @tc.name: fetchData + * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0001 + * @tc.desc: fetchData + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testFetchData01() { + boolean flag = session.fetchData(null); + Assert.assertFalse(flag); + } + + /** + * functional testing fetchData + * + * @tc.name: fetchData + * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0002 + * @tc.desc: fetchData + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testFetchData02() { + long num = session.createSession(null, process); + session.startSession(num, false); + boolean flag = session.fetchData(num); + Assert.assertFalse(flag); + } + + /** + * functional testing fetchData + * + * @tc.name: fetchData + * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0003 + * @tc.desc: fetchData + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testFetchData03() { + boolean flag = session.fetchData(0L); + Assert.assertFalse(flag); + } + + /** + * functional testing fetchData + * + * @tc.name: fetchData + * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0004 + * @tc.desc: fetchData + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testFetchData04() { + boolean flag = session.fetchData(-1L); + Assert.assertFalse(flag); + } + + /** + * functional testing fetchData + * + * @tc.name: fetchData + * @tc.number: OHOS_JAVA_session_SessionManager_fetchData_0005 + * @tc.desc: fetchData + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testFetchData05() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + session.startSession(num, false); + boolean flag = session.fetchData(num); + Assert.assertTrue(flag); + } + + /** + * functional testing end Session + * + * @tc.name: end Session + * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0001 + * @tc.desc: end Session + * @tc.type: functional testing + * @tc.require: AR000FK5S8 + */ + @Test + public void testEndSession01() { + boolean flag = session.endSession(null); + Assert.assertFalse(flag); + } + + /** + * functional testing end Session + * + * @tc.name: end Session + * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0002 + * @tc.desc: end Session + * @tc.type: functional testing + * @tc.require: AR000FK5S8 + */ + @Test + public void testEndSession02() { + boolean flag = session.endSession(1L); + Assert.assertTrue(flag); + } + + /** + * functional testing end Session + * + * @tc.name: end Session + * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0003 + * @tc.desc: end Session + * @tc.type: functional testing + * @tc.require: AR000FK5S8 + */ + @Test + public void testEndSession03() { + boolean flag = session.endSession(0L); + Assert.assertFalse(flag); + } + + /** + * functional testing end Session + * + * @tc.name: end Session + * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0004 + * @tc.desc: end Session + * @tc.type: functional testing + * @tc.require: AR000FK5S8 + */ + @Test + public void testEndSession04() { + boolean flag = session.endSession(-1L); + Assert.assertFalse(flag); + } + + /** + * functional testing end Session + * + * @tc.name: end Session + * @tc.number: OHOS_JAVA_session_SessionManager_endSession_0005 + * @tc.desc: end Session + * @tc.type: functional testing + * @tc.require: AR000FK5S8 + */ + @Test + public void testEndSession05() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + boolean flag = session.endSession(num); + Assert.assertTrue(flag); + } + + /** + * functional testing delete Session + * + * @tc.name: delete Session + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0001 + * @tc.desc: delete Session + * @tc.type: functional testing + * @tc.require: AR000FK5SA + */ + @Test + public void testDeleteSession01() { + boolean flag = session.deleteSession(null); + Assert.assertFalse(flag); + } + + /** + * functional testing delete Session + * + * @tc.name: delete Session + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0002 + * @tc.desc: delete Session + * @tc.type: functional testing + * @tc.require: AR000FK5SA + */ + @Test + public void testDeleteSession02() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + ProfilerChartsView view = new ProfilerChartsView(num, true, new TaskScenePanelChart()); + boolean flag = session.deleteSession(num); + Assert.assertTrue(flag); + } + + /** + * functional testing delete Session + * + * @tc.name: delete Session + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0003 + * @tc.desc: delete Session + * @tc.type: functional testing + * @tc.require: AR000FK5SA + */ + @Test + public void testDeleteSession03() { + boolean flag = session.deleteSession(0L); + Assert.assertFalse(flag); + } + + /** + * functional testing delete Session + * + * @tc.name: delete Session + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0004 + * @tc.desc: delete Session + * @tc.type: functional testing + * @tc.require: AR000FK5SA + */ + @Test + public void testDeleteSession04() { + boolean flag = session.deleteSession(-1L); + Assert.assertFalse(flag); + } + + /** + * functional testing delete Session + * + * @tc.name: delete Session + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSession_0005 + * @tc.desc: delete Session + * @tc.type: functional testing + * @tc.require: AR000FK5SA + */ + @Test + public void testDeleteSession05() { + long num = session.createSession(device, process); + ProfilerChartsView view = new ProfilerChartsView(num, true, new TaskScenePanelChart()); + boolean flag = session.deleteSession(num); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0001 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile01() { + boolean flag = session.saveSessionDataToFile(0L, deviceProcessInfo, ""); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0002 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile02() { + boolean flag = session.saveSessionDataToFile(-1L, deviceProcessInfo, ""); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0003 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile03() { + boolean flag = session.saveSessionDataToFile(1L, deviceProcessInfo, ""); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0004 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile04() { + boolean flag = session.saveSessionDataToFile(1L, null, ""); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0005 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile05() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + session.fetchData(num); + boolean flag = session.saveSessionDataToFile(num, deviceProcessInfo, "/"); + Assert.assertFalse(flag); + } + + /** + * functional testing saveSessionDataToFile + * + * @tc.name: saveSessionDataToFile + * @tc.number: OHOS_JAVA_session_SessionManager_saveSessionDataToFile_0006 + * @tc.desc: save SessionData To File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testSaveSessionDataToFile06() { + boolean flag = session.saveSessionDataToFile(1L, deviceProcessInfo, null); + Assert.assertFalse(flag); + } + + /** + * functional testing localSessionDataFromFile + * + * @tc.name: localSessionDataFromFile + * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0001 + * @tc.desc: local SessionData From File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testLocalSessionDataFromFile01() { + JProgressBar jProgressBar = new JProgressBar(); + Optional optional = session.localSessionDataFromFile(jProgressBar, null); + Assert.assertFalse(optional.isPresent()); + } + + /** + * functional testing localSessionDataFromFile + * + * @tc.name: localSessionDataFromFile + * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0002 + * @tc.desc: local SessionData From File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testLocalSessionDataFromFile02() { + File file = new File(""); + Optional optional = session.localSessionDataFromFile(null, file); + Assert.assertFalse(optional.isPresent()); + } + + /** + * functional testing localSessionDataFromFile + * + * @tc.name: localSessionDataFromFile + * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0003 + * @tc.desc: local SessionData From File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testLocalSessionDataFromFile03() { + Optional optional = session.localSessionDataFromFile(null, null); + Assert.assertFalse(optional.isPresent()); + } + + /** + * functional testing localSessionDataFromFile + * + * @tc.name: localSessionDataFromFile + * @tc.number: OHOS_JAVA_session_SessionManager_localSessionDataFromFile_0004 + * @tc.desc: local SessionData From File + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testLocalSessionDataFromFile05() { + JProgressBar jProgressBar = new JProgressBar(); + File rootPath = new File(this.getClass().getResource("/Demo.trace").getFile().toString()); + Optional deviceProcessInfoNew = session.localSessionDataFromFile(jProgressBar, rootPath); + Assert.assertNotNull(deviceProcessInfoNew); + } + + /** + * functional testing deleteSessionByOffLineDivece + * + * @tc.name: deleteSessionByOffLineDivece + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSessionByOffLineDivece_0001 + * @tc.desc: delete Session By OffLineDivece + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testDeleteSessionByOffLineDevice01() { + session.deleteSessionByOffLineDevice(device); + Assert.assertTrue(true); + } + + /** + * functional testing deleteSessionByOffLineDivece + * + * @tc.name: deleteSessionByOffLineDivece + * @tc.number: OHOS_JAVA_session_SessionManager_deleteSessionByOffLineDivece_0002 + * @tc.desc: delete Session By OffLineDivece + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testDeleteSessionByOffLineDevice02() { + session.deleteSessionByOffLineDevice(null); + Assert.assertTrue(true); + } + + /** + * functional testing deleteLocalSession + * + * @tc.name: deleteLocalSession + * @tc.number: OHOS_JAVA_session_SessionManager_deleteLocalSession_0001 + * @tc.desc: delete LocalSession + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testDeleteLocalSession() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + session.deleteLocalSession(num); + Assert.assertTrue(true); + } + + /** + * functional testing stop AllSession + * + * @tc.name: stop AllSession + * @tc.number: OHOS_JAVA_session_SessionManager_stopAllSession_0001 + * @tc.desc: stop AllSession + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testStopAllSession() { + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 3333, channel); + long num = session.createSession(device, process); + session.startSession(num, false); + session.stopAllSession(); + Assert.assertTrue(true); + } + + /** + * functional testing getPluginPath + * + * @tc.name: getPluginPath + * @tc.number: OHOS_JAVA_session_SessionManager_getPluginPath_0001 + * @tc.desc: getPluginPath + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testGetPluginPath() { + String pluginPath = session.getPluginPath(); + Assert.assertNotNull(pluginPath); + } + + /** + * functional testing getPluginPath + * + * @tc.name: getPluginPath + * @tc.number: OHOS_JAVA_session_SessionManager_getPluginPath_0002 + * @tc.desc: getPluginPath + * @tc.type: functional testing + * @tc.require: SR000FK5S6 + */ + @Test + public void testGetPluginPathFalse() { + session.setDevelopMode(false); + String pluginPath = session.getPluginPath(); + Assert.assertNotNull(pluginPath); + } + + private int getIntData() { + requestId++; + if (requestId == Integer.MAX_VALUE) { + requestId = 0; + } + return requestId; + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/TraceManagerTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/SystemTraceHelperTest.java similarity index 59% rename from host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/TraceManagerTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/SystemTraceHelperTest.java index 5e2046054..14aa18b52 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/TraceManagerTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/datasources/utils/trace/service/SystemTraceHelperTest.java @@ -1,291 +1,298 @@ -/* - * 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. - */ - -package ohos.devtools.datasources.utils.trace.service; - -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import io.grpc.util.MutableHandlerRegistry; -import ohos.devtools.datasources.transport.grpc.HiProfilerClient; -import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; -import ohos.devtools.datasources.transport.grpc.ProfilerClient; -import ohos.devtools.datasources.transport.grpc.service.CommonTypes; -import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; -import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; -import ohos.devtools.datasources.utils.common.GrpcException; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -/** - * get Trace Data Test Class - * - * @version 1.0 - * @date 2021/04/13 16:58 - **/ -public class TraceManagerTest { - private static volatile Integer requestId = 1; - - /** - * grpcCleanup - */ - public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - - /** - * DeviceIPPortInfo class - */ - private DeviceIPPortInfo deviceIPPortInfo; - private ManagedChannel channel; - private String serverName; - private MockProfilerServiceImplBase getFeatureImpl; - private MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); - - /** - * TraceManager init - * - * @tc.name: TraceManager init - * @tc.number: OHOS_JAVA_trace_TraceManager_init_0001 - * @tc.desc: TraceManager init - * @tc.type: functional testing - * @tc.require: SR-032 - * @throws IOException IOException - */ - @Before - public void initObj() throws IOException { - SessionManager.getInstance().setDevelopMode(true); - deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setIp(""); - deviceIPPortInfo.setPort(5001); - deviceIPPortInfo.setForwardPort(5001); - serverName = InProcessServerBuilder.generateName(); - getFeatureImpl = new MockProfilerServiceImplBase() { - /** - * init getCapabilities - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libbytraceplugin.z.so") - .setPath("/data/local/tmp/libbytraceplugin.z.so").build()).build(); - - ProfilerServiceTypes.ProfilerPluginCapability pluginCapabilityPtrace = - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( - ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() - .setName("/data/local/tmp/libptrace_plugin.z.so") - .setPath("/data/local/tmp/libptrace_plugin.z.so").build()).build(); - - ProfilerServiceTypes.GetCapabilitiesResponse reply = - ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) - .addCapabilities(pluginCapabilityPtrace).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init createSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void createSession(ProfilerServiceTypes.CreateSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.CreateSessionResponse reply = - ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init startSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void startSession(ProfilerServiceTypes.StartSessionRequest request, - StreamObserver responseObserver) { - CommonTypes.ProfilerPluginState profilerPluginState = - CommonTypes.ProfilerPluginState.newBuilder().build(); - ProfilerServiceTypes.StartSessionResponse reply = - ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0) - .addPluginStatus(profilerPluginState).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init fetchData - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void fetchData(ProfilerServiceTypes.FetchDataRequest request, - StreamObserver responseObserver) { - MemoryPluginResult.AppSummary sss = - MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) - .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()) - .setPrivateOther(getIntData()).setSystem(0).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfo0 = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) - .setMemsummary(sss).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfo1 = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh") - .setRssShmemKb(2222222).build(); - MemoryPluginResult.ProcessMemoryInfo processesInfo2 = - MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns") - .setRssShmemKb(3333333).build(); - MemoryPluginResult.MemoryData aaa = - MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfo0) - .addProcessesinfo(processesInfo1).addProcessesinfo(processesInfo2).build(); - CommonTypes.ProfilerPluginData data = - CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) - .setData(aaa.toByteString()).build(); - ProfilerServiceTypes.FetchDataResponse fetchDataResponse = - ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0) - .setHasMore(false).addPluginData(data).build(); - responseObserver.onNext(fetchDataResponse); - responseObserver.onCompleted(); - } - - /** - * init stopSession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void stopSession(ProfilerServiceTypes.StopSessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.StopSessionResponse reply = - ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - /** - * init destroySession - * - * @param request request - * @param responseObserver responseObserver - */ - @Override - public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, - StreamObserver responseObserver) { - ProfilerServiceTypes.DestroySessionResponse reply = - ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); - responseObserver.onNext(reply); - responseObserver.onCompleted(); - } - - }; - grpcCleanup.register( - InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() - .start()); - channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - serviceRegistry.addService(getFeatureImpl); - } - - /** - * TraceManager get Singleton - * - * @tc.name: TraceManager getSingleton - * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 - * @tc.desc: TraceManager getSingleton - * @tc.type: functional testing - * @tc.require: SR-032 - */ - @Test - public void getSingletonTest() { - TraceManager traceManager = TraceManager.getSingleton(); - Assert.assertNotNull(traceManager); - } - - private int getIntData() { - requestId++; - if (requestId == Integer.MAX_VALUE) { - requestId = 0; - } - return requestId; - } - - /** - * TraceManager create Session By Trace Request - * - * @tc.name: TraceManager createSessionByTraceRequest - * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 - * @tc.desc: TraceManager createSessionByTraceRequest - * @tc.type: functional testing - * @tc.require: SR-032 - * @throws GrpcException GrpcException - */ - @Test - public void createSessionByTraceRequestTest() throws GrpcException { - TraceManager traceManager = TraceManager.getSingleton(); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 5001, channel); - String sessionId = traceManager.createSessionByTraceRequest(deviceIPPortInfo, "idle", 5, 10, true); - Assert.assertNotNull(sessionId); - } - - /** - * TraceManager stop And Destroy Session - * - * @tc.name: TraceManager stopAndDestroySession - * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 - * @tc.desc: TraceManager stopAndDestroySession - * @tc.type: functional testing - * @tc.require: SR-032 - * @throws GrpcException GrpcException - */ - @Test - public void stopAndDestroySessionTest() throws GrpcException { - TraceManager traceManager = TraceManager.getSingleton(); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 5001, channel); - String sessionId = traceManager.createSessionByTraceRequest(deviceIPPortInfo, "idle", 5, 10, true); - traceManager.stopAndDestroySession(deviceIPPortInfo, sessionId); - } - - /** - * TraceManager create Session Request Perfetto - * - * @tc.name: TraceManager createSessionRequestPerfetto - * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 - * @tc.desc: TraceManager createSessionRequestPerfetto - * @tc.type: functional testing - * @tc.require: SR-032 - * @throws GrpcException GrpcException - */ - @Test - public void createSessionRequestPerfettoTest() throws GrpcException { - TraceManager traceManager = TraceManager.getSingleton(); - ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 5001, channel); - String sessionId = traceManager.createSessionRequestPerfetto(deviceIPPortInfo, "idle", 5, true); - Assert.assertNotNull(sessionId); - } -} +/* + * 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. + */ + +package ohos.devtools.datasources.utils.trace.service; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import ohos.devtools.datasources.transport.grpc.HiProfilerClient; +import ohos.devtools.datasources.transport.grpc.MockProfilerServiceImplBase; +import ohos.devtools.datasources.transport.grpc.ProfilerClient; +import ohos.devtools.datasources.transport.grpc.SystemTraceHelper; +import ohos.devtools.datasources.transport.grpc.service.CommonTypes; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; +import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes; +import ohos.devtools.datasources.utils.common.GrpcException; +import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +/** + * get Trace Data Test Class + */ +public class SystemTraceHelperTest { + private static volatile Integer requestId = 1; + + /** + * grpcCleanup + */ + public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + private DeviceIPPortInfo deviceIPPortInfo; + private ManagedChannel channel; + private String serverName; + private MockProfilerServiceImplBase getFeatureImpl; + private MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + + /** + * TraceManager init + * + * @tc.name: TraceManager init + * @tc.number: OHOS_JAVA_trace_TraceManager_init_0001 + * @tc.desc: TraceManager init + * @tc.type: functional testing + * @tc.require: SR-032 + * @throws IOException IOException + */ + @Before + public void initObj() throws IOException { + SessionManager.getInstance().setDevelopMode(true); + setDeviceInfo(); + getFeatureImpl = new MockProfilerServiceImplBase() { + /** + * init getCapabilities + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void getCapabilities(ProfilerServiceTypes.GetCapabilitiesRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.GetCapabilitiesResponse reply = getGetCapabilitiesResponse(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init createSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void createSession(ProfilerServiceTypes.CreateSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.CreateSessionResponse reply = + ProfilerServiceTypes.CreateSessionResponse.newBuilder().setSessionId(1).setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init startSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void startSession(ProfilerServiceTypes.StartSessionRequest request, + StreamObserver responseObserver) { + beginSession(responseObserver); + responseObserver.onCompleted(); + } + + /** + * init fetchData + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void fetchData(ProfilerServiceTypes.FetchDataRequest request, + StreamObserver responseObserver) { + SystemTraceHelperTest.this.dataFetch(responseObserver); + } + + /** + * init stopSession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void stopSession(ProfilerServiceTypes.StopSessionRequest request, + StreamObserver responseObserver) { + ProfilerServiceTypes.StopSessionResponse reply = + ProfilerServiceTypes.StopSessionResponse.newBuilder().build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + /** + * init destroySession + * + * @param request request + * @param responseObserver responseObserver + */ + @Override + public void destroySession(ProfilerServiceTypes.DestroySessionRequest request, + StreamObserver responseObserver) { + SystemTraceHelperTest.this.destroy(responseObserver); + } + }; + register(); + } + + private void dataFetch(StreamObserver responseObserver) { + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = getFetchDataResponse(); + responseObserver.onNext(fetchDataResponse); + responseObserver.onCompleted(); + } + + private void destroy(StreamObserver responseObserver) { + ProfilerServiceTypes.DestroySessionResponse reply = + ProfilerServiceTypes.DestroySessionResponse.newBuilder().setStatus(0).build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } + + private void register() throws IOException { + grpcCleanup.register( + InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry).directExecutor().build() + .start()); + channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + serviceRegistry.addService(getFeatureImpl); + } + + private void setDeviceInfo() { + deviceIPPortInfo = new DeviceIPPortInfo(); + deviceIPPortInfo.setIp(""); + deviceIPPortInfo.setPort(5001); + deviceIPPortInfo.setForwardPort(5001); + serverName = InProcessServerBuilder.generateName(); + } + + private void beginSession(StreamObserver responseObserver) { + CommonTypes.ProfilerPluginState profilerPluginState = CommonTypes.ProfilerPluginState.newBuilder().build(); + ProfilerServiceTypes.StartSessionResponse reply = + ProfilerServiceTypes.StartSessionResponse.newBuilder().setStatus(0).addPluginStatus(profilerPluginState) + .build(); + responseObserver.onNext(reply); + } + + private ProfilerServiceTypes.GetCapabilitiesResponse getGetCapabilitiesResponse() { + ProfilerServiceTypes.ProfilerPluginCapability pluginCapability = ProfilerServiceTypes.ProfilerPluginCapability + .newBuilder(ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libbytraceplugin.z.so").setPath("/data/local/tmp/libbytraceplugin.z.so") + .build()).build(); + + ProfilerServiceTypes.ProfilerPluginCapability pluginCapabilityPtrace = + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder( + ProfilerServiceTypes.ProfilerPluginCapability.newBuilder() + .setName("/data/local/tmp/libptrace_plugin.z.so").setPath("/data/local/tmp/libptrace_plugin.z.so") + .build()).build(); + + ProfilerServiceTypes.GetCapabilitiesResponse reply = + ProfilerServiceTypes.GetCapabilitiesResponse.newBuilder().addCapabilities(pluginCapability) + .addCapabilities(pluginCapabilityPtrace).setStatus(0).build(); + return reply; + } + + private ProfilerServiceTypes.FetchDataResponse getFetchDataResponse() { + MemoryPluginResult.AppSummary sss = + MemoryPluginResult.AppSummary.newBuilder().setJavaHeap(getIntData()).setNativeHeap(getIntData()) + .setCode(getIntData()).setStack(getIntData()).setGraphics(getIntData()).setPrivateOther(getIntData()) + .setSystem(0).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfo0 = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31141).setName("rcu_gp").setRssShmemKb(1) + .setMemsummary(sss).build(); + MemoryPluginResult.ProcessMemoryInfo processesInfo1 = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31142).setName("rcu_bh").setRssShmemKb(2222222) + .build(); + MemoryPluginResult.ProcessMemoryInfo processesInfo2 = + MemoryPluginResult.ProcessMemoryInfo.newBuilder().setPid(31144).setName("netns").setRssShmemKb(3333333) + .build(); + MemoryPluginResult.MemoryData aaa = + MemoryPluginResult.MemoryData.newBuilder().addProcessesinfo(processesInfo0).addProcessesinfo(processesInfo1) + .addProcessesinfo(processesInfo2).build(); + CommonTypes.ProfilerPluginData data = + CommonTypes.ProfilerPluginData.newBuilder().setName("memory-plugin").setStatus(0) + .setData(aaa.toByteString()).build(); + ProfilerServiceTypes.FetchDataResponse fetchDataResponse = + ProfilerServiceTypes.FetchDataResponse.newBuilder().setResponseId(123456789).setStatus(0).setHasMore(false) + .addPluginData(data).build(); + return fetchDataResponse; + } + + /** + * TraceManager get Singleton + * + * @tc.name: TraceManager getSingleton + * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 + * @tc.desc: TraceManager getSingleton + * @tc.type: functional testing + * @tc.require: SR-032 + */ + @Test + public void getSingletonTest() { + SystemTraceHelper systemTraceHelper = SystemTraceHelper.getSingleton(); + Assert.assertNotNull(systemTraceHelper); + } + + private int getIntData() { + requestId++; + if (requestId == Integer.MAX_VALUE) { + requestId = 0; + } + return requestId; + } + + /** + * TraceManager create Session By Trace Request + * + * @tc.name: TraceManager createSessionByTraceRequest + * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 + * @tc.desc: TraceManager createSessionByTraceRequest + * @tc.type: functional testing + * @tc.require: SR-032 + * @throws GrpcException GrpcException + */ + @Test + public void createSessionByTraceRequestTest() throws GrpcException { + SystemTraceHelper systemTraceHelper = SystemTraceHelper.getSingleton(); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 5001, channel); + String sessionId = systemTraceHelper + .createSessionByTraceRequest(deviceIPPortInfo, "idle", 5, + 10, "/data/local/tmp/hiprofiler_data.bytrace",true); + Assert.assertNotNull(sessionId); + } + + /** + * TraceManager stop And Destroy Session + * + * @tc.name: TraceManager stopAndDestroySession + * @tc.number: OHOS_JAVA_trace_TraceManager_getSingleton_0001 + * @tc.desc: TraceManager stopAndDestroySession + * @tc.type: functional testing + * @tc.require: SR-032 + * @throws GrpcException GrpcException + */ + @Test + public void stopAndDestroySessionTest() throws GrpcException { + SystemTraceHelper systemTraceHelper = SystemTraceHelper.getSingleton(); + ProfilerClient client = HiProfilerClient.getInstance().getProfilerClient("", 5001, channel); + String sessionId = systemTraceHelper + .createSessionByTraceRequest(deviceIPPortInfo, "idle", 5, + 10, "/data/local/tmp/hiprofiler_data.bytrace", true); + systemTraceHelper.stopAndDestroySession(deviceIPPortInfo, sessionId); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDaoTest.java new file mode 100644 index 000000000..923b91ab1 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDaoTest.java @@ -0,0 +1,162 @@ +/* + * 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. + */ + +package ohos.devtools.services.cpu; + +import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData; +import ohos.devtools.views.charts.model.ChartDataModel; +import org.junit.Assert; +import org.junit.Test; + +import java.util.LinkedHashMap; +import java.util.List; + +/** + * CpuDao Test + */ +public class CpuDaoTest { + private static final int TEST_START = 0; + private static final int TEST_END = 1000; + + /** + * getInstance Test + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getInstanceTest_0001 + * @tc.desc: getInstance Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstanceTest01() { + CpuDao cpuDao = CpuDao.getInstance(); + Assert.assertNotNull(cpuDao); + } + + /** + * getInstance Test + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getInstanceTest_0002 + * @tc.desc: getInstance Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstanceTest02() { + CpuDao cpuDao = CpuDao.getInstance(); + CpuDao dao = CpuDao.getInstance(); + Assert.assertEquals(cpuDao, dao); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getAllDataTest_0001 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getAllDataTest01() { + List allData = CpuDao.getInstance().getAllData(1L); + Assert.assertNotNull(allData); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getAllDataTest_0002 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getAllDataTest02() { + List allData = CpuDao.getInstance().getAllData(1L); + List list = CpuDao.getInstance().getAllData(1L); + Assert.assertEquals(allData, list); + } + + /** + * get Cpu Data Test + * + * @tc.name: getCpuDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getCpuDataTest_0001 + * @tc.desc: get Cpu Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getCpuDataTest01() { + LinkedHashMap> cpuData = + CpuDao.getInstance().getCpuData(1L, TEST_START, TEST_END, 0L, true); + Assert.assertNotNull(cpuData); + } + + /** + * get Cpu Data Test + * + * @tc.name: getCpuDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getCpuDataTest_0002 + * @tc.desc: get Cpu Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getCpuDataTest02() { + LinkedHashMap> cpuData = + CpuDao.getInstance().getCpuData(1L, TEST_START, TEST_END, 0L, true); + LinkedHashMap> map = + CpuDao.getInstance().getCpuData(1L, TEST_START, TEST_END, 0L, true); + Assert.assertEquals(cpuData, map); + } + + /** + * get Thread Data Test + * + * @tc.name: getThreadDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getThreadDataTest_0001 + * @tc.desc: get Thread Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getThreadDataTest01() { + LinkedHashMap> threadData = + CpuDao.getInstance().getThreadData(1L, TEST_START, TEST_END, 0L, true); + Assert.assertNotNull(threadData); + } + + /** + * get Thread Data Test + * + * @tc.name: getThreadDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDao_getThreadDataTest_0002 + * @tc.desc: get Thread Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getThreadDataTest02() { + LinkedHashMap> threadData = + CpuDao.getInstance().getThreadData(1L, TEST_START, TEST_END, 0L, true); + LinkedHashMap> map = + CpuDao.getInstance().getThreadData(1L, TEST_START, TEST_END, 0L, true); + Assert.assertEquals(threadData, map); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDataCacheTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDataCacheTest.java new file mode 100644 index 000000000..a499c2644 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/cpu/CpuDataCacheTest.java @@ -0,0 +1,194 @@ +/* + * 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. + */ + +package ohos.devtools.services.cpu; + +import ohos.devtools.views.charts.model.ChartDataModel; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * Cpu Data Cache Test + */ +public class CpuDataCacheTest { + private static final int TEST_START = 0; + private static final int TEST_END = 1000; + private static final String STR = "TEST"; + private List chartDataModels = new ArrayList<>(); + private ChartDataModel chartDataModel; + private CpuDataCache cache; + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + cache = CpuDataCache.getInstance(); + chartDataModel = new ChartDataModel(); + chartDataModel.setValue(1); + chartDataModel.setName(STR); + chartDataModel.setIndex(0); + chartDataModels.add(chartDataModel); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getInstanceTest_0001 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstanceTest01() { + CpuDataCache cpuDataCache = CpuDataCache.getInstance(); + Assert.assertNotNull(cpuDataCache); + } + + /** + * get Instance Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getInstanceTest_0002 + * @tc.desc: get Instance Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstanceTest02() { + CpuDataCache cpuDataCache = CpuDataCache.getInstance(); + CpuDataCache dataCache = CpuDataCache.getInstance(); + Assert.assertEquals(cpuDataCache, dataCache); + } + + /** + * add Cpu Data Model Test + * + * @tc.name: init + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_addCpuDataModelTest_0001 + * @tc.desc: add Cpu Data Model Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void addCpuDataModelTest() { + cache.addCpuDataModel(1L, 0L, chartDataModels); + Assert.assertTrue(true); + } + + /** + * add Thread Data Model Test + * + * @tc.name: addThreadDataModelTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_addThreadDataModelTest_0001 + * @tc.desc: add Thread Data Model Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void addThreadDataModelTest() { + cache.addThreadDataModel(1L, 0L, chartDataModels); + Assert.assertTrue(true); + } + + /** + * get Cpu Data Test + * + * @tc.name: getCpuDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getCpuDataTest_0001 + * @tc.desc: get Cpu Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getCpuDataTest01() { + LinkedHashMap> cpuData = cache.getCpuData(1L, TEST_START, TEST_END); + Assert.assertNotNull(cpuData); + } + + /** + * get Cpu Data Test + * + * @tc.name: getCpuDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getCpuDataTest_0002 + * @tc.desc: get Cpu Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getCpuDataTest02() { + LinkedHashMap> cpuData = cache.getCpuData(1L, TEST_START, TEST_END); + LinkedHashMap> map = cache.getCpuData(1L, TEST_START, TEST_END); + Assert.assertEquals(cpuData, map); + } + + /** + * get Thread Data Test + * + * @tc.name: getThreadDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getThreadDataTest_0001 + * @tc.desc: get Thread Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getThreadDataTest01() { + LinkedHashMap> threadData = cache.getThreadData(1L, TEST_START, TEST_END); + Assert.assertNotNull(threadData); + } + + /** + * get Thread Data Test + * + * @tc.name: getThreadDataTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_getThreadDataTest_0002 + * @tc.desc: get Thread Data Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getThreadDataTest02() { + LinkedHashMap> threadData = cache.getThreadData(1L, TEST_START, TEST_END); + LinkedHashMap> map = cache.getThreadData(1L, TEST_START, TEST_END); + Assert.assertEquals(threadData, map); + } + + /** + * clear Cache By Session Test + * + * @tc.name: clearCacheBySessionTest + * @tc.number: OHOS_JAVA_Service_cpu_CpuDataCache_clearCacheBySessionTest_0001 + * @tc.desc: clear Cache By Session Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void clearCacheBySessionTest() { + cache.clearCacheBySession(1L); + Assert.assertTrue(true); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ChartDataCacheTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ChartDataCacheTest.java deleted file mode 100644 index 0268a23b8..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ChartDataCacheTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * ChartDataCacheTest - * - * @version 1.0 - * @date 2021/04/6 19:16 - **/ -public class ChartDataCacheTest { - private ChartDataCache chartDataCache; - - /** - * functional test - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_Service_ChartDataCache_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Before - public void getInstance() { - chartDataCache = ChartDataCache.getInstance(); - Map dataCacheMap = chartDataCache.getDataCacheMap(); - LinkedHashMap longStringLinkedHashMap = new LinkedHashMap<>(); - longStringLinkedHashMap.put(100L, "test"); - dataCacheMap.put("test", longStringLinkedHashMap); - } - - /** - * functional test - * - * @tc.name: initCache - * @tc.number: OHOS_JAVA_Service_ChartDataCache_initCache_0001 - * @tc.desc: initCache - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void initCache() { - chartDataCache.initCache("test", 50); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: getDataCacheMap - * @tc.number: OHOS_JAVA_Service_ChartDataCache_getDataCacheMap_0001 - * @tc.desc: getDataCacheMap - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void getDataCacheMap() { - chartDataCache.getDataCacheMap(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: addCacheBlock - * @tc.number: OHOS_JAVA_Service_ChartDataCache_addCacheBlock_0001 - * @tc.desc: addCacheBlock - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void addCacheBlock() { - LinkedHashMap longStringLinkedHashMap = new LinkedHashMap<>(); - chartDataCache.addCacheBlock("test", longStringLinkedHashMap); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: getDataCache - * @tc.number: OHOS_JAVA_Service_ChartDataCache_getDataCache_0001 - * @tc.desc: getDataCache - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void getDataCache() { - LinkedHashMap test = chartDataCache.getDataCache("test", 10, 100, 2000L); - Assert.assertNotNull(test); - } - - /** - * functional test - * - * @tc.name: clearDataCache - * @tc.number: OHOS_JAVA_Service_ChartDataCache_clearDataCache_0001 - * @tc.desc: clearDataCache - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void clearDataCache() { - chartDataCache.clearDataCache("test"); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ClassInfoDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ClassInfoDaoTest.java index 9fad96320..e408c5a08 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ClassInfoDaoTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/ClassInfoDaoTest.java @@ -1,155 +1,194 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * ClassInfoDaoTest - * - * @version 1.0 - * @date 2021/04/26 15:56 - **/ -public class ClassInfoDaoTest { - /** - * ClassInfoDao - */ - private ClassInfoDao classInfoDao; - - /** - * ClassInfo - */ - private ClassInfo classInfo; - - /** - * functional testing init - * - * @tc.name: init - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void init() { - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - classInfoDao = ClassInfoDao.getInstance(); - classInfoDao.createClassInfo(); - classInfo = new ClassInfo(); - classInfo.setClassName("className"); - classInfo.setcId(1); - classInfo.setId(1); - classInfoDao.insertClassInfo(classInfo); - } - - /** - * functional testing getInstance - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testGetInstance() { - ClassInfoDao instance = ClassInfoDao.getInstance(); - Assert.assertNotNull(instance); - } - - /** - * functional testing insertClassInfo - * - * @tc.name: insertClassInfo - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_insertClassInfo_0001 - * @tc.desc: insertClassInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testinsertClassInfo() { - classInfoDao.insertClassInfo(classInfo); - } - - /** - * functional testing insertClassInfos - * - * @tc.name: insertClassInfos - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_insertClassInfos_0001 - * @tc.desc: insertClassInfos - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testinsertClassInfos() { - List list = new ArrayList<>(); - list.add(classInfo); - classInfoDao.insertClassInfos(list); - } - - /** - * functional testing getAllClassInfoData - * - * @tc.name: getAllClassInfoData - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getAllClassInfoData_0001 - * @tc.desc: getAllClassInfoData - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetAllClassInfoData() { - List list = new ArrayList<>(); - list = classInfoDao.getAllClassInfoData(1L); - Assert.assertNotNull(list); - } - - /** - * functional testing getClassIdByClassName - * - * @tc.name: getClassIdByClassName - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getClassIdByClassName_0001 - * @tc.desc: getClassIdByClassName - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetClassIdByClassName() { - int num = classInfoDao.getClassIdByClassName("className"); - Assert.assertNotNull(num); - } - - /** - * functional testing deleteSessionData - * - * @tc.name: deleteSessionData - * @tc.number: OHOS_JAVA_memory_ClassInfoDao_deleteSessionData_0001 - * @tc.desc: deleteSessionData - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetdeleteSessionData() { - classInfoDao.deleteSessionData(1L); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import ohos.devtools.services.memory.agentdao.ClassInfoDao; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * ClassInfo Dao Test + */ +public class ClassInfoDaoTest { + private ClassInfoDao classInfoDao; + private ClassInfo classInfo; + + /** + * functional testing init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Before + public void init() { + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + classInfoDao = ClassInfoDao.getInstance(); + classInfoDao.createClassInfo(); + classInfo = new ClassInfo(); + classInfo.setClassName("className"); + classInfo.setcId(1); + classInfo.setId(1); + classInfoDao.insertClassInfo(classInfo); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testGetInstance01() { + ClassInfoDao instance = ClassInfoDao.getInstance(); + Assert.assertNotNull(instance); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getInstance_0002 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testGetInstance02() { + ClassInfoDao instance = ClassInfoDao.getInstance(); + ClassInfoDao classInfoDaoInstance = ClassInfoDao.getInstance(); + Assert.assertEquals(instance, classInfoDaoInstance); + } + + /** + * functional testing insertClassInfo + * + * @tc.name: insertClassInfo + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_insertClassInfo_0001 + * @tc.desc: insertClassInfo + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testinsertClassInfo() { + classInfoDao.insertClassInfo(classInfo); + } + + /** + * functional testing insertClassInfos + * + * @tc.name: insertClassInfos + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_insertClassInfos_0001 + * @tc.desc: insertClassInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testinsertClassInfos() { + List list = new ArrayList<>(); + list.add(classInfo); + classInfoDao.insertClassInfos(list); + } + + /** + * functional testing getAllClassInfoData + * + * @tc.name: getAllClassInfoData + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getAllClassInfoData_0001 + * @tc.desc: getAllClassInfoData + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetAllClassInfoData01() { + List list = new ArrayList<>(); + list = classInfoDao.getAllClassInfoData(1L); + Assert.assertNotNull(list); + } + + /** + * functional testing getAllClassInfoData + * + * @tc.name: getAllClassInfoData + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getAllClassInfoData_0002 + * @tc.desc: getAllClassInfoData + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetAllClassInfoData02() { + List list = classInfoDao.getAllClassInfoData(1L); + List classInfoList = classInfoDao.getAllClassInfoData(10L); + Assert.assertNotEquals(list, classInfoList); + } + + /** + * functional testing getClassIdByClassName + * + * @tc.name: getClassIdByClassName + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getClassIdByClassName_0001 + * @tc.desc: getClassIdByClassName + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetClassIdByClassName01() { + int num = classInfoDao.getClassIdByClassName("className"); + Assert.assertNotNull(num); + } + + /** + * functional testing getClassIdByClassName + * + * @tc.name: getClassIdByClassName + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_getClassIdByClassName_0002 + * @tc.desc: getClassIdByClassName + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetClassIdByClassName02() { + int num = classInfoDao.getClassIdByClassName("className"); + int className = classInfoDao.getClassIdByClassName("className"); + Assert.assertEquals(num, className); + } + + /** + * functional testing deleteSessionData + * + * @tc.name: deleteSessionData + * @tc.number: OHOS_JAVA_memory_ClassInfoDao_deleteSessionData_0001 + * @tc.desc: deleteSessionData + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetdeleteSessionData() { + classInfoDao.deleteSessionData(1L); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDaoTest.java new file mode 100644 index 000000000..598431569 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDaoTest.java @@ -0,0 +1,278 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.datatable.MemoryTable; +import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; +import ohos.devtools.services.memory.memorydao.MemoryDao; +import ohos.devtools.views.charts.model.ChartDataModel; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; + +/** + * MemoryDaoTest + */ +public class MemoryDaoTest { + private MemoryTable memoryTable; + private List processMemInfoList; + private MemoryPluginResult.AppSummary appSummary; + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Before + public void init() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(1L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + appSummary = MemoryPluginResult.AppSummary.newBuilder().setCode(1L).build(); + processMemInfo.setData(appSummary); + processMemInfoList = new ArrayList<>(); + memoryTable = new MemoryTable(); + processMemInfoList.add(processMemInfo); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getAllDataTest_0001 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getAllDataTest01() { + memoryTable.insertProcessMemInfo(processMemInfoList); + List list = MemoryDao.getInstance().getAllData(1L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getAllDataTest_0002 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getAllDataTest02() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(10L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + List list = MemoryDao.getInstance().getAllData(10L); + List allData = MemoryDao.getInstance().getAllData(1L); + Assert.assertNotEquals(list, allData); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getAllDataTest_0003 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getAllDataTest03() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(Long.MAX_VALUE); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + List list = MemoryDao.getInstance().getAllData(Long.MAX_VALUE); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getAllDataTest_0004 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getAllDataTest04() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(-1L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + List list = MemoryDao.getInstance().getAllData(-1L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get All Data Test + * + * @tc.name: getAllDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getAllDataTest_0005 + * @tc.desc: get All Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getAllDataTest05() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(0L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + List list = MemoryDao.getInstance().getAllData(0L); + int num = list.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get Data Test + * + * @tc.name: getDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getDataTest_0001 + * @tc.desc: get Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getDataTest01() { + memoryTable.insertProcessMemInfo(processMemInfoList); + LinkedHashMap> memoryData = + MemoryDao.getInstance().getData(1L, 0, 1000, 0L, false); + int num = memoryData.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get Data Test + * + * @tc.name: getDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getDataTest_0002 + * @tc.desc: get Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getDataTest02() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(10L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + LinkedHashMap> memoryData1 = + MemoryDao.getInstance().getData(1L, 0, 1000, 0L, false); + LinkedHashMap> memoryData2 = + MemoryDao.getInstance().getData(10L, 0, 1000, 0L, false); + Assert.assertNotEquals(memoryData1, memoryData2); + } + + /** + * get Data Test + * + * @tc.name: getDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getDataTest_0003 + * @tc.desc: get Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getDataTest03() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(Long.MAX_VALUE); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + LinkedHashMap> memoryData = + MemoryDao.getInstance().getData(Long.MAX_VALUE, 0, 1000, 0L, true); + int num = memoryData.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get Data Test + * + * @tc.name: getDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getDataTest_0004 + * @tc.desc: get Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getDataTest04() { + memoryTable.insertProcessMemInfo(processMemInfoList); + LinkedHashMap> memoryData = + MemoryDao.getInstance().getData(1L, 10, 1000, 0L, true); + int num = memoryData.size(); + Assert.assertNotEquals(0, num); + } + + /** + * get Data Test + * + * @tc.name: getDataTest + * @tc.number: OHOS_JAVA_Service_memory_MemoryDao_getDataTest_0005 + * @tc.desc: get Data Test + * @tc.type: functional testing + * @tc.require: SR-004-AR-003 + */ + @Test + public void getDataTest05() { + ProcessMemInfo processMemInfo = new ProcessMemInfo(); + processMemInfo.setSession(0L); + processMemInfo.setTimeStamp(1L); + processMemInfo.setSessionId(1); + processMemInfo.setData(appSummary); + processMemInfoList.add(processMemInfo); + memoryTable.insertProcessMemInfo(processMemInfoList); + LinkedHashMap> memoryData = + MemoryDao.getInstance().getData(0L, 10, 1000, 0L, true); + int num = memoryData.size(); + Assert.assertNotEquals(0, num); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDataCacheTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDataCacheTest.java new file mode 100644 index 000000000..06588861f --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryDataCacheTest.java @@ -0,0 +1,176 @@ +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.services.memory.memoryservice.MemoryDataCache; +import ohos.devtools.views.charts.model.ChartDataModel; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * Memory Data Cache Test + */ +public class MemoryDataCacheTest { + private static final long SESSION_ID = 1L; + private static final long TIMESTAMP = 0L; + private static final int TIME = 0; + + /** + * functional test + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstance01() { + MemoryDataCache cache = MemoryDataCache.getInstance(); + Assert.assertNotNull(cache); + } + + /** + * functional test + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_getInstance_0002 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getInstance02() { + MemoryDataCache cache = MemoryDataCache.getInstance(); + MemoryDataCache instance = MemoryDataCache.getInstance(); + Assert.assertEquals(cache, instance); + } + + /** + * functional test + * + * @tc.name: initCache + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_addDataModel_0001 + * @tc.desc: addDataModel + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void addDataModel() { + List list = new ArrayList<>() { + { + ChartDataModel model1 = new ChartDataModel(); + model1.setIndex(1); + model1.setValue(1); + add(model1); + ChartDataModel model2 = new ChartDataModel(); + model2.setIndex(2); + model2.setValue(2); + add(model2); + } + }; + MemoryDataCache.getInstance().addDataModel(SESSION_ID, TIMESTAMP, list); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: initCache + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_getData_0001 + * @tc.desc: getData + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getData01() { + List added = new ArrayList<>() { + { + ChartDataModel model1 = new ChartDataModel(); + model1.setIndex(1); + model1.setValue(1); + add(model1); + ChartDataModel model2 = new ChartDataModel(); + model2.setIndex(2); + model2.setValue(2); + add(model2); + } + }; + MemoryDataCache.getInstance().addDataModel(SESSION_ID, TIMESTAMP, added); + Assert.assertNotNull(MemoryDataCache.getInstance().getData(SESSION_ID, 0, 1)); + } + + /** + * functional test + * + * @tc.name: initCache + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_getData_0002 + * @tc.desc: getData + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getData02() { + List added = new ArrayList<>() { + { + ChartDataModel model1 = new ChartDataModel(); + model1.setIndex(1); + model1.setValue(1); + add(model1); + ChartDataModel model2 = new ChartDataModel(); + model2.setIndex(2); + model2.setValue(2); + add(model2); + } + }; + MemoryDataCache.getInstance().addDataModel(SESSION_ID, TIMESTAMP, added); + LinkedHashMap> data = MemoryDataCache.getInstance().getData(SESSION_ID, 0, 1); + LinkedHashMap> map = MemoryDataCache.getInstance().getData(SESSION_ID, 0, 1); + Assert.assertEquals(data, map); + } + + /** + * functional test + * + * @tc.name: initCache + * @tc.number: OHOS_JAVA_Service_MemoryDataCache_clearCacheBySession_0001 + * @tc.desc: getData + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void clearCacheBySession() { + List added = new ArrayList<>() { + { + ChartDataModel model1 = new ChartDataModel(); + model1.setIndex(1); + model1.setValue(1); + add(model1); + ChartDataModel model2 = new ChartDataModel(); + model2.setIndex(2); + model2.setValue(2); + add(model2); + } + }; + MemoryDataCache.getInstance().addDataModel(SESSION_ID, TIMESTAMP, added); + MemoryDataCache.getInstance().clearCacheBySession(SESSION_ID); + Assert.assertTrue(true); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapDaoTest.java index ba371280b..6e9ba0cb7 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapDaoTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapDaoTest.java @@ -1,156 +1,174 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * MemoryHeapDaoTest - * - * @version 1.0 - * @date 2021/04/26 15:56 - **/ -public class MemoryHeapDaoTest { - /** - * MemoryHeapInfo - */ - private MemoryHeapInfo memoryHeapInfo; - - /** - * MemoryHeapDao - */ - private MemoryHeapDao memoryHeapDao; - - /** - * MemoryHeapInfo - */ - private MemoryHeapInfo memoryHeap; - - /** - * functional testing init - * - * @tc.name: init - * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void init() { - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - memoryHeapDao = MemoryHeapDao.getInstance(); - - memoryHeapDao.createMemoryHeapInfo(); - memoryHeapInfo = new MemoryHeapInfo(); - memoryHeap = new MemoryHeapInfo(); - memoryHeapInfo.setcId(1); - memoryHeapInfo.setHeapId(1); - memoryHeapInfo.setSessionId(1L); - memoryHeapInfo.setArrangeStyle("name"); - memoryHeapInfo.setAllocations(10); - memoryHeapInfo.setDeallocations(0); - memoryHeapInfo.setTotalCount(22); - memoryHeapInfo.setShallowSize(22L); - memoryHeapInfo.setCreateTime(1L); - memoryHeapInfo.setInstanceId(2); - memoryHeap.setcId(2); - memoryHeap.setHeapId(2); - memoryHeap.setSessionId(1L); - memoryHeap.setArrangeStyle("name"); - memoryHeap.setAllocations(10); - memoryHeap.setDeallocations(0); - memoryHeap.setTotalCount(11); - memoryHeap.setShallowSize(11L); - memoryHeap.setCreateTime(2L); - memoryHeap.setInstanceId(2); - List list = new ArrayList<>(); - list.add(memoryHeap); - list.add(memoryHeapInfo); - - memoryHeapDao.insertMemoryHeapInfos(list); - } - - /** - * functional testing insertMemoryHeapInfos - * - * @tc.name: insertMemoryHeapInfos - * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_insertMemoryHeapInfos_0001 - * @tc.desc: insertMemoryHeapInfos - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testinsertMemoryHeapInfos() { - List list = new ArrayList<>(); - list.add(memoryHeap); - memoryHeapDao.insertMemoryHeapInfos(list); - } - - /** - * functional testing getAllMemoryHeapInfos - * - * @tc.name: getAllMemoryHeapInfos - * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getAllMemoryHeapInfos_0001 - * @tc.desc: getAllMemoryHeapInfos - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetAllMemoryHeapInfos() { - List list = memoryHeapDao.getAllMemoryHeapInfos(1L); - Assert.assertNotNull(list); - } - - /** - * functional testing insertMemoryHeapInfos - * - * @tc.name: getMemoryHeapInfos - * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getMemoryHeapInfos_0001 - * @tc.desc: getMemoryHeapInfos - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetMemoryHeapInfos() { - List list = memoryHeapDao.getMemoryHeapInfos(1L, 0L, 4L); - Assert.assertNotNull(list); - } - - /** - * functional testing deleteSessionData - * - * @tc.name: deleteSessionData - * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_deleteSessionData_0001 - * @tc.desc: deleteSessionData - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testdeleteSessionData() { - memoryHeapDao.deleteSessionData(1L); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentdao.MemoryHeapDao; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory Heap Dao Test + */ +public class MemoryHeapDaoTest { + private MemoryHeapInfo memoryHeapInfo; + private MemoryHeapDao memoryHeapDao; + private MemoryHeapInfo memoryHeap; + + /** + * functional testing init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Before + public void init() { + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + memoryHeapDao = MemoryHeapDao.getInstance(); + + memoryHeapDao.createMemoryHeapInfo(); + memoryHeapInfo = new MemoryHeapInfo(); + memoryHeap = new MemoryHeapInfo(); + memoryHeapInfo.setcId(1); + memoryHeapInfo.setHeapId(1); + memoryHeapInfo.setSessionId(1L); + memoryHeapInfo.setAllocations(10); + memoryHeapInfo.setDeallocations(0); + memoryHeapInfo.setTotalCount(22); + memoryHeapInfo.setShallowSize(22L); + memoryHeapInfo.setCreateTime(1L); + memoryHeapInfo.setInstanceId(2); + memoryHeap.setcId(2); + memoryHeap.setHeapId(2); + memoryHeap.setSessionId(1L); + memoryHeap.setAllocations(10); + memoryHeap.setDeallocations(0); + memoryHeap.setTotalCount(11); + memoryHeap.setShallowSize(11L); + memoryHeap.setCreateTime(2L); + memoryHeap.setInstanceId(2); + List list = new ArrayList<>(); + list.add(memoryHeap); + list.add(memoryHeapInfo); + + memoryHeapDao.insertMemoryHeapInfos(list); + } + + /** + * functional testing insertMemoryHeapInfos + * + * @tc.name: insertMemoryHeapInfos + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_insertMemoryHeapInfos_0001 + * @tc.desc: insertMemoryHeapInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testinsertMemoryHeapInfos() { + List list = new ArrayList<>(); + list.add(memoryHeap); + memoryHeapDao.insertMemoryHeapInfos(list); + } + + /** + * functional testing getAllMemoryHeapInfos + * + * @tc.name: getAllMemoryHeapInfos + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getAllMemoryHeapInfos_0001 + * @tc.desc: getAllMemoryHeapInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetAllMemoryHeapInfos01() { + List list = memoryHeapDao.getAllMemoryHeapInfos(1L); + Assert.assertNotNull(list); + } + + /** + * functional testing getAllMemoryHeapInfos + * + * @tc.name: getAllMemoryHeapInfos + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getAllMemoryHeapInfos_0002 + * @tc.desc: getAllMemoryHeapInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetAllMemoryHeapInfos02() { + List list = memoryHeapDao.getAllMemoryHeapInfos(1L); + ArrayList allMemoryHeapInfos = memoryHeapDao.getAllMemoryHeapInfos(1L); + Assert.assertNotEquals(list, allMemoryHeapInfos); + } + + /** + * functional testing insertMemoryHeapInfos + * + * @tc.name: getMemoryHeapInfos + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getMemoryHeapInfos_0001 + * @tc.desc: getMemoryHeapInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetMemoryHeapInfos01() { + List list = memoryHeapDao.getMemoryHeapInfos(1L, 0L, 4L); + Assert.assertNotNull(list); + } + + /** + * functional testing insertMemoryHeapInfos + * + * @tc.name: getMemoryHeapInfos + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_getMemoryHeapInfos_0001 + * @tc.desc: getMemoryHeapInfos + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetMemoryHeapInfos02() { + List list = memoryHeapDao.getMemoryHeapInfos(1L, 0L, 4L); + List memoryHeapInfos = memoryHeapDao.getMemoryHeapInfos(1L, 0L, 4L); + Assert.assertEquals(list, memoryHeapInfos); + } + + /** + * functional testing deleteSessionData + * + * @tc.name: deleteSessionData + * @tc.number: OHOS_JAVA_memory_MemoryHeapDao_deleteSessionData_0001 + * @tc.desc: deleteSessionData + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testdeleteSessionData() { + memoryHeapDao.deleteSessionData(1L); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapInfoTest.java deleted file mode 100644 index d08b8d22a..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapInfoTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description MemoryHeapInfoTest - * @Date 2021/4/3 12:22 - **/ -public class MemoryHeapInfoTest { - private MemoryHeapInfo memoryHeapInfo; - - /** - * functional test - * - * @tc.name: getMemoryHeapInfo - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_getMemoryHeapInfo_0001 - * @tc.desc: getMemoryHeapInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void getMemoryHeapInfoTest() { - memoryHeapInfo = new MemoryHeapInfo(); - Assert.assertNotNull(memoryHeapInfo); - } - - /** - * functional test - * - * @tc.name: setHeapId - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setHeapId_0001 - * @tc.desc: setHeapId - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setHeapIdTest() { - memoryHeapInfo.setHeapId(1); - Assert.assertTrue(true); - memoryHeapInfo.getHeapId(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: setAllocations - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setAllocations_0001 - * @tc.desc: setAllocations - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setAllocationsTest() { - memoryHeapInfo.setAllocations(2); - Assert.assertTrue(true); - memoryHeapInfo.getAllocations(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: setArrangeStyle - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setArrangeStyle_0001 - * @tc.desc: setArrangeStyle - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setArrangeStyleTest() { - memoryHeapInfo.setArrangeStyle("xxxx"); - Assert.assertTrue(true); - memoryHeapInfo.getArrangeStyle(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: setCreateTime - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setCreateTime_0001 - * @tc.desc: setCreateTime - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setCreateTimeTest() { - memoryHeapInfo.setCreateTime(7324L); - Assert.assertTrue(true); - memoryHeapInfo.getCreateTime(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: setSessionId - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setSessionId_0001 - * @tc.desc: setSessionId - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setSessionIdTest() { - memoryHeapInfo.setSessionId(3243L); - Assert.assertTrue(true); - memoryHeapInfo.getSessionId(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: setClassName - * @tc.number: OHOS_JAVA_Service_MemoryHeapInfo_setClassName_0001 - * @tc.desc: setClassName - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void setClassNameTest() { - memoryHeapInfo.setClassName("test"); - Assert.assertTrue(true); - memoryHeapInfo.getClassName(); - Assert.assertTrue(true); - } - -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapTest.java index 26c0f8d72..409872e2a 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryHeapTest.java @@ -1,182 +1,159 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; - -/** - * 堆数据测试 - * - * @version 1.0 - * @date 2021/03/30 18:56 - **/ -public class MemoryHeapTest { - private MemoryHeapManager memoryHeapManager; - private MemoryInstanceManager memoryInstanceManager; - private MemoryInstanceDetailsManager memoryInstanceDetailsManager; - private ClassInfoManager classInfoManager; - private ClassInfo classInfo; - private MemoryInstanceInfo memoryInstanceInfo; - private MemoryInstanceDetailsInfo memoryInstanceDetailsInfo; - private MemoryHeapInfo memoryHeapInfo; - - /** - * functional test - * - * @tc.name: initObj - * @tc.number: OHOS_JAVA_Service_MemoryHeap_initObj_0001 - * @tc.desc: initObj - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Before - public void initObj() { - // 应用初始化 Step1 初始化数据中心 - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - - memoryHeapManager = new MemoryHeapManager(); - memoryInstanceManager = new MemoryInstanceManager(); - memoryInstanceDetailsManager = new MemoryInstanceDetailsManager(); - classInfoManager = new ClassInfoManager(); - classInfo = new ClassInfo(); - classInfo.setcId(2); - classInfo.setClassName("java/Lang/String"); - memoryInstanceInfo = new MemoryInstanceInfo(); - memoryInstanceInfo.setInstanceId(2); - memoryInstanceInfo.setcId(1); - memoryInstanceInfo.setInstance("java/Lang/String"); - memoryInstanceInfo.setCreateTime(20210326L); - memoryInstanceInfo.setAllocTime(20210326L); - memoryInstanceInfo.setDeallocTime(20210328L); - memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - memoryInstanceDetailsInfo.setInstanceId(1); - memoryInstanceDetailsInfo.setFrameId(1); - memoryInstanceDetailsInfo.setClassName("java/Lang/String"); - memoryInstanceDetailsInfo.setMethodName("init"); - memoryInstanceDetailsInfo.setFieldName("name"); - memoryInstanceDetailsInfo.setLineNumber(2); - memoryHeapInfo = new MemoryHeapInfo(); - memoryHeapInfo.setcId(1); - memoryHeapInfo.setHeapId(1); - memoryHeapInfo.setSessionId(1L); - memoryHeapInfo.setArrangeStyle("name"); - memoryHeapInfo.setAllocations(10); - memoryHeapInfo.setDeallocations(0); - memoryHeapInfo.setTotalCount(79); - memoryHeapInfo.setShallowSize(348L); - memoryHeapInfo.setCreateTime(20210406L); - } - - /** - * functional test - * - * @tc.name: getMemoryHeap - * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryHeap_0001 - * @tc.desc: getMemoryHeap - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void getMemoryHeap() { - ArrayList memoryHeapInfos = - memoryHeapManager.getMemoryHeapInfos(19354329L, 20210317L, 20210322L); - Assert.assertNotNull(memoryHeapInfos); - } - - /** - * functional test - * - * @tc.name: getMemoryInstance - * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryInstance_0001 - * @tc.desc: getMemoryInstance - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void getMemoryInstance() { - ArrayList memoryInstanceInfos = - memoryInstanceManager.getMemoryInstanceInfos(2, 20210326L, 20210330L); - Assert.assertNotNull(memoryInstanceInfos); - } - - /** - * functional test - * - * @tc.name: getMemoryInstanceDetails - * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryInstanceDetails_0001 - * @tc.desc: getMemoryInstanceDetails - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void getMemoryInstanceDetails() { - ArrayList memoryInstanceDetailsInfos = - memoryInstanceDetailsManager.getMemoryInstanceDetailsInfos(2); - Assert.assertNotNull(memoryInstanceDetailsInfos); - } - - /** - * functional test - * - * @tc.name: insertClassInfo - * @tc.number: OHOS_JAVA_Service_MemoryHeap_insertClassInfo_0001 - * @tc.desc: insertClassInfo - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void insertClassInfo() { - classInfoManager.insertClassInfo(classInfo); - } - - /** - * functional test - * - * @tc.name: insertMemoryInstanceInfo - * @tc.number: OHOS_JAVA_Service_MemoryHeap_insertMemoryInstanceInfo_0001 - * @tc.desc: insertMemoryInstanceInfo - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void insertMemoryInstanceInfo() { - memoryInstanceManager.insertMemoryInstanceInfo(memoryInstanceInfo); - } - - /** - * functional test - * - * @tc.name: insertMemoryInstanceDetailsInfo - * @tc.number: OHOS_JAVA_Service_MemoryHeap_insertMemoryInstanceDetailsInfo_0001 - * @tc.desc: insertMemoryInstanceDetailsInfo - * @tc.type: functional testing - * @tc.require: SR000FK61Q - */ - @Test - public void insertMemoryInstanceDetailsInfo() { - memoryInstanceDetailsManager.insertMemoryInstanceDetailsInfo(memoryInstanceDetailsInfo); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.services.memory.agentbean.AgentHeapBean; +import ohos.devtools.services.memory.agentbean.ClassInfo; +import ohos.devtools.services.memory.agentbean.MemoryHeapInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentbean.MemoryInstanceInfo; +import ohos.devtools.services.memory.agentdao.ClassInfoManager; +import ohos.devtools.services.memory.agentdao.MemoryHeapManager; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsManager; +import ohos.devtools.services.memory.agentdao.MemoryInstanceManager; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Heap data test + */ +public class MemoryHeapTest { + private MemoryHeapManager memoryHeapManager; + private MemoryInstanceManager memoryInstanceManager; + private MemoryInstanceDetailsManager memoryInstanceDetailsManager; + private ClassInfoManager classInfoManager; + private ClassInfo classInfo; + private MemoryInstanceInfo memoryInstanceInfo; + private MemoryInstanceDetailsInfo memoryInstanceDetailsInfo; + private MemoryHeapInfo memoryHeapInfo; + + /** + * functional test + * + * @tc.name: initObj + * @tc.number: OHOS_JAVA_Service_MemoryHeap_initObj_0001 + * @tc.desc: initObj + * @tc.type: functional testing + * @tc.require: SR000FK61Q + */ + @Before + public void initObj() { + // 应用初始化 Step1 初始化数据中心 + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + + memoryHeapManager = new MemoryHeapManager(); + memoryInstanceManager = new MemoryInstanceManager(); + memoryInstanceDetailsManager = new MemoryInstanceDetailsManager(); + classInfoManager = new ClassInfoManager(); + classInfo = new ClassInfo(); + classInfo.setcId(2); + classInfo.setClassName("java/Lang/String"); + memoryInstanceInfo = new MemoryInstanceInfo(); + memoryInstanceInfo.setInstanceId(2); + memoryInstanceInfo.setcId(1); + memoryInstanceInfo.setInstance("java/Lang/String"); + memoryInstanceInfo.setCreateTime(20210326L); + memoryInstanceInfo.setAllocTime(20210326L); + memoryInstanceInfo.setDeallocTime(20210328L); + memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); + memoryInstanceDetailsInfo.setInstanceId(1); + memoryInstanceDetailsInfo.setFrameId(1); + memoryInstanceDetailsInfo.setClassName("java/Lang/String"); + memoryInstanceDetailsInfo.setMethodName("init"); + memoryInstanceDetailsInfo.setFieldName("name"); + memoryInstanceDetailsInfo.setLineNumber(2); + memoryHeapInfo = new MemoryHeapInfo(); + memoryHeapInfo.setcId(1); + memoryHeapInfo.setHeapId(1); + memoryHeapInfo.setSessionId(1L); + memoryHeapInfo.setAllocations(10); + memoryHeapInfo.setDeallocations(0); + memoryHeapInfo.setTotalCount(79); + memoryHeapInfo.setShallowSize(348L); + memoryHeapInfo.setCreateTime(20210406L); + } + + /** + * functional test + * + * @tc.name: getMemoryHeap + * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryHeap_0001 + * @tc.desc: getMemoryHeap + * @tc.type: functional testing + * @tc.require: SR000FK61Q + */ + @Test + public void getMemoryHeap() { + List memoryHeapInfos = + memoryHeapManager.getMemoryHeapInfos(19354329L, 20210317L, 20210322L); + Assert.assertNotNull(memoryHeapInfos); + } + + /** + * functional test + * + * @tc.name: getMemoryInstance + * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryInstance_0001 + * @tc.desc: getMemoryInstance + * @tc.type: functional testing + * @tc.require: SR000FK61Q + */ + @Test + public void getMemoryInstance() { + ArrayList memoryInstanceInfos = + memoryInstanceManager.getMemoryInstanceInfos(2, 20210326L, 20210330L); + Assert.assertNotNull(memoryInstanceInfos); + } + + /** + * functional test + * + * @tc.name: getMemoryInstanceDetails + * @tc.number: OHOS_JAVA_Service_MemoryHeap_getMemoryInstanceDetails_0001 + * @tc.desc: getMemoryInstanceDetails + * @tc.type: functional testing + * @tc.require: SR000FK61Q + */ + @Test + public void getMemoryInstanceDetails() { + ArrayList memoryInstanceDetailsInfos = + memoryInstanceDetailsManager.getMemoryInstanceDetailsInfos(2); + Assert.assertNotNull(memoryInstanceDetailsInfos); + } + + /** + * functional test + * + * @tc.name: insertClassInfo + * @tc.number: OHOS_JAVA_Service_MemoryHeap_insertClassInfo_0001 + * @tc.desc: insertClassInfo + * @tc.type: functional testing + * @tc.require: SR000FK61Q + */ + @Test + public void insertClassInfo() { + classInfoManager.insertClassInfo(classInfo); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDaoTest.java index 54cdbf5df..af5cffcbe 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDaoTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDaoTest.java @@ -1,175 +1,113 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import ohos.devtools.datasources.utils.session.service.SessionManager; - -/** - * MemoryInstanceDaoTest - * - * @version 1.0 - * @date 2021/04/05 17:12 - **/ -public class MemoryInstanceDaoTest { - private MemoryInstanceDao memoryInstanceDao; - private MemoryInstanceInfo memoryInstanceInfo; - private MemoryInstanceInfo memoryInstance; - - /** - * functional testing getInstance - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Before - public void getInstance() { - SessionManager.getInstance().setDevelopMode(true); - memoryInstanceDao = MemoryInstanceDao.getInstance(); - memoryInstanceInfo = new MemoryInstanceInfo(); - memoryInstanceInfo.setId(1); - memoryInstanceInfo.setcId(1); - memoryInstanceInfo.setInstance("String Lang"); - memoryInstanceInfo.setInstanceId(2); - memoryInstanceInfo.setAllocTime(1L); - memoryInstanceInfo.setCreateTime(2L); - memoryInstanceInfo.setAllocTime(3L); - memoryInstanceInfo.setDeallocTime(12L); - memoryInstance = new MemoryInstanceInfo(); - memoryInstance.setId(1); - memoryInstance.setcId(1); - memoryInstance.setInstance("god"); - memoryInstance.setInstanceId(3); - memoryInstance.setCreateTime(4L); - memoryInstance.setAllocTime(11L); - memoryInstance.setDeallocTime(22L); - } - - /** - * functional testing createMemoryInstance - * - * @tc.name: createMemoryInstance - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_createMemoryInstance_0001 - * @tc.desc: createMemoryInstance - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void createMemoryInstance() { - SessionManager.getInstance().setDevelopMode(true); - boolean createMemoryResult = memoryInstanceDao.createMemoryInstance(); - Assert.assertTrue(createMemoryResult); - } - - /** - * functional testing insertMemoryInstanceInfo - * - * @tc.name: insertMemoryInstanceInfo - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_insertMemoryInstanceInfo_0001 - * @tc.desc: insertMemoryInstanceInfo - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testInsertMemoryInstanceInfo() { - memoryInstanceDao.insertMemoryInstanceInfo(memoryInstanceInfo); - } - - /** - * functional testing insertMemoryInstanceInfos - * - * @tc.name: insertMemoryInstanceInfos - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_insertMemoryInstanceInfos_0001 - * @tc.desc: insertMemoryInstanceInfos - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testInsertMemoryInstanceInfos() { - List list = new ArrayList<>(); - list.add(memoryInstanceInfo); - memoryInstanceDao.insertMemoryInstanceInfos(list); - } - - /** - * functional testing getMemoryInstanceInfos - * - * @tc.name: getMemoryInstanceInfos - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_getMemoryInstanceInfos_0001 - * @tc.desc: getMemoryInstanceInfos - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testGetMemoryInstanceInfos() { - List list = new ArrayList<>(); - list = memoryInstanceDao.getMemoryInstanceInfos(1, 0L, 5L); - Assert.assertEquals(1, list.size()); - } - - /** - * functional testing getAllMemoryInstanceInfos - * - * @tc.name: getAllMemoryInstanceInfos - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_getAllMemoryInstanceInfos_0001 - * @tc.desc: getAllMemoryInstanceInfos - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testGetAllMemoryInstanceInfos() { - ArrayList allMemoryInstanceInfos = memoryInstanceDao.getAllMemoryInstanceInfos(); - Assert.assertNotNull(allMemoryInstanceInfos); - } - - /** - * functional testing updateInstanceInfos - * - * @tc.name: updateInstanceInfos - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_updateInstanceInfos_0001 - * @tc.desc: updateInstanceInfos - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testUpdateInstanceInfos() { - memoryInstanceDao.updateInstanceInfos(13L, 2); - } - - /** - * functional testing deleteSessionData - * - * @tc.name: deleteSessionData - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_deleteSessionData_0001 - * @tc.desc: deleteSessionData - * @tc.type: functional testing - * @tc.require: AR000FK61M - */ - @Test - public void testDeleteSessionData() { - memoryInstanceDao.deleteSessionData(1); - } - +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import java.util.ArrayList; + +import ohos.devtools.services.memory.agentbean.MemoryInstanceInfo; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDao; +import ohos.devtools.services.memory.agentdao.MemoryUpdateInfo; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ohos.devtools.datasources.utils.session.service.SessionManager; + +/** + * Memory Instance Dao Test + */ +public class MemoryInstanceDaoTest { + private MemoryInstanceDao memoryInstanceDao; + private MemoryInstanceInfo memoryInstanceInfo; + private MemoryInstanceInfo memoryInstance; + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61M + */ + @Before + public void getInstance() { + SessionManager.getInstance().setDevelopMode(true); + memoryInstanceDao = MemoryInstanceDao.getInstance(); + memoryInstanceInfo = new MemoryInstanceInfo(); + memoryInstanceInfo.setId(1); + memoryInstanceInfo.setcId(1); + memoryInstanceInfo.setInstance("String Lang"); + memoryInstanceInfo.setInstanceId(2); + memoryInstanceInfo.setAllocTime(1L); + memoryInstanceInfo.setCreateTime(2L); + memoryInstanceInfo.setAllocTime(3L); + memoryInstanceInfo.setDeallocTime(12L); + memoryInstance = new MemoryInstanceInfo(); + memoryInstance.setId(1); + memoryInstance.setcId(1); + memoryInstance.setInstance("god"); + memoryInstance.setInstanceId(3); + memoryInstance.setCreateTime(4L); + memoryInstance.setAllocTime(11L); + memoryInstance.setDeallocTime(22L); + } + + /** + * functional testing createMemoryInstance + * + * @tc.name: createMemoryInstance + * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_createMemoryInstance_0001 + * @tc.desc: createMemoryInstance + * @tc.type: functional testing + * @tc.require: AR000FK61M + */ + @Test + public void createMemoryInstance() { + SessionManager.getInstance().setDevelopMode(true); + boolean createMemoryResult = memoryInstanceDao.createMemoryInstance(); + Assert.assertTrue(createMemoryResult); + } + + /** + * functional testing getAllMemoryInstanceInfos + * + * @tc.name: getAllMemoryInstanceInfos + * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_getAllMemoryInstanceInfos_0001 + * @tc.desc: getAllMemoryInstanceInfos + * @tc.type: functional testing + * @tc.require: AR000FK61M + */ + @Test + public void testGetAllMemoryInstanceInfos() { + ArrayList allMemoryInstanceInfos = memoryInstanceDao.getAllMemoryInstanceInfos(); + Assert.assertNotNull(allMemoryInstanceInfos); + } + + /** + * functional testing deleteSessionData + * + * @tc.name: deleteSessionData + * @tc.number: OHOS_JAVA_Service_MemoryInstanceDao_deleteSessionData_0001 + * @tc.desc: deleteSessionData + * @tc.type: functional testing + * @tc.require: AR000FK61M + */ + @Test + public void testDeleteSessionData() { + memoryInstanceDao.deleteSessionData(1); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsDaoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsDaoTest.java index 933d551a6..aebe7935c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsDaoTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsDaoTest.java @@ -1,160 +1,137 @@ -/* - * 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. - */ - -package ohos.devtools.services.memory; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * MemoryInstanceDetailsDaoTest - * - * @version 1.0 - * @date 2021/04/26 15:56 - **/ -public class MemoryInstanceDetailsDaoTest { - /** - * MemoryInstanceDetailsInfo - */ - private MemoryInstanceDetailsInfo memoryInstanceDetailsInfo; - - /** - * MemoryInstanceDetailsDao - */ - private MemoryInstanceDetailsDao memoryInstanceDetailsDao; - - /** - * functional testing init - * - * @tc.name: init - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Before - public void init() { - // 应用初始化 Step1 初始化数据中心 - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - memoryInstanceDetailsDao = MemoryInstanceDetailsDao.getInstance(); - memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - memoryInstanceDetailsInfo.setInstanceId(1); - memoryInstanceDetailsInfo.setClassName("Class"); - memoryInstanceDetailsInfo.setFieldName("field"); - memoryInstanceDetailsInfo.setMethodName("method"); - memoryInstanceDetailsInfo.setFrameId(1); - memoryInstanceDetailsInfo.setLineNumber(1); - memoryInstanceDetailsInfo.setId(1); - } - - /** - * functional testing getInstance - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testGetInstance() { - MemoryInstanceDetailsDao instance = MemoryInstanceDetailsDao.getInstance(); - Assert.assertNotNull(instance); - } - - /** - * functional testing insertMemoryInstanceDetailsInfo - * - * @tc.name: insertMemoryInstanceDetailsInfo - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_insertMemoryInstanceDetailsInfo_0001 - * @tc.desc: insertMemoryInstanceDetailsInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testinsertMemoryInstanceDetailsInfo() { - memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(memoryInstanceDetailsInfo); - } - - /** - * functional testing insertMemoryInstanceDetailsInfo - * - * @tc.name: insertMemoryInstanceDetailsInfo - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_insertMemoryInstanceDetailsInfo_0001 - * @tc.desc: insertMemoryInstanceDetailsInfo - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testinsertMemoryInstanceDetailsInfos() { - List list = new ArrayList<>(); - list.add(memoryInstanceDetailsInfo); - memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(list); - } - - /** - * functional testing getMemoryInstanceDetails - * - * @tc.name: getMemoryInstanceDetails - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getMemoryInstanceDetails_0001 - * @tc.desc: getMemoryInstanceDetails - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetMemoryInstanceDetails() { - List list = memoryInstanceDetailsDao.getMemoryInstanceDetails(1); - Assert.assertNotNull(list); - } - - /** - * functional testing getAllMemoryInstanceDetails - * - * @tc.name: getAllMemoryInstanceDetails - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getAllMemoryInstanceDetails_0001 - * @tc.desc: getAllMemoryInstanceDetails - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testgetAllMemoryInstanceDetails() { - List list = memoryInstanceDetailsDao.getAllMemoryInstanceDetails(); - Assert.assertNotNull(list); - } - - /** - * functional testing deleteSessionData - * - * @tc.name: deleteSessionData - * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_deleteSessionData_0001 - * @tc.desc: deleteSessionData - * @tc.type: functional testing - * @tc.require: AR000FK61N - */ - @Test - public void testdeleteSessionData() { - memoryInstanceDetailsDao.deleteSessionData(1L); - } - -} +/* + * 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. + */ + +package ohos.devtools.services.memory; + +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo; +import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao; +import org.apache.logging.log4j.Level; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Memory Instance Details Dao Test + */ +public class MemoryInstanceDetailsDaoTest { + private MemoryInstanceDetailsInfo memoryInstanceDetailsInfo; + private MemoryInstanceDetailsDao memoryInstanceDetailsDao; + + /** + * functional testing init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Before + public void init() { + // 应用初始化 Step1 初始化数据中心 + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + memoryInstanceDetailsDao = MemoryInstanceDetailsDao.getInstance(); + memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); + memoryInstanceDetailsInfo.setInstanceId(1); + memoryInstanceDetailsInfo.setClassName("Class"); + memoryInstanceDetailsInfo.setFieldName("field"); + memoryInstanceDetailsInfo.setMethodName("method"); + memoryInstanceDetailsInfo.setFrameId(1); + memoryInstanceDetailsInfo.setLineNumber(1); + memoryInstanceDetailsInfo.setId(1); + } + + /** + * functional testing getInstance + * + * @tc.name: getInstance + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getInstance_0001 + * @tc.desc: getInstance + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testGetInstance() { + MemoryInstanceDetailsDao instance = MemoryInstanceDetailsDao.getInstance(); + Assert.assertNotNull(instance); + } + + /** + * functional testing insertMemoryInstanceDetailsInfo + * + * @tc.name: insertMemoryInstanceDetailsInfo + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_insertMemoryInstanceDetailsInfo_0001 + * @tc.desc: insertMemoryInstanceDetailsInfo + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testinsertMemoryInstanceDetailsInfos() { + List list = new ArrayList<>(); + list.add(memoryInstanceDetailsInfo); + memoryInstanceDetailsDao.insertMemoryInstanceDetailsInfo(list); + } + + /** + * functional testing getMemoryInstanceDetails + * + * @tc.name: getMemoryInstanceDetails + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getMemoryInstanceDetails_0001 + * @tc.desc: getMemoryInstanceDetails + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetMemoryInstanceDetails() { + List list = memoryInstanceDetailsDao.getMemoryInstanceDetails(1); + Assert.assertNotNull(list); + } + + /** + * functional testing getAllMemoryInstanceDetails + * + * @tc.name: getAllMemoryInstanceDetails + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_getAllMemoryInstanceDetails_0001 + * @tc.desc: getAllMemoryInstanceDetails + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testgetAllMemoryInstanceDetails() { + List list = memoryInstanceDetailsDao.getAllMemoryInstanceDetails(); + Assert.assertNotNull(list); + } + + /** + * functional testing deleteSessionData + * + * @tc.name: deleteSessionData + * @tc.number: OHOS_JAVA_memory_MemoryInstanceDetailsDao_deleteSessionData_0001 + * @tc.desc: deleteSessionData + * @tc.type: functional testing + * @tc.require: AR000FK61N + */ + @Test + public void testdeleteSessionData() { + memoryInstanceDetailsDao.deleteSessionData(1L); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfoTest.java deleted file mode 100644 index 78e35f18a..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceDetailsInfoTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description MemoryInstanceDetailsInfoTest - * @Date 2021/4/3 20:10 - **/ -public class MemoryInstanceDetailsInfoTest { - /** - * memoryInstanceDetailsInfo - */ - public MemoryInstanceDetailsInfo memoryInstanceDetailsInfo; - - /** - * functional test - * - * @tc.name: init - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDetailsInfo_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK61P - */ - @Before - public void init() { - memoryInstanceDetailsInfo = new MemoryInstanceDetailsInfo(); - } - - /** - * functional test - * - * @tc.name: test - * @tc.number: OHOS_JAVA_Service_MemoryInstanceDetailsInfo_test_0001 - * @tc.desc: test - * @tc.type: functional testing - * @tc.require: AR000FK61P - */ - @Test - public void test() { - memoryInstanceDetailsInfo.setInstanceId(3); - memoryInstanceDetailsInfo.setClassName("test"); - memoryInstanceDetailsInfo.setFieldName("tste"); - memoryInstanceDetailsInfo.setMethodName("test"); - memoryInstanceDetailsInfo.setId(1); - memoryInstanceDetailsInfo.setLineNumber(2); - memoryInstanceDetailsInfo.getInstanceId(); - memoryInstanceDetailsInfo.getClassName(); - memoryInstanceDetailsInfo.getFieldName(); - memoryInstanceDetailsInfo.getMethodName(); - memoryInstanceDetailsInfo.getId(); - memoryInstanceDetailsInfo.getLineNumber(); - memoryInstanceDetailsInfo.toString(); - Assert.assertNotNull(memoryInstanceDetailsInfo); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceInfoTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceInfoTest.java deleted file mode 100644 index 00facad13..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryInstanceInfoTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -import org.junit.Test; - -/** - * @Description MemoryInstanceInfoTest - * @Date 2021/4/2 10:39 - **/ -public class MemoryInstanceInfoTest { - /** - * functional test - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_Service_MemoryInstanceInfo_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: AR000FK61R - */ - @Test - public void getInstance() { - MemoryInstanceInfo memoryInstanceInfo = new MemoryInstanceInfo(); - memoryInstanceInfo.setInstance("ddd"); - memoryInstanceInfo.setAllocTime(123712L); - memoryInstanceInfo.setDeallocTime(123412L); - memoryInstanceInfo.setId(32); - memoryInstanceInfo.getInstance(); - memoryInstanceInfo.getAllocTime(); - memoryInstanceInfo.getDeallocTime(); - memoryInstanceInfo.getId(); - memoryInstanceInfo.toString(); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryServiceTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryServiceTest.java deleted file mode 100644 index 7e691eb0f..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/services/memory/MemoryServiceTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.services.memory; - -/** - * @Description MemoryServiceTest - * @Date 2021/4/3 18:51 - **/ -public class MemoryServiceTest { -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/applicationtrace/AppTracePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/applicationtrace/AppTracePanelTest.java new file mode 100644 index 000000000..5879a364e --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/applicationtrace/AppTracePanelTest.java @@ -0,0 +1,117 @@ +/* + * 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. + */ + +package ohos.devtools.views.applicationtrace; + +import com.intellij.openapi.wm.IdeGlassPane; +import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; +import ohos.devtools.Config; +import org.fest.swing.fixture.FrameFixture; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import java.awt.AWTException; +import java.awt.Dimension; +import java.awt.MouseInfo; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; + +class AppTracePanelTest { + private FrameFixture frame; + private AppTracePanel panel; + private JFrame jFrame; + private Robot robot; + + @BeforeEach + void setUp() { + jFrame = new JFrame(); + try { + robot = new Robot(); + robot.setAutoDelay(2000); + IdeGlassPane ideGlassPane = new IdeGlassPaneImpl(jFrame.getRootPane()); + jFrame.getRootPane().setGlassPane((JPanel) ideGlassPane); + } catch (AWTException e) { + e.printStackTrace(); + } + panel = new AppTracePanel(); + jFrame.add(panel); + frame = new FrameFixture(jFrame); + frame.show(new Dimension(1920, 1080)); + frame.moveTo(new Point(0, 0)); + } + + @AfterEach + void tearDown() { + frame.close(); + frame.cleanUp(); + } + + @Test + void load() { + panel.load(Config.TRACE_APP, + Config.TRACE_CPU, 8593, true); + panel.updateUI(); + + delay(10000); + mouseClick(317, 373); + select(494, 367, 584, 467); + delay(); + } + + private void mouseClick(int x, int y) { + robot.delay(2000); + robot.mouseMove(x, y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + private void keyClick(int keyEvent) { + robot.delay(2000); + robot.keyPress(keyEvent); + robot.keyRelease(keyEvent); + } + + private void select(int x1, int y1, int x2, int y2) { + robot.delay(2000); + robot.mouseMove(x1, y1); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseMove(x2, y2); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + private void wheel(int wheelAmt) { + robot.delay(1000); + robot.mouseWheel(wheelAmt); + } + + private void delay() { + robot.delay(2000); + } + + private void delay(int time) { + robot.delay(time); + } + + private void inspect() { + while (true) { + Point location = MouseInfo.getPointerInfo().getLocation(); + robot.delay(1000); + } + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/FilledLineChartTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/FilledLineChartTest.java index bc72cedd9..edd5823f7 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/FilledLineChartTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/FilledLineChartTest.java @@ -1,63 +1,61 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.charts; - -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description FilledLineChartTest - * @Date 2021/4/2 13:48 - **/ -public class FilledLineChartTest { - private ProfilerChartsView profilerChartsView; - - private FilledLineChart filledLineChart; - - /** - * functional test - * - * @tc.name: getFilledLineChart - * @tc.number: OHOS_JAVA_View_FilledLineChart_getFilledLineChart_0001 - * @tc.desc: getFilledLineChart - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Before - public void getFilledLineChart() { - profilerChartsView = new ProfilerChartsView(39999, true, new TaskScenePanelChart()); - filledLineChart = new FilledLineChart(profilerChartsView); - Assert.assertNotNull(filledLineChart); - } - - /** - * functional test - * - * @tc.name: paintComponent - * @tc.number: OHOS_JAVA_View_FilledLineChart_paintComponent_0001 - * @tc.desc: paintComponent - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void paintComponentTest() { - filledLineChart.revalidate(); - } - +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Filled Line Chart Test + */ +public class FilledLineChartTest { + private ProfilerChartsView profilerChartsView; + + private FilledLineChart filledLineChart; + + /** + * functional test + * + * @tc.name: getFilledLineChart + * @tc.number: OHOS_JAVA_View_FilledLineChart_getFilledLineChart_0001 + * @tc.desc: getFilledLineChart + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void getFilledLineChart() { + profilerChartsView = new ProfilerChartsView(39999, true, new TaskScenePanelChart()); + filledLineChart = new FilledLineChart(profilerChartsView, "", true); + Assert.assertNotNull(filledLineChart); + } + + /** + * functional test + * + * @tc.name: paintComponent + * @tc.number: OHOS_JAVA_View_FilledLineChart_paintComponent_0001 + * @tc.desc: paintComponent + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void paintComponentTest() { + filledLineChart.revalidate(); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/LineChartTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/LineChartTest.java similarity index 83% rename from host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/LineChartTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/views/charts/LineChartTest.java index 8c00a4e8d..1fa99a2bc 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/LineChartTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/LineChartTest.java @@ -13,26 +13,24 @@ * limitations under the License. */ -package ohos.devtools.views.charts.utils; +package ohos.devtools.views.charts; -import ohos.devtools.views.charts.LineChart; import ohos.devtools.views.common.LayoutConstants; import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** - * Chart相关的工具类的测试类 - * - * @since 2021/4/25 14:02 + * Test class of Chart-related tool classes */ public class LineChartTest { /** * ProfilerChartsView */ private ProfilerChartsView view; + private LineChart lineC; /** * functional testing @@ -46,6 +44,7 @@ public class LineChartTest { @Before public void init() { view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + lineC = new LineChart(view, ""); } /** @@ -58,8 +57,8 @@ public class LineChartTest { * @tc.require: AR000FK5UI */ @Test - public void LineChartTest() { - LineChart lineChart = new LineChart(view); + public void lineChartTest() { + LineChart lineChart = new LineChart(view, ""); Assert.assertNotNull(lineChart); } } diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/ProfilerChartTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/ProfilerChartTest.java index e105074c7..658d99222 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/ProfilerChartTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/ProfilerChartTest.java @@ -15,25 +15,28 @@ package ohos.devtools.views.charts; +import com.intellij.ui.components.JBPanel; import ohos.devtools.views.charts.model.ChartDataModel; import ohos.devtools.views.common.LayoutConstants; import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.awt.Color; +import java.awt.event.MouseEvent; +import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; /** - * Chart的抽象父类的测试类 - * - * @since 2021/3/31 16:26 + * Test class of the abstract parent class of Chart */ public class ProfilerChartTest { + private static final String NAME = "Test"; + private static final int TEST_START = 0; private static final int TEST_END = 1000; @@ -54,6 +57,10 @@ public class ProfilerChartTest { private LinkedHashMap> dataMap; + private ProfilerChart chart; + + private List models; + /** * init * @@ -67,11 +74,18 @@ public class ProfilerChartTest { public void init() { initView(); initDataMap(); + chart = new FilledLineChart(view, NAME, true); + ChartDataModel chartDataModel = new ChartDataModel(); + chartDataModel.setIndex(1); + chartDataModel.setColor(Color.GREEN); + chartDataModel.setValue(1); + models = new ArrayList<>(); + models.add(chartDataModel); } private void initView() { view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); - view.getObserver().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); + view.getPublisher().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); } private void initDataMap() { @@ -103,7 +117,6 @@ public class ProfilerChartTest { */ @Test public void refreshChartTest() { - ProfilerChart chart = new FilledLineChart(view); chart.refreshChart(TEST_START, TEST_END, dataMap); Assert.assertTrue(true); } @@ -119,7 +132,7 @@ public class ProfilerChartTest { */ @Test public void getBottomPanelTest() { - ProfilerChartsView profilerChartsView = new FilledLineChart(view).getBottomPanel(); + ProfilerChartsView profilerChartsView = new FilledLineChart(view, NAME, true).getBottomPanel(); Assert.assertNotNull(profilerChartsView); } @@ -134,7 +147,7 @@ public class ProfilerChartTest { */ @Test public void getEndTimeTest() { - int endTime = new FilledLineChart(view).getEndTime(); + int endTime = new FilledLineChart(view, NAME, true).getEndTime(); Assert.assertNotNull(endTime); } @@ -149,8 +162,265 @@ public class ProfilerChartTest { */ @Test public void getStartTimeTest() { - int startTime = new FilledLineChart(view).getStartTime(); + int startTime = new FilledLineChart(view, NAME, true).getStartTime(); Assert.assertNotNull(startTime); } + /** + * functional test + * + * @tc.name: refreshLegendsTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_refreshLegendsTest_0001 + * @tc.desc: refresh Legends Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void refreshLegendsTest() { + chart.refreshChart(TEST_START, TEST_END, dataMap); + chart.refreshLegends(); + Assert.assertTrue(true); + } + + /** + * paint Component Test + * + * @tc.name: paintComponentTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_paintComponentTest_0001 + * @tc.desc: paint Component Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void paintComponentTest() { + chart.revalidate(); + Assert.assertTrue(true); + } + + /** + * get Yaxis Label Str Test + * + * @tc.name: getYaxisLabelStrTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_getYaxisLabelStrTest_0001 + * @tc.desc: get Yaxis Label Str Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getYaxisLabelStrTest() { + String yaxisLabelStr = chart.getYaxisLabelStr(10); + Assert.assertNotNull(yaxisLabelStr); + } + + /** + * init Point Test + * + * @tc.name: initPointTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_initPointTest_0001 + * @tc.desc: init Point Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void initPointTest() { + chart.initPoint(); + Assert.assertTrue(true); + } + + /** + * check Mouse For Tool tip Test + * + * @tc.name: checkMouseForTooltipTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_checkMouseForTooltipTest_0001 + * @tc.desc: check Mouse For Tool tip Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void checkMouseForTooltipTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.checkMouseForTooltip(mouseEvent); + Assert.assertTrue(true); + } + + /** + * get Current Line Color Test + * + * @tc.name: getCurrentLineColorTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_getCurrentLineColorTest_0001 + * @tc.desc: get Current Line Color Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getCurrentLineColorTest() { + Color currentLineColor = chart.getCurrentLineColor(1, models); + Assert.assertNotNull(currentLineColor); + } + + /** + * get Next Line Index Test + * + * @tc.name: getNextLineIndexTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_getNextLineIndexTest_0001 + * @tc.desc: get Next Line Index Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getNextLineIndexTest() { + int nextLineIndex = chart.getNextLineIndex(1, models); + Assert.assertNotNull(nextLineIndex); + } + + /** + * get List Sum Test + * + * @tc.name: getListSumTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_getListSumTest_0001 + * @tc.desc: get List Sum Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getListSumTest() { + int listSum = chart.getListSum(models, 1); + Assert.assertNotNull(listSum); + } + + /** + * get Model Value By Index Test + * + * @tc.name: getModelValueByIndexTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_getModelValueByIndexTest_0001 + * @tc.desc: get Model Value By Index Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getModelValueByIndexTest() { + int modelValueByIndex = chart.getModelValueByIndex(models, 1); + Assert.assertNotNull(modelValueByIndex); + } + + /** + * mouse Clicked Test + * + * @tc.name: mouseClickedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseClickedTest_0001 + * @tc.desc: mouse Clicked Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseClickedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseClicked(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Pressed Test + * + * @tc.name: mousePressedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mousePressedTest_0001 + * @tc.desc: mouse Pressed Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mousePressedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mousePressed(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Released Test + * + * @tc.name: mouseReleasedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseReleasedTest_0001 + * @tc.desc: mouse Released Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseReleasedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseReleased(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Entered Test + * + * @tc.name: mouseEnteredTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseEnteredTest_0001 + * @tc.desc: mouse Entered Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseEnteredTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseEntered(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Exited Test + * + * @tc.name: mouseExitedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseExitedTest_0001 + * @tc.desc: mouse Exited Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseExitedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseExited(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Dragged Test + * + * @tc.name: mouseDraggedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseDraggedTest_0001 + * @tc.desc: mouse Dragged Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseDraggedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseDragged(mouseEvent); + Assert.assertTrue(true); + } + + /** + * mouse Moved Test + * + * @tc.name: mouseMovedTest + * @tc.number: OHOS_JAVA_View_ProfilerChart_mouseMovedTest_0001 + * @tc.desc: mouse Moved Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void mouseMovedTest() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + chart.mouseMoved(mouseEvent); + Assert.assertTrue(true); + } } + diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/RectChartTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/RectChartTest.java new file mode 100644 index 000000000..1a8ec7d9a --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/RectChartTest.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package ohos.devtools.views.charts; + +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Rect Chart Test + */ +public class RectChartTest { + private static final String NAME = "Test"; + private static final int TEST_START = 0; + private static final int TEST_END = 1000; + private ProfilerChartsView view; + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_View_RectChart_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + initView(); + } + + private void initView() { + view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + view.getPublisher().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); + } + + /** + * Rect Chart Test + * + * @tc.name: RectChartTest + * @tc.number: OHOS_JAVA_View_RectChart_RectChartTest_0001 + * @tc.desc: Rect Chart Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void rectChartTest() { + RectChart chart = new RectChart(view, NAME); + Assert.assertNotNull(chart); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/LegendTooltipTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/LegendTooltipTest.java index 35b6cc343..4941d55da 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/LegendTooltipTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/LegendTooltipTest.java @@ -16,9 +16,10 @@ package ohos.devtools.views.charts.tooltip; import com.intellij.ui.JBColor; +import ohos.devtools.views.charts.model.ChartDataModel; import ohos.devtools.views.common.LayoutConstants; import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -28,13 +29,12 @@ import java.util.Collections; import java.util.List; /** - * 自定义Tooltip的测试类 - * - * @since 2021/3/31 15:56 + * Custom Tooltip test class */ public class LegendTooltipTest { private static final String TEST_TIME = "00:23:189"; private static final String TEST_TEXT = "Java:123MB"; + private LegendTooltip tooltip; private ProfilerChartsView view; private List tooltipItems; @@ -49,24 +49,11 @@ public class LegendTooltipTest { */ @Before public void init() { + tooltip = new LegendTooltip(); view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); tooltipItems = Collections.singletonList(new TooltipItem(JBColor.GRAY, TEST_TEXT)); } - /** - * functional test - * - * @tc.name: getInstance - * @tc.number: OHOS_JAVA_View_LegendTooltip_getInstance_0001 - * @tc.desc: getInstance - * @tc.type: functional testing - * @tc.require: SR000FK5SL - */ - @Test - public void getInstanceTest() { - Assert.assertNotNull(LegendTooltip.getInstance()); - } - /** * functional test * @@ -78,7 +65,7 @@ public class LegendTooltipTest { */ @Test public void hideTipTest() { - LegendTooltip.getInstance().hideTip(); + tooltip.hideTip(); Assert.assertTrue(true); } @@ -93,7 +80,7 @@ public class LegendTooltipTest { */ @Test public void showTipTest() { - LegendTooltip.getInstance().showTip(view, TEST_TIME, "0", tooltipItems, true); + tooltip.showTip(view, TEST_TIME, "0", tooltipItems, true, "MB"); Assert.assertTrue(true); } @@ -109,7 +96,40 @@ public class LegendTooltipTest { @Test public void followWithMouseTest() { MouseEvent mouseEvent = new MouseEvent(view, 0, 1L, 0, 0, 0, 1, false); - LegendTooltip.getInstance().followWithMouse(mouseEvent); + tooltip.followWithMouse(mouseEvent); Assert.assertTrue(true); } + + /** + * functional test + * + * @tc.name: showThreadStatusTipTest + * @tc.number: OHOS_JAVA_View_LegendTooltip_showThreadStatusTipTest_0001 + * @tc.desc: show ThreadStatus Tip Test + * @tc.type: functional testing + * @tc.require: SR000FK5SL + */ + @Test + public void showThreadStatusTipTest() { + ChartDataModel chartDataModel = new ChartDataModel(); + chartDataModel.setName("Name"); + chartDataModel.setValue(1); + tooltip.showThreadStatusTip(view, TEST_TIME, chartDataModel, true); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: LegendTooltipTest + * @tc.number: OHOS_JAVA_View_LegendTooltip_LegendTooltipTest_0001 + * @tc.desc: Legend Tool tip Test + * @tc.type: functional testing + * @tc.require: SR000FK5SL + */ + @Test + public void legendTooltipTest() { + LegendTooltip legendTooltip = new LegendTooltip(); + Assert.assertNotNull(legendTooltip); + } } diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipColorRectTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipColorRectTest.java index a3c12eadb..578738d7d 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipColorRectTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipColorRectTest.java @@ -1,44 +1,41 @@ -/* - * 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. - */ - -package ohos.devtools.views.charts.tooltip; - -import org.junit.Assert; -import org.junit.Test; - -import java.awt.Color; - -/** - * TooltipColorRectTest - * - * @version 1.0 - * @Date 2021/4/3 21:10 - **/ -public class TooltipColorRectTest { - /** - * functional test - * - * @tc.name: test - * @tc.number: OHOS_JAVA_View_TooltipColorRect_test_0001 - * @tc.desc: test - * @tc.type: functional testing - * @tc.require: AR000FK5SM - */ - @Test - public void test01() { - TooltipColorRect tooltipColorRect = new TooltipColorRect(new Color(255, 255, 255)); - Assert.assertNotNull(tooltipColorRect); - } +/* + * 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. + */ + +package ohos.devtools.views.charts.tooltip; + +import org.junit.Assert; +import org.junit.Test; + +import java.awt.Color; + +/** + * Tool tip Color Rect Test + */ +public class TooltipColorRectTest { + /** + * functional test + * + * @tc.name: test + * @tc.number: OHOS_JAVA_View_TooltipColorRect_test_0001 + * @tc.desc: test + * @tc.type: functional testing + * @tc.require: AR000FK5SM + */ + @Test + public void test01() { + TooltipColorRect tooltipColorRect = new TooltipColorRect(new Color(255, 255, 255)); + Assert.assertNotNull(tooltipColorRect); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipItemTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipItemTest.java new file mode 100644 index 000000000..364debad3 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/tooltip/TooltipItemTest.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + +package ohos.devtools.views.charts.tooltip; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.awt.Color; + +/** + * Tool tip Item Test + */ +public class TooltipItemTest { + private TooltipItem tooltipItem; + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_View_TooltipItem_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: SR000FK5SL + */ + @Before + public void init() { + tooltipItem = new TooltipItem(Color.GREEN, "Test"); + } + + /** + * TooltipItemTest + * + * @tc.name: TooltipItemTest + * @tc.number: OHOS_JAVA_View_TooltipItem_TooltipItemTest_0001 + * @tc.desc: TooltipItemTest + * @tc.type: functional testing + * @tc.require: SR000FK5SL + */ + @Test + public void tooltipItemTest() { + TooltipItem item = new TooltipItem(Color.BLUE, "Test"); + Assert.assertNotNull(item); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartConstantsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartConstantsTest.java deleted file mode 100644 index de5bee656..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartConstantsTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.charts.utils; - -import org.junit.Assert; -import org.junit.Test; - -import java.awt.Color; - -/** - * @Description ChartConstantsTest - * @Date 2021/4/3 18:00 - **/ -public class ChartConstantsTest { - /** - * functional test - * - * @tc.name: init - * @tc.number: OHOS_JAVA_View_ChartConstants_init_0001 - * @tc.desc: init - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - public void init() { - } - - /** - * functional test - * - * @tc.name: test - * @tc.number: OHOS_JAVA_View_ChartConstants_test_0001 - * @tc.desc: test - * @tc.type: functional testing - * @tc.require: AR000FK5UI - */ - @Test - public void test() { - int test01 = ChartConstants.INITIAL_VALUE; - Assert.assertEquals(-1, test01); - int test02 = ChartConstants.CHART_HEADER_HEIGHT; - Assert.assertEquals(20, test02); - int test03 = ChartConstants.SCALE_LINE_LEN; - Assert.assertEquals(4, test03); - int test04 = ChartConstants.UNIT; - Assert.assertEquals(1024, test04); - float test05 = ChartConstants.OPAQUE_VALUE; - Assert.assertNotNull(test05); - int test06 = ChartConstants.Y_AXIS_STR_OFFSET_X; - Assert.assertEquals(15, test06); - int test07 = ChartConstants.Y_AXIS_STR_OFFSET_Y; - Assert.assertEquals(5, test07); - float test08 = ChartConstants.TRANSLUCENT_VALUE; - Assert.assertNotNull(test08); - Color test09 = ChartConstants.DEFAULT_CHART_COLOR; - Assert.assertNotNull(test09); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartUtilsTest.java index c832a6c9d..7f01703a4 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/charts/utils/ChartUtilsTest.java @@ -22,8 +22,6 @@ import java.math.BigDecimal; /** * Test class of Chart-related tool classes - * - * @since 2021/3/31 16:27 */ public class ChartUtilsTest { private static final int[] TEST_ARRAY = {0, 10, 14, 24, 29, 32, 37, 40, 45}; diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/CommonTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/CommonTest.java deleted file mode 100644 index 6f117b0b8..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/CommonTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common; - -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -/** - * @Description CommonTest - * @Date 2021/4/5 13:15 - **/ -public class CommonTest { - private Common common; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_Common_init_0001 - * @tc.desc: chart util test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - common = new Common(); - } - - /** - * update number - * - * @tc.name: 主界面-chart页面 - * @tc.number: OHOS_JAVA_views_Common_updateNum_0001 - * @tc.desc: chart页面工具相关功能接口测试 - * @tc.type: 功能测试 - * @tc.require: SR-001-AR-003 - */ - @Test - public void updateNum() { - JPanel jPanel7 = new JPanel(); - JPanel jPanel4 = new JPanel(); - JPanel jPanel1 = new JPanel(); - jPanel1.add(jPanel4); - jPanel1.add(jPanel7); - JPanel jPanel5 = new JPanel(); - JPanel jPanel2 = new JPanel(); - jPanel2.add(jPanel5); - jPanel2.add(jPanel7); - JPanel jPanel3 = new JPanel(); - JPanel jPanel6 = new JPanel(); - jPanel3.add(jPanel6); - jPanel3.add(jPanel7); - JTabbedPane jTabbedPane = new JTabbedPane(); - jTabbedPane.addTab("test01", jPanel1); - jTabbedPane.addTab("test02", jPanel2); - jTabbedPane.addTab("test03", jPanel3); - common.updateNum(jTabbedPane); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/OperationUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/OperationUtilsTest.java index 1b2e5b303..192935d8d 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/OperationUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/OperationUtilsTest.java @@ -15,6 +15,7 @@ package ohos.devtools.views.common; +import ohos.devtools.views.layout.chartview.utils.OperationUtils; import org.junit.Assert; import org.junit.Test; @@ -22,8 +23,6 @@ import java.math.BigDecimal; /** * ViewUtils test - * - * @since 2021/3/31 14:13 */ public class OperationUtilsTest { private static final int[] TEST_ARRAY = {0, 10, 14, 24, 29, 32, 37, 40, 45}; diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerTimelineTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerTimelineTest.java deleted file mode 100644 index 8e60ab97f..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerTimelineTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart; - -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description profiler time line test - * @Date 2021/4/3 20:29 - **/ -public class ProfilerTimelineTest { - private ProfilerTimeline profilerTimeline; - - private ProfilerChartsView profilerChartsView; - - private TaskScenePanelChart taskScenePanelChart; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: DFX_DFT_Hilog_Java_views_0005 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void init() { - taskScenePanelChart = new TaskScenePanelChart(); - profilerChartsView = new ProfilerChartsView(23423L, true, new TaskScenePanelChart()); - profilerTimeline = new ProfilerTimeline(profilerChartsView, 200, 200, taskScenePanelChart); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_addTablePanel_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void addTablePanel01() { - profilerTimeline.addTablePanel(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_removeTablePanel_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void removeTablePanel01() { - profilerTimeline.removeTablePanel(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_setEndTime_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setEndTime01() { - profilerTimeline.setEndTime(234); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_setMaxDisplayTime_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setMaxDisplayTime01() { - profilerTimeline.setMaxDisplayTime(234); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_setMinMarkInterval_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setMinMarkInterval01() { - profilerTimeline.setMinMarkInterval(234); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_setStartTime_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setStartTime01() { - profilerTimeline.setStartTime(234); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_getEndTime_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getEndTime01() { - profilerTimeline.getEndTime(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_getStartTime_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getStartTime01() { - profilerTimeline.getStartTime(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerTimeline_paint_0001 - * @tc.desc: chart Timeline functional test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void paint01() { - profilerTimeline.revalidate(); - profilerTimeline.repaint(); - } - -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/DataNodeComparesTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/DataNodeComparesTest.java deleted file mode 100644 index 5e24fbacd..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/DataNodeComparesTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import ohos.devtools.views.common.LayoutConstants; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -/** - * DataNodeCompares sorting test - * - * @Description DataNodeCompares sorting test - * @Date 2021/4/5 13:15 - **/ -public class DataNodeComparesTest { - private DataNodeCompares dataNodeCompares; - private Comparator comparator; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_init_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - dataNodeCompares = new DataNodeCompares(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_init_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @After - public void after() { - DataNode dataNode1 = new DataNode(); - DataNode dataNode2 = new DataNode(); - DataNode dataNode3 = new DataNode(); - DataNode dataNode4 = new DataNode(); - dataNode1.addChildren(dataNode2); - dataNode3.addChildren(dataNode4); - dataNode1.addChildren(dataNode3); - ArrayList dataNodes = new ArrayList<>(); - dataNodes.add(dataNode1); - Collections.sort(dataNodes, comparator); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare01() { - comparator = dataNodeCompares.chooseCompare(0, LayoutConstants.ASC); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0002 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare02() { - comparator = dataNodeCompares.chooseCompare(1, LayoutConstants.ASC); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0003 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare03() { - comparator = dataNodeCompares.chooseCompare(2, LayoutConstants.ASC); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0004 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare04() { - comparator = dataNodeCompares.chooseCompare(3, LayoutConstants.ASC); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0005 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare05() { - comparator = dataNodeCompares.chooseCompare(4, LayoutConstants.ASC); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0006 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare06() { - comparator = dataNodeCompares.chooseCompare(0, "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0007 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare07() { - comparator = dataNodeCompares.chooseCompare(1, "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0008 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare08() { - comparator = dataNodeCompares.chooseCompare(2, "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0009 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare09() { - comparator = dataNodeCompares.chooseCompare(3, "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DataNodeCompares_chooseCompare_0010 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void chooseCompare10() { - comparator = dataNodeCompares.chooseCompare(4, "test"); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/JTreeTableTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/JTreeTableTest.java deleted file mode 100644 index 2497757fa..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/treetable/JTreeTableTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.chart.treetable; - -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; -import java.util.Locale; - -/** - * @Description JTreeTable test - * @Date 2021/4/5 13:15 - **/ -public class JTreeTableTest { - /** - * JTreeTable - */ - private JTreeTable jTreeTable; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_JTreeTable_init_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - jTreeTable = new JTreeTable(new AgentDataModel(new DataNode())); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_JTreeTable_getTreeTableModel_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void getTreeTableModel() { - TreeTableModel treeTableModel = jTreeTable.getTreeTableModel(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_JTreeTable_setTreeTableModel_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void setTreeTableModel() { - TreeTableModel treeTableModel = jTreeTable.getTreeTableModel(); - jTreeTable.setTreeTableModel(treeTableModel); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_JTreeTable_convertRowToText_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void convertRowToText() { - Locale defaultLocale = JTreeTable.TreeTableCellRenderer.getDefaultLocale(); - JTreeTable.TreeTableCellRenderer.setDefaultLocale(defaultLocale); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_JTreeTable_setBounds_0001 - * @tc.desc: chart of Memory functional test - * @tc.type: functional testing - * @tc.require: SR-001-AR-003 - */ - @Test - public void setBounds() { - boolean lightweightComponent = JTreeTable.TreeTableCellRenderer.isLightweightComponent(new JPanel()); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/customcomp/CustomProgressBarTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/customcomp/CustomProgressBarTest.java new file mode 100644 index 000000000..de615d927 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/customcomp/CustomProgressBarTest.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.customcomp; + +import org.junit.Assert; +import org.junit.Test; + +import javax.swing.JPanel; + +/** + * Custom Progress Bar Test + */ +public class CustomProgressBarTest { + /** + * CustomProgressBarTest + * + * @tc.name: CustomProgressBarTest + * @tc.number: OHOS_JAVA_View_CustomProgressBar_CustomProgressBarTest_0001 + * @tc.desc: Custom Progress Bar Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void customProgressBarTest() { + CustomProgressBar customProgressBar = new CustomProgressBar(new JPanel()); + Assert.assertNotNull(customProgressBar); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/HosDialogTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/HosDialogTest.java deleted file mode 100644 index 7d7b5dea4..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/HosDialogTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.common.hoscomp; - -import ohos.devtools.datasources.utils.monitorconfig.service.MonitorConfigManager; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.SampleDialogWrapper; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.apache.logging.log4j.LogManager; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.HashMap; -import java.util.LinkedList; - -/** - * @Description HosDialog test - * @Date 2021/4/3 20:29 - **/ -@RunWith(PowerMockRunner.class) -@PrepareForTest({SampleDialogWrapper.class, HosDialog.class, LogManager.class}) -@PowerMockIgnore({"javax.swing.*"}) -public class HosDialogTest { - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HosDialog_getSessionInfo_0001 - * @tc.desc: chart HosDialog test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - * @throws Exception throw Exception - */ - @Test - public void getSessionInfo() throws Exception { - SampleDialogWrapper mock = PowerMockito.mock(SampleDialogWrapper.class); - PowerMockito.mockStatic(LogManager.class); - PowerMockito.whenNew(SampleDialogWrapper.class).withAnyArguments().thenReturn(mock); - Mockito.when(mock.showAndGet()).thenReturn(true); - HashMap> stringLinkedListHashMap = new HashMap<>(); - LinkedList strings = new LinkedList<>(); - strings.add("java"); - strings.add("native"); - stringLinkedListHashMap.put("Memory", strings); - MonitorConfigManager.dataMap.put(23478L, stringLinkedListHashMap); - HosDialog hosDialog = new HosDialog(23478L, new ProfilerChartsView(23478L, false, new TaskScenePanelChart())); - HosDialog hosDialog1 = new HosDialog(23478L, new ProfilerChartsView(23478L, true, new TaskScenePanelChart())); - hosDialog.getSessionInfo(); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/LoadingPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/LoadingPanelTest.java new file mode 100644 index 000000000..3e14ac2f9 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/hoscomp/LoadingPanelTest.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.common.hoscomp; + +import ohos.devtools.views.layout.chartview.LoadingPanel; +import org.junit.Assert; +import org.junit.Test; + +/** + * Loading Panel Test + */ +public class LoadingPanelTest { + /** + * Loading Panel Test + * + * @tc.name: LoadingPanelTest + * @tc.number: OHOS_JAVA_View_LoadingPanel_LoadingPanelTest_0001 + * @tc.desc: Loading Panel Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void loadingPanelTest() { + LoadingPanel loadingPanel = new LoadingPanel(); + Assert.assertNotNull(loadingPanel); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataFilterTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataFilterTest.java new file mode 100644 index 000000000..ff2ed6fa8 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataFilterTest.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package ohos.devtools.views.common.treetable; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import javax.swing.tree.DefaultMutableTreeNode; + +/** + * Data Filter Test + */ +public class DataFilterTest { + private static final String TEST_STRING = "Test"; + private DataFilter dataFilter; + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_View_DataFilter_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + dataFilter = new DataFilter(); + } + + /** + * pass Tree Node Test + * + * @tc.name: passTreeNodeTest + * @tc.number: OHOS_JAVA_View_DataFilter_passTreeNodeTest_0001 + * @tc.desc: pass Tree Node Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void passTreeNodeTest() { + DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(); + boolean res = dataFilter.passTreeNode(treeNode, TEST_STRING); + Assert.assertTrue(res); + } + + /** + * set Filter Test + * + * @tc.name: setFilterTest + * @tc.number: OHOS_JAVA_View_DataFilter_setFilterTest_0001 + * @tc.desc: set Filter Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void setFilterTest() { + dataFilter.setFilter(true, TEST_STRING); + Assert.assertTrue(true); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeComparesTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeComparesTest.java deleted file mode 100644 index d62ceb8d1..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeComparesTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package ohos.devtools.views.common.treetable; - -import ohos.devtools.views.common.chart.treetable.DataNodeCompares; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Comparator; - -/** - * DataNodeCompares test - * - * @Description DataNodeCompares test - * @Date 2021/4/3 20:29 - **/ -public class DataNodeComparesTest { - /** - * test int - */ - private DataNodeCompares dataNodeCompares = new DataNodeCompares(); - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNodeCompares_classNameString - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void testclassNameString() { - Comparator classNameCompareAsc = dataNodeCompares.chooseCompare(0, "ASCENDING"); - Comparator allocationsCompareAsc = dataNodeCompares.chooseCompare(1, "ASCENDING"); - Comparator deallocationsCompareAsc = dataNodeCompares.chooseCompare(2, "ASCENDING"); - Comparator totalCompareAsc = dataNodeCompares.chooseCompare(3, "ASCENDING"); - Comparator shallowSizeCompareAsc = dataNodeCompares.chooseCompare(4, "ASCENDING"); - Comparator classNameCompareDsc = dataNodeCompares.chooseCompare(0, "ASCENDING1"); - Comparator allocationsCompareDsc = dataNodeCompares.chooseCompare(1, "ASCENDING1"); - Comparator deallocationsCompareDsc = dataNodeCompares.chooseCompare(2, "ASCENDING1"); - Comparator totalCompareDsc = dataNodeCompares.chooseCompare(3, "ASCENDING1"); - Comparator shallowSizeCompareDsc = dataNodeCompares.chooseCompare(4, "ASCENDING1"); - Comparator classNameString = DataNodeCompares.classNameString; - Assert.assertNotNull(classNameCompareAsc); - Assert.assertNotNull(classNameCompareDsc); - Assert.assertNotNull(allocationsCompareAsc); - Assert.assertNotNull(allocationsCompareDsc); - Assert.assertNotNull(deallocationsCompareAsc); - Assert.assertNotNull(deallocationsCompareDsc); - Assert.assertNotNull(totalCompareAsc); - Assert.assertNotNull(totalCompareDsc); - Assert.assertNotNull(shallowSizeCompareAsc); - Assert.assertNotNull(shallowSizeCompareDsc); - Assert.assertNotNull(classNameString); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeTest.java deleted file mode 100644 index ad8e25855..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/treetable/DataNodeTest.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package ohos.devtools.views.common.treetable; - -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.ViewConstants; -import ohos.devtools.views.common.chart.treetable.DataNode; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; - -/** - * DataNodeTest - * - * @Description DataNode test - * @Date 2021/4/3 20:29 - **/ -public class DataNodeTest { - /** - * id - */ - private Integer id = ViewConstants.NUM_2; - - /** - * cId - */ - private Integer cId = ViewConstants.NUM_3; - - /** - * heapId - */ - private Integer heapId = ViewConstants.NUM_4; - - /** - * sessionId - */ - private Long sessionId = Constant.ABNORMAL; - - /** - * className - */ - private String className = Constant.CPU_PLUG_NAME; - - /** - * allocations - */ - private Integer allocations = ViewConstants.NUM_5; - - /** - * deallocations - */ - private Integer deallocations = ViewConstants.NUM_6; - - /** - * totalCount - */ - private Integer totalCount = ViewConstants.NUM_7; - - /** - * shallowSize - */ - private Long shallowSize = Constant.ABNORMAL; - - /** - * dataNode - */ - private DataNode dataNode = new DataNode(); - - /** - * dataNodeOteher - */ - private DataNode dataNodeOteher = new DataNode(); - - /** - * children - */ - private ArrayList children = new ArrayList<>(); - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Before - public void initObj() { - dataNode.setId(id); - dataNode.setcId(cId); - dataNode.setHeapId(heapId); - dataNode.setSessionId(sessionId); - dataNode.setClassName(className); - dataNode.setAllocations(allocations); - dataNode.setDeallocations(deallocations); - dataNode.setTotalCount(totalCount); - dataNode.setShallowSize(shallowSize); - dataNode.setChildren(children); - dataNodeOteher.setId(2); - dataNodeOteher.setcId(2); - dataNodeOteher.setHeapId(2); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getIdTest() { - int idTest = dataNode.getId(); - Assert.assertEquals(idTest, ViewConstants.NUM_2); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getCIdTest() { - int cidTest = dataNode.getcId(); - Assert.assertEquals(cidTest, ViewConstants.NUM_3); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getHeapIdTest() { - int heapIdTest = dataNode.getHeapId(); - Assert.assertEquals(heapIdTest, ViewConstants.NUM_4); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getSessionIdTest() { - long num = dataNode.getSessionId(); - Assert.assertEquals(num, -1); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getClassNameTest() { - String name = dataNode.getClassName(); - Assert.assertEquals(name, Constant.CPU_PLUG_NAME); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getAllocationsTest() { - int num = dataNode.getAllocations(); - Assert.assertEquals(num, ViewConstants.NUM_5); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getDeallocationsTest() { - int num = dataNode.getDeallocations(); - Assert.assertEquals(num, ViewConstants.NUM_6); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getTotalCountTest() { - int num = dataNode.getTotalCount(); - Assert.assertEquals(num, ViewConstants.NUM_7); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void getShallowSizeTest() { - long num = dataNode.getShallowSize(); - Assert.assertEquals(num, -1); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void addChildrenTest() { - dataNode.addChildren(dataNode); - ArrayList childrenTest = dataNode.getChildren(); - Assert.assertNotNull(childrenTest); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void equalsTest() { - boolean flag = dataNode.equals(dataNodeOteher); - Assert.assertFalse(flag); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void equalsTest1() { - boolean flag = dataNode.equals(dataNode); - Assert.assertTrue(flag); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void hashCodeTest() { - int num = dataNode.hashCode(); - Assert.assertNotNull(num); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void toStrTest() { - String str = dataNode.toStr(); - Assert.assertNotNull(str); - } - - /** - * functional testing - * - * @tc.name: sort - * @tc.number: OHOS_JAVA_treetable_DataNode_initObj - * @tc.desc: sort - * @tc.type: functional testing - * @tc.require: SR000FK5S6 - */ - @Test - public void toStringTest() { - String str = dataNode.toString(); - Assert.assertNotNull(str); - } - -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/HomeWindowTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/HomeWindowTest.java deleted file mode 100644 index 943c3142c..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/HomeWindowTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.views.layout.swing.HomeWindow; -import org.apache.logging.log4j.Level; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description frame test - * @Date 2021/4/2 11:25 - **/ -public class HomeWindowTest { - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HomeWindow_data_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void data() { - // Application initialization Step1 Initialize the data center - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HomeWindow_getHomeWindow_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getHomeWindow() { - new HomeWindow(); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemConfigPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemConfigPanelTest.java new file mode 100644 index 000000000..eee40feb9 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemConfigPanelTest.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout; + +import com.intellij.ui.components.JBCheckBox; +import com.intellij.ui.components.JBPanel; +import org.junit.Assert; +import org.junit.Test; + +import java.awt.event.MouseEvent; +import java.util.ArrayList; + +/** + * SystemConfigPanelTest + */ +public class SystemConfigPanelTest { + /** + * get Instance addActionListenerTest + * + * @tc.name: addActionListenerTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_addActionListenerTest_0001 + * @tc.desc: addActionListenerTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void addActionListenerTest01() { + new SystemConfigPanel(new TaskPanel()).addActionListener(new JBCheckBox()); + Assert.assertTrue(true); + } + + /** + * get Instance addDeviceRefreshTest + * + * @tc.name: addDeviceRefreshTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_addDeviceRefreshTest_0001 + * @tc.desc: addDeviceRefreshTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void addDeviceRefreshTest01() { + new SystemConfigPanel(new TaskPanel()).addDeviceRefresh(); + Assert.assertTrue(true); + } + + /** + * get Instance mouseReleasedTest + * + * @tc.name: mouseReleasedTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_mouseReleasedTest_0001 + * @tc.desc: mouseReleasedTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void mouseReleasedTest01() { + JBPanel jBPanel = new JBPanel(); + MouseEvent mouseEvent = new MouseEvent(jBPanel, 1, 1, 1, 1, 1, 1, true, 1); + new SystemConfigPanel(new TaskPanel()).mouseReleased(mouseEvent); + Assert.assertTrue(true); + } + + /** + * get Instance getClassificationSelectTest + * + * @tc.name: getClassificationSelectTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_getClassificationSelectTest_0001 + * @tc.desc: getClassificationSelectTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getClassificationSelectTest01() { + boolean flag = new SystemConfigPanel(new TaskPanel()).getClassificationSelect(); + Assert.assertTrue(flag); + } + + /** + * get Instance getEventTest + * + * @tc.name: getEventTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_getEventTest_0001 + * @tc.desc: getEventTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getEventTest01() { + new SystemConfigPanel(new TaskPanel()).getEvent(new ArrayList<>(), new ArrayList<>()); + Assert.assertTrue(true); + } + + /** + * get Instance itemStateChangedTest + * + * @tc.name: itemStateChangedTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_itemStateChangedTest_0001 + * @tc.desc: itemStateChangedTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void itemStateChangedTest01() { + new SystemConfigPanel(new TaskPanel()).itemStateChanged(null); + Assert.assertTrue(true); + } + + /** + * get Instance itemStateChangedTest + * + * @tc.name: itemStateChangedTest + * @tc.number: OHOS_JAVA_layout_SystemConfigPanel_itemStateChangedTest_0002 + * @tc.desc: itemStateChangedTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void itemStateChangedTest02() { + new SystemConfigPanel(new TaskPanel()).addDeviceRefresh(); + new SystemConfigPanel(new TaskPanel()).itemStateChanged(null); + Assert.assertTrue(true); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/GraphicsJpanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemPanelTest.java similarity index 57% rename from host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/GraphicsJpanelTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemPanelTest.java index 15717be1f..4f26562ac 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/GraphicsJpanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/SystemPanelTest.java @@ -13,27 +13,28 @@ * limitations under the License. */ -package ohos.devtools.views.layout.swing; +package ohos.devtools.views.layout; +import com.intellij.ui.components.JBPanel; +import org.junit.Assert; import org.junit.Test; /** - * @Description GraphicsJpanelTest - * @Date 2021/4/3 14:35 - **/ -public class GraphicsJpanelTest { + * SystemPanelTest + */ +public class SystemPanelTest { /** - * functional testing + * get Instance getSystemPanelTest * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_GraphicsJpanel_paint_0001 - * @tc.desc: chart scene test + * @tc.name: getSystemPanelTest + * @tc.number: OHOS_JAVA_layout_SystemPanel_getSystemPanelTest_0001 + * @tc.desc: getSystemPanelTest * @tc.type: functional testing - * @tc.require: SR-002-AR-001 + * @tc.require: SR-010 */ @Test - public void paint() { - GraphicsJpanel graphicsJpanel = new GraphicsJpanel(new TaskPanel()); - graphicsJpanel.repaint(); + public void getSystemPanelTest01() { + SystemPanel systemPanel = new SystemPanel(new JBPanel(), null); + Assert.assertNotNull(systemPanel); } -} \ No newline at end of file +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ItemsViewTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ItemsViewTest.java new file mode 100644 index 000000000..afaa04e8f --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ItemsViewTest.java @@ -0,0 +1,84 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview; + +import ohos.devtools.views.common.LayoutConstants; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Items View Test + */ +public class ItemsViewTest { + private static final int TEST_START = 0; + + private static final int TEST_END = 1000; + + private ItemsView items; + + private ProfilerChartsView view; + + private void initView() { + view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + view.getPublisher().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); + } + + /** + * init + * + * @tc.name: DiskIoViewTest + * @tc.number: OHOS_JAVA_View_ItemsView_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + initView(); + items = new ItemsView(view); + } + + /** + * Items View Test + * + * @tc.name: ItemsViewTest + * @tc.number: OHOS_JAVA_View_ItemsView_ItemsViewTest_0001 + * @tc.desc: Items View Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void itemsViewTest() { + ItemsView itemsView = new ItemsView(view); + Assert.assertNotNull(itemsView); + } + + /** + * update Show Height Test + * + * @tc.name: updateShowHeightTest + * @tc.number: OHOS_JAVA_View_ItemsView_updateShowHeightTest_0001 + * @tc.desc: update Show Height Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void updateShowHeightTest() { + items.updateShowHeight(1); + Assert.assertTrue(true); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerChartsViewTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerChartsViewTest.java index b6755751e..f292c5416 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerChartsViewTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerChartsViewTest.java @@ -16,18 +16,16 @@ package ohos.devtools.views.layout.chartview; import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.ProfilerMonitorItem; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.memory.MemoryItemView; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.swing.JPanel; +import java.lang.reflect.InvocationTargetException; /** * ProfilerChartsView test - * - * @since 2021/2/10 10:43 */ public class ProfilerChartsViewTest { /** @@ -94,70 +92,16 @@ public class ProfilerChartsViewTest { * @tc.desc: chart Memory test * @tc.type: functional test * @tc.require: SR-002-AR-001 + * @throws InvocationTargetException InvocationTargetException + * @throws NoSuchMethodException NoSuchMethodException + * @throws InstantiationException InstantiationException + * @throws IllegalAccessException IllegalAccessException */ @Test - public void addMonitorItemViewTest() { - view.addMonitorItemView(ProfilerMonitorItem.MEMORY); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_addMemoryStageView_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-002-AR-001 - */ - @Test - public void addMemoryStageViewTest() { - MemoryStageView memoryStageView = view.addMemoryStageView(); - Assert.assertNotNull(memoryStageView); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_compRulerDrawn_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-002-AR-001 - */ - @Test - public void compRulerDrawnTest() { - view.compRulerDrawn(new JPanel()); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_resetRulerDrawStatus_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-002-AR-001 - */ - @Test - public void resetRulerDrawStatusTest() { - view.resetRulerDrawStatus(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_refreshCompRuler_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-002-AR-001 - */ - @Test - public void refreshCompRulerTest() { - view.refreshCompRuler(); + public void addMonitorItemViewTest() + throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + view.addMonitorItemView(memoryItem); Assert.assertTrue(true); } @@ -175,19 +119,4 @@ public class ProfilerChartsViewTest { JPanel jPanel = view.getMainPanel(); Assert.assertNotNull(jPanel); } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_getRulerXCoordinate_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-002-AR-001 - */ - @Test - public void getRulerXCoordinateTest() { - int number = view.getRulerXCoordinate(); - Assert.assertNotNull(number); - } } diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerScrollbarTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerScrollbarTest.java similarity index 93% rename from host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerScrollbarTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerScrollbarTest.java index 7234b2abd..955274d46 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/common/chart/ProfilerScrollbarTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/ProfilerScrollbarTest.java @@ -13,11 +13,9 @@ * limitations under the License. */ -package ohos.devtools.views.common.chart; +package ohos.devtools.views.layout.chartview; import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -27,8 +25,6 @@ import java.awt.AWTException; /** * profiler scrollbar test - * - * @since 2021/3/31 15:44 */ public class ProfilerScrollbarTest { private ProfilerScrollbar bar; diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanelTest.java new file mode 100644 index 000000000..c9877857e --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryAgentHeapInfoPanelTest.java @@ -0,0 +1,79 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ItemsView; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Memory Agent Heap Info Panel Test + */ +public class MemoryAgentHeapInfoPanelTest { + private static final int TEST_START = 0; + private static final int TEST_END = 1000; + private MemoryItemView memoryItemView; + private MemoryAgentHeapInfoPanel memoryAgentHeapInfoPanel; + private ProfilerChartsView view; + + private void initView() { + view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + view.getPublisher().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); + } + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_View_MemoryAgentHeapInfoPanel_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + initView(); + ItemsView itemsView = new ItemsView(view); + memoryItemView = new MemoryItemView(); + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + memoryItemView.init(view, itemsView, memoryItem); + memoryAgentHeapInfoPanel = new MemoryAgentHeapInfoPanel(memoryItemView, 1L, "Test"); + } + + /** + * Memory Agent Heap Info Panel Test + * + * @tc.name: MemoryAgentHeapInfoPanelTest + * @tc.number: OHOS_JAVA_View_MemoryAgentHeapInfoPanel_MemoryAgentHeapInfoPanelTest_0001 + * @tc.desc: Memory Agent Heap Info Panel Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void memoryAgentHeapInfoPanelTest() { + ItemsView itemsView = new ItemsView(view); + memoryItemView = new MemoryItemView(); + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + memoryItemView.init(view, itemsView, memoryItem); + MemoryAgentHeapInfoPanel memoryAgentHeapInfo = new MemoryAgentHeapInfoPanel(memoryItemView, 1L, "Test"); + Assert.assertNotNull(memoryAgentHeapInfo); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryItemViewTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryItemViewTest.java new file mode 100644 index 000000000..47fbc0827 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryItemViewTest.java @@ -0,0 +1,104 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ItemsView; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Memory Item View Test + */ +public class MemoryItemViewTest { + private static final int TEST_START = 0; + private static final int TEST_END = 1000; + private MemoryItemView memoryItemView; + private ProfilerChartsView view; + + private void initView() { + view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + view.getPublisher().getStandard().updateDisplayTimeRange(TEST_START, TEST_END); + } + + /** + * init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_View_MemoryItemView_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Before + public void init() { + initView(); + ItemsView itemsView = new ItemsView(view); + memoryItemView = new MemoryItemView(); + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + memoryItemView.init(view, itemsView, memoryItem); + } + + /** + * get SemiSimplified Clock String Test + * + * @tc.name: getSemiSimplifiedClockStringTest + * @tc.number: OHOS_JAVA_View_MemoryItemView_getSemiSimplifiedClockStringTest_0001 + * @tc.desc: get SemiSimplified Clock String Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getSemiSimplifiedClockStringTest() { + String semiSimplifiedClockString = memoryItemView.getSemiSimplifiedClockString(1L); + Assert.assertNotNull(semiSimplifiedClockString); + } + + /** + * get Full Clock String Tes + * + * @tc.name: getFullClockStringTes + * @tc.number: OHOS_JAVA_View_MemoryItemView_getFullClockStringTes_0001 + * @tc.desc: get Full Clock String Tes + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void getFullClockStringTes() { + String fullClockString = memoryItemView.getFullClockString(1L); + Assert.assertNotNull(fullClockString); + } + + /** + * set Third Level TreeTable Test + * + * @tc.name: setThirdLevelTreeTableTest + * @tc.number: OHOS_JAVA_View_MemoryItemView_setThirdLevelTreeTableTest_0001 + * @tc.desc: set Third Level TreeTable Test + * @tc.type: functional testing + * @tc.require: AR000FK5UI + */ + @Test + public void setThirdLevelTreeTableTest() { + JBPanel jbPanel = memoryItemView.setThirdLevelTreeTable(1L, 1, "Test"); + Assert.assertNotNull(jbPanel); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanelTest.java new file mode 100644 index 000000000..4858e2826 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/memory/MemoryTreeTablePanelTest.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.layout.chartview.memory; + +import org.junit.Assert; +import org.junit.Test; + +/** + * MemoryTreeTablePanelTest + */ +public class MemoryTreeTablePanelTest { + /** + * getMemoryTreeTablePanelTest + * + * @tc.name: getMemoryTreeTablePanelTest + * @tc.number: OHOS_JAVA_memory_MemoryTreeTablePanel_getMemoryTreeTablePanelTest_0001 + * @tc.desc: getMemoryTreeTablePanelTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getMemoryTreeTablePanelTest01() { + MemoryTreeTablePanel memoryTreeTablePanel = + new MemoryTreeTablePanel(new MemoryItemView(), 10L, "chartName"); + Assert.assertNotNull(memoryTreeTablePanel); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/CacheObserverTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/CacheObserverTest.java deleted file mode 100644 index 204157be8..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/CacheObserverTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description CacheObserver test - * @Date 2021/4/2 11:25 - **/ -public class CacheObserverTest { - /** - * Cache observer - */ - public CacheObserver cacheObserver; - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_init_0001 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - cacheObserver = new CacheObserver(37L); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_refreshStandard_0001 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshStandard() { - cacheObserver.refreshStandard(new ChartStandard(37L), 10, 50, 30); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_refreshView_0001 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshView01() { - cacheObserver.refreshView(new ChartDataRange(), 21L, true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_refreshView_0002 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshView02() { - ChartDataRange chartDataRange = new ChartDataRange(); - chartDataRange.setEndTime(-2); - cacheObserver.refreshView(chartDataRange, 21L, false); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_refreshView_0003 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshView03() { - ChartDataRange chartDataRange = new ChartDataRange(); - chartDataRange.setEndTime(510); - cacheObserver.refreshView(chartDataRange, 21L, true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_CacheObserver_refreshView_0004 - * @tc.desc: chart CacheObserver test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshView04() { - ChartDataRange chartDataRange = new ChartDataRange(); - chartDataRange.setEndTime(510); - cacheObserver.refreshView(chartDataRange, 21L, false); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserverTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserverTest.java index 10749a7a0..ba8e1d9e6 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserverTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryChartObserverTest.java @@ -20,21 +20,21 @@ import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; import ohos.devtools.views.charts.model.ChartDataRange; import ohos.devtools.views.charts.model.ChartStandard; import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.ProfilerMonitorItem; +import ohos.devtools.views.layout.chartview.ProfilerMonitorItem; import ohos.devtools.views.layout.chartview.ProfilerChartsView; import ohos.devtools.views.layout.chartview.event.IChartEventObserver; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.memory.MemoryItemView; import org.apache.logging.log4j.Level; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.lang.reflect.InvocationTargetException; import java.util.List; /** * MemoryChartObserver test - * - * @since 2021/3/31 20:03 */ public class MemoryChartObserverTest { private static final int TEST_START = 0; @@ -59,9 +59,14 @@ public class MemoryChartObserverTest { DataBaseApi apo = DataBaseApi.getInstance(); apo.initDataSourceManager(); ProfilerChartsView view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); - view.addMonitorItemView(ProfilerMonitorItem.MEMORY); - - List observers = view.getObserver().getListeners(); + try { + ProfilerMonitorItem memoryItem = new ProfilerMonitorItem(2, "Memory", MemoryItemView.class); + view.addMonitorItemView(memoryItem); + } catch (InvocationTargetException | NoSuchMethodException | InstantiationException + | IllegalAccessException operationException) { + operationException.printStackTrace(); + } + List observers = view.getPublisher().getObservers(); for (IChartEventObserver event : observers) { if (event instanceof MemoryChartObserver) { observer = (MemoryChartObserver) event; @@ -80,11 +85,29 @@ public class MemoryChartObserverTest { * @tc.require: SR-001-AR-003 */ @Test - public void refreshStandardTest() { + public void refreshStandardTest01() { ChartStandard newStandard = new ChartStandard(0L); newStandard.setMaxDisplayMillis(TEST_DISPLAY); newStandard.setMinMarkInterval(TEST_MARK); - observer.refreshStandard(newStandard, TEST_START, TEST_END, TEST_DISPLAY); + observer.refreshStandard(TEST_START, TEST_END, TEST_DISPLAY, newStandard.getMinMarkInterval()); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_MemoryChartObserver_init_0002 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void refreshStandardTest02() { + ChartStandard newStandard = new ChartStandard(-1L); + newStandard.setMaxDisplayMillis(TEST_DISPLAY); + newStandard.setMinMarkInterval(TEST_MARK); + observer.refreshStandard(TEST_START, TEST_END, TEST_DISPLAY, newStandard.getMinMarkInterval()); Assert.assertTrue(true); } diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserverTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserverTest.java deleted file mode 100644 index 64763af25..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/MemoryStageObserverTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.ProfilerMonitorItem; -import ohos.devtools.views.layout.chartview.MemoryStageView; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.chartview.event.IChartEventObserver; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -/** - * MemoryStageObserver test - * - * @since 2021/3/31 20:16 - */ -public class MemoryStageObserverTest { - private static final int TEST_START = 0; - - private static final int TEST_END = 9000; - - private static final int TEST_DISPLAY = 10000; - - private static final int TEST_MARK = 1000; - - private MemoryStageObserver observer; - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_MemoryStageObserver_init_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - ProfilerChartsView view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); - view.addMonitorItemView(ProfilerMonitorItem.MEMORY); - MemoryStageView memoryStageView = view.addMemoryStageView(); - memoryStageView.addChart(); - - List observers = view.getObserver().getListeners(); - for (IChartEventObserver event : observers) { - if (event instanceof MemoryStageObserver) { - observer = (MemoryStageObserver) event; - break; - } - } - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_MemoryStageObserver_refreshStandard_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshStandardTest() { - ChartStandard newStandard = new ChartStandard(0L); - newStandard.setMaxDisplayMillis(TEST_DISPLAY); - newStandard.setMinMarkInterval(TEST_MARK); - observer.refreshStandard(newStandard, TEST_START, TEST_END, TEST_DISPLAY); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_MemoryStageObserver_refreshView_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void refreshViewTest() { - ChartDataRange range = new ChartDataRange(); - range.setStartTime(TEST_START); - range.setEndTime(TEST_END); - observer.refreshView(range, 0L, false); - Assert.assertTrue(true); - } -} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserverTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisherTest.java similarity index 88% rename from host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserverTest.java rename to host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisherTest.java index 33a0cc8b8..77df82c2c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewObserverTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/ProfilerChartsViewPublisherTest.java @@ -1,297 +1,297 @@ -/* - * 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. - */ - -package ohos.devtools.views.layout.chartview.observer; - -import ohos.devtools.datasources.utils.common.util.DateTimeUtil; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.views.charts.model.ChartDataRange; -import ohos.devtools.views.charts.model.ChartStandard; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import ohos.devtools.views.layout.chartview.event.IChartEventObserver; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static ohos.devtools.views.common.LayoutConstants.CHART_START_DELAY; - -/** - * ProfilerChartsViewObserver test - * - * @since 2021/3/31 18:46 - */ -public class ProfilerChartsViewObserverTest { - /** - * log - */ - private static final Logger LOGGER = LogManager.getLogger(ProfilerChartsViewObserverTest.class); - - /** - * Chart RUN_NAME - */ - private static final String RUN_NAME = "ProfilerChartsViewMonitorTimer"; - - /** - * Chart RUN_NAME_SCROLLBAR - */ - private static final String RUN_NAME_SCROLLBAR = "ScrollbarTimer"; - - private static final long TEST_START_LONG = 1617188313000L; - - private static final long TEST_END_LONG = 1617188323111L; - - private static final int TEST_START = 0; - - private static final int TEST_END = 9000; - - private static final int TEST_DISPLAY = 10000; - - private static final int TEST_MARK = 1000; - - private static final int TEST_NEW_START = 2000; - - private static final int TEST_NEW_END = 12000; - - private ProfilerChartsViewObserver observer; - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_init_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Before - public void init() { - ProfilerChartsView view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); - observer = view.getObserver(); - boolean isScrollbarShow = false; - ChartStandard standard = new ChartStandard(324L); - standard.setFirstTimestamp(32478L); - standard.setLastTimestamp(3274973L); - standard.updateSelectedStart(3); - standard.updateSelectedEnd(34453); - QuartzManager.getInstance().addExecutor(RUN_NAME, () -> { - // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 - standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - CHART_START_DELAY); - int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; - }); - QuartzManager.getInstance().addExecutor(RUN_NAME_SCROLLBAR, () -> { - // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 - standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - CHART_START_DELAY); - int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); - int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; - }); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_showTraceResult_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void showTraceResultTest() { - observer.showTraceResult(TEST_START_LONG, TEST_END_LONG); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_startRefresh_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void startRefreshTest() { - observer.startRefresh(TEST_START_LONG); - destroy(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_pauseRefresh_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void pauseRefreshTest() { - observer.startRefresh(TEST_START_LONG); - observer.pauseRefresh(); - destroy(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_stopRefresh_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void stopRefreshTest() { - observer.startRefresh(TEST_START_LONG); - observer.stopRefresh(false); - destroy(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_restartRefresh_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void restartRefreshTest() { - observer.startRefresh(TEST_START_LONG); - observer.stopRefresh(false); - observer.restartRefresh(); - destroy(); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_attach_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void attachTest() { - IChartEventObserver ob = new IChartEventObserver() { - @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - } - - @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { - } - }; - observer.attach(ob); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_detach_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void detachTest() { - IChartEventObserver ob = new IChartEventObserver() { - @Override - public void refreshStandard(ChartStandard standard, int startTime, int endTime, int maxDisplayTime) { - } - - @Override - public void refreshView(ChartDataRange range, long firstTimestamp, boolean isUseCache) { - } - }; - observer.attach(ob); - observer.detach(ob); - observer.detach(null); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_notifyRefresh_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void notifyRefreshTest() { - observer.notifyRefresh(TEST_START, TEST_END); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_charZoom_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void charZoomTest() { - observer.charZoom(TEST_START, TEST_END, TEST_DISPLAY); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_msTimeZoom_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - @Test - public void msTimeZoomTest() { - observer.msTimeZoom(TEST_DISPLAY, TEST_MARK, TEST_NEW_START, TEST_NEW_END); - Assert.assertTrue(true); - } - - /** - * functional test - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ProfilerChartsView_destroy_0001 - * @tc.desc: chart Memory test - * @tc.type: functional test - * @tc.require: SR-001-AR-003 - */ - private void destroy() { - QuartzManager.getInstance().endExecutor(RUN_NAME); - QuartzManager.getInstance().endExecutor(RUN_NAME_SCROLLBAR); - } -} +/* + * 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. + */ + +package ohos.devtools.views.layout.chartview.observer; + +import ohos.devtools.datasources.utils.common.util.DateTimeUtil; +import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; +import ohos.devtools.views.charts.model.ChartDataRange; +import ohos.devtools.views.charts.model.ChartStandard; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.layout.chartview.ProfilerChartsView; +import ohos.devtools.views.layout.chartview.event.IChartEventObserver; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import static ohos.devtools.views.layout.chartview.utils.ChartViewConstants.CHART_START_DELAY; + +/** + * ProfilerChartsViewObserver test + */ +public class ProfilerChartsViewPublisherTest { + /** + * log + */ + private static final Logger LOGGER = LogManager.getLogger(ProfilerChartsViewPublisherTest.class); + + /** + * Chart RUN_NAME + */ + private static final String RUN_NAME = "ProfilerChartsViewMonitorTimer"; + + /** + * Chart RUN_NAME_SCROLLBAR + */ + private static final String RUN_NAME_SCROLLBAR = "ScrollbarTimer"; + + private static final String CHART_NAME = "Test"; + + private static final long TEST_START_LONG = 1617188313000L; + + private static final long TEST_END_LONG = 1617188323111L; + + private static final int TEST_START = 0; + + private static final int TEST_END = 9000; + + private static final int TEST_DISPLAY = 10000; + + private static final int TEST_MARK = 1000; + + private static final int TEST_NEW_START = 2000; + + private static final int TEST_NEW_END = 12000; + + private ProfilerChartsViewPublisher observer; + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_init_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Before + public void init() { + ProfilerChartsView view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); + observer = view.getPublisher(); + boolean isScrollbarShow = false; + ChartStandard standard = new ChartStandard(324L); + standard.setFirstTimestamp(32478L); + standard.setLastTimestamp(3274973L); + standard.updateSelectedStart(CHART_NAME, 3); + standard.updateSelectedEnd(CHART_NAME, 34453); + QuartzManager.getInstance().addExecutor(RUN_NAME, () -> { + // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 + standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - CHART_START_DELAY); + int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); + int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; + }); + QuartzManager.getInstance().addExecutor(RUN_NAME_SCROLLBAR, () -> { + // 保存LastTimestamp,为当前时间戳减去Chart启动延迟 + standard.setLastTimestamp(DateTimeUtil.getNowTimeLong() - CHART_START_DELAY); + int end = (int) (standard.getLastTimestamp() - standard.getFirstTimestamp()); + int start = end > standard.getMaxDisplayMillis() ? end - standard.getMaxDisplayMillis() : 0; + }); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_showTraceResult_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void showTraceResultTest() { + observer.showTraceResult(TEST_START_LONG, TEST_END_LONG); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_startRefresh_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void startRefreshTest() { + observer.startRefresh(TEST_START_LONG); + destroy(); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_pauseRefresh_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void pauseRefreshTest() { + observer.startRefresh(TEST_START_LONG); + observer.pauseRefresh(); + destroy(); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_stopRefresh_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void stopRefreshTest() { + observer.startRefresh(TEST_START_LONG); + observer.stopRefresh(false); + destroy(); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_restartRefresh_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void restartRefreshTest() { + observer.startRefresh(TEST_START_LONG); + observer.stopRefresh(false); + observer.restartRefresh(); + destroy(); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_attach_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void attachTest() { + IChartEventObserver ob = new IChartEventObserver() { + @Override + public void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval) { + } + + @Override + public void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache) { + } + }; + observer.attach(ob); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_detach_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void detachTest() { + IChartEventObserver ob = new IChartEventObserver() { + @Override + public void refreshStandard(int startTime, int endTime, int maxDisplayMillis, int minMarkInterval) { + } + + @Override + public void refreshView(ChartDataRange range, long firstTimestamp, boolean useCache) { + } + }; + observer.attach(ob); + observer.detach(ob); + observer.detach(null); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_notifyRefresh_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void notifyRefreshTest() { + observer.notifyRefresh(TEST_START, TEST_END); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_charZoom_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void charZoomTest() { + observer.charZoom(TEST_START, TEST_END, TEST_DISPLAY); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_msTimeZoom_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + @Test + public void msTimeZoomTest() { + observer.msTimeZoom(TEST_DISPLAY, TEST_MARK, TEST_NEW_START, TEST_NEW_END); + Assert.assertTrue(true); + } + + /** + * functional test + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_ProfilerChartsView_destroy_0001 + * @tc.desc: chart Memory test + * @tc.type: functional test + * @tc.require: SR-001-AR-003 + */ + private void destroy() { + QuartzManager.getInstance().endExecutor(RUN_NAME); + QuartzManager.getInstance().endExecutor(RUN_NAME_SCROLLBAR); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/TimelineObserverTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/TimelineObserverTest.java index d55321a6b..5d0aaabbd 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/TimelineObserverTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/chartview/observer/TimelineObserverTest.java @@ -20,7 +20,7 @@ import ohos.devtools.views.charts.model.ChartStandard; import ohos.devtools.views.common.LayoutConstants; import ohos.devtools.views.layout.chartview.ProfilerChartsView; import ohos.devtools.views.layout.chartview.event.IChartEventObserver; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -29,8 +29,6 @@ import java.util.List; /** * TimelineObserver test - * - * @since 2021/3/31 19:51 */ public class TimelineObserverTest { private static final int TEST_START = 0; @@ -55,7 +53,7 @@ public class TimelineObserverTest { @Before public void init() { ProfilerChartsView view = new ProfilerChartsView(LayoutConstants.NUM_L, true, new TaskScenePanelChart()); - List observers = view.getObserver().getListeners(); + List observers = view.getPublisher().getObservers(); for (IChartEventObserver event : observers) { if (event instanceof TimelineObserver) { observer = (TimelineObserver) event; @@ -78,7 +76,7 @@ public class TimelineObserverTest { ChartStandard newStandard = new ChartStandard(0L); newStandard.setMaxDisplayMillis(TEST_DISPLAY); newStandard.setMinMarkInterval(TEST_MARK); - observer.refreshStandard(newStandard, TEST_START, TEST_END, TEST_DISPLAY); + observer.refreshStandard(TEST_START, TEST_END, TEST_DISPLAY, newStandard.getMinMarkInterval()); Assert.assertTrue(true); } diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEventTest.java deleted file mode 100644 index 8a045a87f..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessJpanelEventTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.datasources.utils.quartzmanager.QuartzManager; -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.layout.swing.DeviceProcessJpanel; -import ohos.devtools.views.layout.swing.TaskScenePanel; -import org.apache.logging.log4j.Level; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; -import java.util.ArrayList; -import java.util.List; - -import static ohos.devtools.views.common.Constant.DEVICEREFRESH; - -/** - * @Description DeviceProcessJpanelEventTest - * @Date 2021/4/3 16:14 - **/ -public class DeviceProcessJpanelEventTest { - private DeviceProcessJpanelEvent deviceProcessJpanelEvent; - private DeviceProcessJpanel deviceProcessJpanel; - private List processInfos; - private TaskScenePanel taskScenePanel; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_init_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Before - public void init() { - SessionManager.getInstance().setDevelopMode(true); - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - MultiDeviceManager.getInstance(); - processInfos = new ArrayList<>(); - ProcessInfo process = new ProcessInfo(); - process.setDeviceId("fffff"); - process.setProcessId(43543); - process.setProcessName("435gs"); - processInfos.add(process); - deviceProcessJpanel = new DeviceProcessJpanel(new TaskScenePanelEvent(), new JPanel(), new TaskScenePanel()); - deviceProcessJpanelEvent = new DeviceProcessJpanelEvent(); - deviceProcessJpanelEvent.searchJButtonSelect(deviceProcessJpanel, processInfos); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_devicesInfoJComboBoxUpdate_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void devicesInfoJComboBoxUpdateTest01() { - deviceProcessJpanelEvent.devicesInfoJComboBoxUpdate(deviceProcessJpanel); - QuartzManager.getInstance().startExecutor(DEVICEREFRESH, 0, 5); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_searchJButtonSelect_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void searchJButtonSelectTest() { - List processInfo = new ArrayList<>(); - deviceProcessJpanelEvent.searchJButtonSelect(deviceProcessJpanel, processInfo); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_itemStateChanged_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void itemStateChangedTest01() { - deviceProcessJpanelEvent.itemStateChanged(deviceProcessJpanel, taskScenePanel, "test", new JPanel()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_itemStateChanged_0002 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void itemStateChangedTest02() { - deviceProcessJpanelEvent.itemStateChanged(deviceProcessJpanel, taskScenePanel, "", new JPanel()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_itemStateChanged_0003 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void itemStateChangedTest03() { - deviceProcessJpanelEvent.itemStateChanged(deviceProcessJpanel, taskScenePanel, "", null); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_itemStateChanged_0004 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-001-AR-001 - */ - @Test - public void itemStateChangedTest04() { - deviceProcessJpanelEvent.itemStateChanged(deviceProcessJpanel, taskScenePanel, null, null); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessPanelEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessPanelEventTest.java new file mode 100644 index 000000000..bcc1dd138 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/DeviceProcessPanelEventTest.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.event; + +import com.intellij.ui.components.JBPanel; +import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; +import ohos.devtools.datasources.utils.device.service.MultiDeviceManager; +import ohos.devtools.datasources.utils.process.entity.ProcessInfo; +import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; +import ohos.devtools.datasources.utils.session.service.SessionManager; +import ohos.devtools.views.layout.DeviceProcessPanel; +import org.apache.logging.log4j.Level; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Device Process panel Event Test + */ +public class DeviceProcessPanelEventTest { + private DeviceProcessPanelEvent deviceProcessPanelEvent; + private DeviceProcessPanel deviceProcessJpanel; + private List processInfos; + + /** + * functional testing + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_init_0001 + * @tc.desc: chart test + * @tc.type: functional testing + * @tc.require: SR-001-AR-001 + */ + @Before + public void init() { + SessionManager.getInstance().setDevelopMode(true); + ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); + DataBaseApi apo = DataBaseApi.getInstance(); + apo.initDataSourceManager(); + MultiDeviceManager.getInstance(); + processInfos = new ArrayList<>(); + ProcessInfo process = new ProcessInfo(); + process.setDeviceId("fffff"); + process.setProcessId(43543); + process.setProcessName("435gs"); + processInfos.add(process); + deviceProcessJpanel = new DeviceProcessPanel(new JBPanel(), 1, 0); + deviceProcessPanelEvent = new DeviceProcessPanelEvent(); + deviceProcessPanelEvent.searchJButtonSelect(deviceProcessJpanel, processInfos); + } + + /** + * functional testing + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_searchJButtonSelect_0001 + * @tc.desc: chart test + * @tc.type: functional testing + * @tc.require: SR-001-AR-001 + */ + @Test + public void searchJButtonSelectTest() { + List processInfo = new ArrayList<>(); + deviceProcessPanelEvent.searchJButtonSelect(deviceProcessJpanel, processInfo); + } + + /** + * functional testing + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_DeviceProcessJpanelEvent_itemStateChanged_0001 + * @tc.desc: chart test + * @tc.type: functional testing + * @tc.require: SR-001-AR-001 + */ + @Test + public void itemStateChangedTest01() { + deviceProcessPanelEvent.itemStateChanged(deviceProcessJpanel); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/HomeWindowEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/HomeWindowEventTest.java deleted file mode 100644 index 4c93c55e9..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/HomeWindowEventTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.views.layout.swing.HomeWindow; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description HomeWindowEventTest - * @Date 2021/4/3 16:10 - **/ -public class HomeWindowEventTest { - private HomeWindowEvent homeWindowEvent; - private HomeWindow homeWindow; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HomeWindowEvent_init_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void init() { - homeWindowEvent = new HomeWindowEvent(); - homeWindow = new HomeWindow(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HomeWindowEvent_clickAddTask_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void clickAddTaskTest() { - homeWindowEvent.clickAddTask(homeWindow); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_HomeWindowEvent_clickUpdateLogLevel_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void clickUpdateLogLevelTest() { - homeWindowEvent.clickUpdateLogLevel(homeWindow); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskPanelEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskPanelEventTest.java deleted file mode 100644 index 6689d0598..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskPanelEventTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskScenePanel; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; -import java.awt.Component; - -/** - * @Description TaskPanelEventTest - * @Date 2021/4/3 14:35 - **/ -public class TaskPanelEventTest { - private TaskScenePanelEvent taskScenePanelEvent; - private TaskScenePanel taskScenePanel; - private TaskPanel taskPanel; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_getTaskScenePanel_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void getTaskScenePanelEvent() { - taskScenePanelEvent = new TaskScenePanelEvent(); - taskScenePanel = new TaskScenePanel(); - taskPanel = new TaskPanel(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_clickClose_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void clickCloseTest() { - taskScenePanelEvent.clickAddDevice(taskScenePanel, taskScenePanelEvent); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_checkBoxSelect_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void checkBoxSelectTest() { - taskScenePanelEvent.checkBoxSelect(taskScenePanel); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_lastStep_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void lastStepTest() { - taskScenePanelEvent.lastStep(taskScenePanel, taskPanel); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_listenerJPanelSouth_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void listenerJPanelSouthTest() { - taskScenePanelEvent.listenerJPanelSouth(taskScenePanel); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_judgCompontent_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void judgCompontentTest() { - taskScenePanelEvent.judgCompontent(new Component[] {new JPanel()}, "error"); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanelEvent_startTask_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void startTaskTest() { - taskScenePanelEvent.startTask(taskScenePanel, taskPanel); - Assert.assertTrue(true); - } - -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelChartEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelChartEventTest.java index 7b0dab7ed..304394472 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelChartEventTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelChartEventTest.java @@ -15,15 +15,13 @@ package ohos.devtools.views.layout.event; -import ohos.devtools.views.common.hoscomp.HosJButton; -import ohos.devtools.views.layout.swing.TaskScenePanelChart; +import ohos.devtools.views.layout.chartview.TaskScenePanelChart; import org.junit.Before; import org.junit.Test; /** - * @Description TaskPanelEventTest - * @Date 2021/4/3 14:35 - **/ + * Task Panel Event Test + */ public class TaskScenePanelChartEventTest { private TaskScenePanelChartEvent taskScenePanelChartEvent; @@ -54,22 +52,4 @@ public class TaskScenePanelChartEventTest { public void clickDelete() { taskScenePanelChartEvent.clickDelete(new TaskScenePanelChart()); } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelChartEvent_getjButtonUp_0001 - * @tc.desc: chart Memory test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getjButtonUp() { - TaskScenePanelChart taskScenePanelChart = new TaskScenePanelChart(); - taskScenePanelChartEvent.clickDelete(taskScenePanelChart); - HosJButton jButtonDelete = taskScenePanelChart.getJButtonDelete(); - jButtonDelete.doClick(); - } - } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelEventTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelEventTest.java deleted file mode 100644 index 465167074..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/event/TaskScenePanelEventTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.event; - -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo; -import ohos.devtools.datasources.utils.process.entity.ProcessInfo; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.views.common.Constant; -import ohos.devtools.views.common.hoscomp.HosJLabel; -import ohos.devtools.views.layout.swing.TaskPanel; -import ohos.devtools.views.layout.swing.TaskScenePanel; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.util.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; -import java.awt.Component; -import java.util.HashMap; -import java.util.List; - -/** - * @Description TaskPanelEventTest - * @Date 2021/4/3 14:35 - **/ -public class TaskScenePanelEventTest { - private TaskScenePanelEvent taskScenePanelEvent; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_getTaskScenePanelEvent_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void getTaskScenePanelEvent() { - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - taskScenePanelEvent = new TaskScenePanelEvent(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_obtainMap_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void obtainMap() { - DeviceIPPortInfo deviceIPPortInfo = new DeviceIPPortInfo(); - deviceIPPortInfo.setPort(5555); - deviceIPPortInfo.setIp(""); - ProcessInfo processInfo = new ProcessInfo(); - HashMap deviceIPPortInfoProcessInfoHashMap = new HashMap<>(); - deviceIPPortInfoProcessInfoHashMap.put(deviceIPPortInfo, processInfo); - Constant.map.put("test", deviceIPPortInfoProcessInfoHashMap); - TaskScenePanel taskScenePanel = new TaskScenePanel(); - taskScenePanel.addCheckBox(); - TaskPanel taskPanel = new TaskPanel(); - List hosJLabels = taskScenePanelEvent.obtainMap(taskScenePanel, taskPanel); - Assert.isEmpty(hosJLabels); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_gain_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void gain() { - JPanel taskPanel = new JPanel(); - String gain = taskScenePanelEvent.gain(taskPanel); - org.junit.Assert.assertNotNull(gain); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_judgCompontent_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void judgCompontent() { - JPanel jPanel = new JPanel(); - JPanel jPanel2 = new JPanel(); - jPanel.add(jPanel2); - Component[] components = jPanel.getComponents(); - String test = taskScenePanelEvent.judgCompontent(components, "test"); - org.junit.Assert.assertNotNull(test); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_lastStep_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void lastStep() { - TaskScenePanel taskScenePanel = new TaskScenePanel(); - TaskPanel taskPanel = new TaskPanel(); - taskScenePanelEvent.lastStep(taskScenePanel, taskPanel); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelEvent_listenerJPanelSouth_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void listenerJPanelSouth() { - TaskScenePanel taskScenePanel = new TaskScenePanel(); - taskScenePanelEvent.listenerJPanelSouth(taskScenePanel); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/LevelTablePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/LevelTablePanelTest.java deleted file mode 100644 index 62565e96a..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/LevelTablePanelTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.chart.treetable.DataNode; -import ohos.devtools.views.common.chart.treetable.JTreeTable; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; - -/** - * @Description LevelTablePanelTest - * @Date 2021/4/2 12:57 - **/ -public class LevelTablePanelTest { - private JPanel jPanel = new JPanel(); - private LevelTablePanel LevelTablePanel; - private JTreeTable jTreeTable; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_getLevelTablePanel_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Before - public void getLevelTablePanel() { - TaskScenePanelChart panel = new TaskScenePanelChart(); - ProfilerChartsView view = new ProfilerChartsView(0L, true, panel); - ProfilerChartsView.sessionMap.put(0L, view); - - view.getObserver().getStandard().updateSelectedStart(3); - view.getObserver().getStandard().updateSelectedEnd(34453); - LevelTablePanel = new LevelTablePanel(jPanel, 0L); - Assert.assertNotNull(LevelTablePanel); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_createTable_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void createTableTest() { - LevelTablePanel.createTable(jPanel, 0L); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_getSuspensionTable_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void getSuspensionTableTest() { - LevelTablePanel.getSuspensionTable(); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_setSuspensionTable_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void setSuspensionTableTest() { - LevelTablePanel.setSuspensionTable(jPanel); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_initData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void initDataTest() { - LevelTablePanel.initData(0L); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_buildClassNode_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void buildClassNodeTest() { - DataNode dataNode = LevelTablePanel.buildClassNode(null); - Assert.assertNotNull(dataNode); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_buildClassNode_0002 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void buildClassNodeTest01() { - DataNode dataNode01 = LevelTablePanel.buildClassNode(null); - DataNode dataNode02 = LevelTablePanel.buildClassNode(null); - Assert.assertEquals(dataNode01, dataNode02); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_LevelTablePanel_selectData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-004 - */ - @Test - public void selectDataTest() { - JPanel jPanels = LevelTablePanel.selectData(jTreeTable); - Assert.assertNotNull(jPanels); - } - -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SaveTraceDialogTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SaveTraceDialogTest.java index fb3deb360..8866934ec 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SaveTraceDialogTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SaveTraceDialogTest.java @@ -1,57 +1,52 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.LayoutConstants; -import ohos.devtools.views.common.hoscomp.HosJButton; -import org.junit.Test; -import org.powermock.api.mockito.PowerMockito; - -import javax.swing.JPanel; -import java.awt.Dimension; - -/** - * Save Trace Dialog Test - * - * @version 1.0 - * @date 2021/4/2 13:00 - **/ -public class SaveTraceDialogTest { - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SaveTraceDialog_getSaveTraceDialog_0001 - * @tc.desc: chart trace test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getSaveTraceDialog() { - try { - JPanel fileJpanel = new JPanel(null); - fileJpanel.setPreferredSize(new Dimension(LayoutConstants.FOUR_HUNDRED, LayoutConstants.TWO_HUNDRED_SIXTY)); - fileJpanel.setBackground(ColorConstants.HOME_PANE); - SampleDialogWrapper mock = PowerMockito.mock(SampleDialogWrapper.class); - PowerMockito.whenNew(SampleDialogWrapper.class).withArguments("Save The Task", fileJpanel).thenReturn(mock); - SaveTraceDialog saveTraceDialog = new SaveTraceDialog(); - saveTraceDialog.showCustomDialog(new HosJButton("dd", "ddd")); - } catch (Exception exception) { - exception.printStackTrace(); - } - } +/* + * 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. + */ + +package ohos.devtools.views.layout.swing; + +import ohos.devtools.views.common.ColorConstants; +import ohos.devtools.views.common.LayoutConstants; +import ohos.devtools.views.common.customcomp.CustomJButton; +import ohos.devtools.views.layout.dialog.SampleDialog; +import ohos.devtools.views.layout.dialog.SaveTraceDialog; +import org.junit.Test; +import org.powermock.api.mockito.PowerMockito; + +import javax.swing.JPanel; +import java.awt.Dimension; + +/** + * Save Trace Dialog Test + */ +public class SaveTraceDialogTest { + /** + * functional testing + * + * @tc.name: view chart + * @tc.number: OHOS_JAVA_views_SaveTraceDialog_getSaveTraceDialog_0001 + * @tc.desc: chart trace test + * @tc.type: functional testing + * @tc.require: SR-002-AR-001 + */ + @Test + public void getSaveTraceDialog() { + JPanel fileJpanel = new JPanel(null); + fileJpanel.setPreferredSize(new Dimension(LayoutConstants.FOUR_HUNDRED, LayoutConstants.TWO_HUNDRED_SIXTY)); + fileJpanel.setBackground(ColorConstants.HOME_PANE); + SampleDialog mock = PowerMockito.mock(SampleDialog.class); + PowerMockito.whenNew(SampleDialog.class).withArguments("Save The Task", fileJpanel).thenReturn(mock); + SaveTraceDialog saveTraceDialog = new SaveTraceDialog(); + saveTraceDialog.showCustomDialog(new CustomJButton("Save", "Save Trace"), "Save The Task"); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SuspensionTablePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SuspensionTablePanelTest.java deleted file mode 100644 index 42d389012..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/SuspensionTablePanelTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.datasources.utils.session.service.SessionManager; -import ohos.devtools.views.layout.chartview.ProfilerChartsView; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.table.DefaultTableModel; - -/** - * @Description SuspensionTablePanelTest - * @Date 2021/4/3 10:33 - **/ -public class SuspensionTablePanelTest { - /** - * SESSIONID - */ - private static final long SESSIONID = 0L; - - /** - * SuspensionTablePanel - */ - private SuspensionTablePanel suspensionTablePanel = new SuspensionTablePanel(); - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_createSuspensionTableTest_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Before - public void createSuspensionTableTest() { - SessionManager.getInstance().setDevelopMode(true); - TaskScenePanelChart panel = new TaskScenePanelChart(); - ProfilerChartsView view = new ProfilerChartsView(SESSIONID, true, panel); - ProfilerChartsView.sessionMap.put(SESSIONID, view); - - view.getObserver().getStandard().updateSelectedStart(3); - view.getObserver().getStandard().updateSelectedEnd(34453); - JPanel suspensionTable = suspensionTablePanel.createSuspensionTable(new JPanel(), 1, SESSIONID, "test"); - Assert.assertNotNull(suspensionTable); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_initData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void initDataTest() { - suspensionTablePanel.initData(new DefaultTableModel(), 1, "test", SESSIONID); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_createChildTable_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void createChildTableTrueTest() { - suspensionTablePanel.createChildTable(1, true, new JPanel(), new JLayeredPane()); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_createChildTable_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void createChildTableFalseTest() { - suspensionTablePanel.createChildTable(1, false, new JPanel(), new JLayeredPane()); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_selectData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void selectDataTest() { - suspensionTablePanel.selectData(); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_insertData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void insertDataTest() { - suspensionTablePanel.insertData(new DefaultTableModel(), "2", ""); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_SuspensionTablePanel_selectData_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-001-AR-005 - */ - @Test - public void selectData() { - suspensionTablePanel.selectData(new DefaultTableModel()); - Assert.assertTrue(true); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskPanelTest.java deleted file mode 100644 index e341ffec2..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskPanelTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import com.intellij.ui.components.JBTabbedPane; -import ohos.devtools.views.common.ColorConstants; -import ohos.devtools.views.common.Constant; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import java.awt.Color; - -/** - * @Description TaskPanelTest - * @Date 2021/4/3 15:27 - **/ -public class TaskPanelTest { - private HomeWindow homeWindow; - private TaskPanel taskPanel; - private TaskPanelWelcome taskPanelWelcome; - private JPanel jPanel; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_init_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void init() { - homeWindow = new HomeWindow(); - taskPanelWelcome = new TaskPanelWelcome(); - jPanel = homeWindow.getTaskPanel(); - Constant.jtasksTab = new JBTabbedPane(); - taskPanel = new TaskPanel(jPanel, taskPanelWelcome); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_setAttributes_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setAttributesTest01() { - taskPanel.setAttributes(jPanel); - JLabel chooseButton = taskPanel.getChooseButton(); - Assert.assertEquals(Color.WHITE, chooseButton.getForeground()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_setAttributes_0002 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setAttributesTest02() { - taskPanel.setAttributes(null); - JLabel chooseButton = taskPanel.getChooseButton(); - Assert.assertEquals(Color.WHITE, chooseButton.getForeground()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_setAttributes_0003 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setAttributesTest03() { - taskPanel.setAttributes(new JPanel()); - JLabel chooseButton = taskPanel.getChooseButton(); - Assert.assertEquals(Color.WHITE, chooseButton.getForeground()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_taskLabel_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void taskLabelTest01() { - JLabel jLabel = new JLabel(); - taskPanel.taskLabel(jLabel, new JLabel(), new JLabel()); - Assert.assertEquals(ColorConstants.APPLYTUN_COLOR, jLabel.getBackground()); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskPanel_taskLabel_0002 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void taskLabelTest02() { - taskPanel.taskLabel(null, null, null); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelChartTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelChartTest.java deleted file mode 100644 index e2b7d70dc..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelChartTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import ohos.devtools.views.common.hoscomp.HosJLabel; -import org.junit.Test; - -import java.util.ArrayList; - -/** - * @Description TaskScenePanelChartTest - * @Date 2021/4/2 13:07 - **/ -public class TaskScenePanelChartTest { - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanelChart_getTaskScenePanelChart_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getTaskScenePanelChart() { - ArrayList hosJLabels = new ArrayList<>(); - HosJLabel hosJLabel = new HosJLabel(); - hosJLabel.setFirstStamp(32445L); - hosJLabels.add(hosJLabel); - new TaskScenePanelChart(new TaskPanel(), hosJLabels); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelTest.java deleted file mode 100644 index fc0fee005..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/swing/TaskScenePanelTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.swing; - -import com.intellij.ui.components.JBTabbedPane; -import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; -import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; -import ohos.devtools.views.common.Constant; -import org.apache.logging.log4j.Level; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JPanel; - -/** - * @Description TaskScenePanelTest - * @Date 2021/4/3 10:40 - **/ -public class TaskScenePanelTest { - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanel_initObj_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void initObj() { - // Application initialization Step1 Initialize the data center - ProfilerLogManager.getSingleton().updateLogLevel(Level.ERROR); - DataBaseApi apo = DataBaseApi.getInstance(); - apo.initDataSourceManager(); - Constant.jtasksTab = new JBTabbedPane(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanel_setBorderTopCenter_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setBorderTopCenterTest() { - TaskScenePanel taskScenePanel = new TaskScenePanel(new TaskPanel(new JPanel(), new TaskPanelWelcome())); - taskScenePanel.setBorderTopCenter(); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanel_addCheckBox_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void addCheckBoxTest() { - TaskScenePanel taskScenePanel = new TaskScenePanel(new TaskPanel(new JPanel(), new TaskPanelWelcome())); - taskScenePanel.addCheckBox(); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanel_setJPanelCenterRight_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setJPanelCenterRightTest() { - TaskScenePanel taskScenePanel = new TaskScenePanel(new TaskPanel(new JPanel(), new TaskPanelWelcome())); - taskScenePanel.setJPanelCenterRight(); - Assert.assertTrue(true); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_TaskScenePanel_setAttributes_0001 - * @tc.desc: chart scene test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void setAttributesTest() { - TaskScenePanel taskScenePanel = new TaskScenePanel(new TaskPanel(new JPanel(), new TaskPanelWelcome())); - taskScenePanel.setAttributes(); - Assert.assertTrue(true); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/ColorTableCellRendererTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/ColorTableCellRendererTest.java deleted file mode 100644 index 8e11e3192..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/ColorTableCellRendererTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.util; - -import com.intellij.ui.table.JBTable; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.table.DefaultTableModel; -import java.awt.Component; -import java.util.Vector; - -/** - * @Description FileUtil test - * @Date 2021/4/2 11:25 - **/ -public class ColorTableCellRendererTest { - private ColorTableCellRenderer colorTableCellRenderer; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ColorTableCellRenderer_getColorTableCellRenderer_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void getColorTableCellRenderer() { - colorTableCellRenderer = new ColorTableCellRenderer(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_ColorTableCellRenderer_getTableCellRendererComponent_0001 - * @tc.desc: chart table test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void getTableCellRendererComponent() { - JBTable jbTable = new JBTable(); - Vector vector = new Vector(3); - vector.add(0, "周杰伦"); - vector.add(1, "蔡依林"); - vector.add(2, "费玉清"); - Object obj = jbTable.getModel(); - DefaultTableModel tableModel = null; - String[] columnNames = {"列名1", "列名2", "列名3"}; - if (obj instanceof DefaultTableModel) { - tableModel = (DefaultTableModel)obj; - tableModel.setColumnIdentifiers(columnNames); - tableModel.addRow(vector); - tableModel.setValueAt("Edfs", 0, 0); - tableModel.setValueAt("Dewr", 0, 1); - tableModel.setValueAt("Iewer", 0, 2); - jbTable.setModel(tableModel); - } - String str = "sjkdlf"; - Component tableCellRendererComponent = - colorTableCellRenderer.getTableCellRendererComponent(jbTable, str, true, true, 0, 0); - Component tableCellRendererComponent1 = - colorTableCellRenderer.getTableCellRendererComponent(jbTable, str, true, true, 0, 1); - Component tableCellRendererComponent2 = - colorTableCellRenderer.getTableCellRendererComponent(jbTable, str, true, true, 0, 2); - Assert.assertNotNull(tableCellRendererComponent); - Assert.assertNotNull(tableCellRendererComponent1); - Assert.assertNotNull(tableCellRendererComponent2); - } - -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/FileUtilTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/FileUtilTest.java deleted file mode 100644 index 688997f3e..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/FileUtilTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.util; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @Description FileUtil test - * @Date 2021/4/2 11:25 - **/ -public class FileUtilTest { - private FileUtil fileUtil; - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_FileUtil_getFileUtil_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Before - public void getFileUtil() { - fileUtil = new FileUtil(); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_FileUtil_writeFile_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void writeFile() { - fileUtil.writeFile("E:\\", "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_FileUtil_writeFile_0002 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void writeFileTest01() { - fileUtil.writeFile("E:\\", ""); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_FileUtil_writeFile_0003 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void writeFileTest02() { - fileUtil.writeFile("", "test"); - } - - /** - * functional testing - * - * @tc.name: view chart - * @tc.number: OHOS_JAVA_views_FileUtil_readTxtFile_0001 - * @tc.desc: chart test - * @tc.type: functional testing - * @tc.require: SR-002-AR-001 - */ - @Test - public void readTxtFileTest01() { - String txtStr = "D:\\"; - try { - txtStr = fileUtil.readTxtFile("E:\\"); - Assert.assertNotNull(txtStr); - } catch (Exception exception) { - Assert.assertNotNull(txtStr); - } - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/SvgIconTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/SvgIconTest.java deleted file mode 100644 index 39aedd2d7..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/util/SvgIconTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.layout.util; - -/** - * @Description SvgIcon test - * @Date 2021/4/3 17:07 - **/ -public class SvgIconTest { -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/OpenFileDialogUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/OpenFileDialogUtilsTest.java new file mode 100644 index 000000000..c556441ca --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/OpenFileDialogUtilsTest.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.layout.utils; + +import com.intellij.ui.components.JBPanel; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; + +/** + * OpenFileDialogUtilsTest + */ +public class OpenFileDialogUtilsTest { + private OpenFileDialogUtils openFileDialogUtils; + + /** + * get Instance init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_layout_OpenFileDialogUtils_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Before + public void init() { + openFileDialogUtils = OpenFileDialogUtils.getInstance(); + } + + /** + * get Instance getInstanceTest + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_layout_OpenFileDialogUtils_getInstanceTest_0001 + * @tc.desc: getInstanceTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest01() { + OpenFileDialogUtils openFileDialogUtilsInstance = OpenFileDialogUtils.getInstance(); + Assert.assertNotNull(openFileDialogUtilsInstance); + } + + /** + * get Instance getInstanceTest + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_layout_OpenFileDialogUtils_getInstanceTest_0002 + * @tc.desc: getInstanceTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest02() { + OpenFileDialogUtils openFileDialogUtils1 = OpenFileDialogUtils.getInstance(); + OpenFileDialogUtils openFileDialogUtils2 = OpenFileDialogUtils.getInstance(); + Assert.assertEquals(openFileDialogUtils1, openFileDialogUtils2); + } + + /** + * get Instance loadTraceTest + * + * @tc.name: loadTraceTest + * @tc.number: OHOS_JAVA_layout_OpenFileDialogUtils_loadTraceTest_0001 + * @tc.desc: loadTraceTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void loadTraceTest01() { + openFileDialogUtils.loadTrace(new JBPanel(), new File(""), new JBPanel(), true); + Assert.assertTrue(true); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/TraceStreamerUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/TraceStreamerUtilsTest.java new file mode 100644 index 000000000..0654d8398 --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/layout/utils/TraceStreamerUtilsTest.java @@ -0,0 +1,147 @@ +/* + * 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. + */ + +package ohos.devtools.views.layout.utils; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * TraceStreamerUtilsTest + */ +public class TraceStreamerUtilsTest { + private TraceStreamerUtils traceStreamerUtils; + + /** + * get Instance init + * + * @tc.name: init + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_init_0001 + * @tc.desc: init + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Before + public void init() { + traceStreamerUtils = TraceStreamerUtils.getInstance(); + } + + /** + * get Instance getInstanceTest + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getInstanceTest_0001 + * @tc.desc: getInstanceTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest01() { + TraceStreamerUtils traceStreamerUtilsInstance = TraceStreamerUtils.getInstance(); + Assert.assertNotNull(traceStreamerUtilsInstance); + } + + /** + * get Instance getInstanceTest + * + * @tc.name: getInstanceTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getInstanceTest_0002 + * @tc.desc: getInstanceTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getInstanceTest02() { + TraceStreamerUtils traceStreamerUtils1 = TraceStreamerUtils.getInstance(); + TraceStreamerUtils traceStreamerUtils2 = TraceStreamerUtils.getInstance(); + Assert.assertEquals(traceStreamerUtils1, traceStreamerUtils2); + } + + /** + * get Instance getBaseDirTest + * + * @tc.name: getBaseDirTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getBaseDirTest_0001 + * @tc.desc: getBaseDirTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getBaseDirTest01() { + String str = traceStreamerUtils.getBaseDir(); + Assert.assertNotEquals("", str); + } + + /** + * get Instance getLogPathTest + * + * @tc.name: getLogPathTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getLogPathTest_0001 + * @tc.desc: getLogPathTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getLogPathTest01() { + String str = traceStreamerUtils.getLogPath(); + Assert.assertNotEquals("", str); + } + + /** + * get Instance getDbPathTest + * + * @tc.name: getDbPathTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getDbPathTest_0001 + * @tc.desc: getDbPathTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getDbPathTest01() { + String str = traceStreamerUtils.getDbPath(); + Assert.assertNotEquals("", str); + } + + /** + * get Instance getDbPathTwoTest + * + * @tc.name: getDbPathTwoTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getDbPathTwoTest_0001 + * @tc.desc: getDbPathTwoTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getDbPathTwoTest01() { + String str = traceStreamerUtils.getDbPath("dbName"); + Assert.assertNotEquals("", str); + } + + /** + * get Instance getTraceStreamerAppTest + * + * @tc.name: getTraceStreamerAppTest + * @tc.number: OHOS_JAVA_layout_TraceStreamerUtils_getTraceStreamerAppTest_0001 + * @tc.desc: getTraceStreamerAppTest + * @tc.type: functional testing + * @tc.require: SR-010 + */ + @Test + public void getTraceStreamerAppTest01() { + String str = traceStreamerUtils.getTraceStreamerApp(); + Assert.assertNotEquals("", str); + } +} diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUProcessBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUProcessBeanTest.java index 6c1f55389..0acac23db 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUProcessBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUProcessBeanTest.java @@ -1,128 +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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test CPUProcessBean class - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class CPUProcessBeanTest { - /** - * test get the AvgDuration . - */ - @Test - void getAvgDuration() { - assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ - setAvgDuration(3L); - }}.getAvgDuration()); - } - - /** - * test set the AvgDuration . - */ - @Test - void setAvgDuration() { - assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ - setAvgDuration(3L); - }}.getAvgDuration()); - } - - /** - * test get the WallDuration . - */ - @Test - void getWallDuration() { - assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ - setWallDuration(3L); - }}.getWallDuration()); - } - - /** - * test set the WallDuration . - */ - @Test - void setWallDuration() { - assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ - setWallDuration(3L); - }}.getWallDuration()); - } - - /** - * test get the Pid . - */ - @Test - void getPid() { - assertEquals("pid", new CPUProcessBean(0, 0, "", "", "") {{ - setPid("pid"); - }}.getPid()); - } - - /** - * test set the Pid . - */ - @Test - void setPid() { - assertEquals("pid", new CPUProcessBean(0, 0, "", "", "") {{ - setPid("pid"); - }}.getPid()); - } - - /** - * test get the Occurrences . - */ - @Test - void getOccurrences() { - assertEquals("Occurrences", new CPUProcessBean(0, 0, "", "", "") {{ - setOccurrences("Occurrences"); - }}.getOccurrences()); - } - - /** - * test set the Occurrences . - */ - @Test - void setOccurrences() { - assertEquals("Occurrences", new CPUProcessBean(0, 0, "", "", "") {{ - setOccurrences("Occurrences"); - }}.getOccurrences()); - } - - /** - * test get the Process . - */ - @Test - void getProcess() { - assertEquals("Process", new CPUProcessBean(0, 0, "", "", "") {{ - setProcess("Process"); - }}.getProcess()); - } - - /** - * test set the Process . - */ - @Test - void setProcess() { - assertEquals("Process", new CPUProcessBean(0, 0, "", "", "") {{ - setProcess("Process"); - }}.getProcess()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test CPUProcessBean class + * + * @date 2021/4/24 18:04 + */ +class CPUProcessBeanTest { + /** + * test get the AvgDuration . + */ + @Test + void getAvgDuration() { + assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ + setAvgDuration(3L); + }}.getAvgDuration()); + } + + /** + * test set the AvgDuration . + */ + @Test + void setAvgDuration() { + assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ + setAvgDuration(3L); + }}.getAvgDuration()); + } + + /** + * test get the WallDuration . + */ + @Test + void getWallDuration() { + assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ + setWallDuration(3L); + }}.getWallDuration()); + } + + /** + * test set the WallDuration . + */ + @Test + void setWallDuration() { + assertEquals(3L, new CPUProcessBean(0, 0, "", "", "") {{ + setWallDuration(3L); + }}.getWallDuration()); + } + + /** + * test get the Pid . + */ + @Test + void getPid() { + assertEquals("pid", new CPUProcessBean(0, 0, "", "", "") {{ + setPid("pid"); + }}.getPid()); + } + + /** + * test set the Pid . + */ + @Test + void setPid() { + assertEquals("pid", new CPUProcessBean(0, 0, "", "", "") {{ + setPid("pid"); + }}.getPid()); + } + + /** + * test get the Occurrences . + */ + @Test + void getOccurrences() { + assertEquals("Occurrences", new CPUProcessBean(0, 0, "", "", "") {{ + setOccurrences("Occurrences"); + }}.getOccurrences()); + } + + /** + * test set the Occurrences . + */ + @Test + void setOccurrences() { + assertEquals("Occurrences", new CPUProcessBean(0, 0, "", "", "") {{ + setOccurrences("Occurrences"); + }}.getOccurrences()); + } + + /** + * test get the Process . + */ + @Test + void getProcess() { + assertEquals("Process", new CPUProcessBean(0, 0, "", "", "") {{ + setProcess("Process"); + }}.getProcess()); + } + + /** + * test set the Process . + */ + @Test + void setProcess() { + assertEquals("Process", new CPUProcessBean(0, 0, "", "", "") {{ + setProcess("Process"); + }}.getProcess()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUThreadBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUThreadBeanTest.java index 4ed235528..e96add22a 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUThreadBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CPUThreadBeanTest.java @@ -1,168 +1,167 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test CPUThreadBean class - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class CPUThreadBeanTest { - /** - * test get the avgDuration . - */ - @Test - void getAvgDuration() { - assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setAvgDuration(3L); - }}.getAvgDuration()); - } - - /** - * test set the avgDuration . - */ - @Test - void setAvgDuration() { - assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setAvgDuration(3L); - }}.getAvgDuration()); - } - - /** - * test get the WallDuration . - */ - @Test - void getWallDuration() { - assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setWallDuration(3L); - }}.getWallDuration()); - } - - /** - * test set the WallDuration . - */ - @Test - void setWallDuration() { - assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setWallDuration(3L); - }}.getWallDuration()); - } - - /** - * test get the Pid . - */ - @Test - void getPid() { - assertEquals("Pid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setPid("Pid"); - }}.getPid()); - } - - /** - * test set the Pid . - */ - @Test - void setPid() { - assertEquals("Pid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setPid("Pid"); - }}.getPid()); - } - - /** - * test get the Tid . - */ - @Test - void getTid() { - assertEquals("Tid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setTid("Tid"); - }}.getTid()); - } - - /** - * test set the Tid . - */ - @Test - void setTid() { - assertEquals("Tid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setTid("Tid"); - }}.getTid()); - } - - /** - * test get the Occurrences . - */ - @Test - void getOccurrences() { - assertEquals("Occurrences", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setOccurrences("Occurrences"); - }}.getOccurrences()); - } - - /** - * test set the Occurrences . - */ - @Test - void setOccurrences() { - assertEquals("Occurrences", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setOccurrences("Occurrences"); - }}.getOccurrences()); - } - - /** - * test get the Process . - */ - @Test - void getProcess() { - assertEquals("Process", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setProcess("Process"); - }}.getProcess()); - } - - /** - * test set the Process . - */ - @Test - void setProcess() { - assertEquals("Process", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setProcess("Process"); - }}.getProcess()); - } - - /** - * test get the Thread . - */ - @Test - void getThread() { - assertEquals("Thread", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setThread("Thread"); - }}.getThread()); - } - - /** - * test set the Thread . - */ - @Test - void setThread() { - assertEquals("Thread", new CPUThreadBean(0, 0, "", "", "", "", "") {{ - setThread("Thread"); - }}.getThread()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test CPUThreadBean class + * + * @date 2021/4/24 18:04 + */ +class CPUThreadBeanTest { + /** + * test get the avgDuration . + */ + @Test + void getAvgDuration() { + assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setAvgDuration(3L); + }}.getAvgDuration()); + } + + /** + * test set the avgDuration . + */ + @Test + void setAvgDuration() { + assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setAvgDuration(3L); + }}.getAvgDuration()); + } + + /** + * test get the WallDuration . + */ + @Test + void getWallDuration() { + assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setWallDuration(3L); + }}.getWallDuration()); + } + + /** + * test set the WallDuration . + */ + @Test + void setWallDuration() { + assertEquals(3L, new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setWallDuration(3L); + }}.getWallDuration()); + } + + /** + * test get the Pid . + */ + @Test + void getPid() { + assertEquals("Pid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setPid("Pid"); + }}.getPid()); + } + + /** + * test set the Pid . + */ + @Test + void setPid() { + assertEquals("Pid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setPid("Pid"); + }}.getPid()); + } + + /** + * test get the Tid . + */ + @Test + void getTid() { + assertEquals("Tid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setTid("Tid"); + }}.getTid()); + } + + /** + * test set the Tid . + */ + @Test + void setTid() { + assertEquals("Tid", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setTid("Tid"); + }}.getTid()); + } + + /** + * test get the Occurrences . + */ + @Test + void getOccurrences() { + assertEquals("Occurrences", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setOccurrences("Occurrences"); + }}.getOccurrences()); + } + + /** + * test set the Occurrences . + */ + @Test + void setOccurrences() { + assertEquals("Occurrences", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setOccurrences("Occurrences"); + }}.getOccurrences()); + } + + /** + * test get the Process . + */ + @Test + void getProcess() { + assertEquals("Process", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setProcess("Process"); + }}.getProcess()); + } + + /** + * test set the Process . + */ + @Test + void setProcess() { + assertEquals("Process", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setProcess("Process"); + }}.getProcess()); + } + + /** + * test get the Thread . + */ + @Test + void getThread() { + assertEquals("Thread", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setThread("Thread"); + }}.getThread()); + } + + /** + * test set the Thread . + */ + @Test + void setThread() { + assertEquals("Thread", new CPUThreadBean(0, 0, "", "", "", "", "") {{ + setThread("Thread"); + }}.getThread()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuDataTest.java index d58515378..08650ae36 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuDataTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuDataTest.java @@ -1,483 +1,482 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.util.ArrayList; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test cpuData class - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class CpuDataTest { - /** - * test get the number of cpu . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getCpu() throws NoSuchFieldException, IllegalAccessException { - int random = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("cpu"); - field.setAccessible(true); - field.set(cpuData, random); - assertEquals(random, cpuData.getCpu()); - } - - /** - * test set the number of cpu . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setCpu() throws NoSuchFieldException, IllegalAccessException { - int random = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - cpuData.setCpu(random); - final Field field = cpuData.getClass().getDeclaredField("cpu"); - field.setAccessible(true); - assertEquals(random, field.get(cpuData)); - } - - /** - * test set the name . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getName() throws NoSuchFieldException, IllegalAccessException { - String name = "name"; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("name"); - field.setAccessible(true); - field.set(cpuData, name); - assertEquals(name, cpuData.getName()); - } - - /** - * test set the name . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setName() throws NoSuchFieldException, IllegalAccessException { - String name = "name"; - CpuData cpuData = new CpuData(); - cpuData.setName(name); - final Field field = cpuData.getClass().getDeclaredField("name"); - field.setAccessible(true); - assertEquals(name, field.get(cpuData)); - } - - /** - * test set the stats . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getStats() throws NoSuchFieldException, IllegalAccessException { - ArrayList stats = new ArrayList<>() {{ - add(1); - }}; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("stats"); - field.setAccessible(true); - field.set(cpuData, stats); - assertEquals(stats, cpuData.getStats()); - } - - /** - * test set the stats . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setStats() throws NoSuchFieldException, IllegalAccessException { - ArrayList stats = new ArrayList<>() {{ - add(1); - }}; - CpuData cpuData = new CpuData(); - cpuData.setStats(stats); - final Field field = cpuData.getClass().getDeclaredField("stats"); - field.setAccessible(true); - assertEquals(stats, field.get(cpuData)); - } - - /** - * test set the endState . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getEndState() throws NoSuchFieldException, IllegalAccessException { - String endState = "endState"; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("endState"); - field.setAccessible(true); - field.set(cpuData, endState); - assertEquals(endState, cpuData.getEndState()); - } - - /** - * test set the endState . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setEndState() throws NoSuchFieldException, IllegalAccessException { - String endState = "endState"; - CpuData cpuData = new CpuData(); - cpuData.setEndState(endState); - final Field field = cpuData.getClass().getDeclaredField("endState"); - field.setAccessible(true); - assertEquals(endState, field.get(cpuData)); - } - - /** - * test get the priority . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getPriority() throws NoSuchFieldException, IllegalAccessException { - int priority = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("priority"); - field.setAccessible(true); - field.set(cpuData, priority); - assertEquals(priority, cpuData.getPriority()); - } - - /** - * test set the priority . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setPriority() throws NoSuchFieldException, IllegalAccessException { - int priority = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - cpuData.setPriority(priority); - final Field field = cpuData.getClass().getDeclaredField("priority"); - field.setAccessible(true); - assertEquals(priority, field.get(cpuData)); - } - - /** - * test get the schedId . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getSchedId() throws NoSuchFieldException, IllegalAccessException { - int schedId = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("schedId"); - field.setAccessible(true); - field.set(cpuData, schedId); - assertEquals(schedId, cpuData.getSchedId()); - } - - /** - * test set the schedId . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setSchedId() throws NoSuchFieldException, IllegalAccessException { - int schedId = (int) (Math.random() * 100); - CpuData cpuData = new CpuData(); - cpuData.setPriority(schedId); - assertEquals(schedId, cpuData.getPriority()); - } - - /** - * test get the startTime . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getStartTime() throws NoSuchFieldException, IllegalAccessException { - long startTime = Double.doubleToLongBits((Math.random() * 100)); - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("startTime"); - field.setAccessible(true); - field.set(cpuData, startTime); - assertEquals(startTime, cpuData.getStartTime()); - } - - /** - * test set the startTime . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setStartTime() throws NoSuchFieldException, IllegalAccessException { - long startTime = Double.doubleToLongBits((Math.random() * 100)); - CpuData cpuData = new CpuData(); - cpuData.setStartTime(startTime); - final Field field = cpuData.getClass().getDeclaredField("startTime"); - field.setAccessible(true); - assertEquals(startTime, field.get(cpuData)); - } - - /** - * test get the duration . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getDuration() throws NoSuchFieldException, IllegalAccessException { - long duration = Double.doubleToLongBits((Math.random() * 100)); - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("duration"); - field.setAccessible(true); - field.set(cpuData, duration); - assertEquals(duration, cpuData.getDuration()); - } - - /** - * test set the duration . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setDuration() throws NoSuchFieldException, IllegalAccessException { - long duration = Double.doubleToLongBits((Math.random() * 100)); - CpuData cpuData = new CpuData(); - cpuData.setDuration(duration); - final Field field = cpuData.getClass().getDeclaredField("duration"); - field.setAccessible(true); - assertEquals(duration, field.get(cpuData)); - } - - /** - * test get the type . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getType() throws NoSuchFieldException, IllegalAccessException { - String type = "type"; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("type"); - field.setAccessible(true); - field.set(cpuData, type); - assertEquals(type, cpuData.getType()); - } - - /** - * test set the type . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setType() throws NoSuchFieldException, IllegalAccessException { - String type = "type"; - CpuData cpuData = new CpuData(); - cpuData.setType(type); - final Field field = cpuData.getClass().getDeclaredField("type"); - field.setAccessible(true); - assertEquals(type, field.get(cpuData)); - } - - /** - * test get the id . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getId() throws NoSuchFieldException, IllegalAccessException { - int id = 1; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("id"); - field.setAccessible(true); - field.set(cpuData, id); - assertEquals(id, cpuData.getId()); - } - - /** - * test set the id . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setId() throws NoSuchFieldException, IllegalAccessException { - int id = 1; - CpuData cpuData = new CpuData(); - cpuData.setId(id); - final Field field = cpuData.getClass().getDeclaredField("id"); - field.setAccessible(true); - assertEquals(id, field.get(cpuData)); - } - - /** - * test get the tid . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getTid() throws NoSuchFieldException, IllegalAccessException { - int tid = 1; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("tid"); - field.setAccessible(true); - field.set(cpuData, tid); - assertEquals(tid, cpuData.getTid()); - } - - /** - * test set the tid . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setTid() throws NoSuchFieldException, IllegalAccessException { - CpuData cpuData = new CpuData(); - cpuData.setId(1); - assertEquals(1, cpuData.getId()); - } - - /** - * test get the ProcessCmdLine . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getProcessCmdLine() throws NoSuchFieldException, IllegalAccessException { - String processCmdLine = "processCmdLine"; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("processCmdLine"); - field.setAccessible(true); - field.set(cpuData, processCmdLine); - assertEquals(processCmdLine, cpuData.getProcessCmdLine()); - } - - /** - * test set the ProcessCmdLine . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setProcessCmdLine() throws NoSuchFieldException, IllegalAccessException { - String processCmdLine = "processCmdLine"; - CpuData cpuData = new CpuData(); - cpuData.setProcessCmdLine(processCmdLine); - final Field field = cpuData.getClass().getDeclaredField("processCmdLine"); - field.setAccessible(true); - assertEquals(processCmdLine, field.get(cpuData)); - } - - /** - * test get the ProcessName . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getProcessName() throws NoSuchFieldException, IllegalAccessException { - String processName = "processName"; - CpuData cpuData = new CpuData(); - final Field field = cpuData.getClass().getDeclaredField("processName"); - field.setAccessible(true); - field.set(cpuData, processName); - assertEquals(processName, cpuData.getProcessName()); - } - - /** - * test set the ProcessName . - */ - @Test - void setProcessName() { - String processName = "processName"; - CpuData cpuData = new CpuData(); - cpuData.setProcessCmdLine(processName); - assertEquals(processName, cpuData.getProcessCmdLine()); - } - - /** - * test get the ProcessId . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void getProcessId() throws NoSuchFieldException, IllegalAccessException { - CpuData cpuData = new CpuData(); - cpuData.setProcessId(1); - assertEquals(1, cpuData.getProcessId()); - } - - /** - * test set the ProcessName . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void setProcessId() throws NoSuchFieldException, IllegalAccessException { - CpuData cpuData = new CpuData(); - cpuData.setProcessId(1); - assertEquals(1, cpuData.getProcessId()); - } - - /** - * test set the select . - * - * @throws NoSuchFieldException throw NoSuchFieldException - * @throws IllegalAccessException throw IllegalAccessException - */ - @Test - void select() throws NoSuchFieldException, IllegalAccessException { - CpuData cpuData = new CpuData(); - cpuData.select(true); - final Field field = cpuData.getClass().getDeclaredField("isSelected"); - field.setAccessible(true); - assertEquals(true, field.get(cpuData)); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test cpuData class + * + * @date 2021/4/24 18:04 + */ +class CpuDataTest { + /** + * test get the number of cpu . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getCpu() throws NoSuchFieldException, IllegalAccessException { + int random = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("cpu"); + field.setAccessible(true); + field.set(cpuData, random); + assertEquals(random, cpuData.getCpu()); + } + + /** + * test set the number of cpu . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setCpu() throws NoSuchFieldException, IllegalAccessException { + int random = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + cpuData.setCpu(random); + final Field field = cpuData.getClass().getDeclaredField("cpu"); + field.setAccessible(true); + assertEquals(random, field.get(cpuData)); + } + + /** + * test set the name . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getName() throws NoSuchFieldException, IllegalAccessException { + String name = "name"; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("name"); + field.setAccessible(true); + field.set(cpuData, name); + assertEquals(name, cpuData.getName()); + } + + /** + * test set the name . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setName() throws NoSuchFieldException, IllegalAccessException { + String name = "name"; + CpuData cpuData = new CpuData(); + cpuData.setName(name); + final Field field = cpuData.getClass().getDeclaredField("name"); + field.setAccessible(true); + assertEquals(name, field.get(cpuData)); + } + + /** + * test set the stats . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getStats() throws NoSuchFieldException, IllegalAccessException { + ArrayList stats = new ArrayList<>() {{ + add(1); + }}; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("stats"); + field.setAccessible(true); + field.set(cpuData, stats); + assertEquals(stats, cpuData.getStats()); + } + + /** + * test set the stats . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setStats() throws NoSuchFieldException, IllegalAccessException { + ArrayList stats = new ArrayList<>() {{ + add(1); + }}; + CpuData cpuData = new CpuData(); + cpuData.setStats(stats); + final Field field = cpuData.getClass().getDeclaredField("stats"); + field.setAccessible(true); + assertEquals(stats, field.get(cpuData)); + } + + /** + * test set the endState . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getEndState() throws NoSuchFieldException, IllegalAccessException { + String endState = "endState"; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("endState"); + field.setAccessible(true); + field.set(cpuData, endState); + assertEquals(endState, cpuData.getEndState()); + } + + /** + * test set the endState . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setEndState() throws NoSuchFieldException, IllegalAccessException { + String endState = "endState"; + CpuData cpuData = new CpuData(); + cpuData.setEndState(endState); + final Field field = cpuData.getClass().getDeclaredField("endState"); + field.setAccessible(true); + assertEquals(endState, field.get(cpuData)); + } + + /** + * test get the priority . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getPriority() throws NoSuchFieldException, IllegalAccessException { + int priority = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("priority"); + field.setAccessible(true); + field.set(cpuData, priority); + assertEquals(priority, cpuData.getPriority()); + } + + /** + * test set the priority . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setPriority() throws NoSuchFieldException, IllegalAccessException { + int priority = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + cpuData.setPriority(priority); + final Field field = cpuData.getClass().getDeclaredField("priority"); + field.setAccessible(true); + assertEquals(priority, field.get(cpuData)); + } + + /** + * test get the schedId . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getSchedId() throws NoSuchFieldException, IllegalAccessException { + int schedId = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("schedId"); + field.setAccessible(true); + field.set(cpuData, schedId); + assertEquals(schedId, cpuData.getSchedId()); + } + + /** + * test set the schedId . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setSchedId() throws NoSuchFieldException, IllegalAccessException { + int schedId = (int) (Math.random() * 100); + CpuData cpuData = new CpuData(); + cpuData.setPriority(schedId); + assertEquals(schedId, cpuData.getPriority()); + } + + /** + * test get the startTime . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getStartTime() throws NoSuchFieldException, IllegalAccessException { + long startTime = Double.doubleToLongBits((Math.random() * 100)); + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("startTime"); + field.setAccessible(true); + field.set(cpuData, startTime); + assertEquals(startTime, cpuData.getStartTime()); + } + + /** + * test set the startTime . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setStartTime() throws NoSuchFieldException, IllegalAccessException { + long startTime = Double.doubleToLongBits((Math.random() * 100)); + CpuData cpuData = new CpuData(); + cpuData.setStartTime(startTime); + final Field field = cpuData.getClass().getDeclaredField("startTime"); + field.setAccessible(true); + assertEquals(startTime, field.get(cpuData)); + } + + /** + * test get the duration . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getDuration() throws NoSuchFieldException, IllegalAccessException { + long duration = Double.doubleToLongBits((Math.random() * 100)); + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("duration"); + field.setAccessible(true); + field.set(cpuData, duration); + assertEquals(duration, cpuData.getDuration()); + } + + /** + * test set the duration . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setDuration() throws NoSuchFieldException, IllegalAccessException { + long duration = Double.doubleToLongBits((Math.random() * 100)); + CpuData cpuData = new CpuData(); + cpuData.setDuration(duration); + final Field field = cpuData.getClass().getDeclaredField("duration"); + field.setAccessible(true); + assertEquals(duration, field.get(cpuData)); + } + + /** + * test get the type . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getType() throws NoSuchFieldException, IllegalAccessException { + String type = "type"; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("type"); + field.setAccessible(true); + field.set(cpuData, type); + assertEquals(type, cpuData.getType()); + } + + /** + * test set the type . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setType() throws NoSuchFieldException, IllegalAccessException { + String type = "type"; + CpuData cpuData = new CpuData(); + cpuData.setType(type); + final Field field = cpuData.getClass().getDeclaredField("type"); + field.setAccessible(true); + assertEquals(type, field.get(cpuData)); + } + + /** + * test get the id . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getId() throws NoSuchFieldException, IllegalAccessException { + int id = 1; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("id"); + field.setAccessible(true); + field.set(cpuData, id); + assertEquals(id, cpuData.getId()); + } + + /** + * test set the id . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setId() throws NoSuchFieldException, IllegalAccessException { + int id = 1; + CpuData cpuData = new CpuData(); + cpuData.setId(id); + final Field field = cpuData.getClass().getDeclaredField("id"); + field.setAccessible(true); + assertEquals(id, field.get(cpuData)); + } + + /** + * test get the tid . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getTid() throws NoSuchFieldException, IllegalAccessException { + int tid = 1; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("tid"); + field.setAccessible(true); + field.set(cpuData, tid); + assertEquals(tid, cpuData.getTid()); + } + + /** + * test set the tid . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setTid() throws NoSuchFieldException, IllegalAccessException { + CpuData cpuData = new CpuData(); + cpuData.setId(1); + assertEquals(1, cpuData.getId()); + } + + /** + * test get the ProcessCmdLine . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getProcessCmdLine() throws NoSuchFieldException, IllegalAccessException { + String processCmdLine = "processCmdLine"; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("processCmdLine"); + field.setAccessible(true); + field.set(cpuData, processCmdLine); + assertEquals(processCmdLine, cpuData.getProcessCmdLine()); + } + + /** + * test set the ProcessCmdLine . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setProcessCmdLine() throws NoSuchFieldException, IllegalAccessException { + String processCmdLine = "processCmdLine"; + CpuData cpuData = new CpuData(); + cpuData.setProcessCmdLine(processCmdLine); + final Field field = cpuData.getClass().getDeclaredField("processCmdLine"); + field.setAccessible(true); + assertEquals(processCmdLine, field.get(cpuData)); + } + + /** + * test get the ProcessName . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getProcessName() throws NoSuchFieldException, IllegalAccessException { + String processName = "processName"; + CpuData cpuData = new CpuData(); + final Field field = cpuData.getClass().getDeclaredField("processName"); + field.setAccessible(true); + field.set(cpuData, processName); + assertEquals(processName, cpuData.getProcessName()); + } + + /** + * test set the ProcessName . + */ + @Test + void setProcessName() { + String processName = "processName"; + CpuData cpuData = new CpuData(); + cpuData.setProcessCmdLine(processName); + assertEquals(processName, cpuData.getProcessCmdLine()); + } + + /** + * test get the ProcessId . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void getProcessId() throws NoSuchFieldException, IllegalAccessException { + CpuData cpuData = new CpuData(); + cpuData.setProcessId(1); + assertEquals(1, cpuData.getProcessId()); + } + + /** + * test set the ProcessName . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void setProcessId() throws NoSuchFieldException, IllegalAccessException { + CpuData cpuData = new CpuData(); + cpuData.setProcessId(1); + assertEquals(1, cpuData.getProcessId()); + } + + /** + * test set the select . + * + * @throws NoSuchFieldException throw NoSuchFieldException + * @throws IllegalAccessException throw IllegalAccessException + */ + @Test + void select() throws NoSuchFieldException, IllegalAccessException { + CpuData cpuData = new CpuData(); + cpuData.select(true); + final Field field = cpuData.getClass().getDeclaredField("isSelected"); + field.setAccessible(true); + assertEquals(true, field.get(cpuData)); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuFreqDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuFreqDataTest.java index 0d6a3c1ee..50deeed09 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuFreqDataTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuFreqDataTest.java @@ -1,176 +1,175 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import javax.swing.JButton; -import javax.swing.JComponent; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test CpuFreqData class - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class CpuFreqDataTest { - /** - * test get the number of cpu . - */ - @Test - void getCpu() { - assertEquals(3, new CpuFreqData() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test set the number of cpu . - */ - @Test - void setCpu() { - assertEquals(3, new CpuFreqData() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test set the number . - */ - @Test - void getValue() { - assertEquals(3L, new CpuFreqData() {{ - setValue(3L); - }}.getValue()); - } - - /** - * test set the value . - */ - @Test - void setValue() { - assertEquals(3L, new CpuFreqData() {{ - setValue(3L); - }}.getValue()); - } - - /** - * test get the StartTime . - */ - @Test - void getStartTime() { - assertEquals(3L, new CpuFreqData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test set the StartTime . - */ - @Test - void setStartTime() { - assertEquals(3L, new CpuFreqData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test get the Duration . - */ - @Test - void getDuration() { - assertEquals(3L, new CpuFreqData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test set the Duration . - */ - @Test - void setDuration() { - assertEquals(3L, new CpuFreqData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test get the root . - */ - @Test - void getRoot() { - JComponent jComponent = new JButton(); - assertEquals(jComponent, new CpuFreqData() {{ - setRoot(jComponent); - }}.getRoot()); - } - - /** - * test set the root . - */ - @Test - void setRoot() { - JComponent jComponent = new JButton(); - assertEquals(jComponent, new CpuFreqData() {{ - setRoot(jComponent); - }}.getRoot()); - } - - /** - * test get the FlagFocus . - */ - @Test - void isFlagFocus() { - boolean flagFocus = true; - assertEquals(flagFocus, new CpuFreqData() {{ - setFlagFocus(flagFocus); - }}.isFlagFocus()); - } - - /** - * test set the FlagFocus . - */ - @Test - void setFlagFocus() { - boolean flagFocus = true; - assertEquals(flagFocus, new CpuFreqData() {{ - setFlagFocus(flagFocus); - }}.isFlagFocus()); - } - - /** - * test get the max . - */ - @Test - void getMax() { - assertEquals(10.0D, new CpuFreqData() {{ - setMax(10.0D); - }}.getMax()); - } - - /** - * test set the max . - */ - @Test - void setMax() { - assertEquals(10.0D, new CpuFreqData() {{ - setMax(10.0D); - }}.getMax()); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import javax.swing.JButton; +import javax.swing.JComponent; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test CpuFreqData class + * + * @date 2021/4/24 18:04 + */ +class CpuFreqDataTest { + /** + * test get the number of cpu . + */ + @Test + void getCpu() { + assertEquals(3, new CpuFreqData() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test set the number of cpu . + */ + @Test + void setCpu() { + assertEquals(3, new CpuFreqData() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test set the number . + */ + @Test + void getValue() { + assertEquals(3L, new CpuFreqData() {{ + setValue(3L); + }}.getValue()); + } + + /** + * test set the value . + */ + @Test + void setValue() { + assertEquals(3L, new CpuFreqData() {{ + setValue(3L); + }}.getValue()); + } + + /** + * test get the StartTime . + */ + @Test + void getStartTime() { + assertEquals(3L, new CpuFreqData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test set the StartTime . + */ + @Test + void setStartTime() { + assertEquals(3L, new CpuFreqData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test get the Duration . + */ + @Test + void getDuration() { + assertEquals(3L, new CpuFreqData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test set the Duration . + */ + @Test + void setDuration() { + assertEquals(3L, new CpuFreqData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test get the root . + */ + @Test + void getRoot() { + JComponent jComponent = new JButton(); + assertEquals(jComponent, new CpuFreqData() {{ + setRoot(jComponent); + }}.getRoot()); + } + + /** + * test set the root . + */ + @Test + void setRoot() { + JComponent jComponent = new JButton(); + assertEquals(jComponent, new CpuFreqData() {{ + setRoot(jComponent); + }}.getRoot()); + } + + /** + * test get the FlagFocus . + */ + @Test + void isFlagFocus() { + boolean flagFocus = true; + assertEquals(flagFocus, new CpuFreqData() {{ + setFlagFocus(flagFocus); + }}.isFlagFocus()); + } + + /** + * test set the FlagFocus . + */ + @Test + void setFlagFocus() { + boolean flagFocus = true; + assertEquals(flagFocus, new CpuFreqData() {{ + setFlagFocus(flagFocus); + }}.isFlagFocus()); + } + + /** + * test get the max . + */ + @Test + void getMax() { + assertEquals(10.0D, new CpuFreqData() {{ + setMax(10.0D); + }}.getMax()); + } + + /** + * test set the max . + */ + @Test + void setMax() { + assertEquals(10.0D, new CpuFreqData() {{ + setMax(10.0D); + }}.getMax()); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuRateBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuRateBeanTest.java index c5aff89bb..2e364f2dc 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuRateBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/CpuRateBeanTest.java @@ -1,88 +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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test CpuRateBean class - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class CpuRateBeanTest { - /** - * test get the number of cpu . - */ - @Test - void getCpu() { - assertEquals(3, new CpuRateBean() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test set the number of cpu . - */ - @Test - void setCpu() { - assertEquals(3, new CpuRateBean() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test get the index . - */ - @Test - void getIndex() { - assertEquals(3, new CpuRateBean() {{ - setIndex(3); - }}.getIndex()); - } - - /** - * test set the index . - */ - @Test - void setIndex() { - assertEquals(3, new CpuRateBean() {{ - setIndex(3); - }}.getIndex()); - } - - /** - * test get the rate . - */ - @Test - void getRate() { - assertEquals(3.0D, new CpuRateBean() {{ - setRate(3.0D); - }}.getRate()); - } - - /** - * test set the rate . - */ - @Test - void setRate() { - assertEquals(3.0D, new CpuRateBean() {{ - setRate(3.0D); - }}.getRate()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test CpuRateBean class + * + * @date 2021/4/24 18:04 + */ +class CpuRateBeanTest { + /** + * test get the number of cpu . + */ + @Test + void getCpu() { + assertEquals(3, new CpuRateBean() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test set the number of cpu . + */ + @Test + void setCpu() { + assertEquals(3, new CpuRateBean() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test get the index . + */ + @Test + void getIndex() { + assertEquals(3, new CpuRateBean() {{ + setIndex(3); + }}.getIndex()); + } + + /** + * test set the index . + */ + @Test + void setIndex() { + assertEquals(3, new CpuRateBean() {{ + setIndex(3); + }}.getIndex()); + } + + /** + * test get the rate . + */ + @Test + void getRate() { + assertEquals(3.0D, new CpuRateBean() {{ + setRate(3.0D); + }}.getRate()); + } + + /** + * test set the rate . + */ + @Test + void setRate() { + assertEquals(3.0D, new CpuRateBean() {{ + setRate(3.0D); + }}.getRate()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FlagBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FlagBeanTest.java index 648378606..20f39e7e6 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FlagBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FlagBeanTest.java @@ -1,135 +1,134 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import java.awt.Color; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test FlagBean class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class FlagBeanTest { - /** - * test get the ns . - */ - @Test - void getNs() { - assertEquals(3L, new FlagBean() {{ - setNs(3L); - }}.getNs()); - } - - /** - * test set the ns . - */ - @Test - void setNs() { - assertEquals(3L, new FlagBean() {{ - setNs(3L); - }}.getNs()); - } - - /** - * test get the Visible . - */ - @Test - void isVisible() { - boolean visiable = true; - assertEquals(visiable, new FlagBean() {{ - setVisible(visiable); - }}.isVisible()); - } - - /** - * test set the Visible . - */ - @Test - void setVisible() { - boolean visiable = true; - assertEquals(visiable, new FlagBean() {{ - setVisible(visiable); - }}.isVisible()); - } - - /** - * test get the name . - */ - @Test - void getName() { - assertEquals("name", new FlagBean() {{ - setName("name"); - }}.getName()); - } - - /** - * test set the name . - */ - @Test - void setName() { - assertEquals("name", new FlagBean() {{ - setName("name"); - }}.getName()); - } - - /** - * test get the time . - */ - @Test - void getTime() { - assertEquals(3L, new FlagBean() {{ - setTime(3L); - }}.getTime()); - } - - /** - * test set the time . - */ - @Test - void setTime() { - assertEquals(3L, new FlagBean() {{ - setTime(3L); - }}.getTime()); - } - - /** - * test get the time . - */ - @Test - void getColor() { - Color black = Color.BLACK; - assertEquals(black, new FlagBean() {{ - setColor(black); - }}.getColor()); - } - - /** - * test set the time . - */ - @Test - void setColor() { - Color black = Color.BLACK; - assertEquals(black, new FlagBean() {{ - setColor(black); - }}.getColor()); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import java.awt.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test FlagBean class + * + * @date 2021/4/24 18:05 + */ +class FlagBeanTest { + /** + * test get the ns . + */ + @Test + void getNs() { + assertEquals(3L, new FlagBean() {{ + setNs(3L); + }}.getNs()); + } + + /** + * test set the ns . + */ + @Test + void setNs() { + assertEquals(3L, new FlagBean() {{ + setNs(3L); + }}.getNs()); + } + + /** + * test get the Visible . + */ + @Test + void isVisible() { + boolean visiable = true; + assertEquals(visiable, new FlagBean() {{ + setVisible(visiable); + }}.isVisible()); + } + + /** + * test set the Visible . + */ + @Test + void setVisible() { + boolean visiable = true; + assertEquals(visiable, new FlagBean() {{ + setVisible(visiable); + }}.isVisible()); + } + + /** + * test get the name . + */ + @Test + void getName() { + assertEquals("name", new FlagBean() {{ + setName("name"); + }}.getName()); + } + + /** + * test set the name . + */ + @Test + void setName() { + assertEquals("name", new FlagBean() {{ + setName("name"); + }}.getName()); + } + + /** + * test get the time . + */ + @Test + void getTime() { + assertEquals(3L, new FlagBean() {{ + setTime(3L); + }}.getTime()); + } + + /** + * test set the time . + */ + @Test + void setTime() { + assertEquals(3L, new FlagBean() {{ + setTime(3L); + }}.getTime()); + } + + /** + * test get the time . + */ + @Test + void getColor() { + Color black = Color.BLACK; + assertEquals(black, new FlagBean() {{ + setColor(black); + }}.getColor()); + } + + /** + * test set the time . + */ + @Test + void setColor() { + Color black = Color.BLACK; + assertEquals(black, new FlagBean() {{ + setColor(black); + }}.getColor()); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FunctionBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FunctionBeanTest.java index 41848ab26..7e1435500 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FunctionBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/FunctionBeanTest.java @@ -1,231 +1,230 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test FunctionBean class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class FunctionBeanTest { - /** - * test get the tid . - */ - @Test - void getTid() { - assertEquals(3, new FunctionBean() {{ - setTid(3); - }}.getTid()); - } - - /** - * test set the tid . - */ - @Test - void setTid() { - assertEquals(3, new FunctionBean() {{ - setTid(3); - }}.getTid()); - } - - /** - * test get the ThreadName . - */ - @Test - void getThreadName() { - assertEquals("ThreadName", new FunctionBean() {{ - setThreadName("ThreadName"); - }}.getThreadName()); - } - - /** - * test set the ThreadName . - */ - @Test - void setThreadName() { - assertEquals("ThreadName", new FunctionBean() {{ - setThreadName("ThreadName"); - }}.getThreadName()); - } - - /** - * test get the IsMainThread . - */ - @Test - void getIsMainThread() { - assertEquals(1, new FunctionBean() {{ - setIsMainThread(1); - }}.getIsMainThread()); - } - - /** - * test set the IsMainThread . - */ - @Test - void setIsMainThread() { - assertEquals(1, new FunctionBean() {{ - setIsMainThread(1); - }}.getIsMainThread()); - } - - /** - * test get the TrackId . - */ - @Test - void getTrackId() { - assertEquals(1, new FunctionBean() {{ - setTrackId(1); - }}.getTrackId()); - } - - /** - * test set the TrackId . - */ - @Test - void setTrackId() { - assertEquals(1, new FunctionBean() {{ - setTrackId(1); - }}.getTrackId()); - } - - /** - * test get the StartTime . - */ - @Test - void getStartTime() { - assertEquals(1L, new FunctionBean() {{ - setStartTime(1L); - }}.getStartTime()); - } - - /** - * test set the StartTime . - */ - @Test - void setStartTime() { - assertEquals(1L, new FunctionBean() {{ - setStartTime(1L); - }}.getStartTime()); - } - - /** - * test get the Duration . - */ - @Test - void getDuration() { - assertEquals(1L, new FunctionBean() {{ - setDuration(1L); - }}.getDuration()); - } - - /** - * test set the Duration . - */ - @Test - void setDuration() { - assertEquals(1L, new FunctionBean() {{ - setDuration(1L); - }}.getDuration()); - } - - /** - * test get the FunName . - */ - @Test - void getFunName() { - assertEquals("FunName", new FunctionBean() {{ - setFunName("FunName"); - }}.getFunName()); - } - - /** - * test set the FunName . - */ - @Test - void setFunName() { - assertEquals("FunName", new FunctionBean() {{ - setFunName("FunName"); - }}.getFunName()); - } - - /** - * test get the Depth . - */ - @Test - void getDepth() { - assertEquals(3, new FunctionBean() {{ - setDepth(3); - }}.getDepth()); - } - - /** - * test set the Depth . - */ - @Test - void setDepth() { - assertEquals(3, new FunctionBean() {{ - setDepth(3); - }}.getDepth()); - } - - /** - * test get the Category . - */ - @Test - void getCategory() { - assertEquals("Category", new FunctionBean() {{ - setCategory("Category"); - }}.getCategory()); - } - - /** - * test set the Category . - */ - @Test - void setCategory() { - assertEquals("Category", new FunctionBean() {{ - setCategory("Category"); - }}.getCategory()); - } - - /** - * test get the Selected . - */ - @Test - void isSelected() { - boolean selected = true; - assertEquals(selected, new FunctionBean() {{ - setSelected(selected); - }}.isSelected()); - } - - /** - * test set the Selected . - */ - @Test - void setSelected() { - boolean selected = true; - assertEquals(selected, new FunctionBean() {{ - setSelected(selected); - }}.isSelected()); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test FunctionBean class + * + * @date 2021/4/24 18:05 + */ +class FunctionBeanTest { + /** + * test get the tid . + */ + @Test + void getTid() { + assertEquals(3, new FunctionBean() {{ + setTid(3); + }}.getTid()); + } + + /** + * test set the tid . + */ + @Test + void setTid() { + assertEquals(3, new FunctionBean() {{ + setTid(3); + }}.getTid()); + } + + /** + * test get the ThreadName . + */ + @Test + void getThreadName() { + assertEquals("ThreadName", new FunctionBean() {{ + setThreadName("ThreadName"); + }}.getThreadName()); + } + + /** + * test set the ThreadName . + */ + @Test + void setThreadName() { + assertEquals("ThreadName", new FunctionBean() {{ + setThreadName("ThreadName"); + }}.getThreadName()); + } + + /** + * test get the IsMainThread . + */ + @Test + void getIsMainThread() { + assertEquals(1, new FunctionBean() {{ + setIsMainThread(1); + }}.getIsMainThread()); + } + + /** + * test set the IsMainThread . + */ + @Test + void setIsMainThread() { + assertEquals(1, new FunctionBean() {{ + setIsMainThread(1); + }}.getIsMainThread()); + } + + /** + * test get the TrackId . + */ + @Test + void getTrackId() { + assertEquals(1, new FunctionBean() {{ + setTrackId(1); + }}.getTrackId()); + } + + /** + * test set the TrackId . + */ + @Test + void setTrackId() { + assertEquals(1, new FunctionBean() {{ + setTrackId(1); + }}.getTrackId()); + } + + /** + * test get the StartTime . + */ + @Test + void getStartTime() { + assertEquals(1L, new FunctionBean() {{ + setStartTime(1L); + }}.getStartTime()); + } + + /** + * test set the StartTime . + */ + @Test + void setStartTime() { + assertEquals(1L, new FunctionBean() {{ + setStartTime(1L); + }}.getStartTime()); + } + + /** + * test get the Duration . + */ + @Test + void getDuration() { + assertEquals(1L, new FunctionBean() {{ + setDuration(1L); + }}.getDuration()); + } + + /** + * test set the Duration . + */ + @Test + void setDuration() { + assertEquals(1L, new FunctionBean() {{ + setDuration(1L); + }}.getDuration()); + } + + /** + * test get the FunName . + */ + @Test + void getFunName() { + assertEquals("FunName", new FunctionBean() {{ + setFunName("FunName"); + }}.getFunName()); + } + + /** + * test set the FunName . + */ + @Test + void setFunName() { + assertEquals("FunName", new FunctionBean() {{ + setFunName("FunName"); + }}.getFunName()); + } + + /** + * test get the Depth . + */ + @Test + void getDepth() { + assertEquals(3, new FunctionBean() {{ + setDepth(3); + }}.getDepth()); + } + + /** + * test set the Depth . + */ + @Test + void setDepth() { + assertEquals(3, new FunctionBean() {{ + setDepth(3); + }}.getDepth()); + } + + /** + * test get the Category . + */ + @Test + void getCategory() { + assertEquals("Category", new FunctionBean() {{ + setCategory("Category"); + }}.getCategory()); + } + + /** + * test set the Category . + */ + @Test + void setCategory() { + assertEquals("Category", new FunctionBean() {{ + setCategory("Category"); + }}.getCategory()); + } + + /** + * test get the Selected . + */ + @Test + void isSelected() { + boolean selected = true; + assertEquals(selected, new FunctionBean() {{ + setSelected(selected); + }}.isSelected()); + } + + /** + * test set the Selected . + */ + @Test + void setSelected() { + boolean selected = true; + assertEquals(selected, new FunctionBean() {{ + setSelected(selected); + }}.isSelected()); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessDataTest.java index da7f86f97..a66df9005 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessDataTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessDataTest.java @@ -1,148 +1,147 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ProcessData class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class ProcessDataTest { - /** - * test get the id . - */ - @Test - void getId() { - assertEquals(3, new ProcessData() {{ - setId(3); - }}.getId()); - } - - /** - * test set the id . - */ - @Test - void setId() { - assertEquals(3, new ProcessData() {{ - setId(3); - }}.getId()); - } - - /** - * test get the utid . - */ - @Test - void getUtid() { - assertEquals(3, new ProcessData() {{ - setUtid(3); - }}.getUtid()); - } - - /** - * test set the utid . - */ - @Test - void setUtid() { - assertEquals(3, new ProcessData() {{ - setUtid(3); - }}.getUtid()); - } - - /** - * test et the cpu . - */ - @Test - void getCpu() { - assertEquals(3, new ProcessData() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test set the cpu . - */ - @Test - void setCpu() { - assertEquals(3, new ProcessData() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test get the StartTime . - */ - @Test - void getStartTime() { - assertEquals(3L, new ProcessData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test set the StartTime . - */ - @Test - void setStartTime() { - assertEquals(3L, new ProcessData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test get the Duration . - */ - @Test - void getDuration() { - assertEquals(3L, new ProcessData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test set the Duration . - */ - @Test - void setDuration() { - assertEquals(3L, new ProcessData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test get the State . - */ - @Test - void getState() { - assertEquals("state", new ProcessData() {{ - setState("state"); - }}.getState()); - } - - /** - * test set the State . - */ - @Test - void setState() { - assertEquals("state", new ProcessData() {{ - setState("state"); - }}.getState()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ProcessData class + * + * @date 2021/4/24 18:05 + */ +class ProcessDataTest { + /** + * test get the id . + */ + @Test + void getId() { + assertEquals(3, new ProcessData() {{ + setId(3); + }}.getId()); + } + + /** + * test set the id . + */ + @Test + void setId() { + assertEquals(3, new ProcessData() {{ + setId(3); + }}.getId()); + } + + /** + * test get the utid . + */ + @Test + void getUtid() { + assertEquals(3, new ProcessData() {{ + setUtid(3); + }}.getUtid()); + } + + /** + * test set the utid . + */ + @Test + void setUtid() { + assertEquals(3, new ProcessData() {{ + setUtid(3); + }}.getUtid()); + } + + /** + * test et the cpu . + */ + @Test + void getCpu() { + assertEquals(3, new ProcessData() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test set the cpu . + */ + @Test + void setCpu() { + assertEquals(3, new ProcessData() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test get the StartTime . + */ + @Test + void getStartTime() { + assertEquals(3L, new ProcessData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test set the StartTime . + */ + @Test + void setStartTime() { + assertEquals(3L, new ProcessData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test get the Duration . + */ + @Test + void getDuration() { + assertEquals(3L, new ProcessData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test set the Duration . + */ + @Test + void setDuration() { + assertEquals(3L, new ProcessData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test get the State . + */ + @Test + void getState() { + assertEquals("state", new ProcessData() {{ + setState("state"); + }}.getState()); + } + + /** + * test set the State . + */ + @Test + void setState() { + assertEquals("state", new ProcessData() {{ + setState("state"); + }}.getState()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemDataTest.java index 64d69b88b..d83ccd310 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemDataTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemDataTest.java @@ -1,168 +1,167 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ProcessMemData class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class ProcessMemDataTest { - /** - * test get the MaxValue . - */ - @Test - void getMaxValue() { - assertEquals(3, new ProcessMemData() {{ - setMaxValue(3); - }}.getMaxValue()); - } - - /** - * test set the MaxValue . - */ - @Test - void setMaxValue() { - assertEquals(3, new ProcessMemData() {{ - setMaxValue(3); - }}.getMaxValue()); - } - - /** - * test get the id . - */ - @Test - void getId() { - assertEquals(3, new ProcessMemData() {{ - setId(3); - }}.getId()); - } - - /** - * test set the id . - */ - @Test - void setId() { - assertEquals(3, new ProcessMemData() {{ - setId(3); - }}.getId()); - } - - /** - * test get the type . - */ - @Test - void getType() { - assertEquals("type", new ProcessMemData() {{ - setType("type"); - }}.getType()); - } - - /** - * test set the type . - */ - @Test - void setType() { - assertEquals("type", new ProcessMemData() {{ - setType("type"); - }}.getType()); - } - - /** - * test get the TrackId . - */ - @Test - void getTrackId() { - assertEquals(3, new ProcessMemData() {{ - setTrackId(3); - }}.getTrackId()); - } - - /** - * test set the TrackId . - */ - @Test - void setTrackId() { - assertEquals(3, new ProcessMemData() {{ - setTrackId(3); - }}.getTrackId()); - } - - /** - * test get the Value . - */ - @Test - void getValue() { - assertEquals(3, new ProcessMemData() {{ - setValue(3); - }}.getValue()); - } - - /** - * test set the Value . - */ - @Test - void setValue() { - assertEquals(3, new ProcessMemData() {{ - setValue(3); - }}.getValue()); - } - - /** - * test get the StartTime . - */ - @Test - void getStartTime() { - assertEquals(3L, new ProcessMemData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test set the StartTime . - */ - @Test - void setStartTime() { - assertEquals(3L, new ProcessMemData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test get the Duration . - */ - @Test - void getDuration() { - assertEquals(3L, new ProcessMemData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test set the Duration . - */ - @Test - void setDuration() { - assertEquals(3L, new ProcessMemData() {{ - setDuration(3L); - }}.getDuration()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ProcessMemData class + * + * @date 2021/4/24 18:05 + */ +class ProcessMemDataTest { + /** + * test get the MaxValue . + */ + @Test + void getMaxValue() { + assertEquals(3, new ProcessMemData() {{ + setMaxValue(3); + }}.getMaxValue()); + } + + /** + * test set the MaxValue . + */ + @Test + void setMaxValue() { + assertEquals(3, new ProcessMemData() {{ + setMaxValue(3); + }}.getMaxValue()); + } + + /** + * test get the id . + */ + @Test + void getId() { + assertEquals(3, new ProcessMemData() {{ + setId(3); + }}.getId()); + } + + /** + * test set the id . + */ + @Test + void setId() { + assertEquals(3, new ProcessMemData() {{ + setId(3); + }}.getId()); + } + + /** + * test get the type . + */ + @Test + void getType() { + assertEquals("type", new ProcessMemData() {{ + setType("type"); + }}.getType()); + } + + /** + * test set the type . + */ + @Test + void setType() { + assertEquals("type", new ProcessMemData() {{ + setType("type"); + }}.getType()); + } + + /** + * test get the TrackId . + */ + @Test + void getTrackId() { + assertEquals(3, new ProcessMemData() {{ + setTrackId(3); + }}.getTrackId()); + } + + /** + * test set the TrackId . + */ + @Test + void setTrackId() { + assertEquals(3, new ProcessMemData() {{ + setTrackId(3); + }}.getTrackId()); + } + + /** + * test get the Value . + */ + @Test + void getValue() { + assertEquals(3, new ProcessMemData() {{ + setValue(3); + }}.getValue()); + } + + /** + * test set the Value . + */ + @Test + void setValue() { + assertEquals(3, new ProcessMemData() {{ + setValue(3); + }}.getValue()); + } + + /** + * test get the StartTime . + */ + @Test + void getStartTime() { + assertEquals(3L, new ProcessMemData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test set the StartTime . + */ + @Test + void setStartTime() { + assertEquals(3L, new ProcessMemData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test get the Duration . + */ + @Test + void getDuration() { + assertEquals(3L, new ProcessMemData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test set the Duration . + */ + @Test + void setDuration() { + assertEquals(3L, new ProcessMemData() {{ + setDuration(3L); + }}.getDuration()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemTest.java index 629965b80..af314b642 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessMemTest.java @@ -1,128 +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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ProcessMem class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class ProcessMemTest { - /** - * test get the TrackId . - */ - @Test - void getTrackId() { - assertEquals(3, new ProcessMem() {{ - setTrackId(3); - }}.getTrackId()); - } - - /** - * test set the TrackId . - */ - @Test - void setTrackId() { - assertEquals(3, new ProcessMem() {{ - setTrackId(3); - }}.getTrackId()); - } - - /** - * test get the ProcessName . - */ - @Test - void getProcessName() { - assertEquals("ProcessName", new ProcessMem() {{ - setProcessName("ProcessName"); - }}.getProcessName()); - } - - /** - * test set the ProcessName . - */ - @Test - void setProcessName() { - assertEquals("ProcessName", new ProcessMem() {{ - setProcessName("ProcessName"); - }}.getProcessName()); - } - - /** - * test get the Pid . - */ - @Test - void getPid() { - assertEquals(1, new ProcessMem() {{ - setPid(1); - }}.getPid()); - } - - /** - * test set the Pid . - */ - @Test - void setPid() { - assertEquals(1, new ProcessMem() {{ - setPid(1); - }}.getPid()); - } - - /** - * test get the Upid . - */ - @Test - void getUpid() { - assertEquals(1, new ProcessMem() {{ - setUpid(1); - }}.getUpid()); - } - - /** - * test set the Upid . - */ - @Test - void setUpid() { - assertEquals(1, new ProcessMem() {{ - setUpid(1); - }}.getUpid()); - } - - /** - * test get the TrackName . - */ - @Test - void getTrackName() { - assertEquals("TrackName", new ProcessMem() {{ - setTrackName("TrackName"); - }}.getTrackName()); - } - - /** - * test get the TrackName . - */ - @Test - void setTrackName() { - assertEquals("TrackName", new ProcessMem() {{ - setTrackName("TrackName"); - }}.getTrackName()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ProcessMem class + * + * @date 2021/4/24 18:05 + */ +class ProcessMemTest { + /** + * test get the TrackId . + */ + @Test + void getTrackId() { + assertEquals(3, new ProcessMem() {{ + setTrackId(3); + }}.getTrackId()); + } + + /** + * test set the TrackId . + */ + @Test + void setTrackId() { + assertEquals(3, new ProcessMem() {{ + setTrackId(3); + }}.getTrackId()); + } + + /** + * test get the ProcessName . + */ + @Test + void getProcessName() { + assertEquals("ProcessName", new ProcessMem() {{ + setProcessName("ProcessName"); + }}.getProcessName()); + } + + /** + * test set the ProcessName . + */ + @Test + void setProcessName() { + assertEquals("ProcessName", new ProcessMem() {{ + setProcessName("ProcessName"); + }}.getProcessName()); + } + + /** + * test get the Pid . + */ + @Test + void getPid() { + assertEquals(1, new ProcessMem() {{ + setPid(1); + }}.getPid()); + } + + /** + * test set the Pid . + */ + @Test + void setPid() { + assertEquals(1, new ProcessMem() {{ + setPid(1); + }}.getPid()); + } + + /** + * test get the Upid . + */ + @Test + void getUpid() { + assertEquals(1, new ProcessMem() {{ + setUpid(1); + }}.getUpid()); + } + + /** + * test set the Upid . + */ + @Test + void setUpid() { + assertEquals(1, new ProcessMem() {{ + setUpid(1); + }}.getUpid()); + } + + /** + * test get the TrackName . + */ + @Test + void getTrackName() { + assertEquals("TrackName", new ProcessMem() {{ + setTrackName("TrackName"); + }}.getTrackName()); + } + + /** + * test get the TrackName . + */ + @Test + void setTrackName() { + assertEquals("TrackName", new ProcessMem() {{ + setTrackName("TrackName"); + }}.getTrackName()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessTest.java index 6a41babf5..67cd6c568 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ProcessTest.java @@ -1,68 +1,67 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test Process class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class ProcessTest { - /** - * test get the Pid . - */ - @Test - void getPid() { - assertEquals(3, new Process() {{ - setPid(3); - }}.getPid()); - } - - /** - * test set the Pid . - */ - @Test - void setPid() { - assertEquals(3, new Process() {{ - setPid(3); - }}.getPid()); - } - - /** - * test get the Name . - */ - @Test - void getName() { - assertEquals("Process", new Process() {{ - setName("Process"); - }}.getName()); - } - - /** - * test set the Name . - */ - @Test - void setName() { - assertEquals("Process", new Process() {{ - setName("Process"); - }}.getName()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test Process class + * + * @date 2021/4/24 18:05 + */ +class ProcessTest { + /** + * test get the Pid . + */ + @Test + void getPid() { + assertEquals(3, new Process() {{ + setPid(3); + }}.getPid()); + } + + /** + * test set the Pid . + */ + @Test + void setPid() { + assertEquals(3, new Process() {{ + setPid(3); + }}.getPid()); + } + + /** + * test get the Name . + */ + @Test + void getName() { + assertEquals("Process", new Process() {{ + setName("Process"); + }}.getName()); + } + + /** + * test set the Name . + */ + @Test + void setName() { + assertEquals("Process", new Process() {{ + setName("Process"); + }}.getName()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ThreadDataTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ThreadDataTest.java index b16123758..8b672cd2b 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ThreadDataTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/ThreadDataTest.java @@ -1,228 +1,227 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ThreadData class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class ThreadDataTest { - /** - * test get the uPid . - */ - @Test - void getuPid() { - assertEquals(3, new ThreadData() {{ - setuPid(3); - }}.getuPid()); - } - - /** - * test set the uPid . - */ - @Test - void setuPid() { - assertEquals(3, new ThreadData() {{ - setuPid(3); - }}.getuPid()); - } - - /** - * test set the uTid . - */ - @Test - void getuTid() { - assertEquals(3, new ThreadData() {{ - setuTid(3); - }}.getuTid()); - } - - /** - * test set the uTid . - */ - @Test - void setuTid() { - assertEquals(3, new ThreadData() {{ - setuTid(3); - }}.getuTid()); - } - - /** - * test get the Pid . - */ - @Test - void getPid() { - assertEquals(3, new ThreadData() {{ - setPid(3); - }}.getPid()); - } - - /** - * test set the Pid . - */ - @Test - void setPid() { - assertEquals(3, new ThreadData() {{ - setPid(3); - }}.getPid()); - } - - /** - * test get the Tid . - */ - @Test - void getTid() { - assertEquals(3, new ThreadData() {{ - setTid(3); - }}.getTid()); - } - - /** - * test set the Tid . - */ - @Test - void setTid() { - assertEquals(3, new ThreadData() {{ - setTid(3); - }}.getTid()); - } - - /** - * test get the ProcessName . - */ - @Test - void getProcessName() { - assertEquals("ProcessName", new ThreadData() {{ - setProcessName("ProcessName"); - }}.getProcessName()); - } - - /** - * test set the ProcessName . - */ - @Test - void setProcessName() { - assertEquals("ProcessName", new ThreadData() {{ - setProcessName("ProcessName"); - }}.getProcessName()); - } - - /** - * test get the ThreadName . - */ - @Test - void getThreadName() { - assertEquals("ThreadName", new ThreadData() {{ - setThreadName("ThreadName"); - }}.getThreadName()); - } - - /** - * test set the ThreadName . - */ - @Test - void setThreadName() { - assertEquals("ThreadName", new ThreadData() {{ - setThreadName("ThreadName"); - }}.getThreadName()); - } - - /** - * test get the State . - */ - @Test - void getState() { - assertEquals("State", new ThreadData() {{ - setState("State"); - }}.getState()); - } - - /** - * test set the State . - */ - @Test - void setState() { - assertEquals("State", new ThreadData() {{ - setState("State"); - }}.getState()); - } - - /** - * test get the StartTime . - */ - @Test - void getStartTime() { - assertEquals(3L, new ThreadData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test set the StartTime . - */ - @Test - void setStartTime() { - assertEquals(3L, new ThreadData() {{ - setStartTime(3L); - }}.getStartTime()); - } - - /** - * test get the Duration . - */ - @Test - void getDuration() { - assertEquals(3L, new ThreadData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test set the Duration . - */ - @Test - void setDuration() { - assertEquals(3L, new ThreadData() {{ - setDuration(3L); - }}.getDuration()); - } - - /** - * test get the number of Cpu . - */ - @Test - void getCpu() { - assertEquals(3, new ThreadData() {{ - setCpu(3); - }}.getCpu()); - } - - /** - * test set the number of Cpu . - */ - @Test - void setCpu() { - assertEquals(3, new ThreadData() {{ - setCpu(3); - }}.getCpu()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ThreadData class + * + * @date 2021/4/24 18:05 + */ +class ThreadDataTest { + /** + * test get the uPid . + */ + @Test + void getuPid() { + assertEquals(3, new ThreadData() {{ + setuPid(3); + }}.getuPid()); + } + + /** + * test set the uPid . + */ + @Test + void setuPid() { + assertEquals(3, new ThreadData() {{ + setuPid(3); + }}.getuPid()); + } + + /** + * test set the uTid . + */ + @Test + void getuTid() { + assertEquals(3, new ThreadData() {{ + setuTid(3); + }}.getuTid()); + } + + /** + * test set the uTid . + */ + @Test + void setuTid() { + assertEquals(3, new ThreadData() {{ + setuTid(3); + }}.getuTid()); + } + + /** + * test get the Pid . + */ + @Test + void getPid() { + assertEquals(3, new ThreadData() {{ + setPid(3); + }}.getPid()); + } + + /** + * test set the Pid . + */ + @Test + void setPid() { + assertEquals(3, new ThreadData() {{ + setPid(3); + }}.getPid()); + } + + /** + * test get the Tid . + */ + @Test + void getTid() { + assertEquals(3, new ThreadData() {{ + setTid(3); + }}.getTid()); + } + + /** + * test set the Tid . + */ + @Test + void setTid() { + assertEquals(3, new ThreadData() {{ + setTid(3); + }}.getTid()); + } + + /** + * test get the ProcessName . + */ + @Test + void getProcessName() { + assertEquals("ProcessName", new ThreadData() {{ + setProcessName("ProcessName"); + }}.getProcessName()); + } + + /** + * test set the ProcessName . + */ + @Test + void setProcessName() { + assertEquals("ProcessName", new ThreadData() {{ + setProcessName("ProcessName"); + }}.getProcessName()); + } + + /** + * test get the ThreadName . + */ + @Test + void getThreadName() { + assertEquals("ThreadName", new ThreadData() {{ + setThreadName("ThreadName"); + }}.getThreadName()); + } + + /** + * test set the ThreadName . + */ + @Test + void setThreadName() { + assertEquals("ThreadName", new ThreadData() {{ + setThreadName("ThreadName"); + }}.getThreadName()); + } + + /** + * test get the State . + */ + @Test + void getState() { + assertEquals("State", new ThreadData() {{ + setState("State"); + }}.getState()); + } + + /** + * test set the State . + */ + @Test + void setState() { + assertEquals("State", new ThreadData() {{ + setState("State"); + }}.getState()); + } + + /** + * test get the StartTime . + */ + @Test + void getStartTime() { + assertEquals(3L, new ThreadData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test set the StartTime . + */ + @Test + void setStartTime() { + assertEquals(3L, new ThreadData() {{ + setStartTime(3L); + }}.getStartTime()); + } + + /** + * test get the Duration . + */ + @Test + void getDuration() { + assertEquals(3L, new ThreadData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test set the Duration . + */ + @Test + void setDuration() { + assertEquals(3L, new ThreadData() {{ + setDuration(3L); + }}.getDuration()); + } + + /** + * test get the number of Cpu . + */ + @Test + void getCpu() { + assertEquals(3, new ThreadData() {{ + setCpu(3); + }}.getCpu()); + } + + /** + * test set the number of Cpu . + */ + @Test + void setCpu() { + assertEquals(3, new ThreadData() {{ + setCpu(3); + }}.getCpu()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/WakeupBeanTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/WakeupBeanTest.java index 1b7c9493c..289ba48cf 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/WakeupBeanTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/bean/WakeupBeanTest.java @@ -1,188 +1,187 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.bean; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test WakeupBean class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class WakeupBeanTest { - /** - * test get the WakeupTime . - */ - @Test - void getWakeupTime() { - assertEquals(3L, new WakeupBean() {{ - setWakeupTime(3L); - }}.getWakeupTime()); - } - - /** - * test set the WakeupTime . - */ - @Test - void setWakeupTime() { - assertEquals(3L, new WakeupBean() {{ - setWakeupTime(3L); - }}.getWakeupTime()); - } - - /** - * test get the WakeupCpu . - */ - @Test - void getWakeupCpu() { - assertEquals(3, new WakeupBean() {{ - setWakeupCpu(3); - }}.getWakeupCpu()); - } - - /** - * test set the WakeupCpu . - */ - @Test - void setWakeupCpu() { - assertEquals(3, new WakeupBean() {{ - setWakeupCpu(3); - }}.getWakeupCpu()); - } - - /** - * test get the WakeupProcess . - */ - @Test - void getWakeupProcess() { - assertEquals("WakeupProcess", new WakeupBean() {{ - setWakeupProcess("WakeupProcess"); - }}.getWakeupProcess()); - } - - /** - * test set the WakeupProcess . - */ - @Test - void setWakeupProcess() { - assertEquals("WakeupProcess", new WakeupBean() {{ - setWakeupProcess("WakeupProcess"); - }}.getWakeupProcess()); - } - - /** - * test get the WakeupPid . - */ - @Test - void getWakeupPid() { - assertEquals("WakeupPid", new WakeupBean() {{ - setWakeupPid("WakeupPid"); - }}.getWakeupPid()); - } - - /** - * test set the WakeupPid . - */ - @Test - void setWakeupPid() { - assertEquals("WakeupPid", new WakeupBean() {{ - setWakeupPid("WakeupPid"); - }}.getWakeupPid()); - } - - /** - * test get the WakeupThread . - */ - @Test - void getWakeupThread() { - assertEquals("WakeupThread", new WakeupBean() {{ - setWakeupThread("WakeupThread"); - }}.getWakeupThread()); - } - - /** - * test set the WakeupThread . - */ - @Test - void setWakeupThread() { - assertEquals("WakeupThread", new WakeupBean() {{ - setWakeupThread("WakeupThread"); - }}.getWakeupThread()); - } - - /** - * test get the WakeupTid . - */ - @Test - void getWakeupTid() { - assertEquals("WakeupTid", new WakeupBean() {{ - setWakeupTid("WakeupTid"); - }}.getWakeupTid()); - } - - /** - * test set the WakeupTid . - */ - @Test - void setWakeupTid() { - assertEquals("WakeupTid", new WakeupBean() {{ - setWakeupTid("WakeupTid"); - }}.getWakeupTid()); - } - - /** - * test get the SchedulingLatency . - */ - @Test - void getSchedulingLatency() { - assertEquals(3L, new WakeupBean() {{ - setSchedulingLatency(3L); - }}.getSchedulingLatency()); - } - - /** - * test set the SchedulingLatency . - */ - @Test - void setSchedulingLatency() { - assertEquals(3L, new WakeupBean() {{ - setSchedulingLatency(3L); - }}.getSchedulingLatency()); - } - - /** - * test get the SchedulingDesc . - */ - @Test - void getSchedulingDesc() { - assertEquals("SchedulingDesc", new WakeupBean() {{ - setSchedulingDesc("SchedulingDesc"); - }}.getSchedulingDesc()); - } - - /** - * test set the SchedulingDesc . - */ - @Test - void setSchedulingDesc() { - assertEquals("SchedulingDesc", new WakeupBean() {{ - setSchedulingDesc("SchedulingDesc"); - }}.getSchedulingDesc()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.bean; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test WakeupBean class + * + * @date 2021/4/24 18:05 + */ +class WakeupBeanTest { + /** + * test get the WakeupTime . + */ + @Test + void getWakeupTime() { + assertEquals(3L, new WakeupBean() {{ + setWakeupTime(3L); + }}.getWakeupTime()); + } + + /** + * test set the WakeupTime . + */ + @Test + void setWakeupTime() { + assertEquals(3L, new WakeupBean() {{ + setWakeupTime(3L); + }}.getWakeupTime()); + } + + /** + * test get the WakeupCpu . + */ + @Test + void getWakeupCpu() { + assertEquals(3, new WakeupBean() {{ + setWakeupCpu(3); + }}.getWakeupCpu()); + } + + /** + * test set the WakeupCpu . + */ + @Test + void setWakeupCpu() { + assertEquals(3, new WakeupBean() {{ + setWakeupCpu(3); + }}.getWakeupCpu()); + } + + /** + * test get the WakeupProcess . + */ + @Test + void getWakeupProcess() { + assertEquals("WakeupProcess", new WakeupBean() {{ + setWakeupProcess("WakeupProcess"); + }}.getWakeupProcess()); + } + + /** + * test set the WakeupProcess . + */ + @Test + void setWakeupProcess() { + assertEquals("WakeupProcess", new WakeupBean() {{ + setWakeupProcess("WakeupProcess"); + }}.getWakeupProcess()); + } + + /** + * test get the WakeupPid . + */ + @Test + void getWakeupPid() { + assertEquals(0, new WakeupBean() {{ + setWakeupPid(0); + }}.getWakeupPid()); + } + + /** + * test set the WakeupPid . + */ + @Test + void setWakeupPid() { + assertEquals(0, new WakeupBean() {{ + setWakeupPid(0); + }}.getWakeupPid()); + } + + /** + * test get the WakeupThread . + */ + @Test + void getWakeupThread() { + assertEquals("WakeupThread", new WakeupBean() {{ + setWakeupThread("WakeupThread"); + }}.getWakeupThread()); + } + + /** + * test set the WakeupThread . + */ + @Test + void setWakeupThread() { + assertEquals("WakeupThread", new WakeupBean() {{ + setWakeupThread("WakeupThread"); + }}.getWakeupThread()); + } + + /** + * test get the WakeupTid . + */ + @Test + void getWakeupTid() { + assertEquals(0, new WakeupBean() {{ + setWakeupTid(0); + }}.getWakeupTid()); + } + + /** + * test set the WakeupTid . + */ + @Test + void setWakeupTid() { + assertEquals(0, new WakeupBean() {{ + setWakeupTid(0); + }}.getWakeupTid()); + } + + /** + * test get the SchedulingLatency . + */ + @Test + void getSchedulingLatency() { + assertEquals(3L, new WakeupBean() {{ + setSchedulingLatency(3L); + }}.getSchedulingLatency()); + } + + /** + * test set the SchedulingLatency . + */ + @Test + void setSchedulingLatency() { + assertEquals(3L, new WakeupBean() {{ + setSchedulingLatency(3L); + }}.getSchedulingLatency()); + } + + /** + * test get the SchedulingDesc . + */ + @Test + void getSchedulingDesc() { + assertEquals("SchedulingDesc", new WakeupBean() {{ + setSchedulingDesc("SchedulingDesc"); + }}.getSchedulingDesc()); + } + + /** + * test set the SchedulingDesc . + */ + @Test + void setSchedulingDesc() { + assertEquals("SchedulingDesc", new WakeupBean() {{ + setSchedulingDesc("SchedulingDesc"); + }}.getSchedulingDesc()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/AnalystPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/AnalystPanelTest.java index 5d7264687..1022717e2 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/AnalystPanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/AnalystPanelTest.java @@ -1,133 +1,129 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.bean.FlagBean; -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.ProcessMem; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.util.Db; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test AnalystPanel class - * - * @version 1.0 - * @date 2021/4/24 18:05 - **/ -class AnalystPanelTest { - /** - * test init setUp . - */ - @BeforeEach - void setUp() { - Db.getInstance(); - Db.setDbName("trace.db"); - Db.load(false); - } - - /** - * test add the CpuList . - */ - @Test - void addCpuList() { - AnalystPanel analystPanel = new AnalystPanel(); - ArrayList> lists = new ArrayList<>(); - analystPanel.addCpuList(lists); - assertEquals(lists, AnalystPanel.cpuList); - } - - /** - * test add the ThreadsList . - */ - @Test - void addThreadsList() { - AnalystPanel analystPanel = new AnalystPanel(); - List lists = new ArrayList<>(); - List processMem = new ArrayList<>(); - analystPanel.addThreadsList(lists, processMem); - assertEquals(lists, AnalystPanel.threadsList); - } - - /** - * test add the CpuFreqList . - */ - @Test - void addCpuFreqList() { - AnalystPanel analystPanel = new AnalystPanel(); - ArrayList> lists = new ArrayList<>(); - Map cpuMaxFreq = new HashMap<>(); - analystPanel.addCpuFreqList(lists, cpuMaxFreq); - assertEquals(lists, AnalystPanel.cpuFreqList); - } - - /** - * test add the ThreadsList . - */ - @Test - void clickFunctionData() { - FunctionBean functionBean = new FunctionBean(); - functionBean.setSelected(false); - functionBean.setCategory("cate"); - functionBean.setDepth(1); - functionBean.setFunName("functionBean"); - functionBean.setTid(1); - functionBean.setDepth(1); - functionBean.setTrackId(1); - AnalystPanel analystPanel = new AnalystPanel(); - analystPanel.clickFunctionData(functionBean); - } - - /** - * test function clickThreadData . - */ - @Test - void clickThreadData() { - AnalystPanel analystPanel = new AnalystPanel(); - analystPanel.clickThreadData(new ThreadData()); - assertEquals(10_000_000_000L, AnalystPanel.DURATION); - } - - /** - * test function clickCpuData . - */ - @Test - void clickCpuData() { - AnalystPanel analystPanel = new AnalystPanel(); - analystPanel.clickCpuData(new CpuData()); - assertEquals(10_000_000_000L, AnalystPanel.DURATION); - } - - /** - * test function clickTimeFlag . - */ - @Test - void clickTimeFlag() { - AnalystPanel analystPanel = new AnalystPanel(); - analystPanel.clickTimeFlag(new FlagBean()); - assertEquals(10_000_000_000L, AnalystPanel.DURATION); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import com.intellij.openapi.wm.IdeGlassPane; +import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; +import ohos.devtools.Config; +import org.fest.swing.fixture.FrameFixture; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import java.awt.AWTException; +import java.awt.Dimension; +import java.awt.MouseInfo; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; + +/** + * test AnalystPanel class + * + * @date 2021/4/24 18:05 + */ +class AnalystPanelTest { + private FrameFixture frame; + private AnalystPanel distributedPanel; + private JFrame jFrame; + private Robot robot; + + @BeforeEach + void setUp() { + jFrame = new JFrame(); + try { + robot = new Robot(); + IdeGlassPane ideGlassPane = new IdeGlassPaneImpl(jFrame.getRootPane()); + jFrame.getRootPane().setGlassPane((JPanel) ideGlassPane); + } catch (AWTException e) { + e.printStackTrace(); + } + distributedPanel = new AnalystPanel(); + jFrame.add(distributedPanel); + frame = new FrameFixture(jFrame); + // Display the frame + frame.show(new Dimension(1920, 1080)); + frame.moveTo(new Point(0, 0)); + distributedPanel.load(Config.TRACE_SYS, true); + } + + @AfterEach + void tearDown() { + frame.cleanUp(); + } + + @Test + void load() { + delay(10000); + select(600, 110, 610, 110); + mouseClick(557, 171);//小旗帜 + mouseClick(560, 172);//点击小旗帜 + select(557, 212, 600, 212);//选择cpu区域 + mouseClick(557, 212);//点击cpu切片 + mouseClick(549, 572);//点击clock 节点 + wheel(-600); + mouseClick(13, 371); + wheel(-200); + delay(); + mouseClick(620, 272); + mouseClick(612, 314); + select(520, 253, 668, 555); + delay(); + } + + private void mouseClick(int x, int y) { + robot.delay(2000); + robot.mouseMove(x, y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + private void keyClick(int keyEvent) { + robot.delay(2000); + robot.keyPress(keyEvent); + robot.keyRelease(keyEvent); + } + + private void select(int x1, int y1, int x2, int y2) { + robot.delay(2000); + robot.mouseMove(x1, y1); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseMove(x2, y2); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + private void wheel(int wheelAmt) { + robot.delay(1000); + robot.mouseWheel(wheelAmt); + } + + private void delay() { + robot.delay(2000); + } + + private void delay(int time) { + robot.delay(time); + } + + private void inspect() { + while (true) { + Point location = MouseInfo.getPointerInfo().getLocation(); + robot.delay(1000); + } + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/BottomScrollPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/BottomScrollPanelTest.java index 803fc9b59..45c94d64f 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/BottomScrollPanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/BottomScrollPanelTest.java @@ -1,25 +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. - */ - -package ohos.devtools.views.trace.component; - -/** - * test the BottomScrollPanel class - * - * @version 1.0 - * @date 2021/4/24 18:02 - **/ -class BottomScrollPanelTest { +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +/** + * test the BottomScrollPanel class + * + * @date 2021/4/24 18:02 + */ +class BottomScrollPanelTest { } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ContentPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ContentPanelTest.java index 5fee9b0f1..04895ff69 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ContentPanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ContentPanelTest.java @@ -1,107 +1,96 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.component; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import java.awt.Graphics; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * test the ContentPanel class - * - * @version 1.0 - * @date: 2021/4/24 18:03 - **/ -class ContentPanelTest { - private JFrame testFrame; - - /** - * test function the refreshTab . - */ - @Test - void refreshTab() { - ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); - contentPanel.refreshTab(); - assertNotNull(contentPanel); - } - - /** - * test function the refresh . - */ - @Test - void refresh() { - ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); - contentPanel.refresh(); - assertNotNull(contentPanel); - } - - /** - * test function the rangeChange . - */ - @Test - void rangeChange() { - ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); - contentPanel.rangeChange(0L, 1000L); - assertNotNull(contentPanel); - } - - /** - * test function the paintComponent . - */ - @Test - void paintComponent() { - JPanel panel = new JPanel() { - ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - contentPanel.paintComponent(graphics); - } - }; - this.testFrame.add(panel); - this.testFrame.setVisible(true); - this.testFrame.repaint(); - assertNotNull(this.testFrame); - } - - /** - * init . - */ - @BeforeEach - void setUp() { - if (this.testFrame == null) { - this.testFrame = new JFrame(); - } - } - - /** - * destroy . - */ - @AfterEach - void tearDown() { - if (this.testFrame != null) { - this.testFrame.dispose(); - this.testFrame = null; - } - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import java.awt.Graphics; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * test the ContentPanel class + * + * @date: 2021/4/24 18:03 + */ +class ContentPanelTest { + private JFrame testFrame; + + /** + * test function the refresh . + */ + @Test + void refresh() { + ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); + contentPanel.refresh(); + assertNotNull(contentPanel); + } + + /** + * test function the rangeChange . + */ + @Test + void rangeChange() { + ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); + contentPanel.rangeChange(0L, 1000L); + assertNotNull(contentPanel); + } + + /** + * test function the paintComponent . + */ + @Test + void paintComponent() { + JPanel panel = new JPanel() { + ContentPanel contentPanel = new ContentPanel(new AnalystPanel()); + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + contentPanel.paintComponent(graphics); + } + }; + this.testFrame.add(panel); + this.testFrame.setVisible(true); + this.testFrame.repaint(); + assertNotNull(this.testFrame); + } + + /** + * init . + */ + @BeforeEach + void setUp() { + if (this.testFrame == null) { + this.testFrame = new JFrame(); + } + } + + /** + * destroy . + */ + @AfterEach + void tearDown() { + if (this.testFrame != null) { + this.testFrame.dispose(); + this.testFrame = null; + } + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollFlagPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollFlagPanelTest.java index 574baca3c..9ec5724b9 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollFlagPanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollFlagPanelTest.java @@ -1,77 +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. - */ - -package ohos.devtools.views.trace.component; - -import ohos.devtools.views.trace.bean.FlagBean; -import ohos.devtools.views.trace.listener.IFlagListener; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ScrollFlagPanel class . - * - * @version 1.0 - * @date 2021/4/24 18:03 - **/ -class ScrollFlagPanelTest { - /** - * test set the BeanData . - */ - @Test - void setData() { - FlagBean flagBean = new FlagBean(); - ScrollFlagPanel scrollFlagPanel = new ScrollFlagPanel(flagBean); - scrollFlagPanel.setData(flagBean); - final Field field; - try { - field = scrollFlagPanel.getClass().getDeclaredField("flag"); - field.setAccessible(true); - assertEquals(flagBean, field.get(scrollFlagPanel)); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } - - /** - * test set the listener . - */ - @Test - void setFlagListener() { - FlagBean flagBean = new FlagBean(); - ScrollFlagPanel scrollFlagPanel = new ScrollFlagPanel(flagBean); - IFlagListener listener = new IFlagListener() { - @Override - public void flagRemove(FlagBean flag) { - } - - @Override - public void flagChange(FlagBean flag) { - } - }; - scrollFlagPanel.setFlagListener(listener); - final Field field; - try { - field = scrollFlagPanel.getClass().getDeclaredField("flagListener"); - field.setAccessible(true); - assertEquals(listener, field.get(scrollFlagPanel)); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import ohos.devtools.views.trace.bean.FlagBean; +import ohos.devtools.views.trace.listener.IFlagListener; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ScrollFlagPanel class . + * + * @date 2021/4/24 18:03 + */ +class ScrollFlagPanelTest { + /** + * test set the BeanData . + */ + @Test + void setData() { + FlagBean flagBean = new FlagBean(); + ScrollFlagPanel scrollFlagPanel = new ScrollFlagPanel(flagBean); + scrollFlagPanel.setData(flagBean); + final Field field; + try { + field = scrollFlagPanel.getClass().getDeclaredField("flag"); + field.setAccessible(true); + assertEquals(flagBean, field.get(scrollFlagPanel)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + /** + * test set the listener . + */ + @Test + void setFlagListener() { + FlagBean flagBean = new FlagBean(); + ScrollFlagPanel scrollFlagPanel = new ScrollFlagPanel(flagBean); + IFlagListener listener = new IFlagListener() { + @Override + public void flagRemove(FlagBean flag) { + } + + @Override + public void flagChange(FlagBean flag) { + } + }; + scrollFlagPanel.setFlagListener(listener); + final Field field; + try { + field = scrollFlagPanel.getClass().getDeclaredField("flagListener"); + field.setAccessible(true); + assertEquals(listener, field.get(scrollFlagPanel)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollSlicePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollSlicePanelTest.java index c437a76ab..359fdf3fe 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollSlicePanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollSlicePanelTest.java @@ -1,93 +1,92 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.component; - -import ohos.devtools.views.trace.bean.WakeupBean; -import ohos.devtools.views.trace.listener.IScrollSliceLinkListener; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ScrollSlicePanel class . - * - * @version 1.0 - * @date: 2021/4/24 18:03 - **/ -class ScrollSlicePanelTest { - /** - * test set the Data . - */ - @Test - void setData() { - ScrollSlicePanel scrollSlicePanel = new ScrollSlicePanel(); - List dataSource = new ArrayList<>(); - WakeupBean wakeupBean = new WakeupBean(); - scrollSlicePanel.setData("title", dataSource, wakeupBean); - final Field dataSourceField; - final Field wakeupBeanField; - try { - dataSourceField = scrollSlicePanel.getClass().getDeclaredField("dataSource"); - wakeupBeanField = scrollSlicePanel.getClass().getDeclaredField("wakeupBean"); - dataSourceField.setAccessible(true); - wakeupBeanField.setAccessible(true); - assertEquals(dataSource, dataSourceField.get(scrollSlicePanel)); - assertEquals(wakeupBean, wakeupBeanField.get(scrollSlicePanel)); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } - - /** - * test set the ScrollSliceLinkListener . - */ - @Test - void setScrollSliceLinkListener() { - ScrollSlicePanel scrollSlicePanel = new ScrollSlicePanel(); - IScrollSliceLinkListener listener = new IScrollSliceLinkListener() { - @Override - public void linkClick(Object bean) { - } - }; - scrollSlicePanel.setScrollSliceLinkListener(listener); - final Field field; - try { - field = scrollSlicePanel.getClass().getDeclaredField("listener"); - field.setAccessible(true); - assertEquals(listener, field.get(scrollSlicePanel)); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } - - /** - * test create the SliceData . - */ - @Test - void createSliceData() { - String key = "key"; - String value = "value"; - boolean linkable = true; - ScrollSlicePanel.SliceData sliceData = ScrollSlicePanel.createSliceData(key, value, linkable); - assertEquals(key, sliceData.key); - assertEquals(value, sliceData.value); - assertEquals(linkable, sliceData.linkable); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import ohos.devtools.views.trace.bean.WakeupBean; +import ohos.devtools.views.trace.listener.IScrollSliceLinkListener; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ScrollSlicePanel class . + * + * @date: 2021/4/24 18:03 + */ +class ScrollSlicePanelTest { + /** + * test set the Data . + */ + @Test + void setData() { + ScrollSlicePanel scrollSlicePanel = new ScrollSlicePanel(); + List dataSource = new ArrayList<>(); + WakeupBean wakeupBean = new WakeupBean(); + scrollSlicePanel.setData("title", dataSource, wakeupBean); + final Field dataSourceField; + final Field wakeupBeanField; + try { + dataSourceField = scrollSlicePanel.getClass().getDeclaredField("dataSource"); + wakeupBeanField = scrollSlicePanel.getClass().getDeclaredField("wakeupBean"); + dataSourceField.setAccessible(true); + wakeupBeanField.setAccessible(true); + assertEquals(dataSource, dataSourceField.get(scrollSlicePanel)); + assertEquals(wakeupBean, wakeupBeanField.get(scrollSlicePanel)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + /** + * test set the ScrollSliceLinkListener . + */ + @Test + void setScrollSliceLinkListener() { + ScrollSlicePanel scrollSlicePanel = new ScrollSlicePanel(); + IScrollSliceLinkListener listener = new IScrollSliceLinkListener() { + @Override + public void linkClick(Object bean) { + } + }; + scrollSlicePanel.setScrollSliceLinkListener(listener); + final Field field; + try { + field = scrollSlicePanel.getClass().getDeclaredField("listener"); + field.setAccessible(true); + assertEquals(listener, field.get(scrollSlicePanel)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + /** + * test create the SliceData . + */ + @Test + void createSliceData() { + String key = "key"; + String value = "value"; + boolean linkable = true; + ScrollSlicePanel.SliceData sliceData = ScrollSlicePanel.createSliceData(key, value, linkable); + assertEquals(key, sliceData.key); + assertEquals(value, sliceData.value); + assertEquals(linkable, sliceData.linkable); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollTablePanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollTablePanelTest.java index e000fac4d..e5383ffb9 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollTablePanelTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/ScrollTablePanelTest.java @@ -1,54 +1,53 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.component; - -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.util.ArrayList; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ScrollTablePanel class . - * - * @version 1.0 - * @date 2021/4/24 18:03 - **/ -class ScrollTablePanelTest { - /** - * test set the ColumnsAndData . - */ - @Test - void setColumnsAndData() { - String[] columns = new String[] {}; - ArrayList dataSource = new ArrayList<>(); - ScrollTablePanel scrollTablePanel = new ScrollTablePanel(columns, dataSource); - scrollTablePanel.setColumnsAndData(columns, dataSource); - final Field columnsField; - final Field dataSourceField; - try { - columnsField = scrollTablePanel.getClass().getDeclaredField("columns"); - dataSourceField = scrollTablePanel.getClass().getDeclaredField("dataSource"); - columnsField.setAccessible(true); - dataSourceField.setAccessible(true); - assertEquals(columns, columnsField.get(scrollTablePanel)); - assertEquals(dataSource, dataSourceField.get(scrollTablePanel)); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ScrollTablePanel class . + * + * @date 2021/4/24 18:03 + */ +class ScrollTablePanelTest { + /** + * test set the ColumnsAndData . + */ + @Test + void setColumnsAndData() { + String[] columns = new String[] {}; + ArrayList dataSource = new ArrayList<>(); + ScrollTablePanel scrollTablePanel = new ScrollTablePanel(columns, dataSource); + scrollTablePanel.setColumnsAndData(columns, dataSource); + final Field columnsField; + final Field dataSourceField; + try { + columnsField = scrollTablePanel.getClass().getDeclaredField("columns"); + dataSourceField = scrollTablePanel.getClass().getDeclaredField("dataSource"); + columnsField.setAccessible(true); + dataSourceField.setAccessible(true); + assertEquals(columns, columnsField.get(scrollTablePanel)); + assertEquals(dataSource, dataSourceField.get(scrollTablePanel)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TabPanelTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TabPanelTest.java deleted file mode 100644 index 2fb1f88a3..000000000 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TabPanelTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.component; - -import org.junit.jupiter.api.Test; - -import java.awt.event.MouseEvent; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test TabPanel class . - * - * @version 1.0 - * @date 2021/4/24 18:03 - **/ -class TabPanelTest { - /** - * test function the mouseDragged . - */ - @Test - void mouseDragged() { - TabPanel tabPanel = new TabPanel(); - MouseEvent mouseEvent = new MouseEvent(tabPanel, 1, 1, 1, 1, 1, 1, true, 1); - tabPanel.mouseDragged(mouseEvent); - assertEquals(300, tabPanel.getMHeight()); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - TabPanel tabPanel = new TabPanel(); - MouseEvent mouseEvent = new MouseEvent(tabPanel, 1, 1, 1, 1, 1, 1, true, 1); - tabPanel.mouseMoved(mouseEvent); - assertEquals(300, tabPanel.getMHeight()); - } - - /** - * test function the hideInBottom . - */ - @Test - void hideInBottom() { - TabPanel tabPanel = new TabPanel(); - tabPanel.hideInBottom(); - assertEquals(300, tabPanel.getMHeight()); - } - - /** - * test get the MHeight . - */ - @Test - void getMHeight() { - TabPanel tabPanel = new TabPanel(); - assertEquals(300, tabPanel.getMHeight()); - } - - /** - * test get the MyHeight . - */ - @Test - void getMyHeight() { - assertEquals(0, TabPanel.getMyHeight()); - } -} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TimeViewPortTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TimeViewPortTest.java index 7f5b33f4e..fc21681c1 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TimeViewPortTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/component/TimeViewPortTest.java @@ -1,69 +1,68 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.component; - -import org.junit.jupiter.api.Test; - -import java.awt.event.MouseEvent; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test TimeViewPort class . - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class TimeViewPortTest { - /** - * test set the mousePressed . - */ - @Test - void mousePressed() { - TimeViewPort timeViewPort = new TimeViewPort(height -> { - }, (startNS, endNS) -> { - }); - MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); - timeViewPort.mousePressed(mouseEvent); - assertEquals(0, timeViewPort.getHeight()); - } - - /** - * test set the mouseDragged . - */ - @Test - void mouseDragged() { - TimeViewPort timeViewPort = new TimeViewPort(height -> { - }, (startNS, endNS) -> { - }); - MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); - timeViewPort.mouseDragged(mouseEvent); - assertEquals(0, timeViewPort.getHeight()); - } - - /** - * test set the mouseMoved . - */ - @Test - void mouseMoved() { - TimeViewPort timeViewPort = new TimeViewPort(height -> { - }, (startNS, endNS) -> { - }); - MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); - timeViewPort.mouseMoved(mouseEvent); - assertEquals(0, timeViewPort.getHeight()); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.component; + +import org.junit.jupiter.api.Test; + +import java.awt.event.MouseEvent; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test TimeViewPort class . + * + * @date 2021/4/24 18:04 + */ +class TimeViewPortTest { + /** + * test set the mousePressed . + */ + @Test + void mousePressed() { + TimeViewPort timeViewPort = new TimeViewPort(height -> { + }, (startNS, endNS) -> { + }); + MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); + timeViewPort.mousePressed(mouseEvent); + assertEquals(0, timeViewPort.getHeight()); + } + + /** + * test set the mouseDragged . + */ + @Test + void mouseDragged() { + TimeViewPort timeViewPort = new TimeViewPort(height -> { + }, (startNS, endNS) -> { + }); + MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); + timeViewPort.mouseDragged(mouseEvent); + assertEquals(0, timeViewPort.getHeight()); + } + + /** + * test set the mouseMoved . + */ + @Test + void mouseMoved() { + TimeViewPort timeViewPort = new TimeViewPort(height -> { + }, (startNS, endNS) -> { + }); + MouseEvent mouseEvent = new MouseEvent(timeViewPort, 1, 1, 1, 1, 1, 1, true, 1); + timeViewPort.mouseMoved(mouseEvent); + assertEquals(0, timeViewPort.getHeight()); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/AbstractDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/AbstractDataFragmentTest.java index d09f8a8b9..26ffae5b2 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/AbstractDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/AbstractDataFragmentTest.java @@ -1,140 +1,146 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.awt.Rectangle; -import java.awt.event.MouseEvent; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -/** - * test AbstractDataFragment class . - * - * @version 1.0 - * @date 2021/4/24 18:04 - **/ -class AbstractDataFragmentTest { - private AbstractDataFragment abstractDataFragment; - - /** - * init the setUp . - */ - @BeforeEach - void setUp() { - abstractDataFragment = new AbstractDataFragment() { - @Override - public void mouseClicked(MouseEvent event) { - } - - @Override - public void mousePressed(MouseEvent event) { - } - - @Override - public void mouseExited(MouseEvent event) { - } - - @Override - public void mouseEntered(MouseEvent event) { - } - - @Override - public void mouseMoved(MouseEvent event) { - } - - @Override - public void mouseReleased(MouseEvent event) { - } - }; - } - - /** - * test set the Visible . - */ - @Test - void setVisible() { - boolean currentVis = true; - abstractDataFragment.setVisible(currentVis); - assertEquals(abstractDataFragment.visible, currentVis); - } - - /** - * test the range function . - */ - @Test - void range() { - long startNs = 1L; - long endNs = 5L; - abstractDataFragment.range(startNs, endNs); - assertEquals(startNs, abstractDataFragment.startNS); - assertEquals(endNs, abstractDataFragment.endNS); - } - - /** - * test the getX function . - */ - @Test - void getX() { - abstractDataFragment.range(100L, 1000000L); - Rectangle rectangle = new Rectangle(); - rectangle.width = 1000; - abstractDataFragment.setDataRect(rectangle); - assertEquals(9, abstractDataFragment.getX(10000L)); - } - - /** - * test the getXDouble function . - */ - @Test - void getXDouble() { - abstractDataFragment.range(100L, 1000000L); - Rectangle rectangle = new Rectangle(); - rectangle.width = 1000; - abstractDataFragment.setDataRect(rectangle); - assertEquals(9, abstractDataFragment.getXDouble(10000L)); - } - - /** - * test set the clearSelected . - */ - @Test - void clearSelected() { - abstractDataFragment.clearSelected(); - assertNotEquals(abstractDataFragment, null); - } - - /** - * test set the setRect . - */ - @Test - void setRect() { - Rectangle rectangle = new Rectangle(); - rectangle.width = 1000; - rectangle.height = 100; - rectangle.x = 10; - rectangle.y = 10; - abstractDataFragment.setRect(rectangle); - abstractDataFragment.setRect(100, 100, 100, 100); - assertEquals(100, abstractDataFragment.getRect().x); - assertEquals(100, abstractDataFragment.getRect().y); - assertEquals(100, abstractDataFragment.getRect().height); - assertEquals(100, abstractDataFragment.getRect().width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.util.Utils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.awt.Rectangle; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * test AbstractDataFragment class . + * + * @version 1.0 + * @date 2021/4/24 18:04 + */ +class AbstractDataFragmentTest { + private AbstractDataFragment abstractDataFragment; + + /** + * init the setUp . + */ + @BeforeEach + void setUp() { + abstractDataFragment = new AbstractDataFragment(null, false, false) { + @Override + public void mouseClicked(MouseEvent event) { + } + + @Override + public void mousePressed(MouseEvent event) { + } + + @Override + public void mouseExited(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseMoved(MouseEvent event) { + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + @Override + public void keyReleased(KeyEvent event) { + } + }; + } + + /** + * test set the Visible . + */ + @Test + void setVisible() { + boolean currentVis = true; + abstractDataFragment.setVisible(currentVis); + assertEquals(abstractDataFragment.visible, currentVis); + } + + /** + * test the range function . + */ + @Test + void range() { + long startNs = 1L; + long endNs = 5L; + abstractDataFragment.range(startNs, endNs); + assertEquals(startNs, abstractDataFragment.startNS); + assertEquals(endNs, abstractDataFragment.endNS); + } + + /** + * test the getX function . + */ + @Test + void getX() { + abstractDataFragment.range(100L, 1000000L); + Rectangle rectangle = new Rectangle(); + rectangle.width = 1000; + abstractDataFragment.setDataRect(rectangle); + assertEquals(9, abstractDataFragment.getX(10000L)); + } + + /** + * test the getXDouble function . + */ + @Test + void getXDouble() { + abstractDataFragment.range(100L, 1000000L); + Rectangle rectangle = new Rectangle(); + rectangle.width = 1000; + abstractDataFragment.setDataRect(rectangle); + assertEquals(9, abstractDataFragment.getXDouble(10000L)); + } + + /** + * test set the clearSelected . + */ + @Test + void clearSelected() { + abstractDataFragment.clearSelected(); + assertNotEquals(abstractDataFragment, null); + } + + /** + * test set the setRect . + */ + @Test + void setRect() { + Rectangle rectangle = new Rectangle(); + rectangle.width = 1000; + rectangle.height = 100; + Utils.setX(rectangle, 10); + Utils.setY(rectangle, 10); + abstractDataFragment.setRect(rectangle); + abstractDataFragment.setRect(100, 100, 100, 100); + assertEquals(100, Utils.getX(abstractDataFragment.getRect())); + assertEquals(100, Utils.getY(abstractDataFragment.getRect())); + assertEquals(100, abstractDataFragment.getRect().height); + assertEquals(100, abstractDataFragment.getRect().width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuDataFragmentTest.java index 7ddf5bbb2..447b00e0f 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuDataFragmentTest.java @@ -1,192 +1,168 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * test CpuDataFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:57 - **/ -class CpuDataFragmentTest { - private CpuDataFragment cpuDataFragment; - private JPanel jPanel; - private JFrame testFrame; - - /** - * test function the draw . - */ - @Test - void draw() { - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - cpuDataFragment.draw(graphics2D); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mousePressed . - */ - @Test - void mousePressed() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mousePressed(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mouseExited . - */ - @Test - void mouseExited() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mouseExited(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mouseEntered . - */ - @Test - void mouseEntered() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mouseEntered(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the mouseReleased . - */ - @Test - void mouseReleased() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.mouseReleased(mouseEvent); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.click(mouseEvent, new CpuData()); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the blur . - */ - @Test - void blur() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.blur(mouseEvent, new CpuData()); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * test function the focus . - */ - @Test - void focus() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuDataFragment.focus(mouseEvent, new CpuData()); - Assertions.assertNotNull(cpuDataFragment.favoriteGraph); - } - - /** - * init the setUp . - */ - @BeforeEach - void setUp() { - if (this.testFrame == null) { - this.testFrame = new JFrame(); - } - List list = new ArrayList<>(); - jPanel = new JPanel(); - cpuDataFragment = new CpuDataFragment(jPanel, 1, list); - } - - /** - * on the tearDown . - */ - @AfterEach - void tearDown() { - if (this.testFrame != null) { - this.testFrame.dispose(); - this.testFrame = null; - } - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.bean.CpuData; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + +/** + * test CpuDataFragment class . + * + * @date 2021/4/24 17:57 + */ +class CpuDataFragmentTest { + private CpuDataFragment cpuDataFragment; + private JPanel jPanel; + private JFrame testFrame; + + /** + * test function the draw . + */ + @Test + void draw() { + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + cpuDataFragment.draw(graphics2D); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mousePressed . + */ + @Test + void mousePressed() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mousePressed(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mouseExited . + */ + @Test + void mouseExited() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mouseExited(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mouseEntered . + */ + @Test + void mouseEntered() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mouseEntered(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the mouseReleased . + */ + @Test + void mouseReleased() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.mouseReleased(mouseEvent); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.click(mouseEvent, new CpuData()); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the blur . + */ + @Test + void blur() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.blur(mouseEvent, new CpuData()); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * test function the focus . + */ + @Test + void focus() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuDataFragment.focus(mouseEvent, new CpuData()); + Assertions.assertNotNull(cpuDataFragment.favoriteGraph); + } + + /** + * init the setUp . + */ + @BeforeEach + void setUp() { + if (this.testFrame == null) { + this.testFrame = new JFrame(); + } + List list = new ArrayList<>(); + jPanel = new JPanel(); + cpuDataFragment = new CpuDataFragment(jPanel, 1, list); + } + + /** + * on the tearDown . + */ + @AfterEach + void tearDown() { + if (this.testFrame != null) { + this.testFrame.dispose(); + this.testFrame = null; + } + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragmentTest.java index 15f98315d..c30766d9a 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/CpuFreqDataFragmentTest.java @@ -1,120 +1,95 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.bean.CpuData; -import ohos.devtools.views.trace.bean.CpuFreqData; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * test CpuFreqDataFragment class . - * - * @version 1.0 - * @date: 2021/4/24 17:57 - **/ -class CpuFreqDataFragmentTest { - private CpuFreqDataFragment cpuFreqDataFragment; - private JPanel jPanel; - - /** - * init the setUp . - */ - @BeforeEach - void setUp() { - List list = new ArrayList<>(); - Map map = new HashMap<>() {{ - put("name", "100"); - put("value", "2.5GHZ"); - }}; - jPanel = new JPanel(); - cpuFreqDataFragment = new CpuFreqDataFragment(jPanel, "name", map, list); - } - - /** - * test function the draw . - */ - @Test - void draw() { - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - cpuFreqDataFragment.draw(graphics2D); - Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuFreqDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuFreqDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - cpuFreqDataFragment.click(mouseEvent, new CpuData()); - Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.bean.CpuData; +import ohos.devtools.views.trace.bean.CpuFreqData; +import ohos.devtools.views.trace.bean.CpuFreqMax; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + +/** + * test CpuFreqDataFragment class . + * + * @date: 2021/4/24 17:57 + */ +class CpuFreqDataFragmentTest { + private CpuFreqDataFragment cpuFreqDataFragment; + private JPanel jPanel; + + /** + * init the setUp . + */ + @BeforeEach + void setUp() { + List list = new ArrayList<>(); + CpuFreqMax cpuFreqMax = new CpuFreqMax(); + cpuFreqMax.setName("100"); + cpuFreqMax.setValue(2.5); + jPanel = new JPanel(); + cpuFreqDataFragment = new CpuFreqDataFragment(jPanel, "name", cpuFreqMax, list); + } + + /** + * test function the draw . + */ + @Test + void draw() { + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + cpuFreqDataFragment.draw(graphics2D); + Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuFreqDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuFreqDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + cpuFreqDataFragment.click(mouseEvent, new CpuData()); + Assertions.assertNotNull(cpuFreqDataFragment.favoriteGraph); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/FunctionDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/FunctionDataFragmentTest.java index 88ecc8751..bc19dfd20 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/FunctionDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/FunctionDataFragmentTest.java @@ -1,116 +1,95 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.bean.FunctionBean; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.ArrayList; -import java.util.Map; - -/** - * test FunctionDataFragment class . - * - * @version 1.0 - * @date: 2021/4/24 17:57 - **/ -class FunctionDataFragmentTest { - private FunctionDataFragment functionDataFragment; - private JPanel jPanel; - - /** - * init the setUp . - */ - @BeforeEach - void setUp() { - ArrayList list = new ArrayList<>(); - jPanel = new JPanel(); - functionDataFragment = new FunctionDataFragment(jPanel, list); - functionDataFragment.thread = new ThreadData(); - } - - /** - * test function the draw . - */ - @Test - void draw() { - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - functionDataFragment.draw(graphics2D); - Assertions.assertNotNull(functionDataFragment); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - functionDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(functionDataFragment); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - functionDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(functionDataFragment); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - functionDataFragment.click(mouseEvent, new FunctionBean()); - Assertions.assertNotNull(functionDataFragment); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.bean.FunctionBean; +import ohos.devtools.views.trace.bean.ThreadData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.ArrayList; + +/** + * test FunctionDataFragment class . + * + * @date: 2021/4/24 17:57 + */ +class FunctionDataFragmentTest { + private FunctionDataFragment functionDataFragment; + private JPanel jPanel; + + /** + * init the setUp . + */ + @BeforeEach + void setUp() { + ArrayList list = new ArrayList<>(); + jPanel = new JPanel(); + functionDataFragment = new FunctionDataFragment(jPanel, list); + functionDataFragment.thread = new ThreadData(); + } + + /** + * test function the draw . + */ + @Test + void draw() { + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + functionDataFragment.draw(graphics2D); + Assertions.assertNotNull(functionDataFragment); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + functionDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(functionDataFragment); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + functionDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(functionDataFragment); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + FunctionBean functionBean = new FunctionBean(); + functionBean.setStartTime(1L); + functionBean.setDuration(1L); + functionDataFragment.click(mouseEvent, functionBean); + Assertions.assertNotNull(functionDataFragment); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/MemDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/MemDataFragmentTest.java index dded3173e..f41f1765c 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/MemDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/MemDataFragmentTest.java @@ -1,77 +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. - */ - -package ohos.devtools.views.trace.fragment; - -import ohos.devtools.views.trace.bean.ProcessMem; -import ohos.devtools.views.trace.bean.ThreadData; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.event.MouseEvent; - -/** - * test MemDataFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:57 - **/ -class MemDataFragmentTest { - private MemDataFragment memDataFragment; - private JPanel jPanel; - - /** - * init the memDataFragment . - */ - @BeforeEach - void setUp() { - ProcessMem processMem = new ProcessMem(); - processMem.setProcessName("title"); - jPanel = new JPanel(); - memDataFragment = new MemDataFragment(jPanel, processMem); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - memDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(memDataFragment); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - memDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(memDataFragment); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - memDataFragment.click(mouseEvent, new ThreadData()); - Assertions.assertNotNull(memDataFragment); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import ohos.devtools.views.trace.bean.ProcessMem; +import ohos.devtools.views.trace.bean.ThreadData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.event.MouseEvent; + +/** + * test MemDataFragment class . + * + * @date 2021/4/24 17:57 + */ +class MemDataFragmentTest { + private MemDataFragment memDataFragment; + private JPanel jPanel; + + /** + * init the memDataFragment . + */ + @BeforeEach + void setUp() { + ProcessMem processMem = new ProcessMem(); + processMem.setProcessName("title"); + jPanel = new JPanel(); + memDataFragment = new MemDataFragment(jPanel, processMem); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + memDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(memDataFragment); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + memDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(memDataFragment); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + memDataFragment.click(mouseEvent, new ThreadData()); + Assertions.assertNotNull(memDataFragment); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ProcessDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ProcessDataFragmentTest.java index 291239426..fa33d3d04 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ProcessDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ProcessDataFragmentTest.java @@ -1,112 +1,89 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.bean.Process; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test ProcessDataFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:57 - **/ -class ProcessDataFragmentTest { - private ProcessDataFragment processDataFragment; - private JPanel jPanel; - - /** - * init the memDataFragment . - */ - @BeforeEach - void setUp() { - Process process = new Process(); - jPanel = new JPanel(); - processDataFragment = new ProcessDataFragment(jPanel, process); - } - - /** - * test function the draw . - */ - @Test - void draw() { - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - processDataFragment.draw(graphics2D); - Assertions.assertNotNull(processDataFragment); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - processDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(processDataFragment); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - processDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(processDataFragment); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - processDataFragment.click(mouseEvent); - Assertions.assertNotNull(processDataFragment); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.bean.Process; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** + * test ProcessDataFragment class . + * + * @date 2021/4/24 17:57 + */ +class ProcessDataFragmentTest { + private ProcessDataFragment processDataFragment; + private JPanel jPanel; + + /** + * init the memDataFragment . + */ + @BeforeEach + void setUp() { + Process process = new Process(); + process.setPid(1); + jPanel = new JPanel(); + processDataFragment = new ProcessDataFragment(jPanel, process); + } + + /** + * test function the draw . + */ + @Test + void draw() { + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + processDataFragment.draw(graphics2D); + Assertions.assertNotNull(processDataFragment); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + processDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(processDataFragment); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + processDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(processDataFragment); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + processDataFragment.click(mouseEvent); + Assertions.assertNotNull(processDataFragment); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ThreadDataFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ThreadDataFragmentTest.java index 8f6f7459e..25ef8e5df 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ThreadDataFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ThreadDataFragmentTest.java @@ -1,112 +1,88 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.bean.ThreadData; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test ThreadDataFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:58 - **/ -class ThreadDataFragmentTest { - private ThreadDataFragment threadDataFragment; - private JPanel jPanel; - - /** - * init the threadDataFragment . - */ - @BeforeEach - void setUp() { - ThreadData process = new ThreadData(); - jPanel = new JPanel(); - threadDataFragment = new ThreadDataFragment(jPanel, process); - } - - /** - * test function the draw . - */ - @Test - void draw() { - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - threadDataFragment.draw(graphics2D); - Assertions.assertNotNull(threadDataFragment); - } - - /** - * test function the mouseClicked . - */ - @Test - void mouseClicked() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - threadDataFragment.mouseClicked(mouseEvent); - Assertions.assertNotNull(threadDataFragment); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - threadDataFragment.mouseMoved(mouseEvent); - Assertions.assertNotNull(threadDataFragment); - } - - /** - * test function the click . - */ - @Test - void click() { - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - threadDataFragment.click(mouseEvent, new ThreadData()); - Assertions.assertNotNull(threadDataFragment); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.bean.ThreadData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** + * test ThreadDataFragment class . + * + * @date 2021/4/24 17:58 + */ +class ThreadDataFragmentTest { + private ThreadDataFragment threadDataFragment; + private JPanel jPanel; + + /** + * init the threadDataFragment . + */ + @BeforeEach + void setUp() { + ThreadData process = new ThreadData(); + jPanel = new JPanel(); + threadDataFragment = new ThreadDataFragment(jPanel, process); + } + + /** + * test function the draw . + */ + @Test + void draw() { + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + threadDataFragment.draw(graphics2D); + Assertions.assertNotNull(threadDataFragment); + } + + /** + * test function the mouseClicked . + */ + @Test + void mouseClicked() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + threadDataFragment.mouseClicked(mouseEvent); + Assertions.assertNotNull(threadDataFragment); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + threadDataFragment.mouseMoved(mouseEvent); + Assertions.assertNotNull(threadDataFragment); + } + + /** + * test function the click . + */ + @Test + void click() { + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + threadDataFragment.click(mouseEvent, new ThreadData()); + Assertions.assertNotNull(threadDataFragment); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/AbstractGraphTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/AbstractGraphTest.java index c6f420fa9..dd7f11ba6 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/AbstractGraphTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/AbstractGraphTest.java @@ -1,328 +1,304 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test AbstractGraph class . - * - * @version 1.0 - * @date: 2021/4/24 17:55 - **/ -class AbstractGraphTest { - /** - * test function the draw . - */ - @Test - void draw() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - graph.draw(graphics2D); - Assertions.assertNotNull(graph); - } - - /** - * test function the onFocus . - */ - @Test - void onFocus() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onBlur . - */ - @Test - void onBlur() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onClick . - */ - @Test - void onClick() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onMouseMove . - */ - @Test - void onMouseMove() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the edgeInspect . - */ - @Test - void edgeInspect() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the drawString . - */ - @Test - void drawString() { - AbstractGraph graph = new AbstractGraph() { - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void onFocus(MouseEvent event) { - } - - @Override - public void onBlur(MouseEvent event) { - } - - @Override - public void onClick(MouseEvent event) { - } - - @Override - public void onMouseMove(MouseEvent event) { - } - }; - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** + * test AbstractGraph class . + * + * @date: 2021/4/24 17:55 + */ +class AbstractGraphTest { + /** + * test function the draw . + */ + @Test + void draw() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + graph.draw(graphics2D); + Assertions.assertNotNull(graph); + } + + /** + * test function the onFocus . + */ + @Test + void onFocus() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onBlur . + */ + @Test + void onBlur() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onClick . + */ + @Test + void onClick() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onMouseMove . + */ + @Test + void onMouseMove() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the edgeInspect . + */ + @Test + void edgeInspect() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the drawString . + */ + @Test + void drawString() { + AbstractGraph graph = new AbstractGraph() { + @Override + public void draw(Graphics2D graphics) { + } + + @Override + public void onFocus(MouseEvent event) { + } + + @Override + public void onBlur(MouseEvent event) { + } + + @Override + public void onClick(MouseEvent event) { + } + + @Override + public void onMouseMove(MouseEvent event) { + } + }; + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/CheckGraphTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/CheckGraphTest.java index b316b2fd8..e9cecf7ff 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/CheckGraphTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/CheckGraphTest.java @@ -1,167 +1,143 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test CheckGraph class . - * - * @version 1.0 - * @date 2021/4/24 17:55 - **/ -class CheckGraphTest { - /** - * test function the edgeInspect . - */ - @Test - void edgeInspect() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the drawString . - */ - @Test - void drawString() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the getChecked . - */ - @Test - void getChecked() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setChecked . - */ - @Test - void setChecked() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the draw . - */ - @Test - void draw() { - CheckGraph graph = new CheckGraph(null, null); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - graph.draw(graphics2D); - Assertions.assertNotNull(graph); - } - - /** - * test function the onFocus . - */ - @Test - void onFocus() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onBlur . - */ - @Test - void onBlur() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onClick . - */ - @Test - void onClick() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onMouseMove . - */ - @Test - void onMouseMove() { - CheckGraph graph = new CheckGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +/** + * test CheckGraph class . + * + * @date 2021/4/24 17:55 + */ +class CheckGraphTest { + /** + * test function the edgeInspect . + */ + @Test + void edgeInspect() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the drawString . + */ + @Test + void drawString() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the getChecked . + */ + @Test + void getChecked() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setChecked . + */ + @Test + void setChecked() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the draw . + */ + @Test + void draw() { + CheckGraph graph = new CheckGraph(null, null); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + graph.draw(graphics2D); + Assertions.assertNotNull(graph); + } + + /** + * test function the onFocus . + */ + @Test + void onFocus() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onBlur . + */ + @Test + void onBlur() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onClick . + */ + @Test + void onClick() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onMouseMove . + */ + @Test + void onMouseMove() { + CheckGraph graph = new CheckGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/ExpandGraphTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/ExpandGraphTest.java index 475d4b96f..e4fd8e56b 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/ExpandGraphTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/ExpandGraphTest.java @@ -1,197 +1,173 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test ExpandGraph class . - * - * @version 1.0 - * @date: 2021/4/24 17:56 - **/ -class ExpandGraphTest { - /** - * test function the edgeInspect . - */ - @Test - void edgeInspect() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the drawString . - */ - @Test - void drawString() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the getImage . - */ - @Test - void getImage() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setImage . - */ - @Test - void setImage() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the isExpand . - */ - @Test - void isExpand() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setExpand . - */ - @Test - void setExpand() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the draw . - */ - @Test - void draw() { - ExpandGraph graph = new ExpandGraph(null, null); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - graph.draw(graphics2D); - Assertions.assertNotNull(graph); - } - - /** - * test function the onFocus . - */ - @Test - void onFocus() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onBlur . - */ - @Test - void onBlur() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onClick . - */ - @Test - void onClick() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onMouseMove . - */ - @Test - void onMouseMove() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setOnClickListener . - */ - @Test - void setOnClickListener() { - ExpandGraph graph = new ExpandGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +/** + * test ExpandGraph class . + * + * @date: 2021/4/24 17:56 + */ +class ExpandGraphTest { + /** + * test function the edgeInspect . + */ + @Test + void edgeInspect() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the drawString . + */ + @Test + void drawString() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the getImage . + */ + @Test + void getImage() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setImage . + */ + @Test + void setImage() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the isExpand . + */ + @Test + void isExpand() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setExpand . + */ + @Test + void setExpand() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the draw . + */ + @Test + void draw() { + ExpandGraph graph = new ExpandGraph(null, null); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + graph.draw(graphics2D); + Assertions.assertNotNull(graph); + } + + /** + * test function the onFocus . + */ + @Test + void onFocus() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onBlur . + */ + @Test + void onBlur() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onClick . + */ + @Test + void onClick() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onMouseMove . + */ + @Test + void onMouseMove() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setOnClickListener . + */ + @Test + void setOnClickListener() { + ExpandGraph graph = new ExpandGraph(null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraphTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraphTest.java index 515688673..4982ebe40 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraphTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/graph/FavoriteGraphTest.java @@ -1,233 +1,216 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.graph; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.fragment.AbstractDataFragment; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test FavoriteGraph class . - * - * @version 1.0 - * @date 2021/4/24 17:56 - **/ -class FavoriteGraphTest { - /** - * test function the edgeInspect . - */ - @Test - void edgeInspect() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the drawString . - */ - @Test - void drawString() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the getRightGraph . - */ - @Test - void getRightGraph() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the setRightGraph . - */ - @Test - void setRightGraph() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the isDisplay . - */ - @Test - void isDisplay() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the display . - */ - @Test - void display() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the isFavorite . - */ - @Test - void isFavorite() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the favorite . - */ - @Test - void favorite() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the draw . - */ - @Test - void draw() { - FavoriteGraph graph = new FavoriteGraph(new AbstractDataFragment() { - @Override - public void mouseClicked(MouseEvent event) { - } - - @Override - public void mousePressed(MouseEvent event) { - } - - @Override - public void mouseExited(MouseEvent event) { - } - - @Override - public void mouseEntered(MouseEvent event) { - } - - @Override - public void mouseMoved(MouseEvent event) { - } - - @Override - public void mouseReleased(MouseEvent event) { - } - }, null); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - graph.draw(graphics2D); - Assertions.assertNotNull(graph); - } - - /** - * test function the onFocus . - */ - @Test - void onFocus() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onBlur . - */ - @Test - void onBlur() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onClick . - */ - @Test - void onClick() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } - - /** - * test function the onMouseMove . - */ - @Test - void onMouseMove() { - FavoriteGraph graph = new FavoriteGraph(null, null); - graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); - Assertions.assertEquals(100, graph.rect.width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.graph; + +import com.intellij.util.ui.UIUtil; +import ohos.devtools.views.trace.fragment.AbstractDataFragment; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** + * test FavoriteGraph class . + * + * @date 2021/4/24 17:56 + */ +class FavoriteGraphTest { + /** + * test function the edgeInspect . + */ + @Test + void edgeInspect() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the drawString . + */ + @Test + void drawString() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the getRightGraph . + */ + @Test + void getRightGraph() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the setRightGraph . + */ + @Test + void setRightGraph() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the isDisplay . + */ + @Test + void isDisplay() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the display . + */ + @Test + void display() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the isFavorite . + */ + @Test + void isFavorite() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the favorite . + */ + @Test + void favorite() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * 11223344556677889900--```qwertyuiop[]\asdfghjkl;' + * aszxcvbnm,./?AAAA + * test function the draw . + */ + @Test + void draw() { + FavoriteGraph graph = new FavoriteGraph(new AbstractDataFragment(null, false, false) { + @Override + public void mouseClicked(MouseEvent event) { + } + + @Override + public void mousePressed(MouseEvent event) { + } + + @Override + public void mouseExited(MouseEvent event) { + } + + @Override + public void mouseEntered(MouseEvent event) { + } + + @Override + public void mouseMoved(MouseEvent event) { + } + + @Override + public void mouseReleased(MouseEvent event) { + } + + @Override + public void keyReleased(KeyEvent event) { + } + }, null, null); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + graph.draw(graphics2D); + Assertions.assertNotNull(graph); + } + + /** + * test function the onFocus . + */ + @Test + void onFocus() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onBlur . + */ + @Test + void onBlur() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onClick . + */ + @Test + void onClick() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } + + /** + * test function the onMouseMove . + */ + @Test + void onMouseMove() { + FavoriteGraph graph = new FavoriteGraph(null, null, null); + graph.setRect(0.0F, 0.0F, 100.0F, 100.0F); + Assertions.assertEquals(100, graph.rect.width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragmentTest.java index f92d7c593..390affb17 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/AbstractFragmentTest.java @@ -1,188 +1,187 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Graphics2D; -import java.awt.Rectangle; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; - -/** - * test AbstractFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:53 - **/ -class AbstractFragmentTest { - /** - * test function the getRect . - */ - @Test - void getRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - Rectangle rect = fragment.getRect(); - assertEquals(true, rect != null); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, fragment.getRect().width); - } - - /** - * test function the getDescRect . - */ - @Test - void getDescRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.setDescRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, fragment.getDescRect().width); - } - - /** - * test function the setDescRect . - */ - @Test - void setDescRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.setDescRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, fragment.getDescRect().width); - } - - /** - * test function the getDataRect . - */ - @Test - void getDataRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.setDataRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, fragment.getDataRect().width); - } - - /** - * test function the setDataRect . - */ - @Test - void setDataRect() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.setDataRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, fragment.getDataRect().width); - } - - /** - * test function the getRoot . - */ - @Test - void getRoot() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - JPanel jPanel = new JPanel(); - fragment.setRoot(jPanel); - assertEquals(jPanel, fragment.getRoot()); - } - - /** - * test function the setRoot . - */ - @Test - void setRoot() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - JPanel jPanel = new JPanel(); - fragment.setRoot(jPanel); - assertEquals(jPanel, fragment.getRoot()); - } - - /** - * test function the getLineColor . - */ - @Test - void getLineColor() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - assertNotNull(fragment.getLineColor()); - } - - /** - * test function the getTextColor . - */ - @Test - void getTextColor() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - assertNotNull(fragment.getTextColor()); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - AbstractFragment fragment = new AbstractFragment() { - @Override - public void draw(Graphics2D graphics) { - } - }; - fragment.repaint(); - assertNotNull(fragment); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.Rectangle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * test AbstractFragment class . + * + * @date 2021/4/24 17:53 + */ +class AbstractFragmentTest { + /** + * test function the getRect . + */ + @Test + void getRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + Rectangle rect = fragment.getRect(); + assertEquals(true, rect != null); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, fragment.getRect().width); + } + + /** + * test function the getDescRect . + */ + @Test + void getDescRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.setDescRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, fragment.getDescRect().width); + } + + /** + * test function the setDescRect . + */ + @Test + void setDescRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.setDescRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, fragment.getDescRect().width); + } + + /** + * test function the getDataRect . + */ + @Test + void getDataRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.setDataRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, fragment.getDataRect().width); + } + + /** + * test function the setDataRect . + */ + @Test + void setDataRect() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.setDataRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, fragment.getDataRect().width); + } + + /** + * test function the getRoot . + */ + @Test + void getRoot() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + JPanel jPanel = new JPanel(); + fragment.setRoot(jPanel); + assertEquals(jPanel, fragment.getRoot()); + } + + /** + * test function the setRoot . + */ + @Test + void setRoot() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + JPanel jPanel = new JPanel(); + fragment.setRoot(jPanel); + assertEquals(jPanel, fragment.getRoot()); + } + + /** + * test function the getLineColor . + */ + @Test + void getLineColor() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + assertNotNull(fragment.getLineColor()); + } + + /** + * test function the getTextColor . + */ + @Test + void getTextColor() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + assertNotNull(fragment.getTextColor()); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + AbstractFragment fragment = new AbstractFragment() { + @Override + public void draw(Graphics2D graphics) { + } + }; + fragment.repaint(); + assertNotNull(fragment); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/CpuFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/CpuFragmentTest.java index 9b433cb06..7bde31844 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/CpuFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/CpuFragmentTest.java @@ -1,269 +1,244 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; - -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * test CpuFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:54 - **/ -class CpuFragmentTest { - /** - * test function the draw . - */ - @Test - void draw() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - cpuFragment.draw(graphics2D); - Assertions.assertNotNull(cpuFragment); - } - - /** - * test function the getRect . - */ - @Test - void getRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - assertEquals(true, cpuFragment.getRect() != null); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getDescRect . - */ - @Test - void getDescRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the setDescRect . - */ - @Test - void setDescRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getDataRect . - */ - @Test - void getDataRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the setDataRect . - */ - @Test - void setDataRect() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getRoot . - */ - @Test - void getRoot() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the setRoot . - */ - @Test - void setRoot() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getLineColor . - */ - @Test - void getLineColor() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getTextColor . - */ - @Test - void getTextColor() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the repaint . - */ - @Test - void repaint() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the getSelectX . - */ - @Test - void getSelectX() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setSelectX(100); - assertEquals(100, cpuFragment.getSelectX()); - } - - /** - * test function the setSelectX . - */ - @Test - void setSelectX() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setSelectX(100); - assertEquals(100, cpuFragment.getSelectX()); - } - - /** - * test function the getSelectY . - */ - @Test - void getSelectY() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setSelectY(100); - assertEquals(100, cpuFragment.getSelectY()); - } - - /** - * test function the setSelectY . - */ - @Test - void setSelectY() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setSelectY(100); - assertEquals(100, cpuFragment.getSelectY()); - } - - /** - * test function the setRangeChangeListener . - */ - @Test - void setRangeChangeListener() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the mouseDragged . - */ - @Test - void mouseDragged() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } - - /** - * test function the setRange . - */ - @Test - void setRange() { - CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { - }); - cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); - assertEquals(100, cpuFragment.getRect().width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.image.BufferedImage; + +import static org.junit.Assert.assertEquals; + +/** + * test CpuFragment class . + * + * @date 2021/4/24 17:54 + */ +class CpuFragmentTest { + /** + * test function the draw . + */ + @Test + void draw() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + cpuFragment.draw(graphics2D); + Assertions.assertNotNull(cpuFragment); + } + + /** + * test function the getRect . + */ + @Test + void getRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + assertEquals(true, cpuFragment.getRect() != null); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getDescRect . + */ + @Test + void getDescRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the setDescRect . + */ + @Test + void setDescRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getDataRect . + */ + @Test + void getDataRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the setDataRect . + */ + @Test + void setDataRect() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getRoot . + */ + @Test + void getRoot() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the setRoot . + */ + @Test + void setRoot() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getLineColor . + */ + @Test + void getLineColor() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getTextColor . + */ + @Test + void getTextColor() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the repaint . + */ + @Test + void repaint() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the getSelectX . + */ + @Test + void getSelectX() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setSelectX(100); + assertEquals(100, cpuFragment.getSelectX()); + } + + /** + * test function the setSelectX . + */ + @Test + void setSelectX() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setSelectX(100); + assertEquals(100, cpuFragment.getSelectX()); + } + + /** + * test function the getSelectY . + */ + @Test + void getSelectY() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setSelectY(100); + assertEquals(100, cpuFragment.getSelectY()); + } + + /** + * test function the setSelectY . + */ + @Test + void setSelectY() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setSelectY(100); + assertEquals(100, cpuFragment.getSelectY()); + } + + /** + * test function the setRangeChangeListener . + */ + @Test + void setRangeChangeListener() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the mouseDragged . + */ + @Test + void mouseDragged() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } + + /** + * test function the setRange . + */ + @Test + void setRange() { + CpuFragment cpuFragment = new CpuFragment(new JPanel(), (leftX, rightX, leftNS, rightNS, centerNS) -> { + }); + cpuFragment.setRect(new Rectangle(0, 0, 100, 100)); + assertEquals(100, cpuFragment.getRect().width); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/IFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/IFragmentTest.java index 23e5b3ca4..8315444b6 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/IFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/IFragmentTest.java @@ -1,25 +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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -/** - * test IFragment class . - * - * @version 1.0 - * @date: 2021/4/25 22:29 - **/ -class IFragmentTest { +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +/** + * test IFragment class . + * + * @date: 2021/4/25 22:29 + */ +class IFragmentTest { } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/LeftFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/LeftFragmentTest.java index bd51dd0e5..f6d57caaa 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/LeftFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/LeftFragmentTest.java @@ -1,228 +1,205 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test LeftFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:54 - **/ -class LeftFragmentTest { - /** - * test function the draw . - */ - @Test - void draw() { - LeftFragment fragment = new LeftFragment(new JPanel()); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - fragment.draw(graphics2D); - Assertions.assertNotNull(fragment); - } - - /** - * test function the getRect . - */ - @Test - void getRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getRect().width); - } - - /** - * test function the setRect . - */ - @Test - void setRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getRect().width); - } - - /** - * test function the getDescRect . - */ - @Test - void getDescRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setDescRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getDescRect().width); - } - - /** - * test function the setDescRect . - */ - @Test - void setDescRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setDescRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getDescRect().width); - } - - /** - * test function the getDataRect . - */ - @Test - void getDataRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setDataRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getDataRect().width); - } - - /** - * test function the setDataRect . - */ - @Test - void setDataRect() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setDataRect(new Rectangle(0, 0, 100, 100)); - Assertions.assertEquals(100, fragment.getDataRect().width); - } - - /** - * test function the getLineColor . - */ - @Test - void getLineColor() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.getLineColor(); - Assertions.assertEquals(200, fragment.getRect().width); - } - - /** - * test function the getTextColor . - */ - @Test - void getTextColor() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.getTextColor(); - Assertions.assertEquals(200, fragment.getRect().width); - } - - /** - * test function the getStartTimeS . - */ - @Test - void getStartTimeS() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setStartTimeS("StartTimeS"); - Assertions.assertEquals("StartTimeS", fragment.getStartTimeS()); - } - - /** - * test function the setStartTimeS . - */ - @Test - void setStartTimeS() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setStartTimeS("StartTimeS"); - Assertions.assertEquals("StartTimeS", fragment.getStartTimeS()); - } - - /** - * test function the setStartNS . - */ - @Test - void setStartNS() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setStartNS(100L); - Assertions.assertEquals(100L, fragment.getStartNS()); - } - - /** - * test function the getStartNS . - */ - @Test - void getStartNS() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setStartNS(100L); - Assertions.assertEquals(100L, fragment.getStartNS()); - } - - /** - * test function the getExtendHeight . - */ - @Test - void getExtendHeight() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setExtendHeight(100); - Assertions.assertEquals(100, fragment.getExtendHeight()); - } - - /** - * test function the setExtendHeight . - */ - @Test - void setExtendHeight() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setExtendHeight(100); - Assertions.assertEquals(100, fragment.getExtendHeight()); - } - - /** - * test function the getLogString . - */ - @Test - void getLogString() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setLogString("logString"); - Assertions.assertEquals("logString", fragment.getLogString()); - } - - /** - * test function the setLogString . - */ - @Test - void setLogString() { - LeftFragment fragment = new LeftFragment(new JPanel()); - fragment.setLogString("logString"); - Assertions.assertEquals("logString", fragment.getLogString()); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.image.BufferedImage; + +/** + * test LeftFragment class . + * + * @date 2021/4/24 17:54 + */ +class LeftFragmentTest { + /** + * test function the draw . + */ + @Test + void draw() { + LeftFragment fragment = new LeftFragment(new JPanel()); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + fragment.draw(graphics2D); + Assertions.assertNotNull(fragment); + } + + /** + * test function the getRect . + */ + @Test + void getRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getRect().width); + } + + /** + * test function the setRect . + */ + @Test + void setRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getRect().width); + } + + /** + * test function the getDescRect . + */ + @Test + void getDescRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setDescRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getDescRect().width); + } + + /** + * test function the setDescRect . + */ + @Test + void setDescRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setDescRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getDescRect().width); + } + + /** + * test function the getDataRect . + */ + @Test + void getDataRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setDataRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getDataRect().width); + } + + /** + * test function the setDataRect . + */ + @Test + void setDataRect() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setDataRect(new Rectangle(0, 0, 100, 100)); + Assertions.assertEquals(100, fragment.getDataRect().width); + } + + /** + * test function the getLineColor . + */ + @Test + void getLineColor() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.getLineColor(); + Assertions.assertEquals(200, fragment.getRect().width); + } + + /** + * test function the getTextColor . + */ + @Test + void getTextColor() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.getTextColor(); + Assertions.assertEquals(200, fragment.getRect().width); + } + + /** + * test function the getStartTimeS . + */ + @Test + void getStartTimeS() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setStartTimeS("StartTimeS"); + Assertions.assertEquals("StartTimeS", fragment.getStartTimeS()); + } + + /** + * test function the setStartTimeS . + */ + @Test + void setStartTimeS() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setStartTimeS("StartTimeS"); + Assertions.assertEquals("StartTimeS", fragment.getStartTimeS()); + } + + /** + * test function the setStartNS . + */ + @Test + void setStartNS() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setStartNS(100L); + Assertions.assertEquals(100L, fragment.getStartNS()); + } + + /** + * test function the getStartNS . + */ + @Test + void getStartNS() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setStartNS(100L); + Assertions.assertEquals(100L, fragment.getStartNS()); + } + + /** + * test function the getExtendHeight . + */ + @Test + void getExtendHeight() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setExtendHeight(100); + Assertions.assertEquals(100, fragment.getExtendHeight()); + } + + /** + * test function the setExtendHeight . + */ + @Test + void setExtendHeight() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setExtendHeight(100); + Assertions.assertEquals(100, fragment.getExtendHeight()); + } + + /** + * test function the getLogString . + */ + @Test + void getLogString() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setLogString("logString"); + Assertions.assertEquals("logString", fragment.getLogString()); + } + + /** + * test function the setLogString . + */ + @Test + void setLogString() { + LeftFragment fragment = new LeftFragment(new JPanel()); + fragment.setLogString("logString"); + Assertions.assertEquals("logString", fragment.getLogString()); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/RulerFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/RulerFragmentTest.java index 4f1990833..7c6347a28 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/RulerFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/RulerFragmentTest.java @@ -1,97 +1,61 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.event.MouseEvent; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * test RulerFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:55 - **/ -class RulerFragmentTest { - /** - * test function the draw . - */ - @Test - void draw() { - RulerFragment fragment = new RulerFragment(new JPanel(), (startNS, endNS) -> { - }); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - fragment.draw(graphics2D); - assertNotNull(fragment); - } - - /** - * test function the mouseMoved . - */ - @Test - void mouseMoved() { - RulerFragment fragment = new RulerFragment(new JPanel(), (startNS, endNS) -> { - }); - JPanel jPanel = new JPanel(); - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - fragment.mouseMoved(mouseEvent); - assertEquals(0, fragment.getRect().width); - } - - /** - * test function the mousePressed . - */ - @Test - void mousePressed() { - RulerFragment fragment = new RulerFragment(new JPanel(), (startNS, endNS) -> { - }); - JPanel jPanel = new JPanel(); - MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); - fragment.mousePressed(mouseEvent); - assertEquals(0, fragment.getRect().width); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import com.intellij.util.ui.UIUtil; +import org.junit.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * test RulerFragment class . + * + * @date 2021/4/24 17:55 + */ +class RulerFragmentTest { + /** + * test function the draw . + */ + @Test + void draw() { + RulerFragment fragment = new RulerFragment(new JPanel(), (startNS, endNS) -> { + }); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + fragment.draw(graphics2D); + assertNotNull(fragment); + } + + /** + * test function the mouseMoved . + */ + @Test + void mouseMoved() { + RulerFragment fragment = new RulerFragment(new JPanel(), (startNS, endNS) -> { + }); + JPanel jPanel = new JPanel(); + MouseEvent mouseEvent = new MouseEvent(jPanel, 1, 1, 1, 1, 1, 1, true, 1); + fragment.mouseMoved(mouseEvent); + assertEquals(0, fragment.getRect().width); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/TopFragmentTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/TopFragmentTest.java index ac5592dcd..904002d3f 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/TopFragmentTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/fragment/ruler/TopFragmentTest.java @@ -1,67 +1,43 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.fragment.ruler; - -import com.intellij.util.ui.UIUtil; -import ohos.devtools.views.trace.util.Final; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -/** - * test TopFragment class . - * - * @version 1.0 - * @date 2021/4/24 17:55 - **/ -class TopFragmentTest { - /** - * test function the draw . - */ - @Test - void draw() { - TopFragment fragment = new TopFragment(new JPanel()); - BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2D = image.createGraphics(); - fragment.draw(graphics2D); - Assertions.assertNotNull(fragment); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.fragment.ruler; + +import com.intellij.util.ui.UIUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.swing.JPanel; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +/** + * test TopFragment class . + * + * @date 2021/4/24 17:55 + */ +class TopFragmentTest { + /** + * test function the draw . + */ + @Test + void draw() { + TopFragment fragment = new TopFragment(new JPanel()); + BufferedImage image = UIUtil.createImage(new JPanel(), 1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2D = image.createGraphics(); + fragment.draw(graphics2D); + Assertions.assertNotNull(fragment); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ColorUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ColorUtilsTest.java index 6c0819791..5be70f132 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ColorUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ColorUtilsTest.java @@ -1,69 +1,68 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ohos.devtools.views.trace.util; - -import ohos.devtools.views.trace.bean.CpuData; -import org.junit.jupiter.api.Test; - -import java.awt.Color; - -import static org.junit.Assert.assertEquals; - -/** - * test ColorUtils class . - * - * @version 1.0 - * @date 2021/4/24 17:01 - **/ -class ColorUtilsTest { - /** - * test function the testGetColor . - */ - @Test - void testGetColor() { - Color color = ColorUtils.getColor(1); - assertEquals(152, color.getRed()); - assertEquals(150, color.getGreen()); - assertEquals(128, color.getBlue()); - } - - /** - * test function the testHash . - */ - @Test - void testHash() { - assertEquals(16, ColorUtils.hash("1", ColorUtils.MD_PALETTE.length)); - } - - /** - * test function the testColorForThread . - */ - @Test - void testColorForThread() { - CpuData cpuData = new CpuData(); - cpuData.setProcessId(1); - assertEquals(ColorUtils.MD_PALETTE[16], ColorUtils.colorForThread(cpuData)); - } - - /** - * test function the testColorForTid . - */ - @Test - void testColorForTid() { - assertEquals(ColorUtils.MD_PALETTE[16], ColorUtils.colorForTid(1)); - } - +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import ohos.devtools.views.trace.bean.CpuData; +import org.junit.jupiter.api.Test; + +import java.awt.Color; + +import static org.junit.Assert.assertEquals; + +/** + * test ColorUtils class . + * + * @date 2021/4/24 17:01 + */ +class ColorUtilsTest { + /** + * test function the testGetColor . + */ + @Test + void testGetColor() { + Color color = ColorUtils.getColor(1); + assertEquals(152, color.getRed()); + assertEquals(150, color.getGreen()); + assertEquals(128, color.getBlue()); + } + + /** + * test function the testHash . + */ + @Test + void testHash() { + assertEquals(16, ColorUtils.hash("1", ColorUtils.MD_PALETTE.length)); + } + + /** + * test function the testColorForThread . + */ + @Test + void testColorForThread() { + CpuData cpuData = new CpuData(); + cpuData.setProcessId(1); + assertEquals(ColorUtils.MD_PALETTE[16], ColorUtils.colorForThread(cpuData)); + } + + /** + * test function the testColorForTid . + */ + @Test + void testColorForTid() { + assertEquals(ColorUtils.MD_PALETTE[16], ColorUtils.colorForTid(1)); + } + } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DataUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DataUtilsTest.java new file mode 100644 index 000000000..0e7fdba0b --- /dev/null +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DataUtilsTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.devtools.views.trace.util; + +import com.google.gson.JsonObject; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test DataUtils class . + * + * @date 2021/4/24 17:52 + */ +class DataUtilsTest { + /** + * test function the getJson . + */ + @Test + void getJson() { + JsonObject json = DataUtils.getJson(); + assertEquals(100, json.get("id").getAsInt()); + } +} \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DbTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DbTest.java index 39b52fe2d..1bac65dba 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DbTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/DbTest.java @@ -1,239 +1,109 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.sql.Connection; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test Db class . - * - * @version 1.0 - * @date: 2021/4/24 17:52 - **/ -class DbTest { - /** - * test function the getDbName . - */ - @Test - void getDbName() { - assertEquals("trace.db", Db.getDbName()); - } - - /** - * test function the setDbName . - */ - @Test - void setDbName() { - Db.setDbName("trace.db"); - assertEquals("trace.db", Db.getDbName()); - } - - /** - * test function the getConn . - */ - @Test - void getConn() { - Connection conn = Db.getInstance().getConn(); - assertEquals(true, conn != null); - } - - /** - * test function the free . - */ - @Test - void free() { - Connection conn = Db.getInstance().getConn(); - Db.getInstance().free(conn); - assertEquals(true, conn != null); - } - - /** - * test function the load . - */ - @Test - void load() { - Db.load(false); - assertEquals(true, Db.getInstance() != null); - } - - /** - * test function the getInstance . - */ - @Test - void getInstance() { - assertEquals(true, Db.getInstance() != null); - } - - /** - * test function the getSql . - */ - @Test - void getSql() { - assertEquals(true, Db.getSql("QueryTotalTime") != null); - } - - /** - * test function the queryTotalTime . - */ - @Test - void queryTotalTime() { - long queryTotalTime = Db.getInstance().queryTotalTime(); - assertEquals(true, queryTotalTime > 0); - } - - /** - * test function the queryCpu . - */ - @Test - void queryCpu() { - assertEquals(true, Db.getInstance().queryCpu() != null); - } - - /** - * test function the queryCpuFreq . - */ - @Test - void queryCpuFreq() { - assertEquals(true, Db.getInstance().queryCpuFreq() != null); - } - - /** - * test function the queryCpuMax . - */ - @Test - void queryCpuMax() { - assertEquals(true, Db.getInstance().queryCpuMax() >= 0); - } - - /** - * test function the queryCpuData . - */ - @Test - void queryCpuData() { - assertEquals(true, Db.getInstance().queryCpuData(0) != null); - } - - /** - * test function the queryCpuMaxFreq . - */ - @Test - void queryCpuMaxFreq() { - assertEquals(true, Db.getInstance().queryCpuMaxFreq() != null); - } - - /** - * test function the queryCpuFreqData . - */ - @Test - void queryCpuFreqData() { - assertEquals(true, Db.getInstance().queryCpuFreqData(0) != null); - } - - /** - * test function the queryProcess . - */ - @Test - void queryProcess() { - assertEquals(true, Db.getInstance().queryProcess() != null); - } - - /** - * test function the queryProcessThreads . - */ - @Test - void queryProcessThreads() { - assertEquals(true, Db.getInstance().queryProcessThreads() != null); - } - - /** - * test function the queryProcessData . - */ - @Test - void queryProcessData() { - assertEquals(true, Db.getInstance().queryProcessData(0) != null); - } - - /** - * test function the queryThreadData . - */ - @Test - void queryThreadData() { - assertEquals(true, Db.getInstance().queryThreadData(0) != null); - } - - /** - * test function the queryWakeupThread . - */ - @Test - void queryWakeupThread() { - assertEquals(null, Db.getInstance().queryWakeupThread(null)); - } - - /** - * test function the getCpuUtilizationRate . - */ - @Test - void getCpuUtilizationRate() { - assertEquals(true, Db.getInstance().getCpuUtilizationRate() != null); - } - - /** - * test function the getProcessMem . - */ - @Test - void getProcessMem() { - assertEquals(true, Db.getInstance().getProcessMem() != null); - } - - /** - * test function the getProcessMemData . - */ - @Test - void getProcessMemData() { - assertEquals(true, Db.getInstance().getProcessMemData(0) != null); - } - - /** - * test function the getFunDataByTid . - */ - @Test - void getFunDataByTid() { - assertEquals(true, Db.getInstance().getFunDataByTid(0) != null); - } - - /** - * init the db setup . - */ - @BeforeEach - void setUp() { - Db.getInstance(); - Db.setDbName("trace.db"); - Db.load(false); - } - - /** - * set down . - */ - @AfterEach - void tearDown() { - } +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test Db class . + * + * @date: 2021/4/24 17:52 + */ +class DbTest { + /** + * test function the getDbName . + */ + @Test + void getDbName() { + assertEquals("trace.db", Db.getDbName()); + } + + /** + * test function the setDbName . + */ + @Test + void setDbName() { + Db.setDbName("trace.db"); + assertEquals("trace.db", Db.getDbName()); + } + + /** + * test function the getConn . + */ + @Test + void getConn() { + Connection conn = Db.getInstance().getConn(); + assertEquals(true, conn != null); + } + + /** + * test function the free . + */ + @Test + void free() { + Connection conn = Db.getInstance().getConn(); + Db.getInstance().free(conn); + assertEquals(true, conn != null); + } + + /** + * test function the load . + */ + @Test + void load() { + Db.load(false); + assertEquals(true, Db.getInstance() != null); + } + + /** + * test function the getInstance . + */ + @Test + void getInstance() { + assertEquals(true, Db.getInstance() != null); + } + + /** + * test function the getSql . + */ + @Test + void getSql() { + assertEquals(true, Db.getSql("QueryTotalTime") != null); + } + + /** + * init the db setup . + */ + @BeforeEach + void setUp() { + Db.getInstance(); + Db.setDbName("trace.db"); + Db.load(false); + } + + /** + * set down . + */ + @AfterEach + void tearDown() { + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/FinalTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/FinalTest.java index 9793d88a3..b74cb10da 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/FinalTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/FinalTest.java @@ -1,25 +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. - */ - -package ohos.devtools.views.trace.util; - -/** - * test Final class . - * - * @version 1.0 - * @date 2021/4/24 17:51 - **/ -class FinalTest { +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +/** + * test Final class . + * + * @version 1.0 + * @date 2021/4/24 17:51 + */ +class FinalTest { } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ImageUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ImageUtilsTest.java index ff65a5795..0699b4074 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ImageUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/ImageUtilsTest.java @@ -1,264 +1,263 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import org.junit.jupiter.api.Test; - -import javax.imageio.ImageIO; -import java.awt.Image; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test ImageUtils class . - * - * @version 1.0 - * @date 2021/4/24 17:53 - **/ -class ImageUtilsTest { - /** - * test function the getStarFill . - */ - @Test - void getStarFill() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setStarFill(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getStarFill() != null); - } - - /** - * test function the setStarFill . - */ - @Test - void setStarFill() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setStarFill(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getStarFill() != null); - } - - /** - * test function the getStar . - */ - @Test - void getStar() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setStar(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getStar() != null); - } - - /** - * test function the setStar . - */ - @Test - void setStar() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setStar(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getStar() != null); - } - - /** - * test function the getCheckYes . - */ - @Test - void getCheckYes() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setCheckYes(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getCheckYes() != null); - } - - /** - * test function the setCheckYes . - */ - @Test - void setCheckYes() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setCheckYes(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getCheckYes() != null); - } - - /** - * test function the getCheckNo . - */ - @Test - void getCheckNo() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setCheckNo(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getCheckNo() != null); - } - - /** - * test function the setCheckNo . - */ - @Test - void setCheckNo() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setCheckNo(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getCheckNo() != null); - } - - /** - * test function the getArrowDown . - */ - @Test - void getArrowDown() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowDown(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowDown() != null); - } - - /** - * test function the setArrowDown . - */ - @Test - void setArrowDown() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowDown(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowDown() != null); - } - - /** - * test function the getArrowDownFocus . - */ - @Test - void getArrowDownFocus() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowDownFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowDownFocus() != null); - } - - /** - * test function the setArrowDownFocus . - */ - @Test - void setArrowDownFocus() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowDownFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowDownFocus() != null); - } - - /** - * test function the getArrowUp . - */ - @Test - void getArrowUp() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowUpFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); - } - - /** - * test function the setArrowUp . - */ - @Test - void setArrowUp() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowUpFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); - } - - /** - * test function the getArrowUpFocus . - */ - @Test - void getArrowUpFocus() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowUpFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); - } - - /** - * test function the setArrowUpFocus . - */ - @Test - void setArrowUpFocus() { - try { - Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); - ImageUtils.getInstance().setArrowUpFocus(image); - } catch (IOException e) { - e.printStackTrace(); - } - assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); - } - - /** - * test function the getInstance . - */ - @Test - void getInstance() { - assertEquals(true, ImageUtils.getInstance() != null); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import org.junit.jupiter.api.Test; + +import javax.imageio.ImageIO; +import java.awt.Image; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test ImageUtils class . + * + * @date 2021/4/24 17:53 + */ +class ImageUtilsTest { + /** + * test function the getStarFill . + */ + @Test + void getStarFill() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setStarFill(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getStarFill() != null); + } + + /** + * test function the setStarFill . + */ + @Test + void setStarFill() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setStarFill(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getStarFill() != null); + } + + /** + * test function the getStar . + */ + @Test + void getStar() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setStar(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getStar() != null); + } + + /** + * test function the setStar . + */ + @Test + void setStar() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setStar(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getStar() != null); + } + + /** + * test function the getCheckYes . + */ + @Test + void getCheckYes() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setCheckYes(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getCheckYes() != null); + } + + /** + * test function the setCheckYes . + */ + @Test + void setCheckYes() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setCheckYes(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getCheckYes() != null); + } + + /** + * test function the getCheckNo . + */ + @Test + void getCheckNo() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setCheckNo(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getCheckNo() != null); + } + + /** + * test function the setCheckNo . + */ + @Test + void setCheckNo() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setCheckNo(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getCheckNo() != null); + } + + /** + * test function the getArrowDown . + */ + @Test + void getArrowDown() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowDown(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowDown() != null); + } + + /** + * test function the setArrowDown . + */ + @Test + void setArrowDown() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowDown(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowDown() != null); + } + + /** + * test function the getArrowDownFocus . + */ + @Test + void getArrowDownFocus() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowDownFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowDownFocus() != null); + } + + /** + * test function the setArrowDownFocus . + */ + @Test + void setArrowDownFocus() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowDownFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowDownFocus() != null); + } + + /** + * test function the getArrowUp . + */ + @Test + void getArrowUp() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowUpFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); + } + + /** + * test function the setArrowUp . + */ + @Test + void setArrowUp() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowUpFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); + } + + /** + * test function the getArrowUpFocus . + */ + @Test + void getArrowUpFocus() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowUpFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); + } + + /** + * test function the setArrowUpFocus . + */ + @Test + void setArrowUpFocus() { + try { + Image image = ImageIO.read(ImageUtils.class.getResourceAsStream("/assets/top_star_fill.png")); + ImageUtils.getInstance().setArrowUpFocus(image); + } catch (IOException e) { + e.printStackTrace(); + } + assertEquals(true, ImageUtils.getInstance().getArrowUpFocus() != null); + } + + /** + * test function the getInstance . + */ + @Test + void getInstance() { + assertEquals(true, ImageUtils.getInstance() != null); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/TimeUtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/TimeUtilsTest.java index 0f2a7411c..801585d89 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/TimeUtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/TimeUtilsTest.java @@ -1,46 +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. - */ - -package ohos.devtools.views.trace.util; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * test TimeUtils class . - * - * @version 1.0 - * @date 2021/4/24 17:03 - **/ -class TimeUtilsTest { - /** - * test function the getSecondFromNSecond . - */ - @Test - void getSecondFromNSecond() { - String str = TimeUtils.getSecondFromNSecond(1000L); - assertEquals("1.0us", str); - } - - /** - * test function the getTimeString . - */ - @Test - void getTimeString() { - String timeString = TimeUtils.getTimeString(1000L); - assertEquals("1us", timeString); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * test TimeUtils class . + * + * @date 2021/4/24 17:03 + */ +class TimeUtilsTest { + /** + * test function the getSecondFromNSecond . + */ + @Test + void getSecondFromNSecond() { + String str = TimeUtils.getSecondFromNSecond(1000L); + assertEquals("1.0μs", str); + } + + /** + * test function the getTimeString . + */ + @Test + void getTimeString() { + String timeString = TimeUtils.getTimeString(1000L); + assertEquals("1μs", timeString); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/UtilsTest.java b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/UtilsTest.java index e82ad3bbd..0deb80349 100644 --- a/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/UtilsTest.java +++ b/host/ohosprofiler/src/test/java/ohos/devtools/views/trace/util/UtilsTest.java @@ -1,71 +1,70 @@ -/* - * 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. - */ - -package ohos.devtools.views.trace.util; - -import org.junit.jupiter.api.Test; - -import java.awt.Rectangle; -import java.util.Map; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * test Utils class . - * - * @version 1.0 - * @date 2021/4/24 17:51 - **/ -class UtilsTest { - /** - * test function the getStatusMap . - */ - @Test - void getStatusMap() { - Map statusMap = Utils.getInstance().getStatusMap(); - assertNotNull(statusMap); - assertEquals("Sleeping", statusMap.get("S")); - } - - /** - * test function the getInstance . - */ - @Test - void getInstance() { - Utils instance = Utils.getInstance(); - assertNotEquals(null, instance); - } - - /** - * test function the pointInRect . - */ - @Test - void pointInRect() { - boolean pointInRect = Utils.pointInRect(new Rectangle(0, 0, 100, 100), 50, 50); - assertTrue(pointInRect); - } - - /** - * test function the getEndState . - */ - @Test - void getEndState() { - String endState = Utils.getEndState("S"); - assertEquals("Sleeping", endState); - } +/* + * 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. + */ + +package ohos.devtools.views.trace.util; + +import org.junit.jupiter.api.Test; + +import java.awt.Rectangle; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * test Utils class . + * + * @date 2021/4/24 17:51 + */ +class UtilsTest { + /** + * test function the getStatusMap . + */ + @Test + void getStatusMap() { + Map statusMap = Utils.getInstance().getStatusMap(); + assertNotNull(statusMap); + assertEquals("Sleeping", statusMap.get("S")); + } + + /** + * test function the getInstance . + */ + @Test + void getInstance() { + Utils instance = Utils.getInstance(); + assertNotEquals(null, instance); + } + + /** + * test function the pointInRect . + */ + @Test + void pointInRect() { + boolean pointInRect = Utils.pointInRect(new Rectangle(0, 0, 100, 100), 50, 50); + assertTrue(pointInRect); + } + + /** + * test function the getEndState . + */ + @Test + void getEndState() { + String endState = Utils.getEndState("S"); + assertEquals("Sleeping", endState); + } } \ No newline at end of file diff --git a/host/ohosprofiler/src/test/resources/Demo.trace b/host/ohosprofiler/src/test/resources/Demo.trace deleted file mode 100644 index dff1c979b..000000000 Binary files a/host/ohosprofiler/src/test/resources/Demo.trace and /dev/null differ diff --git a/interfaces/innerkits/share_memory_allocator.h b/interfaces/innerkits/share_memory_allocator.h old mode 100755 new mode 100644 diff --git a/interfaces/innerkits/share_memory_block.h b/interfaces/innerkits/share_memory_block.h old mode 100755 new mode 100644 diff --git a/interfaces/kits/plugin_module_api.h b/interfaces/kits/plugin_module_api.h old mode 100755 new mode 100644 index c92b26b3b..b7a15a0d9 --- a/interfaces/kits/plugin_module_api.h +++ b/interfaces/kits/plugin_module_api.h @@ -17,8 +17,8 @@ #define PLUGIN_MODULE_API_H #include +#include #include -#include #ifdef __cplusplus extern "C" { diff --git a/interfaces/kits/test/BUILD.gn b/interfaces/kits/test/BUILD.gn old mode 100755 new mode 100644 index c45d5961e..f42c125f0 --- a/interfaces/kits/test/BUILD.gn +++ b/interfaces/kits/test/BUILD.gn @@ -14,9 +14,9 @@ import("//build/test.gni") import("../../../device/base/config.gni") -module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/interfaces/kits" +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/device" config("module_private_config") { - visibility = [":*"] + visibility = [ ":*" ] if (current_toolchain != host_toolchain) { defines = [ "HAVE_HILOG" ] } @@ -25,37 +25,39 @@ config("module_private_config") { ohos_unittest("plugin_module_api_ut") { module_out_path = module_output_path deps = [ - "//third_party/googletest:gtest", - "${OHOS_PROFILER_DIR}/protos/types/plugins/memory_data:memory_data_cpp", "${OHOS_PROFILER_DIR}/device/plugins/memory_plugin:memdataplugin", + "${OHOS_PROFILER_DIR}/device/plugins/sample_plugin:sampleplugin", + "${OHOS_PROFILER_DIR}/device/plugins/stream_plugin:streamplugin", + "${OHOS_PROFILER_DIR}/protos/types/plugins/memory_data:memory_data_cpp", + "${OHOS_PROFILER_DIR}/protos/types/plugins/sample_data:sample_data_cpp", + "${OHOS_PROFILER_DIR}/protos/types/plugins/stream_data:stream_data_cpp", + "//third_party/googletest:gtest", + "//utils/native/base:utilsecurec", ] include_dirs = [ "../", "${OHOS_PROFILER_DIR}/device/plugins/memory_plugin/include", + "${OHOS_PROFILER_DIR}/device/plugins/sample_plugin/include", + "${OHOS_PROFILER_DIR}/device/plugins/stream_plugin/include", "${OHOS_PROFILER_DIR}/device/plugins/api/include", "${OHOS_PROFILER_DIR}/device/plugins/api/src", - "${OHOS_PROFILER_DIR}/device/base/include/", + "${OHOS_PROFILER_DIR}/device/base/include", "//third_party/googletest/googletest/include/gtest", + "//utils/native/base/include", ] - sources = [ - "unittest/plugin_module_api_test.cpp", - ] + sources = [ "unittest/plugin_module_api_test.cpp" ] cflags = [ "-pthread", "-Wno-inconsistent-missing-override", - "-Dprivate=public", #allow test code access private members - ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", + "-Dprivate=public", #allow test code access private members ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" configs = [ ":module_private_config" ] - resource_config_file = get_path_info("unittest/ohos_test.xml", "abspath") + resource_config_file = "${OHOS_PROFILER_DIR}/device/ohos_test.xml" } group("unittest") { testonly = true - deps = [ - ":plugin_module_api_ut", - ] + deps = [ ":plugin_module_api_ut" ] } diff --git a/interfaces/kits/test/unittest/ohos_test.xml b/interfaces/kits/test/unittest/ohos_test.xml deleted file mode 100644 index fcc958464..000000000 --- a/interfaces/kits/test/unittest/ohos_test.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - diff --git a/interfaces/kits/test/unittest/plugin_module_api_test.cpp b/interfaces/kits/test/unittest/plugin_module_api_test.cpp index cf3123f19..41306afbb 100644 --- a/interfaces/kits/test/unittest/plugin_module_api_test.cpp +++ b/interfaces/kits/test/unittest/plugin_module_api_test.cpp @@ -24,220 +24,675 @@ #include #include "logging.h" -#include "memory_plugin_config.pb.h" -#include "memory_plugin_result.pb.h" +#include "memory_data_plugin.h" #include "plugin_module_api.h" +#include "sample_plugin.h" +#include "stream_plugin.h" using namespace testing::ext; -#if defined(__i386__) || defined(__x86_64__) -const std::string LIB_PATH = "./hos/out/hos-arm/clang_x64/devtools/devtools/libmemdataplugin.z.so"; -#else -const std::string LIB_PATH = "/system/lib/libmemdataplugin.z.so"; -#endif - namespace { -enum NumType { - BIT_WIDTH = 35, - MS_S = 1000000, - ERR_PARAM = 1, - ERR_ADDR, - ERR_START, -}; +constexpr uint32_t MAX_BUFFER_SIZE = 4 * 1024 * 1024; +std::mutex g_taskMutex; +std::unique_ptr memoryPlugin = nullptr; +std::unique_ptr streamPlugin = nullptr; +std::unique_ptr samplePlugin = nullptr; class PluginModuleApiTest : public ::testing::Test { +public: + PluginModuleCallbacks* memoryCallbacks_; + PluginModuleCallbacks* sampleCallbacks_; + PluginModuleCallbacks* streamCallbacks_; + + PluginModuleStruct memoryModule_; + PluginModuleStruct sampleModule_; + PluginModuleStruct streamModule_; + + WriterStruct* writer_; protected: static void SetUpTestCase() {} static void TearDownTestCase() {} - void SetUp() override {} - void TearDown() override {} - - bool MatchTail(const std::string& name, std::string str) + void SetUp() { - int index = name.size() - str.size(); - if (index < 0) { - return false; - } - return (name.substr(index) == str); + memoryCallbacks_ = nullptr; + sampleCallbacks_ = nullptr; + streamCallbacks_ = nullptr; + memoryModule_ = {memoryCallbacks_, "memory-plugin", MAX_BUFFER_SIZE}; + sampleModule_ = {sampleCallbacks_, "sample-plugin", MAX_BUFFER_SIZE}; + streamModule_ = {streamCallbacks_, "stream-plugin", MAX_BUFFER_SIZE}; + writer_ = nullptr; } - bool ProcessErr(int errNum, void *handle, uint8_t* dataBuffer) - { - switch (errNum) { - case ERR_ADDR: - dlclose(handle); - HILOG_DEBUG(LOG_CORE, "test:check addr err."); - break; - case ERR_START: - dlclose(handle); - free(dataBuffer); - HILOG_DEBUG(LOG_CORE, "test:start err."); - break; - default: - HILOG_DEBUG(LOG_CORE, "test:check param err."); - break; - } - return false; - } + bool PollPluginStub(MemoryDataPlugin& plugin, MemoryConfig& protoConfig, MemoryData& protoData); + bool StreamPluginStub(StreamPlugin& plugin, StreamConfig& protoConfig, StreamData& protoData); + // memory + static int MemDataPluginSessionStart(const uint8_t* configData, uint32_t configSize); + static int MemPluginReportResult(uint8_t* bufferData, uint32_t bufferSize); + static int MemPluginSessionStop(); - bool MemoryPluginTest(MemoryConfig& protoConfig, const std::string libPath) - { - MemoryData memoryData; - if (!MatchTail(libPath, ".so")) { - return ProcessErr(ERR_PARAM, nullptr, nullptr); - } + // stream + static int StreamPluginSessionStart(const uint8_t* configData, uint32_t configSize); + static int StreamPluginSessionStop(); + static int StreamRegisterWriterStruct(WriterStruct* writer); + static long Write(WriterStruct* writer, const void* data, size_t size); + static bool Flush(WriterStruct* writer); - void* handle = dlopen(libPath.c_str(), RTLD_LAZY); - if (handle == nullptr) { - return ProcessErr(ERR_PARAM, nullptr, nullptr); - } - - PluginModuleStruct* memPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); - if (memPlugin == nullptr) { - return ProcessErr(ERR_ADDR, handle, nullptr); - } - uint8_t* dataBuffer = (uint8_t*)malloc(memPlugin->resultBufferSizeHint); - if (dataBuffer == nullptr) { - return ProcessErr(ERR_ADDR, handle, nullptr); - } - - int configlength = protoConfig.ByteSizeLong(); - std::vector config(configlength); - protoConfig.SerializeToArray(config.data(), config.size()); - - if (memPlugin->callbacks->onPluginSessionStart(config.data(), config.size()) < 0) { - return ProcessErr(ERR_START, handle, dataBuffer); - } - - int len = memPlugin->callbacks->onPluginReportResult(dataBuffer, memPlugin->resultBufferSizeHint); - if (len > 0) { - memoryData.ParseFromArray(dataBuffer, len); - } - - memPlugin->callbacks->onPluginSessionStop(); - memPlugin->callbacks->onRegisterWriterStruct(nullptr); - - dlclose(handle); - free(dataBuffer); - return true; - } + // sample + static int SamplePluginSessionStart(const uint8_t* configData, uint32_t configSize); + static int SamplePluginReportResult(uint8_t* bufferData, uint32_t bufferSize); + static int SamplePluginSessionStop(); + void SetSampleConfig(std::vector& configData, uint32_t& configSize); + void SetMemoryConfig(std::vector& configData, uint32_t& configSize); + void SetStreamConfig(std::vector& configData, uint32_t& configSize); }; -HWTEST_F(PluginModuleApiTest, ProtoConfigNullAndInvalidSo, TestSize.Level1) +// memory +int PluginModuleApiTest::MemDataPluginSessionStart(const uint8_t* configData, uint32_t configSize) { - MemoryConfig protoConfig; - EXPECT_FALSE(PluginModuleApiTest::MemoryPluginTest(protoConfig, "1111")); + std::lock_guard guard(g_taskMutex); + memoryPlugin = std::make_unique(); + return memoryPlugin->Start(configData, configSize); } -HWTEST_F(PluginModuleApiTest, ProtoConfigNullAndEffectiveSo, TestSize.Level1) +int PluginModuleApiTest::MemPluginReportResult(uint8_t* bufferData, uint32_t bufferSize) { - MemoryConfig protoConfig; - EXPECT_TRUE(PluginModuleApiTest::MemoryPluginTest(protoConfig, LIB_PATH)); + std::lock_guard guard(g_taskMutex); + return memoryPlugin->Report(bufferData, bufferSize); } -HWTEST_F(PluginModuleApiTest, ProtoConfigMemAndInvalidSo, TestSize.Level1) +int PluginModuleApiTest::MemPluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + CHECK_TRUE(memoryPlugin != nullptr, -1, "memoryPlugin is null!!!"); + memoryPlugin->Stop(); + memoryPlugin = nullptr; + return 0; +} + +// stream +int PluginModuleApiTest::StreamPluginSessionStart(const uint8_t* configData, uint32_t configSize) +{ + std::lock_guard guard(g_taskMutex); + CHECK_TRUE(streamPlugin != nullptr, -1, "PluginStub::start plugin fail!!!"); + return streamPlugin->Start(configData, configSize); +} + +int PluginModuleApiTest::StreamPluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + streamPlugin->Stop(); + streamPlugin = nullptr; + return 0; +} + +int PluginModuleApiTest::StreamRegisterWriterStruct(WriterStruct* writer) +{ + std::lock_guard guard(g_taskMutex); + streamPlugin = std::make_unique(); + streamPlugin->SetWriter(writer); + return 0; +} + +// write +long PluginModuleApiTest::Write(WriterStruct* writer, const void* data, size_t size) +{ + HILOG_INFO(LOG_CORE, "PluginModuleApiTest::Write no implementation !"); + return 0; +} + +bool PluginModuleApiTest::Flush(WriterStruct* writer) +{ + HILOG_INFO(LOG_CORE, "PluginModuleApiTest::Write no implementation !"); + return true; +} + +// sample +int PluginModuleApiTest::SamplePluginSessionStart(const uint8_t* configData, uint32_t configSize) +{ + std::lock_guard guard(g_taskMutex); + samplePlugin = std::make_unique(); + return samplePlugin->Start(configData, configSize); +} + +int PluginModuleApiTest::SamplePluginReportResult(uint8_t* bufferData, uint32_t bufferSize) +{ + std::lock_guard guard(g_taskMutex); + return samplePlugin->Report(bufferData, bufferSize); +} + +int PluginModuleApiTest::SamplePluginSessionStop() +{ + std::lock_guard guard(g_taskMutex); + samplePlugin->Stop(); + samplePlugin = nullptr; + return 0; +} + +void PluginModuleApiTest::SetSampleConfig(std::vector& configData, uint32_t& configSize) +{ + SampleConfig protoConfig; + protoConfig.set_pid(1); + // serialize + protoConfig.SerializeToArray(configData.data(), configData.size()); + configSize = protoConfig.ByteSizeLong(); + printf("SetSampleConfig -->\n"); + for (uint32_t i = 0; i < configSize; i++) + printf("0x%02x", configData[i]); + printf("\n"); +} + +void PluginModuleApiTest::SetMemoryConfig(std::vector& configData, uint32_t& configSize) { MemoryConfig protoConfig; protoConfig.set_report_process_mem_info(true); - EXPECT_FALSE(PluginModuleApiTest::MemoryPluginTest(protoConfig, "1111")); -} - -HWTEST_F(PluginModuleApiTest, ProtoConfigMemAndEffectiveSo, TestSize.Level1) -{ - MemoryConfig protoConfig; - protoConfig.set_report_process_mem_info(true); - EXPECT_TRUE(PluginModuleApiTest::MemoryPluginTest(protoConfig, LIB_PATH)); -} - -HWTEST_F(PluginModuleApiTest, ProtoConfigPidAndInvalidSo, TestSize.Level1) -{ - MemoryConfig protoConfig; - protoConfig.set_report_app_mem_info(true); protoConfig.add_pid(1); - EXPECT_FALSE(PluginModuleApiTest::MemoryPluginTest(protoConfig, "1111")); + // serialize + protoConfig.SerializeToArray(configData.data(), configSize); + configSize = protoConfig.ByteSizeLong(); + printf("SetMemoryConfig memoryConfigData---->configLen(%d)\n", configSize); } -HWTEST_F(PluginModuleApiTest, ProtoConfigPidAndEffectiveSo, TestSize.Level1) +void PluginModuleApiTest::SetStreamConfig(std::vector& configData, uint32_t& configSize) { - MemoryConfig protoConfig; - protoConfig.set_report_app_mem_info(true); - protoConfig.add_pid(1); - EXPECT_TRUE(PluginModuleApiTest::MemoryPluginTest(protoConfig, LIB_PATH)); + StreamConfig protoConfig; + protoConfig.set_pid(1); + // serialize + protoConfig.SerializeToArray(configData.data(), configSize); + configSize = protoConfig.ByteSizeLong(); + printf("SetStreamConfig streamConfigData---->configLen(%d)\n", configSize); } -HWTEST_F(PluginModuleApiTest, MemoryPluginTreeAndInvalidSo, TestSize.Level1) +// 流式调用写接口 +HWTEST_F(PluginModuleApiTest, StreamPluginRegister1, TestSize.Level1) { - MemoryConfig protoConfig; - protoConfig.set_report_process_tree(true); - EXPECT_FALSE(PluginModuleApiTest::MemoryPluginTest(protoConfig, "1111")); + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); + EXPECT_EQ(streamCallbacks_->onRegisterWriterStruct(writer_), 0); + EXPECT_NE(streamPlugin, nullptr); + + EXPECT_EQ(streamPlugin->resultWriter_, nullptr); } -HWTEST_F(PluginModuleApiTest, MemoryPluginTreeAndEffectiveSo, TestSize.Level1) +// 流式调用写接口 +HWTEST_F(PluginModuleApiTest, StreamPluginRegister2, TestSize.Level1) { - MemoryConfig protoConfig; - protoConfig.set_report_process_tree(true); - EXPECT_TRUE(PluginModuleApiTest::MemoryPluginTest(protoConfig, LIB_PATH)); -} - -HWTEST_F(PluginModuleApiTest, ApiCallInvalidSoAndInvalidStruct, TestSize.Level1) -{ - PluginModuleStruct* memPlugin = nullptr; - void* handle = dlopen(LIB_PATH.c_str(), RTLD_LAZY); - ASSERT_NE(handle, nullptr); - - memPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); - ASSERT_NE(memPlugin, nullptr); - - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStart(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginReportResult(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStop(), 0); - ASSERT_EQ(memPlugin->callbacks->onRegisterWriterStruct(nullptr), 0); -} - -HWTEST_F(PluginModuleApiTest, ApiCallEffectiveSoAndInvalidStruct, TestSize.Level1) -{ - PluginModuleStruct* memPlugin = nullptr; - void* handle = dlopen(LIB_PATH.c_str(), RTLD_LAZY); - ASSERT_NE(handle, nullptr); - - memPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); - ASSERT_NE(memPlugin, nullptr); - - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStart(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginReportResult(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStop(), 0); - ASSERT_EQ(memPlugin->callbacks->onRegisterWriterStruct(nullptr), 0); -} - -HWTEST_F(PluginModuleApiTest, ApiCallInvalidSoAndEffectiveStruct, TestSize.Level1) -{ - PluginModuleStruct* memPlugin = nullptr; - void* handle = dlopen(LIB_PATH.c_str(), RTLD_LAZY); - ASSERT_NE(handle, nullptr); - - memPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); - ASSERT_NE(memPlugin, nullptr); + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); WriterStruct writer; + writer_ = &writer; + EXPECT_EQ(streamCallbacks_->onRegisterWriterStruct(writer_), 0); + EXPECT_NE(streamPlugin, nullptr); - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStart(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStop(), 0); - ASSERT_EQ(memPlugin->callbacks->onRegisterWriterStruct(&writer), 0); + EXPECT_NE(streamPlugin->resultWriter_, nullptr); + EXPECT_NE(streamPlugin->resultWriter_->write, nullptr); } -HWTEST_F(PluginModuleApiTest, ApiCallEffectiveSoAndEffectiveStruct, TestSize.Level1) +// 流式调用写接口 +HWTEST_F(PluginModuleApiTest, StreamPluginRegister3, TestSize.Level1) { - PluginModuleStruct* memPlugin = nullptr; - void* handle = dlopen(LIB_PATH.c_str(), RTLD_LAZY); - ASSERT_NE(handle, nullptr); + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; - memPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); - ASSERT_NE(memPlugin, nullptr); + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); + WriterStruct writer = { + Write, + Flush, + }; + writer_ = &writer; + EXPECT_EQ(streamCallbacks_->onRegisterWriterStruct(writer_), 0); + EXPECT_NE(streamPlugin, nullptr); + EXPECT_NE(streamPlugin->resultWriter_, nullptr); + EXPECT_NE(streamPlugin->resultWriter_->write, nullptr); + EXPECT_NE(streamPlugin->resultWriter_->flush, nullptr); +} + +// 轮询式调用写接口 +HWTEST_F(PluginModuleApiTest, SamplePluginRegister, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + + EXPECT_EQ(sampleCallbacks_->onRegisterWriterStruct, nullptr); + EXPECT_EQ(samplePlugin, nullptr); +} + +HWTEST_F(PluginModuleApiTest, MemPluginRegister, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + memoryCallbacks_ = &callbacks; + + EXPECT_EQ(memoryCallbacks_->onRegisterWriterStruct, nullptr); + EXPECT_EQ(memoryPlugin, nullptr); +} + +// 流式插件正常启动 +HWTEST_F(PluginModuleApiTest, StreamPluginStartSucc, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); + WriterStruct writer = { + Write, + Flush, + }; + writer_ = &writer; + streamCallbacks_->onRegisterWriterStruct(writer_); + EXPECT_NE(streamPlugin, nullptr); + + EXPECT_NE(streamCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); + SetStreamConfig(configData, configLen); + EXPECT_EQ(streamCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + + streamCallbacks_->onPluginSessionStop(); +} + +// 流式异常启动 +HWTEST_F(PluginModuleApiTest, StreamPluginStartFail, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); WriterStruct writer; - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStart(nullptr, 0), 0); - ASSERT_EQ(memPlugin->callbacks->onPluginSessionStop(), 0); - ASSERT_EQ(memPlugin->callbacks->onRegisterWriterStruct(&writer), 0); + writer_ = &writer; + streamCallbacks_->onRegisterWriterStruct(writer_); + EXPECT_NE(streamPlugin, nullptr); + + EXPECT_NE(streamCallbacks_->onPluginSessionStart, nullptr); + std::vector configData(MAX_BUFFER_SIZE); + EXPECT_EQ(streamCallbacks_->onPluginSessionStart(configData.data(), configData.size()), -1); +} + +// 轮询式异常启动 +HWTEST_F(PluginModuleApiTest, SamplePluginStartFail, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(nullptr, 0), -1); + EXPECT_NE(samplePlugin, nullptr); +} + +// 轮询式插件正常启动 +HWTEST_F(PluginModuleApiTest, SamplePluginStartSucc, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); // config + printf("PluginModuleApiTest before---->configLen(%zu)\n", configData.size()); + SetSampleConfig(configData, configLen); + printf("PluginModuleApiTest after---->configLen(%d)\n", configLen); + for (uint32_t i = 0; i < configLen; i++) + printf("0x%02x", configData[i]); + printf("\n"); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + + sampleCallbacks_->onPluginSessionStop(); +} + +// 多个插件启动 +HWTEST_F(PluginModuleApiTest, MultPluginStart, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + PluginModuleCallbacks memCallbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + memoryCallbacks_ = &memCallbacks; + uint32_t configLen = MAX_BUFFER_SIZE; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + std::vector sampleConfigData(configLen); + SetSampleConfig(sampleConfigData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(sampleConfigData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + sampleCallbacks_->onPluginSessionStop(); + + EXPECT_NE(memoryCallbacks_->onPluginSessionStart, nullptr); + configLen = MAX_BUFFER_SIZE; + std::vector memoryConfigData(configLen); + SetMemoryConfig(memoryConfigData, configLen); + printf("PluginModuleApiTest memoryConfigData---->configLen(%d)\n", configLen); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStart(memoryConfigData.data(), configLen), 0); + EXPECT_NE(memoryPlugin, nullptr); + memoryCallbacks_->onPluginSessionStop(); +} + +// 流式上报 +HWTEST_F(PluginModuleApiTest, StreamPluginReport, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + + EXPECT_EQ(streamCallbacks_->onPluginReportResult, nullptr); +} + +// 轮询式上报 +HWTEST_F(PluginModuleApiTest, SamplePluginReport, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); + SetSampleConfig(configData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + + EXPECT_NE(sampleCallbacks_->onPluginReportResult, nullptr); + std::vector buffer(MAX_BUFFER_SIZE); + EXPECT_NE(sampleCallbacks_->onPluginReportResult(buffer.data(), buffer.size()), 0); + sampleCallbacks_->onPluginSessionStop(); +} + +HWTEST_F(PluginModuleApiTest, MemoryPluginReport, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + memoryCallbacks_ = &callbacks; + + EXPECT_NE(memoryCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); + SetMemoryConfig(configData, configLen); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + EXPECT_NE(memoryPlugin, nullptr); + + EXPECT_NE(memoryCallbacks_->onPluginReportResult, nullptr); + std::vector buffer(MAX_BUFFER_SIZE); + EXPECT_NE(memoryCallbacks_->onPluginReportResult(buffer.data(), buffer.size()), 0); + memoryCallbacks_->onPluginSessionStop(); +} + +// 多个插件上报 +HWTEST_F(PluginModuleApiTest, MultPluginReport1, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + uint32_t configLen = MAX_BUFFER_SIZE; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + std::vector sampleConfigData(configLen); + SetSampleConfig(sampleConfigData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(sampleConfigData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + EXPECT_NE(sampleCallbacks_->onPluginReportResult, nullptr); + std::vector sampleBuffer(MAX_BUFFER_SIZE); + EXPECT_NE(sampleCallbacks_->onPluginReportResult(sampleBuffer.data(), sampleBuffer.size()), 0); + + PluginModuleCallbacks memCallbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + memoryCallbacks_ = &memCallbacks; + + configLen = MAX_BUFFER_SIZE; + EXPECT_NE(memoryCallbacks_->onPluginSessionStart, nullptr); + std::vector memoryConfigData(configLen); + SetMemoryConfig(memoryConfigData, configLen); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStart(memoryConfigData.data(), configLen), 0); + EXPECT_NE(memoryPlugin, nullptr); + EXPECT_NE(memoryCallbacks_->onPluginReportResult, nullptr); + std::vector memoryBuffer(MAX_BUFFER_SIZE); + EXPECT_NE(memoryCallbacks_->onPluginReportResult(memoryBuffer.data(), memoryBuffer.size()), 0); + + sampleCallbacks_->onPluginSessionStop(); + memoryCallbacks_->onPluginSessionStop(); +} + +HWTEST_F(PluginModuleApiTest, MultPluginReport2, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + uint32_t configLen = MAX_BUFFER_SIZE; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + std::vector sampleConfigData(configLen); + SetSampleConfig(sampleConfigData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(sampleConfigData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + EXPECT_NE(sampleCallbacks_->onPluginReportResult, nullptr); + std::vector sampleBuffer(MAX_BUFFER_SIZE); + EXPECT_NE(sampleCallbacks_->onPluginReportResult(sampleBuffer.data(), sampleBuffer.size()), 0); + + PluginModuleCallbacks streamCallbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &streamCallbacks; + + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); + WriterStruct writer = { + Write, + Flush, + }; + writer_ = &writer; + streamCallbacks_->onRegisterWriterStruct(writer_); + EXPECT_NE(streamPlugin, nullptr); + EXPECT_NE(streamPlugin->resultWriter_, nullptr); + EXPECT_NE(streamPlugin->resultWriter_->write, nullptr); + EXPECT_NE(streamPlugin->resultWriter_->flush, nullptr); + + EXPECT_NE(streamCallbacks_->onPluginSessionStart, nullptr); + configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); + SetStreamConfig(configData, configLen); + EXPECT_EQ(streamCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + + sampleCallbacks_->onPluginSessionStop(); + streamCallbacks_->onPluginSessionStop(); +} + +// 流式插件停止 +HWTEST_F(PluginModuleApiTest, StreamPluginStop, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + StreamPluginSessionStart, + 0, + StreamPluginSessionStop, + (RegisterWriterStructCallback)StreamRegisterWriterStruct, + }; + streamCallbacks_ = &callbacks; + + EXPECT_NE(streamCallbacks_->onRegisterWriterStruct, nullptr); + streamCallbacks_->onRegisterWriterStruct(writer_); + EXPECT_NE(streamPlugin, nullptr); + + EXPECT_NE(streamCallbacks_->onPluginSessionStart, nullptr); + std::vector configData(1); + streamCallbacks_->onPluginSessionStart(configData.data(), configData.size()); + + EXPECT_NE(streamCallbacks_->onPluginSessionStop, nullptr); + EXPECT_EQ(streamCallbacks_->onPluginSessionStop(), 0); +} + +// 轮询式插件停止 +HWTEST_F(PluginModuleApiTest, SamplePluginStop, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector configData(configLen); + SetSampleConfig(configData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(configData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + + EXPECT_NE(sampleCallbacks_->onPluginSessionStop, nullptr); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStop(), 0); +} + +HWTEST_F(PluginModuleApiTest, MemoryPluginStop, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + memoryCallbacks_ = &callbacks; + + EXPECT_NE(memoryCallbacks_->onPluginSessionStart, nullptr); + uint32_t configLen = MAX_BUFFER_SIZE; + std::vector memoryConfigData(configLen); + SetMemoryConfig(memoryConfigData, configLen); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStart(memoryConfigData.data(), configLen), 0); + EXPECT_NE(memoryPlugin, nullptr); + + EXPECT_NE(memoryCallbacks_->onPluginSessionStop, nullptr); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStop(), 0); +} + +// 多个插件停止 +HWTEST_F(PluginModuleApiTest, MultPluginStop, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + SamplePluginSessionStart, + SamplePluginReportResult, + SamplePluginSessionStop, + 0, + }; + PluginModuleCallbacks memCallbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + sampleCallbacks_ = &callbacks; + memoryCallbacks_ = &memCallbacks; + uint32_t configLen = MAX_BUFFER_SIZE; + + EXPECT_NE(sampleCallbacks_->onPluginSessionStart, nullptr); + std::vector sampleConfigData(configLen); + SetSampleConfig(sampleConfigData, configLen); + EXPECT_EQ(sampleCallbacks_->onPluginSessionStart(sampleConfigData.data(), configLen), 0); + EXPECT_NE(samplePlugin, nullptr); + + EXPECT_NE(memoryCallbacks_->onPluginSessionStart, nullptr); + configLen = MAX_BUFFER_SIZE; + std::vector memoryConfigData(configLen); + SetMemoryConfig(memoryConfigData, configLen); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStart(memoryConfigData.data(), configLen), 0); + EXPECT_NE(memoryPlugin, nullptr); + + EXPECT_EQ(sampleCallbacks_->onPluginSessionStop(), 0); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStop(), 0); +} + +// 异常停止 +HWTEST_F(PluginModuleApiTest, PluginAbnormalStop, TestSize.Level1) +{ + PluginModuleCallbacks callbacks = { + MemDataPluginSessionStart, + MemPluginReportResult, + MemPluginSessionStop, + 0, + }; + memoryCallbacks_ = &callbacks; + + EXPECT_NE(memoryCallbacks_->onPluginSessionStop, nullptr); + EXPECT_EQ(memoryCallbacks_->onPluginSessionStop(), -1); } } // namespace diff --git a/ohos.build b/ohos.build old mode 100755 new mode 100644 index 43eba370f..05a5dc10a --- a/ohos.build +++ b/ohos.build @@ -4,6 +4,10 @@ "profiler": { "module_list": [ "//developtools/profiler/device:hiprofiler_targets" + ], + "test_list": [ + "//developtools/profiler/device:unittest", + "//developtools/profiler/interfaces/kits/test:unittest" ] } } diff --git a/protos/services/BUILD.gn b/protos/services/BUILD.gn old mode 100755 new mode 100644 diff --git a/protos/services/common_types.proto b/protos/services/common_types.proto old mode 100755 new mode 100644 diff --git a/protos/services/plugin_service.proto b/protos/services/plugin_service.proto old mode 100755 new mode 100644 diff --git a/protos/services/plugin_service_types.proto b/protos/services/plugin_service_types.proto old mode 100755 new mode 100644 diff --git a/protos/services/profiler_service.proto b/protos/services/profiler_service.proto old mode 100755 new mode 100644 index dcbe26902..35e1e1866 --- a/protos/services/profiler_service.proto +++ b/protos/services/profiler_service.proto @@ -38,4 +38,7 @@ service IProfilerService { // destroy tracing session. rpc DestroySession(DestroySessionRequest) returns (DestroySessionResponse); + + // keep tracing session alive, call this interface will restart session expire count down task. + rpc KeepSession(KeepSessionRequest) returns (KeepSessionResponse); } diff --git a/protos/services/profiler_service_types.proto b/protos/services/profiler_service_types.proto old mode 100755 new mode 100644 index f64776bcc..a557e620a --- a/protos/services/profiler_service_types.proto +++ b/protos/services/profiler_service_types.proto @@ -54,6 +54,7 @@ message ProfilerSessionConfig { string result_file = 3; // for OFFLINE mode, result file path uint32 result_max_size = 4; // for OFFLINE mode, result file max size in KB uint32 sample_duration = 5; // for OFFLINE mode, sample duration in ms + uint32 keep_alive_time = 6; // if set to non-zero value, session will auto-destroyed after CreateSession in ms } message CreateSessionRequest { @@ -116,4 +117,13 @@ message DestroySessionResponse { repeated ProfilerPluginState plugin_status = 3; } +// for KeepSession +message KeepSessionRequest { + uint32 request_id = 1; + uint32 session_id = 2; + uint32 keep_alive_time = 3; +} +message KeepSessionResponse { + uint32 status = 1; +} diff --git a/protos/types/plugins/agent_data/BUILD.gn b/protos/types/plugins/agent_data/BUILD.gn old mode 100755 new mode 100644 diff --git a/protos/types/plugins/agent_data/agent_plugin_config.proto b/protos/types/plugins/agent_data/agent_plugin_config.proto old mode 100755 new mode 100644 diff --git a/protos/types/plugins/agent_data/agent_plugin_result.proto b/protos/types/plugins/agent_data/agent_plugin_result.proto old mode 100755 new mode 100644 diff --git a/protos/types/plugins/bytrace_plugin/bytrace_plugin_config.proto b/protos/types/plugins/bytrace_plugin/bytrace_plugin_config.proto old mode 100755 new mode 100644 index 9a2d41e9b..8c2682226 --- a/protos/types/plugins/bytrace_plugin/bytrace_plugin_config.proto +++ b/protos/types/plugins/bytrace_plugin/bytrace_plugin_config.proto @@ -20,4 +20,5 @@ message BytracePluginConfig { uint32 time = 3; // Sets the bytrace running duration in seconds (5s by default) string clock = 4; // Sets the clock, which can be boot (default), global, mono, uptime, or perf. string outfile_name = 5; // Sets the name of the target file (stdout by default). + bool is_root = 6; } \ No newline at end of file diff --git a/protos/types/plugins/cpu_data/BUILD.gn b/protos/types/plugins/cpu_data/BUILD.gn new file mode 100644 index 000000000..b881f9da5 --- /dev/null +++ b/protos/types/plugins/cpu_data/BUILD.gn @@ -0,0 +1,65 @@ +# 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("//build/ohos.gni") +import("../../../protos.gni") + +cpu_data_sources = [ + "./cpu_plugin_config.proto", + "./cpu_plugin_result.proto", +] + +####################################################### +proto_out_dir = "$root_gen_dir/cpp/" + rebase_path(".", "//") +proto_rel_out_dir = rebase_path(proto_out_dir, root_build_dir) + +cpu_data_codegen = [] +foreach(proto, cpu_data_sources) { + name = get_path_info(proto, "name") + cpu_data_codegen += [ + "$proto_out_dir/$name.pb.h", + "$proto_out_dir/$name.pb.cc", + ] +} + +config("cpu_include_config") { + include_dirs = [ "$proto_out_dir" ] +} + +####################################################### +action("cpu_data_cpp_gen") { + script = "${OHOS_PROFILER_DIR}/build/protoc.sh" + sources = cpu_data_sources + outputs = cpu_data_codegen + args = [ + "$libc_dir_proto", + "$root_output_dir_proto", + "--cpp_out", + "$proto_rel_out_dir", + "--proto_path", + rebase_path(".", root_build_dir), + ] + args += rebase_path(sources, root_build_dir) + deps = [ "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc(${host_toolchain})" ] +} + +ohos_source_set("cpu_data_cpp") { + deps = [ ":cpu_data_cpp_gen" ] + public_deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + ] + include_dirs = [ "$proto_out_dir" ] + public_configs = [ ":cpu_include_config" ] + sources = cpu_data_codegen +} diff --git a/protos/types/plugins/cpu_data/cpu_plugin_config.proto b/protos/types/plugins/cpu_data/cpu_plugin_config.proto new file mode 100644 index 000000000..f3a730c98 --- /dev/null +++ b/protos/types/plugins/cpu_data/cpu_plugin_config.proto @@ -0,0 +1,23 @@ +// 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. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + + +// Cpu plug-in configuration, passed to plug-in by plug-in service. +message CpuConfig { + int32 pid = 1; +} diff --git a/protos/types/plugins/cpu_data/cpu_plugin_result.proto b/protos/types/plugins/cpu_data/cpu_plugin_result.proto new file mode 100644 index 000000000..7b1896556 --- /dev/null +++ b/protos/types/plugins/cpu_data/cpu_plugin_result.proto @@ -0,0 +1,71 @@ +// Copyright (c) 2021 Huawei Device Co., Ltd. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message SampleTimeStamp { + uint64 tv_sec = 1; + uint64 tv_nsec = 2; +} + +message CpuCoreFrequency { + int32 min_frequency_khz = 1; + int32 max_frequency_khz = 2; + int32 cur_frequency_khz = 3; +} + +message CpuCoreUsageInfo { + int32 cpu_core = 1; + int64 prev_system_cpu_time_ms = 2; + int64 prev_system_boot_time_ms = 3; + int64 system_cpu_time_ms = 4; + int64 system_boot_time_ms = 5; + CpuCoreFrequency frequency = 6; + bool is_little_core = 7; +} + +message CpuUsageInfo { + int64 prev_process_cpu_time_ms = 1; + int64 prev_system_cpu_time_ms = 2; + int64 prev_system_boot_time_ms = 3; + int64 process_cpu_time_ms = 4; + int64 system_cpu_time_ms = 5; + int64 system_boot_time_ms = 6; + repeated CpuCoreUsageInfo cores = 7; + SampleTimeStamp timestamp = 8; +} + +enum ThreadState { + THREAD_UNSPECIFIED = 0; + THREAD_RUNNING = 1; + THREAD_SLEEPING = 2; + THREAD_STOPPED = 3; + THREAD_WAITING = 4; +} + +message ThreadInfo { + int32 tid = 1; + string thread_name = 2; + ThreadState thread_state = 3; + int64 prev_thread_cpu_time_ms = 4; + int64 thread_cpu_time_ms = 5; + SampleTimeStamp timestamp = 6; +} + +message CpuData { + CpuUsageInfo cpu_usage_info = 1; + repeated ThreadInfo thread_info = 2; +} diff --git a/protos/types/plugins/memory_data/BUILD.gn b/protos/types/plugins/memory_data/BUILD.gn old mode 100755 new mode 100644 diff --git a/protos/types/plugins/memory_data/memory_plugin_common.proto b/protos/types/plugins/memory_data/memory_plugin_common.proto old mode 100755 new mode 100644 diff --git a/protos/types/plugins/memory_data/memory_plugin_config.proto b/protos/types/plugins/memory_data/memory_plugin_config.proto old mode 100755 new mode 100644 index c81ea0a7b..72f824df4 --- a/protos/types/plugins/memory_data/memory_plugin_config.proto +++ b/protos/types/plugins/memory_data/memory_plugin_config.proto @@ -22,12 +22,21 @@ import "memory_plugin_common.proto"; message MemoryConfig { // set true to report process list bool report_process_tree = 1; + // set true to report memory counter from /proc/meminfo bool report_sysmem_mem_info = 2; + // set required counter list of system meminfo, eg:MemTotal, MemFree, etc. repeated SysMeminfoType sys_meminfo_counters = 3; + // set true to report memory counter from /proc/vmstat bool report_sysmem_vmem_info = 4; + // set required counter list of virtual system meminfo, eg:nr_free_pages, nr_anon_pages, etc. repeated SysVMeminfoType sys_vmeminfo_counters = 5; + // set true to report process meminfo from /proc/${pid}/stat bool report_process_mem_info = 6; + // set true to report application memory usage summary, eg:java heap memory, native heap, stack memory, etc. bool report_app_mem_info = 7; + // set true to report application memory by dumpsys service, otherwise, + // application memory will count up by /proc/${pid}/smaps information bool report_app_mem_by_dumpsys = 8; + // set required pid list repeated int32 pid = 9; } diff --git a/protos/types/plugins/memory_data/memory_plugin_result.proto b/protos/types/plugins/memory_data/memory_plugin_result.proto old mode 100755 new mode 100644 diff --git a/protos/types/plugins/sample_data/BUILD.gn b/protos/types/plugins/sample_data/BUILD.gn new file mode 100644 index 000000000..954a9b354 --- /dev/null +++ b/protos/types/plugins/sample_data/BUILD.gn @@ -0,0 +1,65 @@ +# 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("//build/ohos.gni") +import("../../../protos.gni") + +sample_data_sources = [ + "./sample_plugin_config.proto", + "./sample_plugin_result.proto", +] + +####################################################### +proto_out_dir = "$root_gen_dir/cpp/" + rebase_path(".", "//") +proto_rel_out_dir = rebase_path(proto_out_dir, root_build_dir) + +sample_data_codegen = [] +foreach(proto, sample_data_sources) { + name = get_path_info(proto, "name") + sample_data_codegen += [ + "$proto_out_dir/$name.pb.h", + "$proto_out_dir/$name.pb.cc", + ] +} + +config("sample_include_config") { + include_dirs = [ "$proto_out_dir" ] +} + +####################################################### +action("sample_data_cpp_gen") { + script = "${OHOS_PROFILER_DIR}/build/protoc.sh" + sources = sample_data_sources + outputs = sample_data_codegen + args = [ + "$libc_dir_proto", + "$root_output_dir_proto", + "--cpp_out", + "$proto_rel_out_dir", + "--proto_path", + rebase_path(".", root_build_dir), + ] + args += rebase_path(sources, root_build_dir) + deps = [ "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc(${host_toolchain})" ] +} + +ohos_source_set("sample_data_cpp") { + deps = [ ":sample_data_cpp_gen" ] + public_deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + ] + include_dirs = [ "$proto_out_dir" ] + public_configs = [ ":sample_include_config" ] + sources = sample_data_codegen +} diff --git a/protos/types/plugins/sample_data/sample_plugin_config.proto b/protos/types/plugins/sample_data/sample_plugin_config.proto new file mode 100644 index 000000000..262398e4f --- /dev/null +++ b/protos/types/plugins/sample_data/sample_plugin_config.proto @@ -0,0 +1,19 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message SampleConfig { + int32 pid = 1; +} \ No newline at end of file diff --git a/protos/types/plugins/sample_data/sample_plugin_result.proto b/protos/types/plugins/sample_data/sample_plugin_result.proto new file mode 100755 index 000000000..0a8d74393 --- /dev/null +++ b/protos/types/plugins/sample_data/sample_plugin_result.proto @@ -0,0 +1,19 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message SampleData { + uint64 time_ms = 1; +} \ No newline at end of file diff --git a/protos/types/plugins/stream_data/BUILD.gn b/protos/types/plugins/stream_data/BUILD.gn new file mode 100644 index 000000000..8aa3506a1 --- /dev/null +++ b/protos/types/plugins/stream_data/BUILD.gn @@ -0,0 +1,65 @@ +# 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("//build/ohos.gni") +import("../../../protos.gni") + +stream_data_sources = [ + "./stream_plugin_config.proto", + "./stream_plugin_result.proto", +] + +####################################################### +proto_out_dir = "$root_gen_dir/cpp/" + rebase_path(".", "//") +proto_rel_out_dir = rebase_path(proto_out_dir, root_build_dir) + +stream_data_codegen = [] +foreach(proto, stream_data_sources) { + name = get_path_info(proto, "name") + stream_data_codegen += [ + "$proto_out_dir/$name.pb.h", + "$proto_out_dir/$name.pb.cc", + ] +} + +config("stream_include_config") { + include_dirs = [ "$proto_out_dir" ] +} + +####################################################### +action("stream_data_cpp_gen") { + script = "${OHOS_PROFILER_DIR}/build/protoc.sh" + sources = stream_data_sources + outputs = stream_data_codegen + args = [ + "$libc_dir_proto", + "$root_output_dir_proto", + "--cpp_out", + "$proto_rel_out_dir", + "--proto_path", + rebase_path(".", root_build_dir), + ] + args += rebase_path(sources, root_build_dir) + deps = [ "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protoc(${host_toolchain})" ] +} + +ohos_source_set("stream_data_cpp") { + deps = [ ":stream_data_cpp_gen" ] + public_deps = [ + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf", + "${OHOS_PROFILER_3RDPARTY_PROTOBUF_DIR}:protobuf_lite", + ] + include_dirs = [ "$proto_out_dir" ] + public_configs = [ ":stream_include_config" ] + sources = stream_data_codegen +} diff --git a/protos/types/plugins/stream_data/stream_plugin_config.proto b/protos/types/plugins/stream_data/stream_plugin_config.proto new file mode 100644 index 000000000..9d124a74c --- /dev/null +++ b/protos/types/plugins/stream_data/stream_plugin_config.proto @@ -0,0 +1,19 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message StreamConfig { + int32 pid = 1; +} \ No newline at end of file diff --git a/protos/types/plugins/stream_data/stream_plugin_result.proto b/protos/types/plugins/stream_data/stream_plugin_result.proto new file mode 100644 index 000000000..ece7d2410 --- /dev/null +++ b/protos/types/plugins/stream_data/stream_plugin_result.proto @@ -0,0 +1,19 @@ +// 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. +syntax = "proto3"; +option java_package = "ohos.devtools.datasources.transport.grpc.service"; +option optimize_for = LITE_RUNTIME; + +message StreamData { + uint64 time_ms = 1; +} \ No newline at end of file diff --git a/trace_analyzer/README.md b/trace_analyzer/README.md index b468aaa36..e302039a2 100644 --- a/trace_analyzer/README.md +++ b/trace_analyzer/README.md @@ -1,44 +1,40 @@ # trace_streamer开发环境搭建和编译运行指引 -本应用使用gn作为构建工具,支持在linux环境同时编译linux,windows环境的应用,后期会根据开发者需求添加更多的支持。 +本应用使用gn作为构建工具,支持在linux环境同时编译linux,windows和mac使用QtCreator作为开发IDE ## 1、开发环境 -需要Ubuntu20.04,或者将gcc升级到9.3.0版本(后续会降低版本要求) -## 2、编译 -编译前,需搭建本地gn编译环境 -```sh -# gn 和 ninja 工具包 -buildtools/linux64/ -gn 555198版本 -ninja 1.10.0版本 -clang-format version 10.0.0-4ubuntu1版本 -buildtools/clang/bin -buildtools/clang/lib -sqlite文件位于 -buildtools/sqlite +ubuntu使用vscode,windows和mac使用QtCreator +## 2、参与版本编译 +在上级目录的ohos.build文件中,module_list列表中添加 ``` +"//developtools/profiler/trace_analyzer:trace_streamer" +``` +在test_list列表中添加"//developtools/profiler/trace_analyzer/test:unittest"来编译UT +在根目录third_party/sqlite/BUILD.gn文件中,在ohos_shared_library("sqlite")选型中添加 +``` +visibility += [ "//developtools/profiler/trace_analyzer/*" ] +``` +去除 +``` +cflags_c = [ + "-fvisibility=hidden", + ] +``` +# 对外部的依赖 +本应用依赖与sqlite,protobuf(htrace解析部分依赖) + +本应用同时依赖于//developtools/profiler/protos/types/plugins/ftrace_data目录下的部分对象ftrace_data_cpp编译目标来支持htrace的解析 + +ts.gni文件用来区别独立编译和build目录下的ohos.gni用来支持独立编译,开发者需自行编译相关依赖 + ### 2.1、 编译linux版应用 -无需前置操作 - -### 2.2、编译Windows版应用 - -需下载MinGW编译工具链 -```sh -# 安装 mingw-w64 包,用于在 Linux主机上生成 Windows 目标文件: -sudo apt install mingw-w64 -``` +在根目录下执行相关命令进行编译 +### 2.2、编译Windows版和Mac应用 +在项目目录下有pro文件,为QtCreator的工程文件,但部分内容赖在于上面所添加的外部依赖,如果要编译相关平台应用,开发者需自行补充相关工程文件,或者在论坛留言 ### 2.3、开始编译 ```sh -# 生成各平台的ninja编译规则文件 -tools/build_all_configs.py - -# 编译Windows系统的目标文件,windows运行依赖的库在tools/trace_win32_lib -tools/ninja -C out/win_mingw trace_streamer -j 5 - -# 编译Linux系统的目标文件 -tools/ninja -C out/linux_clang trace_streamer -j 5 -tools/ninja -C out/debug_linux_clang trace_streamer -j 5 +参与版本编译即可 ``` ### 3、运行程序 @@ -46,9 +42,9 @@ tools/ninja -C out/debug_linux_clang trace_streamer -j 5 ```sh # Linux 主机可以直接执行: -out/linux_clang/trace_streamer +out/linux/trace_streamer ``` #### 3.2 windows系统 ``` -Windows环境执行,需下载mingw环境,或者使用 wine 执行 +Windows环境执行,需添加相关依赖文件 ``` diff --git a/trace_analyzer/build.sh b/trace_analyzer/build.sh new file mode 100755 index 000000000..69c1a812a --- /dev/null +++ b/trace_analyzer/build.sh @@ -0,0 +1,55 @@ +#! /bin/bash + +# 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. + +echo "begin to check input" +target_os='linux' +is_debug='false' +if [ "$#" -eq "2" ];then + if [ "$1" != 'windows' ] && [ $1 != "linux" ];then + echo "failed" + echo "Usage: `basename $0` windows/linux debug/release" + exit + fi + if [ $2 != "debug" -a $2 != "release" ];then + echo "failed" + echo "Usage: `basename $0` windows/linux debug/release" + exit + fi + if [ $2 == "debug" ];then + is_debug='true' + else + is_debug='false' + fi + target_os=$1 + echo "platform is $target_os" + echo "isdebug: $is_debug" +else + echo "Usage: `basename $0` windows/linux debug/release" + echo "You provided $# parameters,but 2 are required." + echo "use default input paramter" + echo "platform is $target_os" + echo "is_debug:$is_debug" +fi +echo "gen ..." +ext="" +if [ "$is_debug" != 'false' ];then + ext="_debug" +fi +echo "the output file will be at ""$prefix""$target_os" +buildtools/linux64/gn gen out/"$target_os""$ext" --args='is_debug='"$is_debug"' target_os="'"$target_os"'"' +echo "begin to build ..." +touch out/windows/trace_streamer.exe +target_os='linux' +buildtools/linux64/ninja -C out/"$target_os""$ext" diff --git a/trace_analyzer/tools/run-buildtools-binary.sh b/trace_analyzer/build/ohos.gni similarity index 69% rename from trace_analyzer/tools/run-buildtools-binary.sh rename to trace_analyzer/build/ohos.gni index cc6586b57..b28d636b1 100644 --- a/trace_analyzer/tools/run-buildtools-binary.sh +++ b/trace_analyzer/build/ohos.gni @@ -1,5 +1,4 @@ -#!/bin/bash -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,3 +10,11 @@ # 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. +template("ohos_source_set") { + source_set(target_name) { + sources = invoker.sources + deps = invoker.deps + include_dirs = invoker.include_dirs + public_deps = invoker.public_deps + } +} diff --git a/trace_analyzer/buildtools/BUILD.gn b/trace_analyzer/buildtools/BUILD.gn deleted file mode 100644 index 120a7a9f6..000000000 --- a/trace_analyzer/buildtools/BUILD.gn +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -config("sqlite_config") { - include_dirs = [ "third_party_sqlite/include" ] - cflags = [ - "-DSQLITE_THREADSAFE=0", - "-DQLITE_DEFAULT_MEMSTATUS=0", - "-DSQLITE_LIKE_DOESNT_MATCH_BLOBS", - "-DSQLITE_OMIT_DEPRECATED", - "-DSQLITE_OMIT_SHARED_CACHE", - "-DHAVE_USLEEP", - "-DHAVE_UTIME", - "-DSQLITE_BYTEORDER=1234", - "-DSQLITE_DEFAULT_AUTOVACUUM=0", - "-DSQLITE_DEFAULT_MMAP_SIZE=0", - "-DSQLITE_CORE", - "-DSQLITE_TEMP_STORE=3", - "-DSQLITE_OMIT_LOAD_EXTENSION", - "-DSQLITE_OMIT_RANDOMNESS", - ] -} - -source_set("third_party_sqlite") { - sources = [ - "./third_party_sqlite/src/sqlite3.c", - ] - configs -= [ "//gn:extra_warnings" ] - public_configs = [ ":sqlite_config" ] -} - - diff --git a/trace_analyzer/gn/BUILD.gn b/trace_analyzer/gn/BUILD.gn deleted file mode 100644 index dce336fcf..000000000 --- a/trace_analyzer/gn/BUILD.gn +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -group("default_deps") { - public_configs = [ ":default_config" ] - public_deps = [] -} - -config("default_config") { - defines = [] - include_dirs = [ - "..", - "../include", - ] -} - -config("extra_warnings") { - cflags = [ - "-Wall", - "-Wextra", - ] - if (is_clang) { - cflags += [ - "-Wall", - "-Werror", - "-Weverything", - "-Wno-c++98-compat-pedantic", - "-Wno-gnu-statement-expression", - "-Wno-gnu-zero-variadic-macro-arguments", - "-Wno-padded", - "-Wno-reserved-id-macro", - ] - } -} - -config("no_exceptions") { - cflags_cc = [ "-fno-exceptions" ] -} - -config("no_rtti") { - cflags_cc = [ "-fno-rtti" ] -} - -config("c++11") { - cflags_cc = [ "-std=c++11" ] -} - -config("c++17") { - cflags_cc = [ "-std=c++17" ] -} - -config("visibility_hidden") { - cflags = [ "-fvisibility=hidden" ] -} - -config("default") { - asmflags = [] - cflags = [] - cflags_c = [] - cflags_cc = [] - defines = [] - ldflags = [] - libs = [] - - cflags += [ - "-fstrict-aliasing", - "-fstack-protector", - "-fPIC", - "-g", - "-Wformat", - ] - - if (is_linux) { - cflags += [ "-Wa,--noexecstack" ] - } - - if (is_clang) { - cflags += [ - "-fcolor-diagnostics", - "-fdiagnostics-show-template-tree", - ] - } - - if (is_linux) { - libs += [ - "pthread", - "rt", - ] - } - - if (is_debug && is_linux) { - libs += [ "dl" ] - } -} - -config("debug_symbols") { - cflags = [ "-O0" ] - if (is_linux) { - cflags += [ "-funwind-tables" ] - } -} - -config("release") { - cflags = [ - "-fdata-sections", - "-ffunction-sections", - ] - - cflags += [ "-O3" ] - ldflags = [ - "-fuse-ld=gold", - "-fstack-protector", - "-Wl,--gc-sections", - "-Wl,-O1", - ] - if (is_linux) { - ldflags += [ "-Wl,--icf=all" ] - } - defines = [ "NDEBUG" ] -} - -config("shared_library") { - ldflags = [ "-fPIC" ] -} - -config("executable") { - ldflags = [] - - if (is_linux) { - ldflags += [ - "-Wl,-rpath=\$ORIGIN/.", - "-Wl,-rpath-link=.", - ] - } - - if (is_linux) { - ldflags += [ - "-Wl,-rpath=\$ORIGIN/.", - "-Wl,-rpath-link=.", - "-lrt", - ] - } -} diff --git a/trace_analyzer/gn/BUILDCONFIG.gn b/trace_analyzer/gn/BUILDCONFIG.gn deleted file mode 100644 index 81c4385c2..000000000 --- a/trace_analyzer/gn/BUILDCONFIG.gn +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -declare_args() { - is_debug = true - is_clang = true -} - -declare_args() { - ar = "ar" -} - -is_win = false -is_linux = false - -if (target_os == "linux") { - is_win = false - is_linux = true -} else if (target_os == "win"){ - is_win = true - is_linux = false -} - -default_configs = [ - "//gn:debug_symbols", - "//gn:default", - "//gn:c++17", - "//gn:extra_warnings", - "//gn:no_exceptions", - "//gn:no_rtti", - "//gn:visibility_hidden", -] - -if (!is_debug) { - default_configs -= [ "//gn:debug_symbols" ] - default_configs += [ "//gn:release" ] -} - -set_defaults("source_set") { - configs = default_configs -} - -set_defaults("executable") { - configs = default_configs - configs += [ "//gn:executable" ] -} - -set_default_toolchain("//gn/toolchain:gcc_like") diff --git a/trace_analyzer/gn/toolchain/BUILD.gn b/trace_analyzer/gn/toolchain/BUILD.gn deleted file mode 100644 index cb8c173d1..000000000 --- a/trace_analyzer/gn/toolchain/BUILD.gn +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -declare_args() { - if (is_clang) { - cc = "../../buildtools/clang/bin/clang" - cxx = "../../buildtools/clang/bin/clang++" - } else { - cc = "x86_64-w64-mingw32-gcc" - cxx = "x86_64-w64-mingw32-g++" - } -} - -toolchain("gcc_like") { - lib_switch = "-l" - lib_dir_switch = "-L" - - tool("cxx") { - depfile = "{{output}}.d" - command = "$cxx -MMD -MF $depfile {{defines}} {{include_dirs}} {{cflags}} {{cflags_cc}} -c {{source}} -o {{output}}" - depsformat = "gcc" - outputs = [ - "{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o", - ] - description = "compile {{source}}" - } - - tool("cc") { - depfile = "{{output}}.d" - command = "$cc -MMD -MF $depfile {{defines}} {{include_dirs}} {{cflags}} {{cflags_c}} -c {{source}} -o {{output}}" - depsformat = "gcc" - outputs = [ - "{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o", - ] - description = "compile {{source}}" - } - - tool("link") { - command = "$cxx {{ldflags}} {{inputs}} {{solibs}} {{libs}} -o {{output}}" - outputs = [ - "{{root_out_dir}}/{{target_output_name}}{{output_extension}}", - ] - description = "link {{output}}" - } - - tool("stamp") { - command = "touch {{output}}" - description = "touch {{output}}" - } - - tool("copy") { - if (is_win) { - command = "cp -af {{source}}* {{output}}.exe" - description = "COPY {{source}}.exe {{output}}.exe" - } else { - command = "cp -af {{source}} {{output}}" - description = "COPY {{source}} {{output}}" - } - } - } diff --git a/trace_analyzer/include/log.h b/trace_analyzer/include/log.h deleted file mode 100755 index a13179fbc..000000000 --- a/trace_analyzer/include/log.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INCLUDE_TUNING_BASE_LOGGING_H_ -#define INCLUDE_TUNING_BASE_LOGGING_H_ - -#include -#include - -namespace SysTuning { -namespace base { -#define TUNING_LOGI(format, ...) fprintf(stderr, "[%s][%d]: " format "\n", __FILE__, __LINE__, ##__VA_ARGS__) - -#ifdef NDEBUG -#define TUNING_LOGD(format, ...) -#define TUNING_LOGF(format, ...) -#define TUNING_ASSERT(x) -#else -#define TUNING_CRASH \ - do { \ - __builtin_trap(); \ - __builtin_unreachable(); \ - } while (0) - - -#define TUNING_LOGD(format, ...) fprintf(stderr, "[%s][%s][%d]: " format "\n", __FILE__, __FUNCTION__, \ - __LINE__, ##__VA_ARGS__) - -#define TUNING_LOGF(format, ...) \ - do { \ - TUNING_CRASH; \ - } while (0) - -#define TUNING_ASSERT(x) \ - do { \ - if (!(x)) { \ - TUNING_CRASH; \ - } \ - } while (0) - -#endif -} // namespace base -} // namespace SysTuning - -#endif // INCLUDE_TUNING_BASE_LOGGING_H_ diff --git a/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/Info.plist b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/Info.plist new file mode 100755 index 000000000..e3d86b54c --- /dev/null +++ b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/Info.plist @@ -0,0 +1,22 @@ + + + + + NSPrincipalClass + NSApplication + CFBundleIconFile + + CFBundlePackageType + APPL + CFBundleGetInfoString + Created by Qt/QMake + CFBundleSignature + ???? + CFBundleExecutable + trace_streamer + CFBundleIdentifier + xxx.trace-streamer + NOTE + This file was generated by Qt/QMake. + + diff --git a/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/MacOS/trace_streamer b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/MacOS/trace_streamer new file mode 100755 index 000000000..ce661f3a7 Binary files /dev/null and b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/MacOS/trace_streamer differ diff --git a/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/PkgInfo b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/PkgInfo new file mode 100755 index 000000000..6f749b0f3 --- /dev/null +++ b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/PkgInfo @@ -0,0 +1 @@ +APPL???? diff --git a/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/Resources/empty.lproj b/trace_analyzer/prebuilts/mac/trace_streamer.app/Contents/Resources/empty.lproj new file mode 100755 index 000000000..e69de29bb diff --git a/trace_analyzer/prebuilts/trace_streamer.exe b/trace_analyzer/prebuilts/trace_streamer.exe new file mode 100755 index 000000000..3327f592f --- /dev/null +++ b/trace_analyzer/prebuilts/trace_streamer.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f3460bccdb49c918c5f72396eb00dd9a473a3e00803f9e1079456499182eecd +size 4444672 diff --git a/trace_analyzer/prebuilts/windows/trace_streamer.exe b/trace_analyzer/prebuilts/windows/trace_streamer.exe new file mode 100755 index 000000000..f41c47d53 --- /dev/null +++ b/trace_analyzer/prebuilts/windows/trace_streamer.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe51fb63a32a6b447aa68648a4a19d4e182feff49b197aeb2daa67cabb54bc47 +size 3243520 diff --git a/trace_analyzer/src/BUILD.gn b/trace_analyzer/src/BUILD.gn index 7babfd66d..a03cf3575 100755 --- a/trace_analyzer/src/BUILD.gn +++ b/trace_analyzer/src/BUILD.gn @@ -11,13 +11,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -source_set("lib") { +import("//build/ohos.gni") +import("ts.gni") +ohos_source_set("trace_streamer_source") { sources = [ + "cfg/trace_streamer_cfg.cpp", + "cfg/trace_streamer_cfg.h", "filter/clock_filter.cpp", "filter/clock_filter.h", "filter/cpu_filter.cpp", - "filter/event_filter.cpp", - "filter/event_filter.h", "filter/filter_base.cpp", "filter/filter_base.h", "filter/filter_filter.cpp", @@ -28,14 +30,23 @@ source_set("lib") { "filter/process_filter.h", "filter/slice_filter.cpp", "filter/slice_filter.h", - "parser/bytrace_parser.cpp", - "parser/bytrace_parser.h", + "filter/stat_filter.cpp", + "filter/stat_filter.h", + "filter/symbols_filter.cpp", + "filter/symbols_filter.h", + "parser/bytrace_parser/bytrace_event_parser.cpp", + "parser/bytrace_parser/bytrace_event_parser.h", + "parser/bytrace_parser/bytrace_parser.cpp", + "parser/bytrace_parser/bytrace_parser.h", "parser/common_types.h", - "parser/event_parser.cpp", - "parser/event_parser.h", + "parser/event_parser_base.cpp", + "parser/event_parser_base.h", "parser/thread_state.cpp", "parser/thread_state.h", - "table/bound_table.cpp", + "table/callstack_table.cpp", + "table/callstack_table.h", + "table/clock_event_filter_table.cpp", + "table/clock_event_filter_table.h", "table/cpu_measure_filter_table.cpp", "table/cpu_measure_filter_table.h", "table/data_dict_table.cpp", @@ -44,23 +55,27 @@ source_set("lib") { "table/filter_table.h", "table/instants_table.cpp", "table/instants_table.h", - "table/internal_slice_table.cpp", - "table/internal_slice_table.h", - "table/internal_thread.cpp", "table/measure_filter_table.cpp", "table/measure_filter_table.h", "table/measure_table.cpp", "table/measure_table.h", + "table/meta_table.cpp", + "table/meta_table.h", "table/process_filter_table.cpp", "table/process_filter_table.h", "table/process_measure_filter_table.cpp", "table/process_measure_filter_table.h", "table/process_table.cpp", "table/process_table.h", + "table/range_table.cpp", "table/raw_table.cpp", "table/raw_table.h", "table/sched_slice_table.cpp", "table/sched_slice_table.h", + "table/stat_table.cpp", + "table/stat_table.h", + "table/symbols_table.cpp", + "table/symbols_table.h", "table/table_base.cpp", "table/table_base.h", "table/thread_filter_table.cpp", @@ -68,7 +83,6 @@ source_set("lib") { "table/thread_state_table.cpp", "table/thread_state_table.h", "table/thread_table.cpp", - "table/thread_table.h", "trace_data/trace_data_cache.cpp", "trace_data/trace_data_cache.h", "trace_data/trace_data_cache_base.cpp", @@ -81,32 +95,73 @@ source_set("lib") { "trace_data/trace_data_db.h", "trace_data/trace_stdtype.cpp", "trace_data/trace_stdtype.h", - "trace_streamer.cpp", - "trace_streamer.h", - "trace_streamer_filters.cpp", - "trace_streamer_filters.h", + "trace_streamer/trace_streamer_filters.cpp", + "trace_streamer/trace_streamer_filters.h", + "trace_streamer/trace_streamer_selector.cpp", + "trace_streamer/trace_streamer_selector.h", ] include_dirs = [ - "//src/base", - "//src", - "//src/filter", - "//src/table", - "//src/trace_data", + "base", + "..", + "trace_streamer", + "filter", + "table", + "trace_data", + "include", + "./", + "parser", + "base", + "cfg", + "parser/htrace_parser", + "parser/htrace_parser/htrace_event_parser", + "parser/htrace_parser/htrace_cpu_parser", + "//third_party/sqlite/include", + "${OHOS_PROTO_GEN}/types/plugins/ftrace_data", + "${OHOS_PROTO_GEN}", + "//third_party/protobuf/src", ] deps = [ - "../../buildtools:third_party_sqlite", - "../../gn:default_deps", "base", + "parser/htrace_parser:htrace_parser", ] - public_deps = [ "//src/base:base" ] + + if (enable_ts_utest) { + cflags = [ + "-fprofile-arcs", + "-ftest-coverage", + ] + ldflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "--coverage", + ] + } + public_deps = [] } executable("trace_streamer") { - deps = [ - ":lib", - "../../gn:default_deps", + include_dirs = [ + "./", + "include", + "trace_data", + "cfg", + "trace_streamer", + "parser", + "cfg", + "parser/htrace_parser", + "parser/htrace_parser/htrace_event_parser", + "parser/htrace_parser/htrace_cpu_parser", + "//third_party/sqlite/include", + "${OHOS_PROTO_GEN}/types/plugins/ftrace_data", + "${OHOS_PROTO_GEN}", + "//third_party/protobuf/src", "base", - "//src/base:base", + ] + deps = [ + ":trace_streamer_source", + "base", + "include:ibase", + "//third_party/sqlite:sqlite", ] sources = [ "main.cpp" ] } diff --git a/trace_analyzer/src/base/BUILD.gn b/trace_analyzer/src/base/BUILD.gn index 994467384..f382a0879 100644 --- a/trace_analyzer/src/base/BUILD.gn +++ b/trace_analyzer/src/base/BUILD.gn @@ -11,16 +11,26 @@ # See the License for the specific language governing permissions and # limitations under the License. -source_set("base") { - deps = [ - "../../gn:default_deps", - ] - public_deps = [ - "../../include:base", - ] +import("//build/ohos.gni") +import("../ts.gni") +ohos_source_set("base") { + deps = [] + public_deps = [ "../include:ibase" ] + include_dirs = [ "../include" ] sources = [ + "codec_cov.cpp", "file.cpp", "parting_string.cpp", ] + if (enable_ts_utest) { + cflags = [ + "-fprofile-arcs", + "-ftest-coverage", + ] + ldflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "--coverage", + ] + } } - diff --git a/trace_analyzer/tools/gn b/trace_analyzer/src/base/base.pri old mode 100755 new mode 100644 similarity index 70% rename from trace_analyzer/tools/gn rename to trace_analyzer/src/base/base.pri index 6bb4745c5..78eff6d06 --- a/trace_analyzer/tools/gn +++ b/trace_analyzer/src/base/base.pri @@ -1,16 +1,22 @@ -#!/bin/bash -# 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. - -CMD="gn" -source "$(dirname "${BASH_SOURCE[0]}")/run-buildtools-binary.sh" +# 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. + +INCLUDEPATH +=$$PWD +HEADERS += \ + $$PWD/common.h \ + $$PWD/double_map.h + +SOURCES += \ + $$PWD/codec_cov.cpp \ + $$PWD/file.cpp \ + $$PWD/parting_string.cpp diff --git a/trace_analyzer/src/base/codec_cov.cpp b/trace_analyzer/src/base/codec_cov.cpp new file mode 100755 index 000000000..50552aa06 --- /dev/null +++ b/trace_analyzer/src/base/codec_cov.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "codec_cov.h" + +#include +#ifdef _WIN32 +#include +#endif + +namespace SysTuning { +namespace base { +int PreNum(unsigned char byte) +{ + constexpr uint32_t BITS = 8; + unsigned char mask = 0x80; + int num = 0; + for (uint32_t i = 0; i < BITS; i++) { + if ((byte & mask) == mask) { + mask = mask >> 1; + num++; + } else { + break; + } + } + return num; +} + +bool IsUTF8(const uint8_t* data, int len) +{ + constexpr uint8_t MASK = 0x80; + constexpr uint8_t FIRST_BYTE = 0xc0; + constexpr int TARGET = 2; + int num = 0; + int i = 0; + while (i < len) { + if ((data[i] & MASK) == 0x00) { + i++; + continue; + } + if ((num = PreNum(data[i])) > TARGET) { + i++; + for (int j = 0; j < num - 1; j++) { + if ((data[i] & FIRST_BYTE) != MASK) { + return false; + } + i++; + } + } else { + return false; + } + } + return true; +} + +bool IsGBK(const uint8_t* data, int len) +{ + constexpr int STEP = 2; + constexpr uint8_t ASCII_END = 0x7f; + constexpr uint8_t FIRST_BYTE = 0x81; + constexpr uint8_t FIRST_BYTE_END = 0xfe; + constexpr uint8_t SECOND_BYTE_ONE = 0x40; + constexpr uint8_t SECOND_BYTE_TWO_END = 0xfe; + constexpr uint8_t GBK_MASK = 0xf7; + int i = 0; + while (i < len) { + if (data[i] <= ASCII_END) { + i++; + continue; + } else { + if (data[i] >= FIRST_BYTE && data[i] <= FIRST_BYTE_END && data[i + 1] >= SECOND_BYTE_ONE && + data[i + 1] <= SECOND_BYTE_TWO_END && data[i + 1] != GBK_MASK) { + i += STEP; + continue; + } else { + return false; + } + } + } + return true; +} + +CODING GetCoding(const uint8_t* data, int len) +{ + CODING coding; + if (IsUTF8(data, len)) { + coding = UTF8; + } else if (IsGBK(data, len)) { + coding = GBK; + } else { + coding = UNKOWN; + } + return coding; +} + +#ifdef _WIN32 +std::string GbkToUtf8(const char* srcStr) +{ + int len = MultiByteToWideChar(CP_ACP, 0, srcStr, -1, NULL, 0); + std::unique_ptr wstr = std::make_unique(len + 1); + MultiByteToWideChar(CP_ACP, 0, srcStr, -1, wstr.get(), len); + len = WideCharToMultiByte(CP_UTF8, 0, wstr.get(), -1, NULL, 0, NULL, NULL); + std::unique_ptr str = std::make_unique(len + 1); + WideCharToMultiByte(CP_UTF8, 0, wstr.get(), -1, str.get(), len, NULL, NULL); + return std::string(str.get()); +} +#endif +} // namespace base +} // namespace SysTuning diff --git a/trace_analyzer/src/base/common.h b/trace_analyzer/src/base/common.h index eaf056511..82ed2a7a3 100644 --- a/trace_analyzer/src/base/common.h +++ b/trace_analyzer/src/base/common.h @@ -26,32 +26,59 @@ const uint64_t INVALID_UINT64 = std::numeric_limits::max(); const uint64_t MAX_UINT32 = std::numeric_limits::max(); const uint64_t MAX_UINT64 = std::numeric_limits::max(); const uint32_t INVALID_UINT32 = std::numeric_limits::max(); +const uint32_t INVALID_INT32 = std::numeric_limits::max(); const size_t MAX_SIZE_T = std::numeric_limits::max(); +const uint32_t INVALID_ID = std::numeric_limits::max(); +const uint64_t SEC_TO_NS = 1000 * 1000 * 1000; +enum BuiltinClocks { + TS_CLOCK_UNKNOW = 0, + TS_CLOCK_BOOTTIME = 1, + TS_CLOCK_REALTIME = 2, + TS_CLOCK_REALTIME_COARSE = 3, + TS_MONOTONIC = 4, + TS_MONOTONIC_COARSE = 5, + TS_MONOTONIC_RAW = 6, +}; enum RefType { K_REF_NO_REF = 0, - K_REF_UTID = 1, + K_REF_ITID = 1, K_REF_CPUID = 2, K_REF_IRQ = 3, K_REF_SOFT_IRQ = 4, - K_REF_UPID = 5, - K_REF_UTID_LOOKUP_UPID = 6, + K_REF_IPID = 5, + K_REF_ITID_LOOKUP_IPID = 6, K_REF_MAX }; enum EndState { - TASK_RUNNABLE = 0, // R 就绪态或者运行态,进程就绪可以运行,但是不一定正在占有CPU - TASK_INTERRUPTIBLE = 1, // S 浅度睡眠,等待资源,可以响应信号,一般是进程主动sleep进入的状态 - TASK_UNINTERRUPTIBLE = 2, // D 深度睡眠,等待资源,不响应信号,典型场景是进程获取信号量阻塞 - TASK_RUNNING = 3, // Running 线程处于运行状态 - TASK_INTERRUPTED = 4, // I 线程处于中断状态 - TASK_EXIT_DEAD = 16, // X 退出状态,进程即将被销毁。 - TASK_ZOMBIE = 32, // Z 僵尸态,进程已退出或者结束,但是父进程还不知道,没有回收时的状态 - TASK_CLONE = 64, // I 多线程,克隆线程 - TASK_KILLED = 128, // K TASK DEAD 进程被杀死 - TASK_DK = 130, // DK - TASK_WAKEKILL = 256, // W TASK_WAKEKILL 深度睡眠进程,唤醒后直接杀死 - TASK_FOREGROUND = 2048, // R+ 位于后台的进程组 + // (R) ready state or running state, the process is ready to run, but not necessarily occupying the CPU + TASK_RUNNABLE = 0, + // (S) Indicates that the process is in light sleep, waiting for the resource state, and can respond to the signal. + // Generally, the process actively sleeps into 'S' state. + TASK_INTERRUPTIBLE = 1, + // (D) Indicates that the process is in deep sleep, waiting for resources, and does not respond to signals. + // Typical scenario: process acquisition semaphore blocking. + TASK_UNINTERRUPTIBLE = 2, + // (Running) Indicates that the thread is running + TASK_RUNNING = 3, + // (I) Thread in interrupt state + TASK_INTERRUPTED = 4, + // (X) Exit status, the process is about to be destroyed. + TASK_EXIT_DEAD = 16, + // (Z) Zombie state + TASK_ZOMBIE = 32, + // (I) clone thread + TASK_CLONE = 64, + // (K) Process killed + TASK_KILLED = 128, + // (DK) + TASK_DK = 130, + // (W) The process is in a deep sleep state and will be killed directly after waking up + TASK_WAKEKILL = 256, + // (R+) Process groups in the background + TASK_FOREGROUND = 2048, + TASK_MAX = 4096, TASK_INVALID = 9999 }; @@ -60,12 +87,10 @@ enum SchedWakeType { SCHED_WAKEUP = 1, // sched_wakeup }; -using DataIndex = size_t; +using DataIndex = uint64_t; using TableRowId = uint64_t; using InternalPid = uint32_t; using InternalTid = uint32_t; using InternalTime = uint64_t; -#define STACK_HASK_COUNT 2 - #endif diff --git a/trace_analyzer/src/base/double_map.h b/trace_analyzer/src/base/double_map.h index bc5f1b679..93920520d 100644 --- a/trace_analyzer/src/base/double_map.h +++ b/trace_analyzer/src/base/double_map.h @@ -31,8 +31,8 @@ public: } void Insert(T1 t1, T2 t2, T3 t3) { - auto streamIdHookidMap = internamMap_.find(t1); - if (streamIdHookidMap != internamMap_.end()) { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { auto hookId = (*streamIdHookidMap).second.find(t2); if (hookId == (*streamIdHookidMap).second.end()) { (*streamIdHookidMap).second.insert(std::make_pair(t2, t3)); @@ -43,13 +43,13 @@ public: std::map mm = { {t2, t3} }; - internamMap_.insert(std::make_pair(t1, mm)); + internalMap_.insert(std::make_pair(t1, mm)); } } T3 Find(T1 t1, T2 t2) { - auto streamIdHookidMap = internamMap_.find(t1); - if (streamIdHookidMap != internamMap_.end()) { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { auto hookId = (*streamIdHookidMap).second.find(t2); if (hookId == (*streamIdHookidMap).second.end()) { return invalidValue_; @@ -60,9 +60,26 @@ public: return invalidValue_; } } + void Erase(T1 t1) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + internalMap_.erase(streamIdHookidMap); + } + } + void Erase(T1 t1, T2 t2) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + auto hookId = (*streamIdHookidMap).second.find(t2); + if (hookId != (*streamIdHookidMap).second.end()) { + (*streamIdHookidMap).second.erase(hookId); + } + } + } private: - std::map> internamMap_; + std::map> internalMap_; T3 invalidValue_; }; diff --git a/trace_analyzer/src/base/file.cpp b/trace_analyzer/src/base/file.cpp index 058bea59d..1d8bd187e 100644 --- a/trace_analyzer/src/base/file.cpp +++ b/trace_analyzer/src/base/file.cpp @@ -29,13 +29,13 @@ namespace SysTuning { namespace base { -static ErrStatus g_status = ABNORMAL; +static TraceParserStatus g_status = TRACE_PARSER_ABNORMAL; -void SetAnalysisResult(ErrStatus stat) +void SetAnalysisResult(TraceParserStatus stat) { g_status = stat; } -ErrStatus GetAnalysisResult() +TraceParserStatus GetAnalysisResult() { return g_status; } @@ -54,7 +54,7 @@ ssize_t Read(int fd, uint8_t* dst, size_t dstSize) } int OpenFile(const std::string& path, int flags, uint32_t mode) { - TUNING_ASSERT((flags & O_CREAT) == 0 || mode != kFileModeInvalid); + TS_ASSERT((flags & O_CREAT) == 0 || mode != kFileModeInvalid); #if defined(_WIN32) int fd(_open(path.c_str(), flags | O_BINARY, mode)); #else @@ -67,7 +67,7 @@ std::string GetExecutionDirectoryPath() { char currPath[1024] = {0}; #if defined(_WIN32) - ::GetModuleFileName(NULL, currPath, MAX_PATH); + ::GetModuleFileNameA(NULL, currPath, MAX_PATH); (strrchr(currPath, '\\'))[1] = 0; #else readlink("/proc/self/exe", currPath, sizeof(currPath) - 1); diff --git a/trace_analyzer/src/base/triple_map.h b/trace_analyzer/src/base/triple_map.h new file mode 100644 index 000000000..c856d7322 --- /dev/null +++ b/trace_analyzer/src/base/triple_map.h @@ -0,0 +1,79 @@ +/* + * 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 SRC_TRACE_BASE_TRIPLEMAP_H +#define SRC_TRACE_BASE_TRIPLEMAP_H + +#include "double_map.h" + +template +class TripleMap { +public: + TripleMap(T4 invalidValue) + { + invalidValue_ = invalidValue; + } + void SetInvalidRet(T4 invalidValue) + { + invalidValue_ = invalidValue; + } + void Insert(T1 t1, T2 t2, T3 t3, T4 t4) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + (*streamIdHookidMap).second.Insert(t2, t3, t4); + } else { + DoubleMap mm(invalidValue_); + mm.Insert(t2, t3, t4); + internalMap_.insert(std::make_pair(t1, mm)); + } + } + T4 Find(T1 t1, T2 t2, T3 t3) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + return (*streamIdHookidMap).second.Find(t2, t3); + } else { + return invalidValue_; + } + } + void Erase(T1 t1) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + internalMap_.erase(streamIdHookidMap); + } + } + void Erase(T1 t1, T2 t2) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + (*streamIdHookidMap).second.Erase(t2); + } + } + void Erase(T1 t1, T2 t2, T3 t3) + { + auto streamIdHookidMap = internalMap_.find(t1); + if (streamIdHookidMap != internalMap_.end()) { + (*streamIdHookidMap).second.Erase(t2, t3); + } + } + +private: + std::map> internalMap_; + T4 invalidValue_; +}; + +#endif // SRC_TRACE_BASE_TRIPLEMAP_H diff --git a/trace_analyzer/tools/ninja b/trace_analyzer/src/cfg/cfg.pri similarity index 75% rename from trace_analyzer/tools/ninja rename to trace_analyzer/src/cfg/cfg.pri index 4b5f42629..f6cacc948 100755 --- a/trace_analyzer/tools/ninja +++ b/trace_analyzer/src/cfg/cfg.pri @@ -1,16 +1,19 @@ -#!/bin/bash -# 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. - -CMD="ninja" -source "$(dirname "${BASH_SOURCE[0]}")/run-buildtools-binary.sh" +# 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. + +INCLUDEPATH +=$$PWD +HEADERS += \ + $$PWD/trace_streamer_cfg.h + +SOURCES += \ + $$PWD/trace_streamer_cfg.cpp diff --git a/trace_analyzer/src/cfg/trace_streamer_cfg.cpp b/trace_analyzer/src/cfg/trace_streamer_cfg.cpp new file mode 100644 index 000000000..1d86535e2 --- /dev/null +++ b/trace_analyzer/src/cfg/trace_streamer_cfg.cpp @@ -0,0 +1,399 @@ +/* + * 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 "trace_streamer_cfg.h" +#include "log.h" +namespace SysTuning { +namespace TraceCfg { +TraceStreamConfig::TraceStreamConfig() +{ + eventNameMap_ = { + { TRACE_EVENT_BINDER_TRANSACTION, TRACE_ACTION_BINDER_TRANSACTION }, + { TRACE_EVENT_BINDER_TRANSACTION_RECEIVED, TRACE_ACTION_BINDER_TRANSACTION_RECEIVED }, + { TRACE_EVENT_SCHED_SWITCH, TRACE_ACTION_SCHED_SWITCH }, + { TRACE_EVENT_TASK_RENAME, TRACE_ACTION_TASK_RENAME }, + { TRACE_EVENT_TASK_NEWTASK, TRACE_ACTION_TASK_NEWTASK }, + { TRACE_EVENT_TRACING_MARK_WRITE, TRACE_ACTION_TRACING_MARK_WRITE }, + { TRACE_EVENT_SCHED_WAKEUP, TRACE_ACTION_SCHED_WAKEUP }, + { TRACE_EVENT_SCHED_WAKING, TRACE_ACTION_SCHED_WAKING }, + { TRACE_EVENT_CPU_IDLE, TRACE_ACTION_CPU_IDLE }, + { TRACE_EVENT_CPU_FREQUENCY, TRACE_ACTION_CPU_FREQUENCY }, + { TRACE_EVENT_WORKQUEUE_EXECUTE_START, TRACE_ACTION_WORKQUEUE_EXECUTE_START }, + { TRACE_EVENT_WORKQUEUE_EXECUTE_END, TRACE_ACTION_WORKQUEUE_EXECUTE_END }, + { TRACE_EVENT_CLOCK_SET_RATE, TRACE_ACTION_CLOCK_SET_RATE }, + { TRACE_EVENT_CLOCK_ENABLE, TRACE_ACTION_CLOCK_ENABLE }, + { TRACE_EVENT_CLOCK_DISABLE, TRACE_ACTION_CLOCK_DISABLE }, + { TRACE_EVENT_REGULATOR_SET_VOLTAGE, TRACE_ACTION_REGULATOR_SET_VOLTAGE }, + { TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, TRACE_ACTION_REGULATOR_SET_VOLTAGE_COMPLETE }, + { TRACE_EVENT_REGULATOR_DISABLE, TRACE_ACTION_REGULATOR_DISABLE }, + { TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, TRACE_ACTION_REGULATOR_DISABLE_COMPLETE }, + { TRACE_EVENT_IPI_ENTRY, TRACE_ACTION_IPI_ENTRY }, + { TRACE_EVENT_IPI_EXIT, TRACE_ACTION_IPI_EXIT }, + { TRACE_EVENT_IRQ_HANDLER_ENTRY, TRACE_ACTION_IRQ_HANDLER_ENTRY }, + { TRACE_EVENT_IRQ_HANDLER_EXIT, TRACE_ACTION_IRQ_HANDLER_EXIT }, + { TRACE_EVENT_SOFTIRQ_RAISE, TRACE_ACTION_SOFTIRQ_RAISE }, + { TRACE_EVENT_SOFTIRQ_ENTRY, TRACE_ACTION_SOFTIRQ_ENTRY }, + { TRACE_EVENT_SOFTIRQ_EXIT, TRACE_ACTION_SOFTIRQ_EXIT }, + { TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF, TRACE_ACTION_BINDER_TRANSACTION_ALLOC_BUF }, + { TRACE_EVENT_SCHED_WAKEUP_NEW, TRACE_ACTION_SCHED_WAKEUP_NEW }, + { TRACE_EVENT_PROCESS_EXIT, TRACE_ACTION_PROCESS_EXIT }, + { TRACE_EVENT_CLOCK_SYNC, TRACE_ACTION_CLOCK_SYNC }, + { TRACE_MEMORY, TRACE_ACTION_MEMORY }, + { TRACE_EVENT_OTHER, TRACE_ACTION_OTHER }, + }; + eventErrorDescMap_ = { + { STAT_EVENT_RECEIVED, TRACE_STAT_TYPE_RECEIVED_DESC }, + { STAT_EVENT_DATA_LOST, TRACE_STAT_TYPE_LOST_DESC }, + { STAT_EVENT_NOTMATCH, TRACE_STAT_TYPE_NOTMATCH_DESC }, + { STAT_EVENT_NOTSUPPORTED, TRACE_STAT_TYPE_NOTSUPPORTED_DESC }, + { STAT_EVENT_DATA_INVALID, TRACE_STAT_TYPE_DATA_INVALID_DESC }, + }; + serverityLevelDescMap_ = { + { STAT_SEVERITY_LEVEL_INFO, STAT_SEVERITY_LEVEL_INFO_DESC }, + { STAT_SEVERITY_LEVEL_WARN, STAT_SEVERITY_LEVEL_WARN_DESC }, + { STAT_SEVERITY_LEVEL_ERROR, STAT_SEVERITY_LEVEL_ERROR_DESC }, + { STAT_SEVERITY_LEVEL_FATAL, STAT_SEVERITY_LEVEL_FATAL_DESC }, + }; + memNameMap_ = { + { MEM_VM_SIZE, MEM_INFO_VM_SIZE_DESC }, + { MEM_VM_LOCKED, MEM_INFO_LOCKED_DESC }, + { MEM_VM_RSS, MEM_INFO_RSS_DESC }, + { MEM_VM_ANON, MEM_INFO_RSS_ANON_DESC }, + { MEM_RSS_FILE, MEM_INFO_RSS_FILE_DESC }, + { MEM_RSS_SHMEM, MEM_INFO_RSS_SCHEM_DESC }, + { MEM_VM_SWAP, MEM_INFO_SWAP_DESC }, + { MEM_VM_LOCKED, MEM_INFO_VIRT_DESC }, + { MEM_VM_HWM, MEM_INFO_HWM_DESC }, + { MEM_OOM_SCORE_ADJ, MEM_INFO_SCORE_ADJ_DESC }, + }; + InitSecurityMap(); + if (eventNameMap_.size() != TRACE_EVENT_MAX) { + TS_LOGF("eventNameMap_.size() max be %d, logic error", TRACE_EVENT_MAX); + } + if (eventErrorDescMap_.size() != STAT_EVENT_MAX) { + TS_LOGF("eventErrorDescMap_.size() max be %d, logic error", + STAT_EVENT_MAX); + } + if (serverityLevelDescMap_.size() != STAT_SEVERITY_LEVEL_MAX) { + TS_LOGF("serverityLevelDescMap_.size() max be %d, logic error", STAT_SEVERITY_LEVEL_MAX); + } + if (eventParserStatSeverityDescMap_.size() != TRACE_EVENT_MAX) { + TS_LOGF("eventParserStatSeverityDescMap_.size() max be %d, logic error", TRACE_EVENT_MAX); + } + if (memNameMap_.size() != MEM_MAX) { + TS_LOGF("memNameMap_.size() max be %d, logic error", MEM_MAX); + } + for (int i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + if (eventParserStatSeverityDescMap_.at(static_cast(i)).size() != STAT_EVENT_MAX) { + TS_LOGF("every item in eventParserStatSeverityDescMap_ max be %d, logic error", STAT_EVENT_MAX); + } + } +} + +void TraceStreamConfig::InitSecurityMap() +{ + eventParserStatSeverityDescMap_ = { + { TRACE_EVENT_BINDER_TRANSACTION, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_BINDER_TRANSACTION_RECEIVED, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SCHED_SWITCH, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_TASK_RENAME, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_TASK_NEWTASK, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_TRACING_MARK_WRITE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SCHED_WAKEUP, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SCHED_WAKING, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CPU_IDLE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CPU_FREQUENCY, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_WORKQUEUE_EXECUTE_START, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_WORKQUEUE_EXECUTE_END, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CLOCK_SET_RATE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CLOCK_ENABLE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CLOCK_DISABLE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_REGULATOR_SET_VOLTAGE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_REGULATOR_DISABLE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_IPI_ENTRY, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_IPI_EXIT, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_IRQ_HANDLER_ENTRY, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_IRQ_HANDLER_EXIT, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SOFTIRQ_RAISE, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SOFTIRQ_ENTRY, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SOFTIRQ_EXIT, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_SCHED_WAKEUP_NEW, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_PROCESS_EXIT, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_CLOCK_SYNC, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_MEMORY, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + { TRACE_EVENT_OTHER, + { + { STAT_EVENT_RECEIVED, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_DATA_LOST, STAT_SEVERITY_LEVEL_ERROR }, + { STAT_EVENT_NOTMATCH, STAT_SEVERITY_LEVEL_INFO }, + { STAT_EVENT_NOTSUPPORTED, STAT_SEVERITY_LEVEL_WARN }, + { STAT_EVENT_DATA_INVALID, STAT_SEVERITY_LEVEL_ERROR }, + }, + }, + }; +} +} // namespace TraceCfg +} // namespace SysTuning diff --git a/trace_analyzer/src/cfg/trace_streamer_cfg.h b/trace_analyzer/src/cfg/trace_streamer_cfg.h new file mode 100644 index 000000000..cc064e805 --- /dev/null +++ b/trace_analyzer/src/cfg/trace_streamer_cfg.h @@ -0,0 +1,179 @@ +/* + * 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 TRACE_STREAMER_CFG_H +#define TRACE_STREAMER_CFG_H +#include +#include +namespace SysTuning { +namespace TraceCfg { +// all supported events should be defined here +enum SupportedTraceEventType { + TRACE_EVENT_START = 0, + TRACE_EVENT_BINDER_TRANSACTION = TRACE_EVENT_START, + TRACE_EVENT_BINDER_TRANSACTION_RECEIVED, + TRACE_EVENT_SCHED_SWITCH, + TRACE_EVENT_TASK_RENAME, + TRACE_EVENT_TASK_NEWTASK, + TRACE_EVENT_TRACING_MARK_WRITE, + TRACE_EVENT_SCHED_WAKEUP, + TRACE_EVENT_SCHED_WAKING, + TRACE_EVENT_CPU_IDLE, + TRACE_EVENT_CPU_FREQUENCY, + TRACE_EVENT_WORKQUEUE_EXECUTE_START, + TRACE_EVENT_WORKQUEUE_EXECUTE_END, + TRACE_EVENT_CLOCK_SET_RATE, + TRACE_EVENT_CLOCK_ENABLE, + TRACE_EVENT_CLOCK_DISABLE, + TRACE_EVENT_REGULATOR_SET_VOLTAGE, + TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, + TRACE_EVENT_REGULATOR_DISABLE, + TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, + TRACE_EVENT_IPI_ENTRY, + TRACE_EVENT_IPI_EXIT, + TRACE_EVENT_IRQ_HANDLER_ENTRY, + TRACE_EVENT_IRQ_HANDLER_EXIT, + TRACE_EVENT_SOFTIRQ_RAISE, + TRACE_EVENT_SOFTIRQ_ENTRY, + TRACE_EVENT_SOFTIRQ_EXIT, + TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF, + TRACE_EVENT_SCHED_WAKEUP_NEW, + TRACE_EVENT_PROCESS_EXIT, + TRACE_EVENT_CLOCK_SYNC, + TRACE_MEMORY, + TRACE_EVENT_OTHER, + TRACE_EVENT_MAX +}; +enum MemInfoType { + MEM_VM_SIZE, + MEM_VM_RSS, + MEM_VM_ANON, + MEM_RSS_FILE, + MEM_RSS_SHMEM, + MEM_VM_SWAP, + MEM_VM_LOCKED, + MEM_VM_HWM, + MEM_OOM_SCORE_ADJ, + MEM_MAX +}; +enum StatType { + STAT_EVENT_START = 0, + STAT_EVENT_RECEIVED = STAT_EVENT_START, + STAT_EVENT_DATA_LOST, + STAT_EVENT_NOTMATCH, + STAT_EVENT_NOTSUPPORTED, + STAT_EVENT_DATA_INVALID, + STAT_EVENT_MAX +}; + +// there maybe some error while parser trace msgs, here defined the error levels +enum StatSeverityLevel { + STAT_SEVERITY_LEVEL_START = 0, + STAT_SEVERITY_LEVEL_INFO = STAT_SEVERITY_LEVEL_START, + STAT_SEVERITY_LEVEL_WARN, + STAT_SEVERITY_LEVEL_ERROR, + STAT_SEVERITY_LEVEL_FATAL, + STAT_SEVERITY_LEVEL_MAX +}; + + +// the supported metadata +enum MetaDataItem { + METADATA_ITEM_START = 0, + METADATA_ITEM_DATASIZE = METADATA_ITEM_START, + METADATA_ITEM_PARSETOOL_NAME, + METADATA_ITEM_PARSERTOOL_VERSION, + METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME, + METADATA_ITEM_SOURCE_FILENAME, + METADATA_ITEM_OUTPUT_FILENAME, + METADATA_ITEM_PARSERTIME, // the data time while the data parsed + METADATA_ITEM_SOURCE_DATETYPE, // proto-based-trace or txt-based-trace + METADATA_ITEM_MAX +}; + +class TraceStreamConfig { +public: + TraceStreamConfig(); + ~TraceStreamConfig() = default; +public: + std::map eventNameMap_{}; + std::map eventErrorDescMap_{}; + std::map serverityLevelDescMap_{}; + // different msg may have STAT_EVENT_MAX types of exception when parse, and they have different error level + // if you think some error level should be improve or depress, you can edit this map + std::map> eventParserStatSeverityDescMap_{}; + std::map memNameMap_{}; +private: + void InitSecurityMap(); + // all supported events should be defined here, these str can be find in text-based trace + const std::string TRACE_ACTION_BINDER_TRANSACTION = "binder_transaction"; + const std::string TRACE_ACTION_BINDER_TRANSACTION_RECEIVED = "binder_transaction_received"; + const std::string TRACE_ACTION_SCHED_SWITCH = "sched_switch"; + const std::string TRACE_ACTION_TASK_RENAME = "task_rename"; + const std::string TRACE_ACTION_TASK_NEWTASK = "task_newtask"; + const std::string TRACE_ACTION_TRACING_MARK_WRITE = "tracing_mark_write"; + const std::string TRACE_ACTION_SCHED_WAKEUP = "sched_wakeup"; + const std::string TRACE_ACTION_SCHED_WAKING = "sched_waking"; + const std::string TRACE_ACTION_CPU_IDLE = "cpu_idle"; + const std::string TRACE_ACTION_CPU_FREQUENCY = "cpu_frequency"; + const std::string TRACE_ACTION_WORKQUEUE_EXECUTE_START = "workqueue_execute_start"; + const std::string TRACE_ACTION_WORKQUEUE_EXECUTE_END = "workqueue_execute_end"; + + const std::string TRACE_ACTION_CLOCK_SET_RATE = "clock_set_rate"; + const std::string TRACE_ACTION_CLOCK_ENABLE = "clock_enable"; + const std::string TRACE_ACTION_CLOCK_DISABLE = "clock_disable"; + const std::string TRACE_ACTION_REGULATOR_SET_VOLTAGE = "regulator_set_voltage"; + const std::string TRACE_ACTION_REGULATOR_SET_VOLTAGE_COMPLETE = "regulator_set_voltage_complete"; + const std::string TRACE_ACTION_REGULATOR_DISABLE = "regulator_disable"; + const std::string TRACE_ACTION_REGULATOR_DISABLE_COMPLETE = "regulator_disable_complete"; + const std::string TRACE_ACTION_IPI_ENTRY = "ipi_entry"; + const std::string TRACE_ACTION_IPI_EXIT = "ipi_exit"; + const std::string TRACE_ACTION_IRQ_HANDLER_ENTRY = "irq_handler_entry"; + const std::string TRACE_ACTION_IRQ_HANDLER_EXIT = "irq_handler_exit"; + const std::string TRACE_ACTION_SOFTIRQ_RAISE = "softirq_raise"; + const std::string TRACE_ACTION_SOFTIRQ_ENTRY = "softirq_entry"; + const std::string TRACE_ACTION_SOFTIRQ_EXIT = "softirq_exit"; + const std::string TRACE_ACTION_BINDER_TRANSACTION_ALLOC_BUF = "binder_transaction_alloc_buf"; + const std::string TRACE_ACTION_SCHED_WAKEUP_NEW = "sched_wakeup_new"; + const std::string TRACE_ACTION_PROCESS_EXIT = "sched_process_exit"; + const std::string TRACE_ACTION_CLOCK_SYNC = "trace_event_clock_sync"; + const std::string TRACE_ACTION_MEMORY = "memory"; + const std::string TRACE_ACTION_OTHER = "other"; + + const std::string MEM_INFO_VM_SIZE_DESC = "mem.vm.size"; + const std::string MEM_INFO_LOCKED_DESC = "mem.locked"; + const std::string MEM_INFO_RSS_DESC = "mem.rss"; + const std::string MEM_INFO_RSS_ANON_DESC = "mem.rss.anon"; + const std::string MEM_INFO_RSS_FILE_DESC = "mem.rss.file"; + const std::string MEM_INFO_RSS_SCHEM_DESC = "mem.rss.schem"; + const std::string MEM_INFO_SWAP_DESC = "mem.swap"; + const std::string MEM_INFO_VIRT_DESC = "mem.virt"; + const std::string MEM_INFO_HWM_DESC = "mem.hwm"; + const std::string MEM_INFO_SCORE_ADJ_DESC = "oom_score_adj"; + + const std::string TRACE_STAT_TYPE_RECEIVED_DESC = "received"; + const std::string TRACE_STAT_TYPE_LOST_DESC = "data_lost"; + const std::string TRACE_STAT_TYPE_NOTMATCH_DESC = "not_match"; + const std::string TRACE_STAT_TYPE_NOTSUPPORTED_DESC = "not_supported"; + const std::string TRACE_STAT_TYPE_DATA_INVALID_DESC = "invalid_data"; + + const std::string STAT_SEVERITY_LEVEL_INFO_DESC = "info"; + const std::string STAT_SEVERITY_LEVEL_WARN_DESC = "warn"; + const std::string STAT_SEVERITY_LEVEL_ERROR_DESC = "error"; + const std::string STAT_SEVERITY_LEVEL_FATAL_DESC = "fatal"; +}; +} // namespace TraceCfg +} // namespace SysTuning +#endif diff --git a/trace_analyzer/src/filter/clock_filter.cpp b/trace_analyzer/src/filter/clock_filter.cpp index 456e22719..4e1af702a 100644 --- a/trace_analyzer/src/filter/clock_filter.cpp +++ b/trace_analyzer/src/filter/clock_filter.cpp @@ -20,7 +20,7 @@ namespace SysTuning { namespace TraceStreamer { ClockFilter::ClockFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter), primaryClock_(BuiltinClocks::BOOTTIME) + : FilterBase(dataCache, filter), primaryClock_(BuiltinClocks::TS_CLOCK_BOOTTIME) { } @@ -37,6 +37,9 @@ std::string ClockFilter::GenClockKey(ClockId srcClockId, ClockId desClockId) con uint64_t ClockFilter::ToPrimaryTraceTime(ClockId srcClockId, uint64_t srcTs) const { + if (srcClockId == primaryClock_) { + return srcTs; + } return Convert(srcClockId, srcTs, primaryClock_); } diff --git a/trace_analyzer/src/filter/clock_filter.h b/trace_analyzer/src/filter/clock_filter.h index 3cefeccda..9fd5ffb21 100644 --- a/trace_analyzer/src/filter/clock_filter.h +++ b/trace_analyzer/src/filter/clock_filter.h @@ -20,43 +20,46 @@ #include #include #include +#include "common.h" #include "filter_base.h" #include "trace_data_cache.h" #include "trace_streamer_filters.h" namespace SysTuning { namespace TraceStreamer { -enum BuiltinClocks { - REALTIME = 1, - REALTIME_COARSE = 2, - MONOTONIC = 3, - MONOTONIC_COARSE = 4, - MONOTONIC_RAW = 5, - BOOTTIME = 6, -}; +/* + * TS_REALTIME: A settable system-wide clock that measures real time. Its time represents seconds and nanoseconds + * since the Epoch. + * TS_REALTIME_COARSE: A faster but less precise version of TS_REALTIME. This clock is not settable. + * TS_MONOTONIC: The number of seconds that the system has been running since it was booted.The CLOCK_MONOTONIC + * clock is not affected by discontinuous jumps in the system time ,but is affected by the incremental adjustments + * performed by adjtime(3) and NTP. This clock does not count time that the system is suspended. + * TS_MONOTONIC_COARSE: A faster but less precise version of TS_MONOTONIC. + * TS_MONOTONIC_RAW: Similar to TS_MONOTONIC, but provides access to a raw hardware-based time that is not subject + * to NTP adjustments or the incremental adjustments performed by adjtime(3). This clock does not count time that the + * system is suspended. + * TS_BOOTTIME: A nonsettable system-wide clock that is identical to TS_MONOTONIC, except that it also includes + * any time that the system is suspended. + */ +using ClockId = uint32_t; +struct SnapShot { + ClockId clockId; + uint64_t ts; +}; class ClockFilter : private FilterBase { public: - using ClockId = uint32_t; using ConvertClockMap = std::map; - class SnapShot { - public: - ClockId clockId; - uint64_t ts; - }; - - explicit ClockFilter(TraceDataCache*, const TraceStreamerFilters*); + ClockFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); ~ClockFilter() override; - uint64_t ToPrimaryTraceTime(ClockId srcClockId, uint64_t srcTs) const; - uint64_t Convert(ClockId srcClockId, uint64_t srcTs, ClockId desClockId) const; - void SetPrimaryClock(ClockId primary) { primaryClock_ = primary; } - + uint64_t ToPrimaryTraceTime(ClockId srcClockId, uint64_t srcTs) const; + uint64_t Convert(ClockId srcClockId, uint64_t srcTs, ClockId desClockId) const; void AddClockSnapshot(const std::vector& snapShot); private: diff --git a/trace_analyzer/src/filter/cpu_filter.cpp b/trace_analyzer/src/filter/cpu_filter.cpp index ef784f4ef..0f6f6dc8c 100644 --- a/trace_analyzer/src/filter/cpu_filter.cpp +++ b/trace_analyzer/src/filter/cpu_filter.cpp @@ -19,8 +19,13 @@ namespace SysTuning { namespace TraceStreamer { CpuFilter::CpuFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) : FilterBase(dataCache, filter) {} CpuFilter::~CpuFilter() = default; -uint64_t CpuFilter::InsertSwitchEvent(uint64_t ts, uint64_t cpu, uint64_t prevPid, uint64_t prevPior, - uint64_t prevState, uint64_t nextPid, uint64_t nextPior) +void CpuFilter::InsertSwitchEvent(uint64_t ts, + uint64_t cpu, + uint64_t prevPid, + uint64_t prevPior, + uint64_t prevState, + uint64_t nextPid, + uint64_t nextPior) { auto index = traceDataCache_->GetSchedSliceData()->AppendSchedSlice(ts, 0, cpu, nextPid, 0, nextPior); @@ -33,86 +38,100 @@ uint64_t CpuFilter::InsertSwitchEvent(uint64_t ts, uint64_t cpu, uint64_t prevPi } if (nextPid) { - auto lastRow = RowOfUidUThreadState(nextPid); + CheckWakeingEvent(nextPid); + auto lastRow = RowOfInternalTidThreadState(nextPid); if (lastRow != INVALID_UINT64) { traceDataCache_->GetThreadStateData()->UpdateDuration(lastRow, ts); } - index = traceDataCache_->GetThreadStateData()->AppendThreadState(ts, 0, cpu, nextPid, TASK_RUNNING); - FilterUidRow(nextPid, index, TASK_RUNNING); + index = + traceDataCache_->GetThreadStateData()->AppendThreadState(ts, INVALID_UINT64, cpu, nextPid, TASK_RUNNING); + FilterInternalTidRow(nextPid, index, TASK_RUNNING); if (cpuToRowThreadState_.find(cpu) == cpuToRowThreadState_.end()) { cpuToRowThreadState_.insert(std::make_pair(cpu, index)); - cpuToUtidThreadState_.insert(std::make_pair(cpu, nextPid)); } else { cpuToRowThreadState_.at(cpu) = index; - cpuToUtidThreadState_.at(cpu) = nextPid; } } if (prevPid) { - auto lastRow = RowOfUidUThreadState(prevPid); - auto lastState = StateOfUidThreadState(prevPid); + CheckWakeingEvent(nextPid); + auto lastRow = RowOfInternalTidThreadState(prevPid); if (lastRow != INVALID_UINT64) { traceDataCache_->GetThreadStateData()->UpdateDuration(lastRow, ts); - auto temp = traceDataCache_->GetThreadStateData()->AppendThreadState( - ts, static_cast(-1), static_cast(-1), prevPid, prevState); - FilterUidRow(prevPid, temp, prevState); + auto temp = traceDataCache_->GetThreadStateData()->AppendThreadState(ts, INVALID_UINT64, INVALID_UINT64, + prevPid, prevState); + FilterInternalTidRow(prevPid, temp, prevState); } - UNUSED(lastState); } - return 0; } -uint64_t CpuFilter::FilterUidRow(uint64_t uid, uint64_t row, uint64_t state) +bool CpuFilter::InsertProcessExitEvent(uint64_t ts, uint64_t cpu, uint64_t pid) { - if (uidToRowThreadState_.find(uid) != uidToRowThreadState_.end()) { - uidToRowThreadState_.at(uid) = TPthread {row, state}; + UNUSED(cpu); + auto lastRow = RowOfInternalTidThreadState(pid); + if (lastRow != INVALID_UINT64) { + traceDataCache_->GetThreadStateData()->UpdateDuration(lastRow, ts); + return true; + } + return false; +} +uint64_t CpuFilter::FilterInternalTidRow(uint64_t uid, uint64_t row, uint64_t state) +{ + if (internalTidToRowThreadState_.find(uid) != internalTidToRowThreadState_.end()) { + internalTidToRowThreadState_.at(uid) = TPthread{row, state}; } else { - uidToRowThreadState_.insert(std::make_pair(uid, TPthread {row, state})); + internalTidToRowThreadState_.insert(std::make_pair(uid, TPthread{row, state})); } return 0; } -uint64_t CpuFilter::RowOfUidUThreadState(uint64_t uid) const +uint64_t CpuFilter::RowOfInternalTidThreadState(uint64_t uid) const { - auto row = uidToRowThreadState_.find(uid); - if (row != uidToRowThreadState_.end()) { + auto row = internalTidToRowThreadState_.find(uid); + if (row != internalTidToRowThreadState_.end()) { return (*row).second.row_; } return INVALID_UINT64; } -uint64_t CpuFilter::StateOfUidThreadState(uint64_t uid) const +uint64_t CpuFilter::StateOfInternalTidThreadState(uint64_t uid) const { - auto row = uidToRowThreadState_.find(uid); - if (row != uidToRowThreadState_.end()) { + auto row = internalTidToRowThreadState_.find(uid); + if (row != internalTidToRowThreadState_.end()) { return (*row).second.state_; } return TASK_INVALID; } -uint64_t CpuFilter::InsertWakeingEvent(uint64_t ts, uint64_t internalTid) +void CpuFilter::InsertWakeingEvent(uint64_t ts, uint64_t internalTid) { - uint64_t lastrow = RowOfUidUThreadState(internalTid); - auto lastState = StateOfUidThreadState(internalTid); - if (lastrow != INVALID_UINT64) { - if (lastState != TASK_RUNNING) { - traceDataCache_->GetThreadStateData()->UpdateDuration(lastrow, ts); - } + /* repeated wakeup msg may come, we only record last wakeupmsg, and +the wakeup will only insert to DataCache when a sched_switch comes +*/ + if (lastWakeUpMsg.find(internalTid) != lastWakeUpMsg.end()) { + lastWakeUpMsg.at(internalTid) = ts; + } else { + lastWakeUpMsg.insert(std::make_pair(internalTid, ts)); } - if (lastState != TASK_RUNNING) { - auto index = traceDataCache_->GetThreadStateData()->AppendThreadState( - ts, static_cast(-1), static_cast(-1), internalTid, TASK_RUNNABLE); - FilterUidRow(internalTid, index, TASK_RUNNABLE); - } - return 0; } -uint64_t CpuFilter::FindUtidInThreadStateTableByCpu(uint64_t cpu) const +void CpuFilter::CheckWakeingEvent(uint64_t internalTid) { - auto row = cpuToUtidThreadState_.find(cpu); - if (row != cpuToUtidThreadState_.end()) { - return (*row).second; + if (lastWakeUpMsg.find(internalTid) == lastWakeUpMsg.end()) { + return; } - return INVALID_UINT64; + auto ts = lastWakeUpMsg.at(internalTid); + lastWakeUpMsg.erase(internalTid); + uint64_t lastrow = RowOfInternalTidThreadState(internalTid); + auto lastState = StateOfInternalTidThreadState(internalTid); + if (lastState == TASK_RUNNING) { + return; + } + if (lastrow != INVALID_UINT64) { + traceDataCache_->GetThreadStateData()->UpdateDuration(lastrow, ts); + } + auto index = traceDataCache_->GetThreadStateData()->AppendThreadState(ts, INVALID_UINT64, INVALID_UINT64, + internalTid, TASK_RUNNABLE); + FilterInternalTidRow(internalTid, index, TASK_RUNNABLE); } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/cpu_filter.h b/trace_analyzer/src/filter/cpu_filter.h index 6ca7aca9a..2ac5d626d 100644 --- a/trace_analyzer/src/filter/cpu_filter.h +++ b/trace_analyzer/src/filter/cpu_filter.h @@ -32,36 +32,36 @@ namespace TraceStreamer { class TraceStreamerFilters; class CpuFilter : private FilterBase { public: - explicit CpuFilter(TraceDataCache*, const TraceStreamerFilters*); + CpuFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); CpuFilter(const CpuFilter&) = delete; CpuFilter& operator=(const CpuFilter&) = delete; ~CpuFilter() override; public: - uint64_t FindUtidInThreadStateTableByCpu(uint64_t cpu) const; - uint64_t InsertSwitchEvent(uint64_t ts, - uint64_t cpu, - uint64_t prevPid, - uint64_t prevPior, - uint64_t prevState, - uint64_t nextPid, - uint64_t nextPior); - uint64_t InsertWakeingEvent(uint64_t ts, uint64_t internalTid); - + void InsertSwitchEvent(uint64_t ts, + uint64_t cpu, + uint64_t prevPid, + uint64_t prevPior, + uint64_t prevState, + uint64_t nextPid, + uint64_t nextPior); + void InsertWakeingEvent(uint64_t ts, uint64_t internalTid); + bool InsertProcessExitEvent(uint64_t ts, uint64_t cpu, uint64_t pid); private: - uint64_t FilterUidRow(uint64_t uid, uint64_t row, uint64_t state = TASK_INVALID); - uint64_t RowOfUidUThreadState(uint64_t uid) const; - uint64_t StateOfUidThreadState(uint64_t uid) const; + void CheckWakeingEvent(uint64_t internalTid); + uint64_t FilterInternalTidRow(uint64_t uid, uint64_t row, uint64_t state = TASK_INVALID); + uint64_t RowOfInternalTidThreadState(uint64_t uid) const; + uint64_t StateOfInternalTidThreadState(uint64_t uid) const; std::map cpuToRowThreadState_ = {}; - std::map cpuToUtidThreadState_ = {}; std::map cpuToRowSched_ = {}; + std::map lastWakeUpMsg = {}; struct TPthread { uint64_t row_; uint64_t state_; }; - std::map uidToRowThreadState_ = {}; + std::map internalTidToRowThreadState_ = {}; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/event_filter.cpp b/trace_analyzer/src/filter/event_filter.cpp deleted file mode 100755 index eafec5a01..000000000 --- a/trace_analyzer/src/filter/event_filter.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "event_filter.h" - -#include "filter_filter.h" -#include "process_filter.h" -#include "trace_data_cache.h" -#include "trace_streamer_filters.h" - -namespace SysTuning { -namespace TraceStreamer { -EventFilter::EventFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter), - prevTimestamp_(0), - idleStringId_(traceDataCache_->GetDataIndex("idle")), - filterTypeStringId_(traceDataCache_->GetDataIndex("cpu_measure_filter")) -{ -} - -EventFilter::~EventFilter() = default; - -void EventFilter::UpdateSchedSwitch(uint32_t cpu, - uint64_t timestamp, - uint32_t prevPid, - uint32_t nextPid, - std::string_view nextComm) -{ - UNUSED(prevPid); - if (!UpdateTimestamp(timestamp)) { - TUNING_LOGD("sched_switch event out of order by %.4f ms, skipping", (prevTimestamp_ - timestamp) / 1e6); - return; - } - - TUNING_ASSERT(cpu < MAX_CPUS); - - UpdateDuration(cpu, timestamp); - - DataIndex nameIndex; - if (nextPid == 0) { - nameIndex = idleStringId_; - } else { - nameIndex = traceDataCache_->GetDataIndex(nextComm); - } - - auto internaltid = streamFilters_->processFilter_->SetThreadPid(timestamp, nextPid, nameIndex); - - auto* slices = traceDataCache_->GetSlicesData(); - auto* pendingSlice = &pendingSchedPerCpu_[cpu]; - pendingSlice->storageIndex = slices->AppendSliceData(cpu, timestamp, 0, internaltid); - pendingSlice->pid = nextPid; -} - -uint32_t EventFilter::GetOrCreatCpuCounterFilter(DataIndex name, uint32_t cpu) -{ - auto cpuCounter = traceDataCache_->GetCpuCountersData(); - auto filterId = FindFilterId(name, cpu); - if (filterId == INVALID_UINT32) { - std::string nameStr = traceDataCache_->GetDataFromDict(name); - filterId = streamFilters_->filterFilter_->AddFilter("cpu_counter_track", nameStr); - cpuCounter->AppendCpuCounter(filterId, filterTypeStringId_, name, cpu); - AddFilterId(name, cpu, filterId); - } - - return filterId; -} - -void EventFilter::AddFilterId(DataIndex name, uint32_t cpu, uint32_t filterId) -{ - cpuNameFilters_[std::make_pair(cpu, name)] = filterId; -} - -uint32_t EventFilter::FindFilterId(DataIndex name, uint32_t cpu) const -{ - auto it = cpuNameFilters_.find(std::make_pair(cpu, name)); - if (it != cpuNameFilters_.end()) { - return it->second; - } - - return INVALID_UINT32; -} - -void EventFilter::BinderTransaction(const BinderParamter& binderParamter) const -{ - UNUSED(binderParamter); -} - -void EventFilter::BinderTransactionReceived(uint64_t ts, uint32_t tid, int32_t transactionId) const -{ - UNUSED(ts); - UNUSED(tid); - UNUSED(transactionId); -} - -void EventFilter::UpdateDuration(uint32_t cpu, uint64_t timestamp) -{ - auto* pendingSlice = &pendingSchedPerCpu_[cpu]; - if (pendingSlice->storageIndex >= std::numeric_limits::max()) { - return; - } - - auto* slices = traceDataCache_->GetSchedSliceData(); - size_t idx = pendingSlice->storageIndex; - uint64_t duration = timestamp - slices->TimeStamData()[idx]; - slices->SetDuration(idx, duration); -} - -bool EventFilter::UpdateTimestamp(uint64_t timestamp) -{ - if (timestamp < prevTimestamp_) { - return false; - } - - prevTimestamp_ = timestamp; - return true; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/filter/event_filter.h b/trace_analyzer/src/filter/event_filter.h deleted file mode 100755 index 005b02c9b..000000000 --- a/trace_analyzer/src/filter/event_filter.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef EVENT_FILTER_H -#define EVENT_FILTER_H - -#include -#include -#include -#include "filter_base.h" -#include "trace_data_cache.h" - -namespace SysTuning { -namespace TraceStreamer { -class TraceStreamerFilters; -constexpr size_t MAX_CPUS = 64; -constexpr uint32_t INVALID_UINT32 = std::numeric_limits::max(); - -struct BinderParamter { - uint64_t ts; - uint32_t tid; - int32_t transactionId; - int32_t destNode; - int32_t destTgid; - int32_t destTid; - bool isReply; - uint32_t flags; - DataIndex code; - DataIndex nameIndex; -}; - -class EventFilter : private FilterBase { -public: - explicit EventFilter(TraceDataCache*, const TraceStreamerFilters*); - ~EventFilter() override; - - virtual void UpdateSchedSwitch(uint32_t cpu, - uint64_t timestamp, - uint32_t prevPid, - uint32_t nextPid, - std::string_view nextComm); - - uint32_t GetOrCreatCpuCounterFilter(DataIndex name, uint32_t cpu); - void BinderTransaction(const BinderParamter& binderParamter) const; - void BinderTransactionReceived(uint64_t ts, uint32_t tid, int32_t transactionId) const; - -private: - void AddFilterId(DataIndex name, uint32_t cpu, uint32_t filterId); - uint32_t FindFilterId(DataIndex name, uint32_t cpu) const; - void UpdateDuration(uint32_t cpu, uint64_t timeStamp); - bool UpdateTimestamp(uint64_t timeStamp); - - struct PendingSchedSlice { - size_t storageIndex = std::numeric_limits::max(); - uint32_t pid = 0; - }; - - uint64_t prevTimestamp_; - DataIndex const idleStringId_; - DataIndex const filterTypeStringId_; - std::array pendingSchedPerCpu_ {}; - std::map, uint32_t> cpuNameFilters_ {}; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // EVENT_FILTER_H diff --git a/trace_analyzer/src/filter/filter.pri b/trace_analyzer/src/filter/filter.pri new file mode 100755 index 000000000..9a79dfd28 --- /dev/null +++ b/trace_analyzer/src/filter/filter.pri @@ -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. + +INCLUDEPATH +=$$PWD \ + $$PWD/../cfg +HEADERS += \ + $$PWD/clock_filter.h \ + $$PWD/cpu_filter.h \ + $$PWD/filter_base.h \ + $$PWD/filter_filter.h \ + $$PWD/measure_filter.h \ + $$PWD/process_filter.h \ + $$PWD/slice_filter.h \ + $$PWD/symbols_filter.h \ + $$PWD/stat_filter.h + +SOURCES += \ + $$PWD/clock_filter.cpp \ + $$PWD/cpu_filter.cpp \ + $$PWD/filter_base.cpp \ + $$PWD/filter_filter.cpp \ + $$PWD/measure_filter.cpp \ + $$PWD/process_filter.cpp \ + $$PWD/slice_filter.cpp \ + $$PWD/symbols_filter.cpp \ + $$PWD/stat_filter.cpp diff --git a/trace_analyzer/src/filter/filter_base.h b/trace_analyzer/src/filter/filter_base.h index 06c6d607e..fac893445 100644 --- a/trace_analyzer/src/filter/filter_base.h +++ b/trace_analyzer/src/filter/filter_base.h @@ -28,14 +28,14 @@ namespace SysTuning { namespace TraceStreamer { class FilterBase { public: - explicit FilterBase(TraceDataCache*, const TraceStreamerFilters*); + FilterBase(TraceDataCache* dataCache, const TraceStreamerFilters* filter); FilterBase(const FilterBase&) = delete; FilterBase& operator=(const FilterBase&) = delete; virtual ~FilterBase(); public: - const TraceStreamerFilters *streamFilters_; - TraceDataCache *traceDataCache_; + const TraceStreamerFilters* streamFilters_ {}; + TraceDataCache* traceDataCache_ {}; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/filter_filter.cpp b/trace_analyzer/src/filter/filter_filter.cpp index 400ab9a23..9ed67817f 100644 --- a/trace_analyzer/src/filter/filter_filter.cpp +++ b/trace_analyzer/src/filter/filter_filter.cpp @@ -22,15 +22,16 @@ namespace SysTuning { namespace TraceStreamer { FilterFilter::FilterFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter) {} + : FilterBase(dataCache, filter) +{ +} FilterFilter::~FilterFilter() = default; -uint32_t FilterFilter::AddFilter(std::string type, std::string name) +uint32_t FilterFilter::AddFilter(std::string type, std::string name, uint64_t arg) { - uint32_t sourceArgSetId = 0; - auto* hook = traceDataCache_->GetFilterData(); - size_t id = hook->AppendNewFilterData(type, name, sourceArgSetId); + auto filter = traceDataCache_->GetFilterData(); + size_t id = filter->AppendNewFilterData(type, name, arg); return static_cast(id); } } // namespace TraceStreamer diff --git a/trace_analyzer/src/filter/filter_filter.h b/trace_analyzer/src/filter/filter_filter.h index f7abf62ec..cef929bb0 100644 --- a/trace_analyzer/src/filter/filter_filter.h +++ b/trace_analyzer/src/filter/filter_filter.h @@ -24,12 +24,12 @@ namespace TraceStreamer { class TraceStreamerFilters; class FilterFilter : private FilterBase { public: - explicit FilterFilter(TraceDataCache*, const TraceStreamerFilters*); + FilterFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); FilterFilter(const FilterFilter&) = delete; FilterFilter& operator=(const FilterFilter&) = delete; ~FilterFilter() override; - uint32_t AddFilter(std::string type, std::string name); + uint32_t AddFilter(std::string type, std::string name, uint64_t arg); }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/measure_filter.cpp b/trace_analyzer/src/filter/measure_filter.cpp index 6d0846f5a..4ef2dc929 100644 --- a/trace_analyzer/src/filter/measure_filter.cpp +++ b/trace_analyzer/src/filter/measure_filter.cpp @@ -28,63 +28,53 @@ MeasureFilter::MeasureFilter(TraceDataCache* dataCache, const TraceStreamerFilte { } -MeasureFilter::~MeasureFilter() -{ -} +MeasureFilter::~MeasureFilter() {} -void MeasureFilter::Init(FilterType e) +void MeasureFilter::AppendNewMeasureData(uint64_t internalTid, DataIndex nameIndex, uint64_t timestamp, int64_t value) { - filterType_ = e; + auto filterId = GetOrCreateFilterId(internalTid, nameIndex); + traceDataCache_->GetMeasureData()->AppendMeasureData(0, timestamp, value, filterId); } - -uint32_t MeasureFilter::GetOrCreateCertainFilterId(uint64_t internalTid, DataIndex nameIndex) +uint32_t MeasureFilter::GetOrCreateFilterId(uint64_t internalTid, DataIndex nameIndex) { auto filterId = tidStreamIdFilterIdMap_.Find(internalTid, nameIndex); if (filterId != INVALID_UINT64) { return static_cast(filterId); } - uint32_t newFilterId = - streamFilters_->filterFilter_->AddFilter(filterTypeValue.at(filterType_), - traceDataCache_->GetDataFromDict(nameIndex)); + uint32_t newFilterId = streamFilters_->filterFilter_->AddFilter( + filterTypeValue.at(filterType_), traceDataCache_->GetDataFromDict(nameIndex), internalTid); AddCertainFilterId(internalTid, nameIndex, newFilterId); return newFilterId; } -uint32_t MeasureFilter::GetOrCreateCertainFilterIdByCookie(uint64_t internalTid, DataIndex nameIndex, int64_t cookie) -{ - auto filterId = cookieFilterIdMap_.Find(static_cast(cookie), nameIndex); - if (filterId != INVALID_UINT64) { - return static_cast(filterId); - } - - uint32_t newFilterId = - streamFilters_->filterFilter_->AddFilter(filterTypeValue.at(filterType_), - traceDataCache_->GetDataFromDict(nameIndex)); - cookieFilterIdMap_.Insert(static_cast(cookie), nameIndex, newFilterId); - traceDataCache_->GetProcessFilterData()->AppendProcessFilterData(static_cast(newFilterId), - nameIndex, static_cast(internalTid)); - return newFilterId; -} - void MeasureFilter::AddCertainFilterId(uint64_t internalTid, DataIndex nameIndex, uint64_t filterId) { tidStreamIdFilterIdMap_.Insert(internalTid, nameIndex, filterId); if (filterType_ == E_THREADMEASURE_FILTER) { - traceDataCache_->GetThreadCounterFilterData()->AppendNewData(filterId, - static_cast(nameIndex), internalTid); + traceDataCache_->GetThreadMeasureFilterData()->AppendNewFilter(filterId, static_cast(nameIndex), + internalTid); } else if (filterType_ == E_THREAD_FILTER) { - traceDataCache_->GetThreadFilterData()->AppendNewData(filterId, static_cast(nameIndex), internalTid); + traceDataCache_->GetThreadFilterData()->AppendNewFilter(filterId, static_cast(nameIndex), + internalTid); } else if (filterType_ == E_PROCESS_MEASURE_FILTER) { - traceDataCache_->GetProcessCounterFilterData()->AppendProcessCounterFilterData(static_cast(filterId), - static_cast(nameIndex), static_cast(internalTid)); + traceDataCache_->GetProcessMeasureFilterData()->AppendNewFilter( + static_cast(filterId), static_cast(nameIndex), static_cast(internalTid)); } else if (filterType_ == E_PROCESS_FILTER_FILTER) { - traceDataCache_->GetProcessFilterData()->AppendProcessFilterData(static_cast(filterId), - static_cast(nameIndex), static_cast(internalTid)); + traceDataCache_->GetProcessFilterData()->AppendNewFilter( + static_cast(filterId), static_cast(nameIndex), static_cast(internalTid)); } else if (filterType_ == E_CPU_MEASURE_FILTER) { - traceDataCache_->GetCpuCountersData()->AppendCpuCounter(filterId, - static_cast(nameIndex), internalTid); + traceDataCache_->GetCpuMeasuresData()->AppendNewFilter(filterId, static_cast(nameIndex), internalTid); + } else if (filterType_ == E_CLOCK_RATE_FILTER) { + traceDataCache_->GetClockEventFilterData()->AppendNewFilter(filterId, clockSetRateDataIndex_, + static_cast(nameIndex), internalTid); + } else if (filterType_ == E_CLOCK_ENABLE_FILTER) { + traceDataCache_->GetClockEventFilterData()->AppendNewFilter(filterId, clockEnableDataIndex_, + static_cast(nameIndex), internalTid); + } else if (filterType_ == E_CLOCK_DISABLE_FILTER) { + traceDataCache_->GetClockEventFilterData()->AppendNewFilter(filterId, clockDisableDataIndex_, + static_cast(nameIndex), internalTid); } } } // namespace TraceStreamer diff --git a/trace_analyzer/src/filter/measure_filter.h b/trace_analyzer/src/filter/measure_filter.h index 1e3613959..460a91788 100644 --- a/trace_analyzer/src/filter/measure_filter.h +++ b/trace_analyzer/src/filter/measure_filter.h @@ -32,32 +32,39 @@ enum FilterType { E_THREAD_FILTER, E_PROCESS_MEASURE_FILTER, E_PROCESS_FILTER_FILTER, - E_CPU_MEASURE_FILTER + E_CPU_MEASURE_FILTER, + E_CLOCK_RATE_FILTER, + E_CLOCK_ENABLE_FILTER, + E_CLOCK_DISABLE_FILTER }; class MeasureFilter : private FilterBase { public: - explicit MeasureFilter(TraceDataCache*, const TraceStreamerFilters*, FilterType); - void Init(FilterType); + MeasureFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter, FilterType); MeasureFilter(const MeasureFilter&) = delete; MeasureFilter& operator=(const MeasureFilter&) = delete; ~MeasureFilter() override; - uint32_t GetOrCreateCertainFilterId(uint64_t internalTid, DataIndex nameIndex); - uint32_t GetOrCreateCertainFilterIdByCookie(uint64_t internalTid, DataIndex nameIndex, int64_t cookie); - + void AppendNewMeasureData(uint64_t internalTid, DataIndex nameIndex, uint64_t timestamp, int64_t value); private: + uint32_t GetOrCreateFilterId(uint64_t internalTid, DataIndex nameIndex); void AddCertainFilterId(uint64_t internalTid, DataIndex nameIndex, uint64_t filterId); DoubleMap tidStreamIdFilterIdMap_; DoubleMap cookieFilterIdMap_; FilterType filterType_; const std::map filterTypeValue = { - { E_THREADMEASURE_FILTER, "thread_counter_track" }, - { E_THREAD_FILTER, "thread_track" }, - { E_PROCESS_MEASURE_FILTER, "process_counter_track" }, - { E_PROCESS_FILTER_FILTER, "process_track" }, - { E_CPU_MEASURE_FILTER, "cpu_counter_track" } + { E_THREADMEASURE_FILTER, "thread_measure_filter" }, + { E_THREAD_FILTER, "thread_measure" }, + { E_PROCESS_MEASURE_FILTER, "process_measure_filter" }, + { E_PROCESS_FILTER_FILTER, "process_filter" }, + { E_CPU_MEASURE_FILTER, "cpu_measure_filter" }, + { E_CLOCK_RATE_FILTER, "clock_rate_filter" }, + { E_CLOCK_ENABLE_FILTER, "clock_enable_filter" }, + { E_CLOCK_DISABLE_FILTER, "clock_disable_filter" } }; + DataIndex clockSetRateDataIndex_ = traceDataCache_->GetDataIndex("clock_set_rate"); + DataIndex clockEnableDataIndex_ = traceDataCache_->GetDataIndex("clock_enable"); + DataIndex clockDisableDataIndex_ = traceDataCache_->GetDataIndex("clock_disable"); }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/process_filter.cpp b/trace_analyzer/src/filter/process_filter.cpp index 34858a459..bfed938cd 100644 --- a/trace_analyzer/src/filter/process_filter.cpp +++ b/trace_analyzer/src/filter/process_filter.cpp @@ -23,24 +23,66 @@ using CustomPair = std::pair; namespace SysTuning { namespace TraceStreamer { namespace { - const uint32_t INVALID_ID = std::numeric_limits::max(); +const uint32_t INVALID_ID = std::numeric_limits::max(); } ProcessFilter::ProcessFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - :FilterBase(dataCache, filter) + : FilterBase(dataCache, filter) { tidMappingSet_.insert(CustomPair(0, 0)); - pidMappingSet_.insert(CustomPair(0, 0)); + pidToInternalPidMap_.insert(CustomPair(0, 0)); } ProcessFilter::~ProcessFilter() {} -uint32_t ProcessFilter::UpdateThreadByName(uint64_t timeStamp, uint32_t tid, std::string_view name) +uint32_t ProcessFilter::UpdateOrCreateThreadWithName(uint64_t timeStamp, uint32_t tid, std::string_view name) { DataIndex nameIndex = traceDataCache_->GetDataIndex(name); - return SetThreadPid(timeStamp, tid, nameIndex); + return UpdateOrCreateThreadWithNameIndex(timeStamp, tid, nameIndex); } -uint32_t ProcessFilter::SetThreadPid(uint64_t timeStamp, uint32_t tid, size_t threadNameIndex) +uint32_t ProcessFilter::UpdateOrCreateThread(uint64_t timestamp, uint32_t tid) +{ + return UpdateOrCreateThreadWithNameIndex(timestamp, tid, 0); +} +void ProcessFilter::UpdateOrCreateThreadWithPidAndName(uint32_t tid, uint32_t pid, std::string_view name) +{ + uint32_t internalTid = GetOrCreateThreadWithPid(tid, pid); + auto thread = traceDataCache_->GetThreadData(internalTid); + auto nameIndex = traceDataCache_->GetDataIndex(name); + thread->nameIndex_ = nameIndex; +} + +uint32_t ProcessFilter::GetOrCreateThreadWithPid(uint32_t tid, uint32_t pid) +{ + TraceStdtype::Thread* thread = nullptr; + uint32_t internalTid = GetInternalTid(tid, pid); + if (internalTid != INVALID_ID) { + thread = traceDataCache_->GetThreadData(internalTid); + } else { + std::tie(internalTid, thread) = NewThread(tid); + } + + if (!thread->internalPid_) { + std::tie(thread->internalPid_, std::ignore) = CreateProcessMaybe(pid, thread->startT_); + } + + return internalTid; +} + +uint32_t ProcessFilter::UpdateOrCreateProcessWithName(uint32_t pid, std::string_view name) +{ + uint32_t internalPid = 0; + TraceStdtype::Process* process = nullptr; + std::tie(internalPid, process) = CreateProcessMaybe(pid, 0); + if (process) { + process->cmdLine_ = std::string(name); + } + // Create a main thread which thread_id equal process_id, and is the main thread + GetOrCreateThreadWithPid(pid, pid); + return internalPid; +} + +uint32_t ProcessFilter::UpdateOrCreateThreadWithNameIndex(uint64_t timeStamp, uint32_t tid, DataIndex threadNameIndex) { TraceStdtype::Thread* thread = nullptr; uint32_t internalTid = GetInternalTid(tid); @@ -59,59 +101,21 @@ uint32_t ProcessFilter::SetThreadPid(uint64_t timeStamp, uint32_t tid, size_t th return internalTid; } - -void ProcessFilter::SetThreadName(uint32_t tid, uint32_t pid, std::string_view name) -{ - uint32_t internalTid = SetThreadPid(tid, pid); - auto* thread = traceDataCache_->GetThreadData(internalTid); - auto nameIndex = traceDataCache_->GetDataIndex(name); - thread->nameIndex_ = nameIndex; -} - -uint32_t ProcessFilter::SetThreadPid(uint32_t tid, uint32_t pid) -{ - TraceStdtype::Thread* thread = nullptr; - uint32_t internalTid = GetItidExact(tid, pid); - if (internalTid != INVALID_ID) { - thread = traceDataCache_->GetThreadData(internalTid); - } else { - std::tie(internalTid, thread) = NewThread(tid); - } - - if (!thread->internalPid_) { - std::tie(thread->internalPid_, std::ignore) = CreateProcessMaybe(pid, thread->startT_); - } - - return internalTid; -} - -uint32_t ProcessFilter::UpdateProcess(uint32_t pid, std::string_view name) -{ - uint32_t internalPid = 0; - TraceStdtype::Process* process = nullptr; - std::tie(internalPid, process) = CreateProcessMaybe(pid, 0); - if (process) { - process->cmdLine_ = std::string(name); - } - SetThreadPid(pid, pid); - return internalPid; -} - -uint32_t ProcessFilter::GetItidExact(uint32_t tid, uint32_t pid) const +uint32_t ProcessFilter::GetInternalTid(uint32_t tid, uint32_t pid) const { uint32_t internalTid = INVALID_ID; auto tidsPair = tidMappingSet_.equal_range(tid); for (auto it = tidsPair.first; it != tidsPair.second; it++) { - uint32_t iterUtid = it->second; - auto* iterThread = traceDataCache_->GetThreadData(iterUtid); + uint32_t iterItid = it->second; + auto iterThread = traceDataCache_->GetThreadData(iterItid); if (!iterThread->internalPid_) { - internalTid = iterUtid; + internalTid = iterItid; break; } const auto& iterProcess = traceDataCache_->GetConstProcessData(iterThread->internalPid_); if (iterProcess.pid_ == pid) { - internalTid = iterUtid; + internalTid = iterItid; break; } } @@ -129,20 +133,32 @@ uint32_t ProcessFilter::GetInternalTid(uint32_t tid) const return INVALID_ID; } -uint32_t ProcessFilter::GetInternalPid(uint32_t pid) const +InternalPid ProcessFilter::GetInternalPid(uint32_t pid) const { - auto it = pidMappingSet_.find(pid); - if (it != pidMappingSet_.end()) { + auto it = pidToInternalPidMap_.find(pid); + if (it != pidToInternalPidMap_.end()) { return it->second; } return INVALID_ID; } +InternalTid ProcessFilter::GetOrCreateInternalPid(uint64_t timestamp, uint32_t pid) +{ + auto ipid = GetInternalPid(pid); + if (ipid != INVALID_ID) { + return ipid; + } + + uint32_t internalPid = 0; + TraceStdtype::Process* process = nullptr; + std::tie(internalPid, process) = CreateProcessMaybe(pid, timestamp); + return internalPid; +} std::tuple ProcessFilter::NewThread(uint32_t tid) { - uint32_t internalTid = traceDataCache_->GetInternalThread(tid); + uint32_t internalTid = traceDataCache_->NewInternalThread(tid); tidMappingSet_.emplace(tid, internalTid); - auto* thread = traceDataCache_->GetThreadData(internalTid); + auto thread = traceDataCache_->GetThreadData(internalTid); return std::make_tuple(internalTid, thread); } @@ -150,8 +166,8 @@ std::tuple ProcessFilter::NewThread(uint32_t ti std::tuple ProcessFilter::NewProcess(uint32_t pid) { uint32_t internalPid = traceDataCache_->GetProcessInternalPid(pid); - pidMappingSet_.emplace(pid, internalPid); - auto* process = traceDataCache_->GetProcessData(internalPid); + pidToInternalPidMap_.emplace(pid, internalPid); + auto process = traceDataCache_->GetProcessData(internalPid); return std::make_tuple(internalPid, process); } @@ -160,8 +176,8 @@ std::tuple ProcessFilter::CreateProcessMaybe(u { uint32_t internalPid = INVALID_ID; TraceStdtype::Process* process = nullptr; - auto it = pidMappingSet_.find(pid); - if (it != pidMappingSet_.end()) { + auto it = pidToInternalPidMap_.find(pid); + if (it != pidToInternalPidMap_.end()) { internalPid = it->second; process = traceDataCache_->GetProcessData(internalPid); } else { diff --git a/trace_analyzer/src/filter/process_filter.h b/trace_analyzer/src/filter/process_filter.h index d9087a86f..89f2159b5 100644 --- a/trace_analyzer/src/filter/process_filter.h +++ b/trace_analyzer/src/filter/process_filter.h @@ -26,26 +26,27 @@ namespace SysTuning { namespace TraceStreamer { class ProcessFilter : private FilterBase { public: - explicit ProcessFilter(TraceDataCache*, const TraceStreamerFilters*); + ProcessFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); ~ProcessFilter() override; - uint32_t SetThreadPid(uint64_t timestamp, uint32_t tid, DataIndex threadNameIndex); - uint32_t UpdateThreadByName(uint64_t timestamp, uint32_t tid, std::string_view name); - - uint32_t SetThreadPid(uint32_t tid, uint32_t tgid); - void SetThreadName(uint32_t tid, uint32_t pid, std::string_view name); - uint32_t UpdateProcess(uint32_t pid, std::string_view name); - std::tuple CreateProcessMaybe(uint32_t pid, uint64_t start_ns); - + uint32_t UpdateOrCreateProcessWithName(uint32_t pid, std::string_view name); + uint32_t UpdateOrCreateThreadWithName(uint64_t timestamp, uint32_t tid, std::string_view name); + void UpdateOrCreateThreadWithPidAndName(uint32_t tid, uint32_t pid, std::string_view name); + uint32_t GetOrCreateThreadWithPid(uint32_t tid, uint32_t pid); + uint32_t UpdateOrCreateThread(uint64_t timestamp, uint32_t tid); + InternalPid GetInternalPid(uint32_t pid) const; + InternalTid GetOrCreateInternalPid(uint64_t timestamp, uint32_t pid); private: + uint32_t UpdateOrCreateThreadWithNameIndex(uint64_t timestamp, uint32_t tid, DataIndex threadNameIndex); + std::tuple CreateProcessMaybe(uint32_t pid, uint64_t start_ns); std::tuple NewThread(uint32_t tid); std::tuple NewProcess(uint32_t pid); InternalTid GetInternalTid(uint32_t tid) const; - InternalTid GetInternalPid(uint32_t pid) const; - InternalTid GetItidExact(uint32_t tid, uint32_t pid) const; + InternalTid GetInternalTid(uint32_t tid, uint32_t pid) const; +private: std::multimap tidMappingSet_ = {}; - std::map pidMappingSet_ = {}; + std::map pidToInternalPidMap_ = {}; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/slice_filter.cpp b/trace_analyzer/src/filter/slice_filter.cpp index 28ae42ae7..e53142759 100755 --- a/trace_analyzer/src/filter/slice_filter.cpp +++ b/trace_analyzer/src/filter/slice_filter.cpp @@ -19,112 +19,126 @@ #include #include "common.h" +#include "log.h" #include "measure_filter.h" #include "process_filter.h" -#include "trace_data_cache.h" -#include "trace_streamer_filters.h" namespace SysTuning { namespace TraceStreamer { SliceFilter::SliceFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter) {} + : FilterBase(dataCache, filter), asyncEventMap_(INVALID_UINT64), asyncEventSize_(0) +{ +} SliceFilter::~SliceFilter() = default; -void SliceFilter::BeginSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId, DataIndex cat, DataIndex name) +bool SliceFilter::BeginSlice(uint64_t timestamp, + uint32_t pid, + uint32_t threadGroupId, + DataIndex cat, + DataIndex nameIndex) { - InternalTid internalTid = streamFilters_->processFilter_->SetThreadPid(pid, threadGroupId); + InternalTid internalTid = streamFilters_->processFilter_->GetOrCreateThreadWithPid(pid, threadGroupId); pidTothreadGroupId_[pid] = threadGroupId; - uint32_t filterId = streamFilters_->threadFilter_->GetOrCreateCertainFilterId(internalTid, 0); - struct SliceData sliceData = {timestamp, 0, internalTid, filterId, cat, name}; - FinishedSliceStack(sliceData.timestamp, sliceStackMap_[sliceData.internalTid]); - BeginSliceInternal(sliceData); + struct SliceData sliceData = {timestamp, 0, internalTid, cat, nameIndex}; + return BeginSliceInternal(sliceData); } -void SliceFilter::AsyncBeginSlice(uint64_t timestamp, uint32_t pid, - uint32_t threadGroupId, int64_t cookie, DataIndex name) +void SliceFilter::StartAsyncSlice(uint64_t timestamp, + uint32_t pid, + uint32_t threadGroupId, + int64_t cookie, + DataIndex nameIndex) { - UNUSED(timestamp); - - InternalTid internalTid = streamFilters_->processFilter_->SetThreadPid(pid, threadGroupId); - auto filterId = streamFilters_->processFilterFilter_->GetOrCreateCertainFilterIdByCookie(internalTid, name, cookie); - UNUSED(filterId); + InternalPid internalPid = streamFilters_->processFilter_->GetOrCreateInternalPid(timestamp, threadGroupId); + auto lastFilterId = asyncEventMap_.Find(internalPid, cookie, nameIndex); + auto slices = traceDataCache_->GetInternalSlicesData(); + if (lastFilterId != INVALID_UINT64) { + asyncEventDisMatchCount++; + FinishAsyncSlice(timestamp, pid, threadGroupId, cookie, nameIndex); + } + asyncEventSize_++; + asyncEventMap_.Insert(internalPid, cookie, nameIndex, asyncEventSize_); + size_t index = + slices->AppendInternalAsyncSlice(timestamp, 0, internalPid, INVALID_UINT64, nameIndex, 0, cookie, std::nullopt); + asyncEventFilterMap_.insert(std::make_pair(asyncEventSize_, AsyncEvent{timestamp, index})); } -void SliceFilter::AsyncEndSlice(uint64_t timestamp, uint32_t pid, int64_t cookie) +void SliceFilter::FinishAsyncSlice(uint64_t timestamp, + uint32_t pid, + uint32_t threadGroupId, + int64_t cookie, + DataIndex nameIndex) { - UNUSED(timestamp); UNUSED(pid); - UNUSED(cookie); -} - -void SliceFilter::BeginSliceInternal(const SliceData& sliceData) -{ - auto* sliceStack = &sliceStackMap_[sliceData.internalTid]; - auto* slices = traceDataCache_->GetInternalSlicesData(); - const uint8_t depth = static_cast(sliceStack->size()); - if (depth >= std::numeric_limits::max()) { - TUNING_LOGF("stack depth out of range."); + InternalPid internalPid = streamFilters_->processFilter_->GetOrCreateInternalPid(timestamp, threadGroupId); + auto lastFilterId = asyncEventMap_.Find(internalPid, cookie, nameIndex); + auto slices = traceDataCache_->GetInternalSlicesData(); + if (lastFilterId == INVALID_UINT64) { // if failed + asyncEventDisMatchCount++; return; } + if (asyncEventFilterMap_.find(lastFilterId) == asyncEventFilterMap_.end()) { + TS_LOGE("logic error"); + asyncEventDisMatchCount++; + return; + } + // update timestamp + asyncEventFilterMap_.at(lastFilterId).timestamp = timestamp; + slices->SetDuration(asyncEventFilterMap_.at(lastFilterId).row, timestamp); + asyncEventFilterMap_.erase(lastFilterId); + asyncEventMap_.Erase(internalPid, cookie, nameIndex); +} - uint64_t parentStackId = 0; +bool SliceFilter::BeginSliceInternal(const SliceData& sliceData) +{ + auto sliceStack = &sliceStackMap_[sliceData.internalTid]; + auto slices = traceDataCache_->GetInternalSlicesData(); + if (sliceStack->size() >= std::numeric_limits::max()) { + TS_LOGE("stack depth out of range."); + return false; + } + const uint8_t depth = static_cast(sliceStack->size()); std::optional parentId = std::nullopt; if (depth != 0) { size_t lastDepth = sliceStack->back(); - parentStackId = slices->StackIdsData()[lastDepth]; parentId = std::make_optional(slices->IdsData()[lastDepth]); } size_t index = slices->AppendInternalSlice(sliceData.timestamp, sliceData.duration, sliceData.internalTid, - sliceData.filterId, sliceData.cat, sliceData.name, depth, 0, parentStackId, parentId); + sliceData.cat, sliceData.name, depth, parentId); sliceStack->push_back(index); - slices->SetStackId(index, GenHashByStack(*sliceStack)); + return true; } -void SliceFilter::EndSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId) +bool SliceFilter::EndSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId) { auto actThreadGroupIdIter = pidTothreadGroupId_.find(pid); if (actThreadGroupIdIter == pidTothreadGroupId_.end()) { - return; + callEventDisMatchCount++; + return false; } uint32_t actThreadGroupId = actThreadGroupIdIter->second; if (threadGroupId != 0 && threadGroupId != actThreadGroupId) { - TUNING_LOGD("pid %u mismatched thread group id %u", pid, actThreadGroupId); + TS_LOGD("pid %u mismatched thread group id %u", pid, actThreadGroupId); } - InternalTid internalTid = streamFilters_->processFilter_->SetThreadPid(pid, actThreadGroupId); - - FinishedSliceStack(timestamp, sliceStackMap_[internalTid]); + InternalTid internalTid = streamFilters_->processFilter_->GetOrCreateThreadWithPid(pid, actThreadGroupId); const auto& stack = sliceStackMap_[internalTid]; if (stack.empty()) { - return; + TS_LOGW("workqueue_execute_end do not match a workqueue_execute_start event"); + callEventDisMatchCount++; + return false; } - auto* slices = traceDataCache_->GetInternalSlicesData(); + auto slices = traceDataCache_->GetInternalSlicesData(); size_t index = stack.back(); - slices->SetDuration(index, timestamp - slices->TimeStamData()[index]); + slices->SetDuration(index, timestamp); sliceStackMap_[internalTid].pop_back(); -} - -void SliceFilter::FinishedSliceStack(uint64_t timestamp, StackOfSlices& sliceStack) -{ - const auto& slices = traceDataCache_->GetConstInternalSlicesData(); - for (int i = static_cast(sliceStack.size()) - 1; i >= 0; i--) { - size_t index = sliceStack[static_cast(i)]; - uint64_t during = slices.DursData()[index]; - if (during == 0) { - continue; - } - - uint64_t endT = slices.TimeStamData()[index] + during; - if (timestamp >= endT) { - sliceStack.pop_back(); - } - } + return true; } uint64_t SliceFilter::GenHashByStack(const StackOfSlices& sliceStack) const @@ -140,7 +154,7 @@ uint64_t SliceFilter::GenHashByStack(const StackOfSlices& sliceStack) const } const uint64_t stackHashMask = uint64_t(-1) >> 1; - return (std::hash {}(hashStr)) & stackHashMask; + return (std::hash{}(hashStr)) & stackHashMask; } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/slice_filter.h b/trace_analyzer/src/filter/slice_filter.h index e935593bb..ca4bbc98b 100755 --- a/trace_analyzer/src/filter/slice_filter.h +++ b/trace_analyzer/src/filter/slice_filter.h @@ -17,43 +17,48 @@ #define SLICE_FILTER_H #include - #include "filter_base.h" #include "trace_data_cache.h" +#include "trace_streamer_filters.h" +#include "triple_map.h" namespace SysTuning { namespace TraceStreamer { -class TraceDataCache; -class TraceStreamerFilters; - struct SliceData { uint64_t timestamp; uint64_t duration; InternalTid internalTid; - uint32_t filterId; DataIndex cat; DataIndex name; }; - +struct AsyncEvent { + uint64_t timestamp; + size_t row; +}; class SliceFilter : private FilterBase { public: - explicit SliceFilter(TraceDataCache*, const TraceStreamerFilters*); + SliceFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); ~SliceFilter() override; - void BeginSlice(uint64_t timestamp, uint32_t ftraceTid, uint32_t atraceTid, DataIndex cat, DataIndex name); - void EndSlice(uint64_t timestamp, uint32_t ftraceTid, uint32_t atraceTid); - void AsyncBeginSlice(uint64_t timestamp, uint32_t ftraceTid, uint32_t atraceTid, int64_t cookie, DataIndex name); - void AsyncEndSlice(uint64_t timestamp, uint32_t pid, int64_t cookie); + bool BeginSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId, DataIndex cat, DataIndex nameIndex); + bool EndSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId); + void StartAsyncSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId, int64_t cookie, DataIndex nameIndex); + void + FinishAsyncSlice(uint64_t timestamp, uint32_t pid, uint32_t threadGroupId, int64_t cookie, DataIndex nameIndex); private: using StackOfSlices = std::vector; - - uint64_t GenHashByStack(const StackOfSlices&) const; - void BeginSliceInternal(const SliceData& sliceData); - void FinishedSliceStack(uint64_t endTs, StackOfSlices&); - + uint64_t GenHashByStack(const StackOfSlices& sliceStack) const; + bool BeginSliceInternal(const SliceData& sliceData); +private: + // The parameter list is tid, cookid, functionName, asyncCallId. + TripleMap asyncEventMap_; + std::map asyncEventFilterMap_; std::unordered_map sliceStackMap_ = {}; std::unordered_map pidTothreadGroupId_ = {}; + uint64_t asyncEventSize_; + uint64_t asyncEventDisMatchCount = 0; + uint64_t callEventDisMatchCount = 0; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/filter/stat_filter.cpp b/trace_analyzer/src/filter/stat_filter.cpp new file mode 100644 index 000000000..e00cb15b7 --- /dev/null +++ b/trace_analyzer/src/filter/stat_filter.cpp @@ -0,0 +1,32 @@ +/* + * 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 "stat_filter.h" +#include "common.h" +#include "filter_filter.h" +#include "log.h" + +namespace SysTuning { +namespace TraceStreamer { +StatFilter::StatFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) : FilterBase(dataCache, filter) {} + +StatFilter::~StatFilter() {} + +void StatFilter::IncreaseStat(SupportedTraceEventType eventType, StatType type) +{ + traceDataCache_->GetStatAndInfo()->IncreaseStat(eventType, type); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/filter/stat_filter.h b/trace_analyzer/src/filter/stat_filter.h new file mode 100644 index 000000000..f78643e6e --- /dev/null +++ b/trace_analyzer/src/filter/stat_filter.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 STAT_FILTER_H +#define STAT_FILTER_H + +#include +#include +#include + +#include "double_map.h" +#include "filter_base.h" +#include "trace_data_cache.h" +#include "trace_streamer_cfg.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +using namespace SysTuning::TraceCfg; +class StatFilter : private FilterBase { +public: + StatFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); + StatFilter(const StatFilter&) = delete; + StatFilter& operator=(const StatFilter&) = delete; + ~StatFilter() override; + void IncreaseStat(SupportedTraceEventType eventType, StatType type); +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif // THREAD_MEASURE_FILTER_H diff --git a/trace_analyzer/src/filter/symbols_filter.cpp b/trace_analyzer/src/filter/symbols_filter.cpp new file mode 100644 index 000000000..9d57d3d3f --- /dev/null +++ b/trace_analyzer/src/filter/symbols_filter.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "symbols_filter.h" +#include +#include +#include + +#include "common.h" +#include "log.h" +#include "measure_filter.h" +#include "process_filter.h" + +namespace SysTuning { +namespace TraceStreamer { +SymbolsFilter::SymbolsFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) + : FilterBase(dataCache, filter) +{ +} + +SymbolsFilter::~SymbolsFilter() = default; +void SymbolsFilter::RegisterFunc(uint64_t addr, DataIndex funcNameDictIndex) +{ + if (symbolsMap_.find(addr) == symbolsMap_.end()) { + symbolsMap_.insert(std::make_pair(addr, funcNameDictIndex)); + traceDataCache_->GetSymbolsData()->InsertSymbol(funcNameDictIndex, addr); + } else { + symbolsMap_.at(addr) = funcNameDictIndex; + } +} + +const DataIndex& SymbolsFilter::GetFunc(uint64_t addr) const +{ + if (symbolsMap_.find(addr) == symbolsMap_.end()) { + auto lastAddr = symbolsMap_.lower_bound(addr); + if (lastAddr == symbolsMap_.end()) { + return INVALID_UINT64; + } + return lastAddr->second; + } else { + return symbolsMap_.at(addr); + } +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/filter/symbols_filter.h b/trace_analyzer/src/filter/symbols_filter.h new file mode 100644 index 000000000..ecc094d40 --- /dev/null +++ b/trace_analyzer/src/filter/symbols_filter.h @@ -0,0 +1,41 @@ +/* + * 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 SYMBOLS_FILTER_H +#define SYMBOLS_FILTER_H + +#include +#include "filter_base.h" +#include "trace_data_cache.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +class SymbolsFilter : private FilterBase { +public: + SymbolsFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); + ~SymbolsFilter() override; + + void RegisterFunc(uint64_t addr, DataIndex funcNameDictIndex); + + const DataIndex& GetFunc(uint64_t addr) const; + +private: + std::map symbolsMap_ = {}; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // SLICE_FILTER_H diff --git a/trace_analyzer/include/BUILD.gn b/trace_analyzer/src/include/BUILD.gn similarity index 85% rename from trace_analyzer/include/BUILD.gn rename to trace_analyzer/src/include/BUILD.gn index 1f52b697d..e0f6aa748 100755 --- a/trace_analyzer/include/BUILD.gn +++ b/trace_analyzer/src/include/BUILD.gn @@ -10,13 +10,17 @@ # 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. - -source_set("base") { +import("//build/ohos.gni") +ohos_source_set("ibase") { sources = [ + "codec_cov.h", "file.h", "log.h", "parting_string.h", "string_to_numerical.h", ] + include_dirs = [] + public_deps = [] + deps = [] sources += [ "/usr/x86_64-w64-mingw32/include/windows.h" ] } diff --git a/trace_analyzer/src/include/codec_cov.h b/trace_analyzer/src/include/codec_cov.h new file mode 100644 index 000000000..c2699efbb --- /dev/null +++ b/trace_analyzer/src/include/codec_cov.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_TUNING_BASE_CODEC_COV_H_ +#define INCLUDE_TUNING_BASE_CODEC_COV_H_ + +#include +#include + +namespace SysTuning { +namespace base { +int PreNum(unsigned char byte); + +bool IsUTF8(const uint8_t* data, int len); + +bool IsGBK(const uint8_t* data, int len); + +typedef enum { GBK, UTF8, UNKOWN } CODING; + +CODING GetCoding(const uint8_t* data, int len); + +#ifdef _WIN32 +std::string GbkToUtf8(const char* srcStr); +#endif +} // namespace base +} // namespace SysTuning + +#endif diff --git a/trace_analyzer/include/file.h b/trace_analyzer/src/include/file.h similarity index 78% rename from trace_analyzer/include/file.h rename to trace_analyzer/src/include/file.h index 0db3e439d..359e038e8 100755 --- a/trace_analyzer/include/file.h +++ b/trace_analyzer/src/include/file.h @@ -22,13 +22,18 @@ namespace SysTuning { namespace base { constexpr uint32_t kFileModeInvalid = 0xFFFFFFFF; -enum ErrStatus { NORMAL = 0, FILE_TYPE_ERROR = 1, PARSE_ERROR = 2, ABNORMAL = 3 }; +enum TraceParserStatus { + TRACE_PARSER_NORMAL = 0, + TRACE_PARSER_FILE_TYPE_ERROR = 1, + TRACE_PARSE_ERROR = 2, + TRACE_PARSER_ABNORMAL = 3 +}; -void SetAnalysisResult(ErrStatus stat); +void SetAnalysisResult(TraceParserStatus stat); -ErrStatus GetAnalysisResult(); +TraceParserStatus GetAnalysisResult(); -ssize_t Read(int fd, uint8_t* dst, size_t dst_size); +ssize_t Read(int fd, uint8_t* dst, size_t dstSize); int OpenFile(const std::string& path, int flags, uint32_t mode = kFileModeInvalid); diff --git a/trace_analyzer/src/include/log.h b/trace_analyzer/src/include/log.h new file mode 100755 index 000000000..cbc67fc55 --- /dev/null +++ b/trace_analyzer/src/include/log.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_TS_BASE_LOGGING_H_ +#define INCLUDE_TS_BASE_LOGGING_H_ + +#include +#include + +namespace SysTuning { +namespace base { +#define TS_CRASH \ + do { \ + __builtin_trap(); \ + __builtin_unreachable(); \ + } while (0) +enum LogLevel {LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL}; +const enum LogLevel g_currentLogLevel = LOG_DEBUG; +#define LOGWITHLEVEL(level, motify, fmt, ...) \ + do { \ + if (level >= SysTuning::base::g_currentLogLevel) { \ + fprintf(stdout, "[-%c][%s][%d]: " fmt "\n", motify, __FUNCTION__, \ + __LINE__, ##__VA_ARGS__); \ + if (level == SysTuning::base::LOG_FATAL) { \ + TS_CRASH; \ + } \ + } \ + } while (0) +#define TS_LOGE(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_ERROR, 'E', fmt, ##__VA_ARGS__) +#define TS_LOGF(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_FATAL, 'F', fmt, ##__VA_ARGS__) +#ifdef NDEBUG +#define TS_LOGD(format, ...) +#define TS_LOGI(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_INFO, 'I', fmt, ##__VA_ARGS__) +#define TS_LOGW(format, ...) +#define TS_ASSERT(x) +#else +#define TS_LOGD(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_DEBUG, 'D', fmt, ##__VA_ARGS__) +#define TS_LOGI(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_INFO, 'I', fmt, ##__VA_ARGS__) +#define TS_LOGW(fmt, ...) LOGWITHLEVEL(SysTuning::base::LOG_WARN, 'W', fmt, ##__VA_ARGS__) + +#define TS_ASSERT(x) \ + do { \ + if (!(x)) { \ + TS_CRASH; \ + } \ + } while (0) + +#endif +} // namespace base +} // namespace SysTuning + +#endif // INCLUDE_TS_BASE_LOGGING_H_ diff --git a/trace_analyzer/include/parting_string.h b/trace_analyzer/src/include/parting_string.h similarity index 94% rename from trace_analyzer/include/parting_string.h rename to trace_analyzer/src/include/parting_string.h index b07989a57..a49c3fef6 100755 --- a/trace_analyzer/include/parting_string.h +++ b/trace_analyzer/src/include/parting_string.h @@ -36,7 +36,7 @@ private: PartingString& operator=(const PartingString&) = delete; std::string str_; - char* cur_; + char* cur_ = nullptr; std::string::iterator begin_; std::string::iterator end_; const char delimiter_; diff --git a/trace_analyzer/include/string_to_numerical.h b/trace_analyzer/src/include/string_to_numerical.h similarity index 100% rename from trace_analyzer/include/string_to_numerical.h rename to trace_analyzer/src/include/string_to_numerical.h diff --git a/trace_analyzer/src/main.cpp b/trace_analyzer/src/main.cpp old mode 100644 new mode 100755 index 8ffa346dd..f656444aa --- a/trace_analyzer/src/main.cpp +++ b/trace_analyzer/src/main.cpp @@ -15,139 +15,213 @@ #include #include +#include #include #include #include -#include #include #include #include #include "file.h" +#include "filter/slice_filter.h" #include "log.h" -#include "trace_streamer.h" +#include "parser/bytrace_parser/bytrace_event_parser.h" +#include "parser/bytrace_parser/bytrace_parser.h" + +#include "thread_state.h" +#include "trace_streamer/trace_streamer_selector.h" +#include "trace_streamer_filters.h" +using namespace SysTuning::TraceStreamer; namespace SysTuning { namespace TraceStreamer { -namespace { +using namespace SysTuning::TraceStreamer; +using namespace SysTuning::base; constexpr size_t G_CHUNK_SIZE = 1024 * 1024; -TraceStreamer* g_traceStreamer; +constexpr int G_MIN_PARAM_NUM = 2; +constexpr size_t G_FILE_PERMISSION = 664; +size_t g_loadSize = 0; +const char* TRACE_STREAM_VERSION = "1.1.102"; // version +const char* TRACE_STREAM_PUBLISHVERSION = "2021/8/30"; // publish datetime -void ExportStatusToLog(base::ErrStatus stauts) +void ExportStatusToLog(TraceParserStatus stauts) { - std::string path = base::GetExecutionDirectoryPath() + "/trace_streamer.log"; + std::string path = GetExecutionDirectoryPath() + "/trace_streamer.log"; std::ofstream out(path, std::ios_base::trunc); out << (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) - .count() + .count() << ":" << stauts << std::endl; out.close(); } - -int ExportDatabase(const std::string& outputName) +void ShowHelpInfo(const char* argv) { - return g_traceStreamer->ExportDatabase(outputName); -} - -void ShowHelpInfo(char** argv) -{ - TUNING_LOGI( - "trace analyse tool, it can transfer a bytrace file into a " + TS_LOGI( + "trace analyze tool, it can transfer a bytrace/htrace file into a " "SQLite database and save result to a local file trace_streamer.log.\n" "Usage: %s FILE -e sqlite_out.pb\n" + " or %s FILE -c\n" "Options:\n" " -e transfer a bytrace file into a SQLiteBased DB.\n" + " -c command line mode.\n" " -v show version.", - argv[0]); + argv, argv); } - void PrintVersion() { - printf("version 0.1.106\n"); + fprintf(stderr, "version %s\n", TRACE_STREAM_VERSION); } -int FileRead(TraceStreamer& ta, int fd) +bool ReadAndParser(SysTuning::TraceStreamer::TraceStreamerSelector& ta, int fd) { - ssize_t loadSize = 0; + auto startTime = + (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) + .count(); + g_loadSize = 0; while (true) { std::unique_ptr buf = std::make_unique(std::move(G_CHUNK_SIZE)); - auto rsize = base::Read(fd, buf.get(), G_CHUNK_SIZE); + auto rsize = Read(fd, buf.get(), G_CHUNK_SIZE); if (rsize == 0) { break; } if (rsize < 0) { - TUNING_LOGI("Reading trace file failed (errno: %d, %s)", errno, strerror(errno)); - return 1; + TS_LOGI("Reading trace file failed (errno: %d, %s)", errno, strerror(errno)); + return false; } - loadSize += rsize; - if (!ta.Parse(std::move(buf), static_cast(rsize))) { - return 1; + g_loadSize += rsize; + if (!ta.ParseTraceDataSegment(std::move(buf), static_cast(rsize))) { + return false; }; - fprintf(stdout, "\rLoading file: %.2f MB\r", static_cast(loadSize) / 1E6); + printf("\rLoadingFile:\t%.2f MB\r", static_cast(g_loadSize) / 1E6); } - - return 0; + ta.WaitForParserEnd(); + auto endTime = + (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) + .count(); + fprintf(stdout, "\nParserDuration:\t%u ms\n", static_cast(endTime - startTime)); + fprintf(stdout, "ParserSpeed:\t%.2f MB/s\n", (g_loadSize / (endTime - startTime) / 1E3)); + return true; } - -int EnterTraceStreamer(int argc, char** argv) +int OpenAndParserFile(TraceStreamerSelector& ts, const std::string& traceFilePath) { - if (argc < G_MIN_PARAM_NUM) { - ShowHelpInfo(argv); + int fd(OpenFile(traceFilePath, O_RDONLY, G_FILE_PERMISSION)); + if (fd < 0) { + TS_LOGI("%s does not exist", traceFilePath.c_str()); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); return 1; } + if (!ReadAndParser(ts, fd)) { + close(fd); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); + return 1; + } + MetaData* metaData = ts.GetMetaData(); + std::string fileNameTmp = traceFilePath; +#ifdef _WIN32 + if (!base::GetCoding(reinterpret_cast(fileNameTmp.c_str()), fileNameTmp.length())) { + fileNameTmp = base::GbkToUtf8(fileNameTmp.c_str()); + } +#endif + metaData->SetSourceFileName(fileNameTmp); + metaData->SetTraceType((ts.DataType() == TRACE_FILETYPE_H_TRACE) ? "proto-based-trace" : "txt-based-trace"); + + close(fd); + return 0; +} +int ExportDatabase(TraceStreamerSelector& ts, const std::string& sqliteFilePath) +{ + auto startTime = + (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) + .count(); + if (!sqliteFilePath.empty()) { + MetaData* metaData = ts.GetMetaData(); + std::string fileNameTmp = sqliteFilePath; +#ifdef _WIN32 + if (!base::GetCoding(reinterpret_cast(fileNameTmp.c_str()), fileNameTmp.length())) { + fileNameTmp = base::GbkToUtf8(fileNameTmp.c_str()); + } +#endif + metaData->SetOutputFileName(fileNameTmp); + metaData->SetParserToolVersion(TRACE_STREAM_VERSION); + metaData->SetParserToolPublishDateTime(TRACE_STREAM_PUBLISHVERSION); + metaData->SetTraceDataSize(g_loadSize); + fprintf(stdout, "ExportDatabase begin...\n"); + if (ts.ExportDatabase(sqliteFilePath)) { + fprintf(stdout, "ExportDatabase failed\n"); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); + return 1; + } + fprintf(stdout, "ExportDatabase end\n"); + } + ExportStatusToLog(GetAnalysisResult()); + auto endTime = + (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) + .count(); + endTime += 1; // for any exception of endTime == startTime + fprintf(stdout, "ExportDuration:\t%u ms\n", static_cast(endTime - startTime)); + fprintf(stdout, "ExportSpeed:\t%.2f MB/s\n", (g_loadSize / (endTime - startTime) / 1E3)); + return 0; +} +} // namespace TraceStreamer +} // namespace SysTuning +int main(int argc, char** argv) +{ + if (argc < G_MIN_PARAM_NUM) { + ShowHelpInfo(argv[0]); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); + return 1; + } std::string traceFilePath; std::string sqliteFilePath; + bool interactiveState = false; + bool exportMetaTable = true; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-e")) { if (++i == argc) { - ShowHelpInfo(argv); + ShowHelpInfo(argv[0]); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); return 1; } sqliteFilePath = std::string(argv[i]); continue; - } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--v") - || !strcmp(argv[i], "-version") || !strcmp(argv[i], "--version")) { + } else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command")) { + interactiveState = true; + continue; + } else if (!strcmp(argv[i], "-nm") || !strcmp(argv[i], "--nometa")) { + exportMetaTable = false; + continue; + } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--v") || !strcmp(argv[i], "-version") || + !strcmp(argv[i], "--version")) { PrintVersion(); return 0; } traceFilePath = std::string(argv[i]); } - if (traceFilePath.empty()) { - ShowHelpInfo(argv); + if (traceFilePath.empty() || (!interactiveState && sqliteFilePath.empty())) { + ShowHelpInfo(argv[0]); + ExportStatusToLog(TRACE_PARSER_ABNORMAL); return 1; } - std::unique_ptr ta = std::make_unique(); - int fd(base::OpenFile(traceFilePath, O_RDONLY, G_FILE_PERMISSION)); - if (fd < 0) { - TUNING_LOGI("%s does not exist", traceFilePath.c_str()); + TraceStreamerSelector ts; + ts.EnableMetaTable(exportMetaTable); + if (OpenAndParserFile(ts, traceFilePath)) { return 1; } - if (FileRead(*ta, fd)) { - close(fd); + if (interactiveState && sqliteFilePath.empty()) { + sqliteFilePath = "default.db"; + } + if (ExportDatabase(ts, sqliteFilePath)) { + ExportStatusToLog(TRACE_PARSER_ABNORMAL); return 1; } - - close(fd); - - g_traceStreamer = ta.get(); - - if (!sqliteFilePath.empty()) { - return ExportDatabase(sqliteFilePath); + ExportStatusToLog(GetAnalysisResult()); + if (interactiveState) { + ts.SearchData(sqliteFilePath); } - return 0; } -} // namespace -} // namespace TraceStreamer -} // namespace SysTuning - -int main(int argc, char** argv) -{ - int result = SysTuning::TraceStreamer::EnterTraceStreamer(argc, argv); - SysTuning::TraceStreamer::ExportStatusToLog(SysTuning::base::GetAnalysisResult()); - return result; -} diff --git a/trace_analyzer/src/parser/bytrace_parser.cpp b/trace_analyzer/src/parser/bytrace_parser.cpp deleted file mode 100755 index d31c91191..000000000 --- a/trace_analyzer/src/parser/bytrace_parser.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "bytrace_parser.h" - -namespace SysTuning { -namespace TraceStreamer { -BytraceParser::BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) - : eventParser_(std::make_unique(dataCache, ctx)) -{ -} - -BytraceParser::~BytraceParser() = default; - -bool BytraceParser::Parse(std::unique_ptr bufferStr, size_t size) -{ - if (parserState_ == END) { - return true; - } - - parserState_ = RUNNING; - packagesBuffer_.insert(packagesBuffer_.end(), &bufferStr[0], &bufferStr[size]); - auto packagesBegin = packagesBuffer_.begin(); - - while (1) { - auto packagesLine = std::find(packagesBegin, packagesBuffer_.end(), '\n'); - if (packagesLine == packagesBuffer_.end()) { - break; - } - - std::string bufferLine(packagesBegin, packagesLine); - - if (IsTraceData(bufferLine)) { - isByTrace_ = true; - goto NEXT_LINE; - } - - if (isByTrace_) { - if (bufferLine.find(script_.c_str()) != std::string::npos) { - parserState_ = END; - break; - } else if (!bufferLine.empty() && (bufferLine.compare(0, std::string("#").length(), "#") != 0)) { - BytraceLine line; - if (LineParser(bufferLine, line) == SUCCESS) { - eventParser_->ParseLine(std::move(line)); - } - } - } - - NEXT_LINE: - packagesBegin = packagesLine + 1; - continue; - } - - if (parserState_ == END) { - packagesBuffer_.clear(); - } else { - packagesBuffer_.erase(packagesBuffer_.begin(), packagesBegin); - } - return true; -} - -ParseResult BytraceParser::LineParser(const std::string& buffer, BytraceLine& line) const -{ - std::smatch matcheLine; - bool matched = std::regex_search(buffer, matcheLine, bytraceMatcher_); - if (!matched) { - TUNING_LOGD("Not support this event (line: %s)", buffer.c_str()); - return ERROR; - } - - size_t index = 0; - std::string pidStr = matcheLine[++index].str(); - std::optional optionalPid = base::StrToUInt32(pidStr); - if (!optionalPid.has_value()) { - TUNING_LOGD("Illegal pid: %s", pidStr.c_str()); - return ERROR; - } - - std::string tGidStr = matcheLine[++index].str(); - std::string cpuStr = matcheLine[++index].str(); - std::optional optionalCpu = base::StrToUInt32(cpuStr); - if (!optionalCpu.has_value()) { - TUNING_LOGD("Illegal cpu %s", cpuStr.c_str()); - return ERROR; - } - std::string timeStr = matcheLine[++index].str(); - std::optional optionalTime = base::StrToDouble(timeStr); - if (!optionalTime.has_value()) { - TUNING_LOGD("Illegal ts %s", timeStr.c_str()); - return ERROR; - } - std::string eventName = matcheLine[++index].str(); - - line.pid = optionalPid.value(); - line.cpu = optionalCpu.value(); - line.ts = static_cast(optionalTime.value() * 1e9); - line.task = StrTrim(matcheLine.prefix()); - line.tGidStr = tGidStr; - line.eventName = eventName; - line.argsStr = StrTrim(matcheLine.suffix()); - - return SUCCESS; -} - -// Remove space at the beginning and end of the string -std::string BytraceParser::StrTrim(const std::string& input) const -{ - std::string str = input; - auto posBegin = std::find_if(str.begin(), str.end(), IsNotSpace); - str.erase(str.begin(), posBegin); - - auto posEnd = std::find_if(str.rbegin(), str.rend(), IsNotSpace); - str.erase(posEnd.base(), str.end()); - - return str; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/parser/bytrace_parser.h b/trace_analyzer/src/parser/bytrace_parser.h deleted file mode 100755 index e336d5a2e..000000000 --- a/trace_analyzer/src/parser/bytrace_parser.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef BYTRACE_PARSER_H -#define BYTRACE_PARSER_H - -#include - -#include "event_parser.h" -#include "log.h" -#include "string_to_numerical.h" -#include "trace_data/trace_data_cache.h" -#include "trace_streamer_filters.h" - -namespace SysTuning { -namespace TraceStreamer { -class BytraceParser { -public: - explicit BytraceParser(TraceDataCache*, const TraceStreamerFilters*); - ~BytraceParser(); - - bool Parse(std::unique_ptr, size_t size); - -private: - enum BytraceParserState { IDLE, RUNNING, END }; - - BytraceParserState parserState_ = IDLE; - bool isByTrace_ = false; - std::deque packagesBuffer_ = {0}; - std::unique_ptr eventParser_; - const std::regex bytraceMatcher_ = - std::regex(R"(-(\d+)\s+\(?\s*(\d+|-+)?\)?\s?\[(\d+)\]\s*)" - R"([a-zA-Z0-9.]{0,5}\s+(\d+\.\d+):\s+(\S+):)"); - - const std::string script_ = R"()"; - - inline static bool IsNotSpace(char c) - { - return !std::isspace(c); - } - inline static bool IsTraceData(const std::string& buffer) - { - return ((buffer.compare(0, std::string("#").length(), "#") == 0) || - buffer.find("TASK-PID") != std::string::npos); - } - - ParseResult LineParser(const std::string& buffer, BytraceLine& line) const; - std::string StrTrim(const std::string& input) const; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // _BYTRACE_PARSER_H_ diff --git a/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.cpp b/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.cpp new file mode 100755 index 000000000..303fe307d --- /dev/null +++ b/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.cpp @@ -0,0 +1,727 @@ +/* + * 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 "bytrace_event_parser.h" +#include +#include +#include + +#include "common.h" +#include "cpu_filter.h" +#include "filter_filter.h" +#include "measure_filter.h" +#include "parting_string.h" +#include "process_filter.h" +#include "slice_filter.h" +#include "stat_filter.h" +#include "string_to_numerical.h" +#include "thread_state.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +std::string GetFunctionName(const std::string_view& text, const std::string_view& delimiter) +{ + std::string str(""); + if (delimiter.empty()) { + return str; + } + + std::size_t foundIndex = text.find(delimiter); + if (foundIndex != std::string::npos) { + std::size_t funIndex = foundIndex + delimiter.size(); + str = std::string(text.substr(funIndex, text.size() - funIndex)); + } + return str; +} +} // namespace + +BytraceEventParser::BytraceEventParser(TraceDataCache* dataCache, const TraceStreamerFilters* filter) + : EventParserBase(dataCache, filter), + ioWaitId_(const_cast(dataCache)->GetDataIndex("io_wait")), + workQueueId_(const_cast(dataCache)->GetDataIndex("workqueue")), + schedWakeupId_(const_cast(dataCache)->GetDataIndex("sched_wakeup")), + schedBlockedReasonId_(const_cast(dataCache)->GetDataIndex("sched_blocked_reason")), + pointLength_(1), + maxPointLength_(2), + byHex_(16) +{ + eventToFunctionMap_ = { + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_SWITCH), + bind(&BytraceEventParser::SchedSwitchEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_TASK_RENAME), + bind(&BytraceEventParser::TaskRenameEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_TASK_NEWTASK), + bind(&BytraceEventParser::TaskNewtaskEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_TRACING_MARK_WRITE), + bind(&BytraceEventParser::TracingMarkWriteEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP), + bind(&BytraceEventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKING), + bind(&BytraceEventParser::SchedWakingEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_CPU_IDLE), + bind(&BytraceEventParser::CpuIdleEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY), + bind(&BytraceEventParser::CpuFrequencyEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_START), + bind(&BytraceEventParser::WorkqueueExecuteStartEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_END), + bind(&BytraceEventParser::WorkqueueExecuteEndEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_SET_RATE), + bind(&BytraceEventParser::SetRateEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_ENABLE), + bind(&BytraceEventParser::ClockEnableEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_DISABLE), + bind(&BytraceEventParser::ClockDisableEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE), + bind(&BytraceEventParser::RegulatorSetVoltageEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE), + bind(&BytraceEventParser::RegulatorSetVoltageCompleteEvent, this, std::placeholders::_1, + std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE), + bind(&BytraceEventParser::RegulatorDisableEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE), + bind(&BytraceEventParser::RegulatorDisableCompleteEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_IPI_ENTRY), + bind(&BytraceEventParser::IpiEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_IPI_EXIT), + bind(&BytraceEventParser::IpiExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_ENTRY), + bind(&BytraceEventParser::IrqHandlerEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_EXIT), + bind(&BytraceEventParser::IrqHandlerExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_RAISE), + bind(&BytraceEventParser::SoftIrqRaiseEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_ENTRY), + bind(&BytraceEventParser::SoftIrqEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_EXIT), + bind(&BytraceEventParser::SoftIrqExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF), + bind(&BytraceEventParser::BinderTransactionAllocBufEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP_NEW), + bind(&BytraceEventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_PROCESS_EXIT), + bind(&BytraceEventParser::ProcessExitEvent, this, std::placeholders::_1, std::placeholders::_2)}}; +} + +bool BytraceEventParser::SchedSwitchEvent(const ArgsMap& args, const BytraceLine& line) const +{ + if (args.empty() || args.size() < MIN_SCHED_ARGS_COUNT) { + TS_LOGD("Failed to parse sched_switch event, no args or args size < 6"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_SWITCH, STAT_EVENT_DATA_INVALID); + return false; + } + auto prevCommStr = std::string_view(args.at("prev_comm")); + auto nextCommStr = std::string_view(args.at("next_comm")); + auto prevPrioValue = base::StrToInt32(args.at("prev_prio")); + auto nextPrioValue = base::StrToInt32(args.at("next_prio")); + auto prevPidValue = base::StrToUInt32(args.at("prev_pid")); + auto nextPidValue = base::StrToUInt32(args.at("next_pid")); + if (!(!prevCommStr.empty() && prevPidValue.has_value() && prevPrioValue.has_value() && nextPidValue.has_value() && + nextPrioValue.has_value())) { + TS_LOGD("Failed to parse sched_switch event"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_SWITCH, STAT_EVENT_DATA_INVALID); + return false; + } + + auto prevStateStr = args.at("prev_state"); + uint64_t prevState = ThreadState(prevStateStr.c_str()).State(); + // traceDataCache_->GetThreadStateDleata()->State + auto nextInternalTid = + streamFilters_->processFilter_->UpdateOrCreateThreadWithName(line.ts, nextPidValue.value(), nextCommStr); + auto uprevtid = + streamFilters_->processFilter_->UpdateOrCreateThreadWithName(line.ts, prevPidValue.value(), prevCommStr); + streamFilters_->cpuFilter_->InsertSwitchEvent(line.ts, line.cpu, uprevtid, + static_cast(prevPrioValue.value()), prevState, + nextInternalTid, static_cast(nextPrioValue.value())); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_SWITCH, STAT_EVENT_RECEIVED); + return true; +} + +bool BytraceEventParser::TaskRenameEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto prevCommStr = std::string_view(args.at("newcomm")); + auto pidValue = base::StrToUInt32(args.at("pid")); + streamFilters_->processFilter_->UpdateOrCreateThreadWithName(line.ts, pidValue.value(), prevCommStr); + return true; +} + +bool BytraceEventParser::TaskNewtaskEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto commonStr = std::string_view(args.at("comm")); + auto pidValue = base::StrToUInt32(args.at("pid")); + + uint32_t ftracePid = 0; + if (!line.tGidStr.empty() && line.tGidStr != "-----") { + std::optional tgid = base::StrToUInt32(line.tGidStr); + if (tgid) { + ftracePid = tgid.value(); + } + } + + static const uint32_t threadPid = 2; + static const uint32_t cloneThread = 0x00010000; + auto cloneFlags = base::StrToUInt64(args.at("clone_flags"), byHex_).value(); + if ((cloneFlags & cloneThread) == 0 && ftracePid != threadPid) { + streamFilters_->processFilter_->UpdateOrCreateProcessWithName(static_cast(pidValue.value()), + commonStr); + } else if (ftracePid == threadPid) { + streamFilters_->processFilter_->GetOrCreateThreadWithPid(static_cast(pidValue.value()), threadPid); + } + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TASK_NEWTASK, STAT_EVENT_RECEIVED); + return true; +} + +bool BytraceEventParser::TracingMarkWriteEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + ParsePrintEvent(line.ts, line.pid, line.argsStr.c_str()); + return true; +} + +bool BytraceEventParser::SchedWakeupEvent(const ArgsMap& args, const BytraceLine& line) const +{ + if (args.size() < MIN_SCHED_WAKEUP_ARGS_COUNT) { + TS_LOGD("Failed to parse SchedWakeupEvent event, no args or args size < 2"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_DATA_INVALID); + return false; + } + std::optional wakePidValue = base::StrToUInt32(args.at("pid")); + if (!wakePidValue.has_value()) { + TS_LOGD("Failed to convert wake_pid"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_DATA_INVALID); + return false; + } + DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_wakeup")); + auto instants = traceDataCache_->GetInstantsData(); + InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(line.ts, wakePidValue.value()); + instants->AppendInstantEventData(line.ts, name, internalTid); + streamFilters_->cpuFilter_->InsertWakeingEvent(line.ts, internalTid); + std::optional targetCpu = base::StrToUInt32(args.at("target_cpu")); + if (targetCpu.has_value()) { + traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKEUP, targetCpu.value(), internalTid); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_RECEIVED); + } + return true; +} + +bool BytraceEventParser::SchedWakingEvent(const ArgsMap& args, const BytraceLine& line) const +{ + std::optional wakePidValue = base::StrToUInt32(args.at("pid")); + if (!wakePidValue.has_value()) { + TS_LOGD("Failed to convert wake_pid"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_DATA_INVALID); + return false; + } + DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_waking")); + auto instants = traceDataCache_->GetInstantsData(); + InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(line.ts, line.pid); + instants->AppendInstantEventData(line.ts, name, internalTid); + std::optional targetCpu = base::StrToUInt32(args.at("target_cpu")); + if (targetCpu.has_value()) { + traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKING, targetCpu.value(), internalTid); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_RECEIVED); + } + return true; +} + +bool BytraceEventParser::CpuIdleEvent(const ArgsMap& args, const BytraceLine& line) const +{ + std::optional eventCpuValue = base::StrToUInt32(args.at("cpu_id")); + std::optional newStateValue = base::StrToInt64(args.at("state")); + if (!eventCpuValue.has_value()) { + TS_LOGD("Failed to convert event cpu"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_DATA_INVALID); + return false; + } + if (!newStateValue.has_value()) { + TS_LOGD("Failed to convert state"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_DATA_INVALID); + return false; + } + auto cpuIdleNameIndex = traceDataCache_->GetDataIndex(line.eventName.c_str()); + streamFilters_->cpuMeasureFilter_->AppendNewMeasureData(eventCpuValue.value(), cpuIdleNameIndex, line.ts, + newStateValue.value()); + // Add cpu_idle event to raw_data_table + traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_CPU_IDLE, eventCpuValue.value(), 0); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_RECEIVED); + return true; +} + +bool BytraceEventParser::CpuFrequencyEvent(const ArgsMap& args, const BytraceLine& line) const +{ + std::optional eventCpuValue = base::StrToUInt32(args.at("cpu_id")); + std::optional newStateValue = base::StrToInt64(args.at("state")); + + if (!newStateValue.has_value()) { + TS_LOGD("Failed to convert state"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_DATA_INVALID); + return false; + } + if (!eventCpuValue.has_value()) { + TS_LOGD("Failed to convert event cpu"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_DATA_INVALID); + return false; + } + + auto cpuidleNameIndex = traceDataCache_->GetDataIndex(line.eventName.c_str()); + streamFilters_->cpuMeasureFilter_->AppendNewMeasureData(eventCpuValue.value(), cpuidleNameIndex, line.ts, + newStateValue.value()); + return true; +} + +bool BytraceEventParser::WorkqueueExecuteStartEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + auto splitStr = GetFunctionName(line.argsStr, "function "); + auto splitStrIndex = traceDataCache_->GetDataIndex(splitStr); + bool result = streamFilters_->sliceFilter_->BeginSlice(line.ts, line.pid, line.pid, workQueueId_, splitStrIndex); + if (result) { + traceDataCache_->GetInternalSlicesData()->AppendDistributeInfo(); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_START, STAT_EVENT_RECEIVED); + return true; + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_START, STAT_EVENT_DATA_LOST); + return false; + } +} + +bool BytraceEventParser::WorkqueueExecuteEndEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + if (streamFilters_->sliceFilter_->EndSlice(line.ts, line.pid, line.pid)) { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_RECEIVED); + return true; + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_NOTMATCH); + return false; + } +} + +bool BytraceEventParser::ProcessExitEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto comm = std::string_view(args.at("comm")); + auto pid = base::StrToUInt32(args.at("pid")); + if (!pid.has_value()) { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_PROCESS_EXIT, STAT_EVENT_DATA_INVALID); + return false; + } + auto itid = streamFilters_->processFilter_->UpdateOrCreateThreadWithName(line.ts, pid.value(), comm); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_PROCESS_EXIT, STAT_EVENT_RECEIVED); + if (streamFilters_->cpuFilter_->InsertProcessExitEvent(line.ts, line.cpu, itid)) { + return true; + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_PROCESS_EXIT, STAT_EVENT_NOTMATCH); + return false; + } +} + +bool BytraceEventParser::SetRateEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto name = std::string_view(args.at("name")); + auto state = base::StrToInt64(args.at("state")); + auto cpu = base::StrToUInt64(args.at("cpu_id")); + DataIndex nameIndex = traceDataCache_->GetDataIndex(name); + streamFilters_->clockRateFilter_->AppendNewMeasureData(cpu.value(), nameIndex, line.ts, state.value()); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CLOCK_SET_RATE, STAT_EVENT_RECEIVED); + return true; +} + +bool BytraceEventParser::ClockEnableEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto name = std::string_view(args.at("name")); + auto state = base::StrToInt64(args.at("state")); + auto cpuId = base::StrToUInt64(args.at("cpu_id")); + DataIndex nameIndex = traceDataCache_->GetDataIndex(name); + streamFilters_->clockEnableFilter_->AppendNewMeasureData(cpuId.value(), nameIndex, line.ts, state.value()); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CLOCK_ENABLE, STAT_EVENT_RECEIVED); + return true; +} +bool BytraceEventParser::ClockDisableEvent(const ArgsMap& args, const BytraceLine& line) const +{ + auto name = std::string_view(args.at("name")); + auto state = base::StrToInt64(args.at("state")); + auto cpuId = base::StrToUInt64(args.at("cpu_id")); + DataIndex nameIndex = traceDataCache_->GetDataIndex(name); + streamFilters_->clockDisableFilter_->AppendNewMeasureData(cpuId.value(), nameIndex, line.ts, state.value()); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CLOCK_ENABLE, STAT_EVENT_RECEIVED); + return true; +} + +bool BytraceEventParser::RegulatorSetVoltageEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::RegulatorSetVoltageCompleteEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, + STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::RegulatorDisableEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::RegulatorDisableCompleteEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_NOTSUPPORTED); + return true; +} + +bool BytraceEventParser::IpiEntryEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_ENTRY, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_ENTRY, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::IpiExitEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_EXIT, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_EXIT, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::IrqHandlerEntryEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IRQ_HANDLER_ENTRY, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IRQ_HANDLER_ENTRY, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::IrqHandlerExitEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IRQ_HANDLER_EXIT, STAT_EVENT_RECEIVED); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IRQ_HANDLER_EXIT, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool BytraceEventParser::SoftIrqRaiseEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + return true; +} +bool BytraceEventParser::SoftIrqEntryEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + return true; +} +bool BytraceEventParser::SoftIrqExitEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + return true; +} +bool BytraceEventParser::BinderTransactionAllocBufEvent(const ArgsMap& args, const BytraceLine& line) const +{ + UNUSED(args); + UNUSED(line); + return true; +} +bool BytraceEventParser::ParseDataItem(const BytraceLine& line, const ArgsMap& args, uint32_t tgid) const +{ + traceDataCache_->UpdateTraceTime(line.ts); + if (tgid) { + streamFilters_->processFilter_->GetOrCreateThreadWithPid(line.pid, tgid); + streamFilters_->processFilter_->UpdateOrCreateThreadWithPidAndName(line.pid, tgid, line.task); + } + + auto it = eventToFunctionMap_.find(line.eventName); + if (it != eventToFunctionMap_.end()) { + return it->second(args, line); + } + TS_LOGW("UnRecognizable event name:%s", line.eventName.c_str()); + traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_NOTSUPPORTED); + return false; +} + +void BytraceEventParser::ParsePrintEvent(uint64_t ts, uint32_t pid, std::string_view event) const +{ + TracePoint point; + if (GetTracePoint(event, point) == SUCCESS) { + ParseTracePoint(ts, pid, point); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TRACING_MARK_WRITE, STAT_EVENT_RECEIVED); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TRACING_MARK_WRITE, STAT_EVENT_DATA_INVALID); + } +} + +void BytraceEventParser::ParseTracePoint(uint64_t ts, uint32_t pid, TracePoint point) const +{ + switch (point.phase_) { + case 'B': { + if (streamFilters_->sliceFilter_->BeginSlice(ts, pid, point.tgid_, 0, + traceDataCache_->GetDataIndex(point.name_))) { + // add distributed data + traceDataCache_->GetInternalSlicesData()->AppendDistributeInfo( + point.chainId_, point.spanId_, point.parentSpanId_, point.flag_, point.args_); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TRACING_MARK_WRITE, STAT_EVENT_DATA_LOST); + } + break; + } + case 'E': { + streamFilters_->sliceFilter_->EndSlice(ts, pid, point.tgid_); + break; + } + case 'S': { + auto cookie = static_cast(point.value_); + streamFilters_->sliceFilter_->StartAsyncSlice(ts, pid, point.tgid_, cookie, + traceDataCache_->GetDataIndex(point.name_)); + break; + } + case 'F': { + auto cookie = static_cast(point.value_); + streamFilters_->sliceFilter_->FinishAsyncSlice(ts, pid, point.tgid_, cookie, + traceDataCache_->GetDataIndex(point.name_)); + break; + } + case 'C': { + DataIndex nameIndex = traceDataCache_->GetDataIndex(point.name_); + uint32_t internalPid = streamFilters_->processFilter_->GetInternalPid(point.tgid_); + if (internalPid != INVALID_ID) { + streamFilters_->processMeasureFilter_->AppendNewMeasureData(internalPid, nameIndex, ts, point.value_); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TRACING_MARK_WRITE, STAT_EVENT_DATA_INVALID); + } + break; + } + default: + TS_LOGD("point missing!"); + break; + } +} + +ParseResult BytraceEventParser::CheckTracePoint(std::string_view pointStr) const +{ + if (pointStr.size() == 0) { + TS_LOGD("get trace point data size is 0!"); + return ERROR; + } + + std::string clockSyncSts = "trace_event_clock_sync"; + if (pointStr.compare(0, clockSyncSts.length(), clockSyncSts.c_str()) == 0) { + TS_LOGD("skip trace point :%s!", clockSyncSts.c_str()); + return ERROR; + } + + if (pointStr.find_first_of('B') != 0 && pointStr.find_first_of('E') != 0 && pointStr.find_first_of('C') != 0 && + pointStr.find_first_of('S') != 0 && pointStr.find_first_of('F') != 0) { + TS_LOGD("trace point not supported : [%c] !", pointStr[0]); + return ERROR; + } + + if (pointStr.find_first_of('E') != 0 && pointStr.size() == 1) { + TS_LOGD("point string size error!"); + return ERROR; + } + + if (pointStr.size() >= maxPointLength_) { + if ((pointStr[1] != '|') && (pointStr[1] != '\n')) { + TS_LOGD("not support data formart!"); + return ERROR; + } + } + + return SUCCESS; +} + +uint32_t BytraceEventParser::GetThreadGroupId(std::string_view pointStr, size_t& length) const +{ + for (size_t i = maxPointLength_; i < pointStr.size(); i++) { + if (pointStr[i] == '|' || pointStr[i] == '\n') { + break; + } + + if (pointStr[i] < '0' || pointStr[i] > '9') { + return ERROR; + } + + length++; + } + + std::string str(pointStr.data() + maxPointLength_, length); + return base::StrToUInt32(str).value_or(0); +} + +std::string_view BytraceEventParser::GetPointNameForBegin(std::string_view pointStr, size_t tGidlength) const +{ + size_t index = maxPointLength_ + tGidlength + pointLength_; + + size_t length = pointStr.size() - index - ((pointStr.back() == '\n') ? 1 : 0); + std::string_view name = std::string_view(pointStr.data() + index, length); + return name; +} + +ParseResult BytraceEventParser::HandlerB(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const +{ + outPoint.name_ = GetPointNameForBegin(pointStr, tGidlength); + if (outPoint.name_.empty()) { + TS_LOGD("point name is empty!"); + return ERROR; + } + // Use $# to differentiate distributed data + if (outPoint.name_.find("$#") == std::string::npos) { + return SUCCESS; + } + // Resolve distributed calls + const std::regex distributeMatcher = std::regex(R"((?:^\[([a-z0-9]+),(\d+),(\d+)\]:?([CS]?)\$#)?(.*)\$#(.*)$)"); + std::smatch matcheLine; + bool matched = std::regex_match(outPoint.name_, matcheLine, distributeMatcher); + if (matched) { + size_t index = 0; + outPoint.chainId_ = matcheLine[++index].str(); + outPoint.spanId_ = matcheLine[++index].str(); + outPoint.parentSpanId_ = matcheLine[++index].str(); + outPoint.flag_ = matcheLine[++index].str(); + outPoint.name_ = matcheLine[++index].str(); + outPoint.args_ = matcheLine[++index].str(); + } + return SUCCESS; +} + +ParseResult BytraceEventParser::HandlerE(void) const +{ + return SUCCESS; +} + +size_t BytraceEventParser::GetNameLength(std::string_view pointStr, size_t nameIndex) const +{ + size_t namelength = 0; + for (size_t i = nameIndex; i < pointStr.size(); i++) { + if (pointStr[i] == '|') { + namelength = i - nameIndex; + break; + } + } + return namelength; +} + +size_t BytraceEventParser::GetValueLength(std::string_view pointStr, size_t valueIndex) const +{ + size_t valuePipe = pointStr.find('|', valueIndex); + size_t valueLen = pointStr.size() - valueIndex; + if (valuePipe != std::string_view::npos) { + valueLen = valuePipe - valueIndex; + } + + if (valueLen == 0) { + return 0; + } + + if (pointStr[valueIndex + valueLen - pointLength_] == '\n') { + valueLen--; + } + + return valueLen; +} + +ParseResult BytraceEventParser::HandlerCSF(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const +{ + // point name + size_t nameIndex = maxPointLength_ + tGidlength + pointLength_; + size_t namelength = GetNameLength(pointStr, nameIndex); + if (namelength == 0) { + TS_LOGD("point name length is error!"); + return ERROR; + } + outPoint.name_ = std::string_view(pointStr.data() + nameIndex, namelength); + + // point value + size_t valueIndex = nameIndex + namelength + pointLength_; + size_t valueLen = GetValueLength(pointStr, valueIndex); + if (valueLen == 0) { + TS_LOGD("point value length is error!"); + return ERROR; + } + + std::string valueStr(pointStr.data() + valueIndex, valueLen); + if (!base::StrToUInt64(valueStr).has_value()) { + TS_LOGD("point value is error!"); + return ERROR; + } + outPoint.value_ = base::StrToUInt64(valueStr).value(); + + size_t valuePipe = pointStr.find('|', valueIndex); + if (valuePipe != std::string_view::npos) { + size_t groupLen = pointStr.size() - valuePipe - pointLength_; + if (groupLen == 0) { + return ERROR; + } + + if (pointStr[pointStr.size() - pointLength_] == '\n') { + groupLen--; + } + + outPoint.categoryGroup_ = std::string_view(pointStr.data() + valuePipe + 1, groupLen); + } + + return SUCCESS; +} + +ParseResult BytraceEventParser::GetTracePoint(std::string_view pointStr, TracePoint& outPoint) const +{ + if (CheckTracePoint(pointStr) != SUCCESS) { + return ERROR; + } + + size_t tGidlength = 0; + + outPoint.phase_ = pointStr.front(); + outPoint.tgid_ = GetThreadGroupId(pointStr, tGidlength); + + ParseResult ret = ERROR; + switch (outPoint.phase_) { + case 'B': { + ret = HandlerB(pointStr, outPoint, tGidlength); + break; + } + case 'E': { + ret = HandlerE(); + break; + } + case 'S': + case 'F': + case 'C': { + ret = HandlerCSF(pointStr, outPoint, tGidlength); + break; + } + default: + return ERROR; + } + return ret; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.h b/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.h new file mode 100755 index 000000000..d688bb2ac --- /dev/null +++ b/trace_analyzer/src/parser/bytrace_parser/bytrace_event_parser.h @@ -0,0 +1,91 @@ +/* + * 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 SRC_BYTRACE_EVENT_PARSER_H +#define SRC_BYTRACE_EVENT_PARSER_H + +#include + +#include "common_types.h" +#include "event_parser_base.h" +#include "trace_data_cache.h" +#include "trace_streamer_cfg.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +using ArgsMap = std::unordered_map; +class BytraceEventParser : private EventParserBase { +public: + BytraceEventParser(TraceDataCache* dataCache, const TraceStreamerFilters* filter); + bool ParseDataItem(const BytraceLine& line, const ArgsMap& args, uint32_t tgid) const; + +private: + using FuncCall = std::function; + bool SchedSwitchEvent(const ArgsMap& args, const BytraceLine& line) const; + bool TaskRenameEvent(const ArgsMap& args, const BytraceLine& line) const; + bool TaskNewtaskEvent(const ArgsMap& args, const BytraceLine& line) const; + bool TracingMarkWriteEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SchedWakeupEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SchedWakingEvent(const ArgsMap& args, const BytraceLine& line) const; + bool CpuIdleEvent(const ArgsMap& args, const BytraceLine& line) const; + bool CpuFrequencyEvent(const ArgsMap& args, const BytraceLine& line) const; + bool WorkqueueExecuteStartEvent(const ArgsMap& args, const BytraceLine& line) const; + bool WorkqueueExecuteEndEvent(const ArgsMap& args, const BytraceLine& line) const; + bool ProcessExitEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SetRateEvent(const ArgsMap& args, const BytraceLine& line) const; + bool ClockEnableEvent(const ArgsMap& args, const BytraceLine& line) const; + bool ClockDisableEvent(const ArgsMap& args, const BytraceLine& line) const; + bool RegulatorSetVoltageEvent(const ArgsMap& args, const BytraceLine& line) const; + bool RegulatorSetVoltageCompleteEvent(const ArgsMap& args, const BytraceLine& line) const; + bool RegulatorDisableEvent(const ArgsMap& args, const BytraceLine& line) const; + bool RegulatorDisableCompleteEvent(const ArgsMap& args, const BytraceLine& line) const; + bool IpiEntryEvent(const ArgsMap& args, const BytraceLine& line) const; + bool IpiExitEvent(const ArgsMap& args, const BytraceLine& line) const; + bool IrqHandlerEntryEvent(const ArgsMap& args, const BytraceLine& line) const; + bool IrqHandlerExitEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SoftIrqRaiseEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SoftIrqEntryEvent(const ArgsMap& args, const BytraceLine& line) const; + bool SoftIrqExitEvent(const ArgsMap& args, const BytraceLine& line) const; + bool BinderTransactionAllocBufEvent(const ArgsMap& args, const BytraceLine& line) const; + + void ParsePrintEvent(uint64_t ts, uint32_t pid, std::string_view event) const; + void ParseTracePoint(uint64_t ts, uint32_t pid, TracePoint point) const; + ParseResult GetTracePoint(std::string_view str, TracePoint& out) const; + ParseResult CheckTracePoint(std::string_view pointStr) const; + uint32_t GetThreadGroupId(std::string_view pointStr, size_t& length) const; + std::string_view GetPointNameForBegin(std::string_view pointStr, size_t tGidlength) const; + ParseResult HandlerB(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const; + ParseResult HandlerE(void) const; + ParseResult HandlerCSF(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const; + size_t GetNameLength(std::string_view pointStr, size_t nameIndex) const; + size_t GetValueLength(std::string_view pointStr, size_t valueIndex) const; + +private: + const DataIndex ioWaitId_; + const DataIndex workQueueId_; + const DataIndex schedWakeupId_; + const DataIndex schedBlockedReasonId_; + const uint32_t pointLength_; + const uint32_t maxPointLength_; + const int byHex_; + std::map eventToFunctionMap_{}; + const unsigned int MIN_SCHED_ARGS_COUNT = 6; + const unsigned int MIN_SCHED_WAKEUP_ARGS_COUNT = 2; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // SRC_BYTRACE_EVENT_PARSER_H diff --git a/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.cpp b/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.cpp new file mode 100755 index 000000000..bbccc8c10 --- /dev/null +++ b/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.cpp @@ -0,0 +1,279 @@ +/* + * 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 "bytrace_parser.h" +#include +#include "parting_string.h" +#include "stat_filter.h" +namespace SysTuning { +namespace TraceStreamer { +BytraceParser::BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters) + : ParserBase(filters), + eventParser_(std::make_unique(dataCache, filters)), + dataSegArray(new DataSegment[MAX_SEG_ARRAY_SIZE]) +{ +} + +BytraceParser::~BytraceParser() = default; + +void BytraceParser::WaitForParserEnd() +{ + if (matchLineThreadStarted || parsingDataItemThreadStarted_) { + toExit_ = true; + while (!exited_) { + usleep(sleepDur_ * sleepDur_); + } + } +} +void BytraceParser::ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) +{ + if (isParsingOver_) { + return; + } + packagesBuffer_.insert(packagesBuffer_.end(), &bufferStr[0], &bufferStr[size]); + auto packagesBegin = packagesBuffer_.begin(); + + while (1) { + auto packagesLine = std::find(packagesBegin, packagesBuffer_.end(), '\n'); + if (packagesLine == packagesBuffer_.end()) { + break; + } + + std::string bufferLine(packagesBegin, packagesLine); + + if (IsTraceComment(bufferLine)) { + traceCommentLines_++; + goto NEXT_LINE; + } + if (bufferLine.empty()) { + parsedTraceInvalidLines_++; + goto NEXT_LINE; + } + + if (bufferLine.find(script_.c_str()) != std::string::npos) { + isParsingOver_ = true; + break; + } + ParseTraceDataItem(bufferLine); + + NEXT_LINE: + packagesBegin = packagesLine + 1; + continue; + } + + if (isParsingOver_) { + packagesBuffer_.clear(); + } else { + packagesBuffer_.erase(packagesBuffer_.begin(), packagesBegin); + } + return; +} + +void BytraceParser::ParseTraceDataItem(const std::string& buffer) +{ + while (!toExit_) { + int head = seprateHead_; + if (dataSegArray[head].status.load() != Status_Init) { + TS_LOGD("seprateHead_:\t%d, matchHead_:\t%d, parseHead_:\t%d\n", seprateHead_, matchHead_, parseHead_); + usleep(sleepDur_); + continue; + } + dataSegArray[head].seg = std::move(buffer); + dataSegArray[head].status = Status_Seprated; + seprateHead_ = (seprateHead_ + 1) % MAX_SEG_ARRAY_SIZE; + break; + } + if (!matchLineThreadStarted) { + matchLineThreadStarted = true; + int tmp = maxThread_; + while (tmp--) { + parserThreadCount_++; + std::thread MatchLineThread(&BytraceParser::MatchLine, this); + MatchLineThread.detach(); + fprintf(stdout, "parser Thread:%d/%d start working ...\n", maxThread_ - tmp, maxThread_); + } + } + return; +} +int BytraceParser::GetNextSegment() +{ + int head; + dataSegMux_.lock(); + head = matchHead_; + DataSegment& seg = dataSegArray[head]; + if (seg.status.load() != Status_Seprated) { + if (toExit_) { + parserThreadCount_--; + fprintf(stdout, "exiting parser, parserThread Count:%d\n", parserThreadCount_); + dataSegMux_.unlock(); + if (!parserThreadCount_ && !parsingDataItemThreadStarted_) { + exited_ = true; + } + return ERROR_CODE_EXIT; + } + if (seg.status == Status_Parsing) { + matchHead_ = (matchHead_ + 1) % MAX_SEG_ARRAY_SIZE; + dataSegMux_.unlock(); + return ERROR_CODE_NODATA; + } + dataSegMux_.unlock(); + TS_LOGD("MatchLine watting:\t%d, matchHead_:\t%d, parseHead_:\t%d\n", seprateHead_, matchHead_, parseHead_); + usleep(sleepDur_); + return ERROR_CODE_NODATA; + } + matchHead_ = (matchHead_ + 1) % MAX_SEG_ARRAY_SIZE; + seg.status = Status_Parsing; + dataSegMux_.unlock(); + return head; +} + +void BytraceParser::GetDataSegAttr(DataSegment& seg, const std::smatch& matcheLine) const +{ + size_t index = 0; + std::string pidStr = matcheLine[++index].str(); + std::optional optionalPid = base::StrToUInt32(pidStr); + if (!optionalPid.has_value()) { + TS_LOGD("Illegal pid: %s", pidStr.c_str()); + seg.status = Status_Invalid; + return; + } + + std::string tGidStr = matcheLine[++index].str(); + std::string cpuStr = matcheLine[++index].str(); + std::optional optionalCpu = base::StrToUInt32(cpuStr); + if (!optionalCpu.has_value()) { + TS_LOGD("Illegal cpu %s", cpuStr.c_str()); + seg.status = Status_Invalid; + return; + } + std::string timeStr = matcheLine[++index].str(); + std::optional optionalTime = base::StrToDouble(timeStr); + if (!optionalTime.has_value()) { + TS_LOGD("Illegal ts %s", timeStr.c_str()); + seg.status = Status_Invalid; + return; + } + std::string eventName = matcheLine[++index].str(); + seg.bufLine.task = StrTrim(matcheLine.prefix()); + seg.bufLine.argsStr = StrTrim(matcheLine.suffix()); + seg.bufLine.pid = optionalPid.value(); + seg.bufLine.cpu = optionalCpu.value(); + seg.bufLine.ts = static_cast(optionalTime.value() * 1e9); + seg.bufLine.tGidStr = tGidStr; + seg.bufLine.eventName = eventName; + GetDataSegArgs(seg); + seg.status = Status_Parsed; +} + +void BytraceParser::GetDataSegArgs(DataSegment& seg) const +{ + seg.args.clear(); + if (!seg.bufLine.tGidStr.empty() && seg.bufLine.tGidStr != "-----") { + seg.tgid = base::StrToUInt32(seg.bufLine.tGidStr).value_or(0); + } + + for (base::PartingString ss(seg.bufLine.argsStr, ' '); ss.Next();) { + std::string key; + std::string value; + if (!(std::string(ss.GetCur()).find("=") != std::string::npos)) { + key = "name"; + value = ss.GetCur(); + seg.args.emplace(std::move(key), std::move(value)); + continue; + } + for (base::PartingString inner(ss.GetCur(), '='); inner.Next();) { + if (key.empty()) { + key = inner.GetCur(); + } else { + value = inner.GetCur(); + } + } + seg.args.emplace(std::move(key), std::move(value)); + } +} +void BytraceParser::MatchLine() +{ + while (1) { + int head = GetNextSegment(); + if (head < 0) { + if (head == ERROR_CODE_NODATA) { + continue; + } + matchLineThreadStarted = false; + if (!parsingDataItemThreadStarted_) { + exited_ = true; + } + return; + } + DataSegment& seg = dataSegArray[head]; + std::smatch matcheLine; + if (!std::regex_search(seg.seg, matcheLine, bytraceMatcher_)) { + TS_LOGD("Not support this event (line: %s)", seg.seg.c_str()); + seg.status = Status_Invalid; + parsedTraceInvalidLines_++; + continue; + } else { + parsedTraceValidLines_++; + } + GetDataSegAttr(seg, matcheLine); + if (!parsingDataItemThreadStarted_) { + parsingDataItemThreadStarted_ = true; + std::thread ParserThread(&BytraceParser::ParseLine, this); + ParserThread.detach(); + } + } +} +void BytraceParser::ParseLine() +{ + while (1) { + DataSegment& seg = dataSegArray[parseHead_]; + if (seg.status.load() == Status_Invalid) { + seg.status = Status_Init; + parseHead_ = (parseHead_ + 1) % MAX_SEG_ARRAY_SIZE; + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_INVALID); + continue; + } + if (seg.status.load() != Status_Parsed) { + if (toExit_ && !parserThreadCount_) { + fprintf(stdout, "exiting ParseLine Thread\n"); + exited_ = true; + parsingDataItemThreadStarted_ = false; + return; + } + usleep(sleepDur_); + continue; + } + BytraceLine line = seg.bufLine; + uint32_t tgid = seg.tgid; + eventParser_->ParseDataItem(line, seg.args, tgid); + parseHead_ = (parseHead_ + 1) % MAX_SEG_ARRAY_SIZE; + seg.status = Status_Init; + } +} + +// Remove space at the beginning and end of the string +std::string BytraceParser::StrTrim(const std::string& input) const +{ + std::string str = input; + auto posBegin = std::find_if(str.begin(), str.end(), IsNotSpace); + str.erase(str.begin(), posBegin); + + auto posEnd = std::find_if(str.rbegin(), str.rend(), IsNotSpace); + str.erase(posEnd.base(), str.end()); + + return str; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.h b/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.h new file mode 100755 index 000000000..da3c7e18b --- /dev/null +++ b/trace_analyzer/src/parser/bytrace_parser/bytrace_parser.h @@ -0,0 +1,100 @@ +/* + * 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 BYTRACE_PARSER_H +#define BYTRACE_PARSER_H + +#include +#include +#include +#include + +#include "bytrace_event_parser.h" +#include "log.h" +#include "parser_base.h" +#include "string_to_numerical.h" +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +class BytraceParser : public ParserBase { +public: + BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); + ~BytraceParser(); + + void ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) override; + size_t ParsedTraceValidLines() + { + return parsedTraceValidLines_; + } + size_t ParsedTraceInvalidLines() + { + return parsedTraceInvalidLines_; + } + size_t TraceCommentLines() + { + return traceCommentLines_; + } + void WaitForParserEnd(); + +private: + enum ErrorCode { ERROR_CODE_EXIT = -2, ERROR_CODE_NODATA = -1 }; + int GetNextSegment(); + void GetDataSegAttr(DataSegment& seg, const std::smatch& matcheLine) const; + void GetDataSegArgs(DataSegment& seg) const; + void ParseLine(); + inline static bool IsNotSpace(char c) + { + return !std::isspace(c); + } + inline static bool IsTraceComment(const std::string& buffer) + { + return ((buffer[0] == '#') || buffer.find("TASK-PID") != std::string::npos); + } + + void ParseTraceDataItem(const std::string& buffer) override; + std::string StrTrim(const std::string& input) const; + void MatchLine(); + +private: + using ArgsMap = std::unordered_map; + bool isParsingOver_ = false; + std::unique_ptr eventParser_; + const std::regex bytraceMatcher_ = std::regex(R"(-(\d+)\s+\(?\s*(\d+|-+)?\)?\s?\[(\d+)\]\s*)" + R"([a-zA-Z0-9.]{0,5}\s+(\d+\.\d+):\s+(\S+):)"); + + const std::string script_ = R"()"; + + size_t parsedTraceValidLines_ = 0; + size_t parsedTraceInvalidLines_ = 0; + size_t traceCommentLines_ = 0; + std::mutex dataSegMux_; + int matchHead_ = 0; + std::atomic parsingDataItemThreadStarted_{false}; + bool matchLineThreadStarted = false; + const int MAX_SEG_ARRAY_SIZE = 5000; + const int maxThread_ = 4; // 4 is the best on ubuntu 113MB/s, max 138MB/s, 6 is best on mac m1 21MB/s, + int parserThreadCount_ = 0; + bool toExit_ = false; + bool exited_ = false; + std::unique_ptr dataSegArray; + int seprateHead_ = 0; + int parseHead_ = 0; + const int sleepDur_ = 100; +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif // _BYTRACE_PARSER_H_ diff --git a/trace_analyzer/src/parser/common_types.h b/trace_analyzer/src/parser/common_types.h index d48a2effd..a53f530e6 100755 --- a/trace_analyzer/src/parser/common_types.h +++ b/trace_analyzer/src/parser/common_types.h @@ -16,7 +16,12 @@ #ifndef BYTRACE_COMMON_TYPES_H #define BYTRACE_COMMON_TYPES_H +#include #include +#include +#include "services/common_types.pb.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" +#include "types/plugins/memory_data/memory_plugin_result.pb.h" namespace SysTuning { namespace TraceStreamer { @@ -37,7 +42,6 @@ enum Stat : uint32_t { PARKED = 512, NOLOAD = 1024, TASKNEW = 2048, - MAXSTAT = 2048, VALID = 0X8000, }; @@ -52,13 +56,32 @@ struct BytraceLine { std::string eventName; std::string argsStr; }; - +enum ParseStatus { + Status_Init = 0, + Status_Seprated = 1, + Status_Parsing = 2, + Status_Parsed = 3, + Status_Invalid = 4 +}; +struct DataSegment { + std::string seg; + BytraceLine bufLine; + std::unordered_map args; + uint32_t tgid; + std::atomic status{Status_Init}; +}; struct TracePoint { char phase_ = '\0'; uint32_t tgid_ = 0; - std::string name_; - double value_ = 0; - std::string categoryGroup_; + std::string name_ = ""; + uint64_t value_ = 0; + std::string categoryGroup_ = ""; + // Distributed Data + std::string chainId_ = ""; + std::string spanId_ = ""; + std::string parentSpanId_ = ""; + std::string flag_ = ""; + std::string args_ = ""; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/parser/event_parser.cpp b/trace_analyzer/src/parser/event_parser.cpp deleted file mode 100755 index 3b3d3bab6..000000000 --- a/trace_analyzer/src/parser/event_parser.cpp +++ /dev/null @@ -1,612 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "event_parser.h" -#include -#include - -#include "cpu_filter.h" -#include "event_filter.h" -#include "filter_filter.h" -#include "measure_filter.h" -#include "parting_string.h" -#include "process_filter.h" -#include "slice_filter.h" -#include "string_to_numerical.h" -#include "thread_state.h" - -namespace SysTuning { -namespace TraceStreamer { -namespace { -std::string GetFunctionName(const std::string_view& text, const std::string_view& delimiter) -{ - std::string str(""); - if (delimiter.empty()) { - return str; - } - - std::size_t foundIndex = text.find(delimiter); - if (foundIndex != std::string::npos) { - std::size_t funIndex = foundIndex + delimiter.size(); - str = std::string(text.substr(funIndex, text.size() - funIndex)); - } - return str; -} -} // namespace - -EventParser::EventParser(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : streamFilters_(filter), - ioWaitId_(dataCache->GetDataIndex("io_wait")), - workQueueId_(dataCache->GetDataIndex("workqueue")), - schedWakeupId_(dataCache->GetDataIndex("sched_wakeup")), - schedBlockedReasonId_(dataCache->GetDataIndex("sched_blocked_reason")), - binderId_(dataCache->GetDataIndex("binder")), - pointLength_(1), - maxPointLength_(2), - byHex_(16), - traceDataCache_(dataCache) -{ - eventToFunction_ = { - {"binder_transaction", - bind(&EventParser::BinderTransactionEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"binder_transaction_received", - bind(&EventParser::BinderTransactionReceivedEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"binder_lock", bind(&EventParser::BinderLockEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"binder_locked", bind(&EventParser::BinderLockedEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"binder_unlock", bind(&EventParser::BinderUnLockEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"binder_transaction_alloc_buf", - bind(&EventParser::BinderTransactionAllocBufEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"sched_switch", bind(&EventParser::SchedSwitchEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"task_rename", bind(&EventParser::TaskRenameEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"task_newtask", bind(&EventParser::TaskNewtaskEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"tracing_mark_write", - bind(&EventParser::TracingMarkWriteEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"0", bind(&EventParser::TracingMarkWriteEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"print", bind(&EventParser::TracingMarkWriteEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"sched_wakeup", bind(&EventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"sched_waking", bind(&EventParser::SchedWakingEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"cpu_idle", bind(&EventParser::CpuIdleEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"cpu_frequency", bind(&EventParser::CpuFrequencyEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"workqueue_execute_start", - bind(&EventParser::WorkqueueExecuteStartEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {"workqueue_execute_end", - bind(&EventParser::WorkqueueExecuteEndEvent, this, std::placeholders::_1, std::placeholders::_2)} - }; -} - -bool EventParser::BinderTransactionEvent(ArgsMap args, const BytraceLine line) const -{ - auto transId = base::StrToInt32(args["transaction"]); - if (!transId.has_value()) { - TUNING_LOGD("Failed to convert transaction id"); - return false; - } - auto destNode = base::StrToInt32(args["dest_node"]); - if (!destNode.has_value()) { - TUNING_LOGD("Failed to convert dest_node"); - return false; - } - auto destTgid = base::StrToInt32(args["dest_proc"]); - if (!destTgid.has_value()) { - TUNING_LOGD("Failed to convert dest_tgid"); - return false; - } - auto destTid = base::StrToInt32(args["dest_thread"]); - if (!destTid.has_value()) { - TUNING_LOGD("Failed to convert dest_tid"); - return false; - } - - auto isReply = (base::StrToInt32(args["reply"]).value() == 1); - uint32_t flags = base::StrToUInt32(args["flags"], byHex_).value(); - - std::string codeStr = args["code"] + " Java Layer Dependent"; - DataIndex code = traceDataCache_->GetDataIndex(std::string_view(codeStr)); - - struct BinderParamter binderParamter; - binderParamter.ts = line.ts; - binderParamter.tid = line.pid; - binderParamter.transactionId = transId.value(); - binderParamter.destNode = destNode.value(); - binderParamter.destTgid = destTgid.value(); - binderParamter.destTid = destTid.value(); - binderParamter.isReply = isReply; - binderParamter.flags = flags; - binderParamter.code = code; - binderParamter.nameIndex = traceDataCache_->GetDataIndex(line.eventName.c_str()); - - streamFilters_->eventFilter_->BinderTransaction(binderParamter); - return true; -} - -bool EventParser::BinderTransactionReceivedEvent(ArgsMap args, const BytraceLine line) const -{ - auto transId = base::StrToInt32(args["transaction"]); - if (!transId.has_value()) { - TUNING_LOGD("Failed to convert transaction id"); - return false; - } - - streamFilters_->eventFilter_->BinderTransactionReceived(line.ts, line.pid, transId.value()); - return true; -} - -bool EventParser::BinderLockEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - UNUSED(line); - return true; -} - -bool EventParser::BinderLockedEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - UNUSED(line); - return true; -} - -bool EventParser::BinderUnLockEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - UNUSED(line); - return true; -} - -bool EventParser::BinderTransactionAllocBufEvent(ArgsMap args, const BytraceLine line) const -{ - auto dataSize = base::StrToUInt64(args["data_size"]); - if (!dataSize.has_value()) { - TUNING_LOGD("Failed to parse data_size"); - return false; - } - auto offsetsSize = base::StrToUInt64(args["offsets_size"]); - if (!offsetsSize.has_value()) { - TUNING_LOGD("Failed to parse offsets_size"); - return false; - } - - UNUSED(line); - return true; -} - -bool EventParser::SchedSwitchEvent(ArgsMap args, const BytraceLine line) const -{ - auto prevCommStr = std::string_view(args["prev_comm"]); - auto nextCommStr = std::string_view(args["next_comm"]); - auto prevPrioValue = base::StrToInt32(args["prev_prio"]); - auto nextPrioValue = base::StrToInt32(args["next_prio"]); - auto prevPidValue = base::StrToUInt32(args["prev_pid"]); - auto nextPidValue = base::StrToUInt32(args["next_pid"]); - if (!(prevPidValue.has_value() && prevPrioValue.has_value() && nextPidValue.has_value() && - nextPrioValue.has_value())) { - TUNING_LOGD("Failed to parse sched_switch event"); - return false; - } - - auto prevStateStr = args["prev_state"]; - uint64_t prevState = ThreadState(prevStateStr.c_str()).State(); - streamFilters_->eventFilter_->UpdateSchedSwitch(line.cpu, line.ts, prevPidValue.value(), - nextPidValue.value(), nextCommStr); - auto unexttid = streamFilters_->processFilter_->UpdateThreadByName(line.ts, nextPidValue.value(), nextCommStr); - auto uprevtid = streamFilters_->processFilter_->UpdateThreadByName(line.ts, prevPidValue.value(), prevCommStr); - streamFilters_->cpuFilter_->InsertSwitchEvent(line.ts, line.cpu, uprevtid, - static_cast(prevPrioValue.value()), prevState, unexttid, - static_cast(nextPrioValue.value())); - return true; -} - -bool EventParser::TaskRenameEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(line); - auto prevCommStr = std::string_view(args["newcomm"]); - auto pidValue = base::StrToUInt32(args["pid"]); - streamFilters_->processFilter_->UpdateProcess(pidValue.value(), prevCommStr); - return true; -} - -bool EventParser::TaskNewtaskEvent(ArgsMap args, const BytraceLine line) const -{ - auto commonStr = std::string_view(args["comm"]); - auto pidValue = base::StrToUInt32(args["pid"]); - - uint32_t ftracePid = 0; - if (!line.tGidStr.empty() && line.tGidStr != "-----") { - std::optional tgid = base::StrToUInt32(line.tGidStr); - if (tgid) { - ftracePid = tgid.value(); - } - } - - static const uint32_t threadPid = 2; - static const uint32_t cloneThread = 0x00010000; - auto cloneFlags = base::StrToUInt64(args["clone_flags"], byHex_).value(); - if ((cloneFlags & cloneThread) == 0 && ftracePid != threadPid) { - streamFilters_->processFilter_->UpdateProcess(static_cast(pidValue.value()), commonStr); - } else if (ftracePid == threadPid) { - streamFilters_->processFilter_->SetThreadPid(static_cast(pidValue.value()), threadPid); - } - return true; -} - -bool EventParser::TracingMarkWriteEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - ParsePrintEvent(line.ts, line.pid, line.argsStr.c_str()); - return true; -} - -bool EventParser::SchedWakeupEvent(ArgsMap args, const BytraceLine line) const -{ - std::optional wakePidValue = base::StrToUInt32(args["pid"]); - if (!wakePidValue.has_value()) { - TUNING_LOGD("Failed to convert wake_pid"); - return false; - } - DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_wakeup")); - auto* instants = traceDataCache_->GetInstantsData(); - InternalTid internalTid = streamFilters_->processFilter_->SetThreadPid(line.ts, line.pid, 0); - instants->AppendInstantEventData(line.ts, name, internalTid); - std::optional targetCpu = base::StrToUInt32(args["target_cpu"]); - if (targetCpu.has_value()) { - traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKEUP, targetCpu.value(), internalTid); - } - return true; -} - -bool EventParser::SchedWakingEvent(ArgsMap args, const BytraceLine line) const -{ - std::optional wakePidValue = base::StrToUInt32(args["pid"]); - if (!wakePidValue.has_value()) { - TUNING_LOGD("Failed to convert wake_pid"); - return false; - } - DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_waking")); - auto* instants = traceDataCache_->GetInstantsData(); - InternalTid internalTid = streamFilters_->processFilter_->SetThreadPid(line.ts, line.pid, 0); - instants->AppendInstantEventData(line.ts, name, internalTid); - streamFilters_->cpuFilter_->InsertWakeingEvent(line.ts, internalTid); - std::optional targetCpu = base::StrToUInt32(args["target_cpu"]); - if (targetCpu.has_value()) { - traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKING, targetCpu.value(), internalTid); - } - return true; -} - -bool EventParser::CpuIdleEvent(ArgsMap args, const BytraceLine line) const -{ - std::optional eventCpuValue = base::StrToUInt32(args["cpu_id"]); - std::optional newStateValue = base::StrToDouble(args["state"]); - if (!eventCpuValue.has_value()) { - TUNING_LOGD("Failed to convert event cpu"); - return false; - } - if (!newStateValue.has_value()) { - TUNING_LOGD("Failed to convert state"); - return false; - } - auto cpuIdleNameIndex = traceDataCache_->GetDataIndex(line.eventName.c_str()); - uint32_t filterId = - streamFilters_->cpuCounterFilter_->GetOrCreateCertainFilterId(eventCpuValue.value(), cpuIdleNameIndex); - traceDataCache_->GetCounterData()->AppendCounterData(0, line.ts, newStateValue.value(), filterId); - traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_CPU_IDLE, eventCpuValue.value(), 0); - return true; -} - -bool EventParser::CpuFrequencyEvent(ArgsMap args, const BytraceLine line) const -{ - std::optional newStateValue = base::StrToDouble(args["state"]); - std::optional eventCpuValue = base::StrToUInt32(args["cpu_id"]); - - if (!newStateValue.has_value()) { - TUNING_LOGD("Failed to convert state"); - return false; - } - if (!eventCpuValue.has_value()) { - TUNING_LOGD("Failed to convert event cpu"); - return false; - } - - auto cpuidleNameIndex = traceDataCache_->GetDataIndex(line.eventName.c_str()); - uint32_t filterId = - streamFilters_->cpuCounterFilter_->GetOrCreateCertainFilterId(eventCpuValue.value(), cpuidleNameIndex); - traceDataCache_->GetCounterData()->AppendCounterData(0, line.ts, newStateValue.value(), filterId); - return true; -} - -bool EventParser::WorkqueueExecuteStartEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - auto splitStr = GetFunctionName(line.argsStr, "function "); - DataIndex nameIndex = traceDataCache_->GetDataIndex(std::string_view(splitStr)); - streamFilters_->sliceFilter_->BeginSlice(line.ts, line.pid, line.pid, workQueueId_, nameIndex); - return true; -} - -bool EventParser::WorkqueueExecuteEndEvent(ArgsMap args, const BytraceLine line) const -{ - UNUSED(args); - streamFilters_->sliceFilter_->EndSlice(line.ts, line.pid, line.pid); - return true; -} - -bool EventParser::ParseLine(const BytraceLine& line) const -{ - ArgsMap args; - traceDataCache_->UpdateBoundTime(line.ts); - if (!line.tGidStr.empty() && line.tGidStr != "-----") { - std::optional tgid = base::StrToUInt32(line.tGidStr); - if (tgid) { - streamFilters_->processFilter_->SetThreadPid(line.pid, tgid.value()); - streamFilters_->processFilter_->SetThreadName(line.pid, tgid.value_or(0), std::string_view(line.task)); - } - } - - for (base::PartingString ss(line.argsStr, ' '); ss.Next();) { - std::string key; - std::string value; - if (!(std::string(ss.GetCur()).find("=") != std::string::npos)) { - key = "name"; - value = ss.GetCur(); - args.emplace(std::move(key), std::move(value)); - continue; - } - for (base::PartingString inner(ss.GetCur(), '='); inner.Next();) { - if (key.empty()) { - key = inner.GetCur(); - } else { - value = inner.GetCur(); - } - } - args.emplace(std::move(key), std::move(value)); - } - - auto it = eventToFunction_.find(line.eventName); - if (it != eventToFunction_.end()) { - return it->second(args, line); - } - return true; -} - -void EventParser::ParsePrintEvent(uint64_t ts, uint32_t pid, std::string_view event) const -{ - TracePoint point; - if (GetTracePoint(event, point) == SUCCESS) { - ParseTracePoint(ts, pid, point); - } -} - -void EventParser::ParseTracePoint(uint64_t ts, uint32_t pid, TracePoint point) const -{ - switch (point.phase_) { - case 'B': { - DataIndex nameIndex = traceDataCache_->GetDataIndex(point.name_); - streamFilters_->sliceFilter_->BeginSlice(ts, pid, point.tgid_, 0, nameIndex); - break; - } - case 'E': { - streamFilters_->sliceFilter_->EndSlice(ts, pid, point.tgid_); - break; - } - case 'S': { - DataIndex nameIndex = traceDataCache_->GetDataIndex(point.name_); - auto cookie = static_cast(point.value_); - streamFilters_->sliceFilter_->AsyncBeginSlice(ts, pid, point.tgid_, cookie, nameIndex); - break; - } - case 'F': { - auto cookie = static_cast(point.value_); - streamFilters_->sliceFilter_->AsyncEndSlice(ts, pid, cookie); - break; - } - case 'C': { - if (point.name_ == "ScreenState") { - return; - } - - DataIndex nameIndex = traceDataCache_->GetDataIndex(point.name_); - uint32_t internalPid = streamFilters_->processFilter_->UpdateProcess(point.tgid_, point.name_); - auto filterId = streamFilters_->processCounterFilter_->GetOrCreateCertainFilterId(internalPid, nameIndex); - traceDataCache_->GetCounterData()->AppendCounterData(0, ts, point.value_, filterId); - break; - } - default: - TUNING_LOGD("point missing!"); - break; - } -} - -ParseResult EventParser::CheckTracePoint(std::string_view pointStr) const -{ - if (pointStr.size() == 0) { - TUNING_LOGD("get trace point data size is 0!"); - return ERROR; - } - - std::string clockSyncSts = "trace_event_clock_sync"; - if (pointStr.compare(0, clockSyncSts.length(), clockSyncSts.c_str()) == 0) { - TUNING_LOGD("skip trace point :%s!", clockSyncSts.c_str()); - return ERROR; - } - - if (pointStr.find_first_of('B') != 0 && pointStr.find_first_of('E') != 0 && pointStr.find_first_of('C') != 0 && - pointStr.find_first_of('S') != 0 && pointStr.find_first_of('F') != 0) { - TUNING_LOGD("trace point not supported : [%c] !", pointStr[0]); - return ERROR; - } - - if (pointStr.find_first_of('E') != 0 && pointStr.size() == 1) { - TUNING_LOGD("point string size error!"); - return ERROR; - } - - if (pointStr.size() >= maxPointLength_) { - if ((pointStr[1] != '|') && (pointStr[1] != '\n')) { - TUNING_LOGD("not support data formart!"); - return ERROR; - } - } - - return SUCCESS; -} - -uint32_t EventParser::GetThreadGroupId(std::string_view pointStr, size_t& length) const -{ - for (size_t i = maxPointLength_; i < pointStr.size(); i++) { - if (pointStr[i] == '|' || pointStr[i] == '\n') { - break; - } - - if (pointStr[i] < '0' || pointStr[i] > '9') { - return ERROR; - } - - length++; - } - - std::string str(pointStr.data() + maxPointLength_, length); - return base::StrToUInt32(str).value_or(0); -} - -std::string_view EventParser::GetPointNameForBegin(std::string_view pointStr, size_t tGidlength) const -{ - size_t index = maxPointLength_ + tGidlength + pointLength_; - size_t length = pointStr.size() - index - ((pointStr.back() == '\n') ? 1 : 0); - std::string_view name = std::string_view(pointStr.data() + index, length); - return name; -} - -ParseResult EventParser::HandlerB(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const -{ - outPoint.name_ = GetPointNameForBegin(pointStr, tGidlength); - if (outPoint.name_.empty()) { - TUNING_LOGD("point name is empty!"); - return ERROR; - } - return SUCCESS; -} - -ParseResult EventParser::HandlerE(void) const -{ - return SUCCESS; -} - -size_t EventParser::GetNameLength(std::string_view pointStr, size_t nameIndex) const -{ - size_t namelength = 0; - for (size_t i = nameIndex; i < pointStr.size(); i++) { - if (pointStr[i] == '|') { - namelength = i - nameIndex; - break; - } - } - return namelength; -} - -size_t EventParser::GetValueLength(std::string_view pointStr, size_t valueIndex) const -{ - size_t valuePipe = pointStr.find('|', valueIndex); - size_t valueLen = pointStr.size() - valueIndex; - if (valuePipe != std::string_view::npos) { - valueLen = valuePipe - valueIndex; - } - - if (valueLen == 0) { - return 0; - } - - if (pointStr[valueIndex + valueLen - pointLength_] == '\n') { - valueLen--; - } - - return valueLen; -} - -ParseResult EventParser::HandlerCSF(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const -{ - // point name - size_t nameIndex = maxPointLength_ + tGidlength + pointLength_; - size_t namelength = GetNameLength(pointStr, nameIndex); - if (namelength == 0) { - TUNING_LOGD("point name length is error!"); - return ERROR; - } - outPoint.name_ = std::string_view(pointStr.data() + nameIndex, namelength); - - // point value - size_t valueIndex = nameIndex + namelength + pointLength_; - size_t valueLen = GetValueLength(pointStr, valueIndex); - if (valueLen == 0) { - TUNING_LOGD("point value length is error!"); - return ERROR; - } - - std::string valueStr(pointStr.data() + valueIndex, valueLen); - if (!base::StrToDouble(valueStr).has_value()) { - TUNING_LOGD("point value is error!"); - return ERROR; - } - outPoint.value_ = base::StrToDouble(valueStr).value(); - - size_t valuePipe = pointStr.find('|', valueIndex); - if (valuePipe != std::string_view::npos) { - size_t groupLen = pointStr.size() - valuePipe - pointLength_; - if (groupLen == 0) { - return ERROR; - } - - if (pointStr[pointStr.size() - pointLength_] == '\n') { - groupLen--; - } - - outPoint.categoryGroup_ = std::string_view(pointStr.data() + valuePipe + 1, groupLen); - } - - return SUCCESS; -} - -ParseResult EventParser::GetTracePoint(std::string_view pointStr, TracePoint& outPoint) const -{ - if (CheckTracePoint(pointStr) != SUCCESS) { - return ERROR; - } - - size_t tGidlength = 0; - - outPoint.phase_ = pointStr.front(); - outPoint.tgid_ = GetThreadGroupId(pointStr, tGidlength); - - ParseResult ret = ERROR; - switch (outPoint.phase_) { - case 'B': { - ret = HandlerB(pointStr, outPoint, tGidlength); - break; - } - case 'E': { - ret = HandlerE(); - break; - } - case 'S': - case 'F': - case 'C': { - ret = HandlerCSF(pointStr, outPoint, tGidlength); - break; - } - default: - return ERROR; - } - return ret; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/parser/event_parser.h b/trace_analyzer/src/parser/event_parser.h deleted file mode 100755 index 82f29cdf8..000000000 --- a/trace_analyzer/src/parser/event_parser.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SRC_EVENT_PARSER_H -#define SRC_EVENT_PARSER_H - -#include - -#include "common_types.h" -#include "trace_data_cache.h" -#include "trace_streamer_filters.h" - -namespace SysTuning { -namespace TraceStreamer { -class EventParser { -public: - explicit EventParser(TraceDataCache*, const TraceStreamerFilters*); - bool ParseLine(const BytraceLine&) const; - -private: - const TraceStreamerFilters *streamFilters_; - const DataIndex ioWaitId_; - const DataIndex workQueueId_; - const DataIndex schedWakeupId_; - const DataIndex schedBlockedReasonId_; - const DataIndex binderId_; - const uint32_t pointLength_; - const uint32_t maxPointLength_; - const int byHex_; - - using ArgsMap = std::unordered_map; - using FuncCall = std::function; - std::map eventToFunction_ {}; - - bool BinderTransactionEvent(ArgsMap args, const BytraceLine line) const; - bool BinderTransactionReceivedEvent(ArgsMap args, const BytraceLine line) const; - bool BinderLockEvent(ArgsMap args, const BytraceLine line) const; - bool BinderLockedEvent(ArgsMap args, const BytraceLine line) const; - bool BinderUnLockEvent(ArgsMap args, const BytraceLine line) const; - bool BinderTransactionAllocBufEvent(ArgsMap args, const BytraceLine line) const; - bool SchedSwitchEvent(ArgsMap args, const BytraceLine line) const; - bool TaskRenameEvent(ArgsMap args, const BytraceLine line) const; - bool TaskNewtaskEvent(ArgsMap args, const BytraceLine line) const; - bool TracingMarkWriteEvent(ArgsMap args, const BytraceLine line) const; - bool SchedWakeupEvent(ArgsMap args, const BytraceLine line) const; - bool SchedWakingEvent(ArgsMap args, const BytraceLine line) const; - bool CpuIdleEvent(ArgsMap args, const BytraceLine line) const; - bool CpuFrequencyEvent(ArgsMap args, const BytraceLine line) const; - bool WorkqueueExecuteStartEvent(ArgsMap args, const BytraceLine line) const; - bool WorkqueueExecuteEndEvent(ArgsMap args, const BytraceLine line) const; - - void ParsePrintEvent(uint64_t ts, uint32_t pid, std::string_view event) const; - void ParseTracePoint(uint64_t ts, uint32_t pid, TracePoint point) const; - ParseResult GetTracePoint(std::string_view str, TracePoint& out) const; - ParseResult CheckTracePoint(std::string_view pointStr) const; - uint32_t GetThreadGroupId(std::string_view pointStr, size_t& length) const; - std::string_view GetPointNameForBegin(std::string_view pointStr, size_t tGidlength) const; - ParseResult HandlerB(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const; - ParseResult HandlerE(void) const; - ParseResult HandlerCSF(std::string_view pointStr, TracePoint& outPoint, size_t tGidlength) const; - size_t GetNameLength(std::string_view pointStr, size_t nameIndex) const; - size_t GetValueLength(std::string_view pointStr, size_t valueIndex) const; -private: - TraceDataCache *traceDataCache_; -}; -} // namespace TraceStreamer -} // namespace SysTuning - -#endif // _EVENT_PARSER_H_ diff --git a/trace_analyzer/src/parser/event_parser_base.cpp b/trace_analyzer/src/parser/event_parser_base.cpp new file mode 100644 index 000000000..a4bdbf4f5 --- /dev/null +++ b/trace_analyzer/src/parser/event_parser_base.cpp @@ -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. + */ + +#include "event_parser_base.h" +namespace SysTuning { +namespace TraceStreamer { +EventParserBase::EventParserBase(TraceDataCache* dataCache, const TraceStreamerFilters* filter) + : streamFilters_(filter), traceDataCache_(dataCache) +{ +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/event_parser_base.h b/trace_analyzer/src/parser/event_parser_base.h new file mode 100644 index 000000000..c4021a288 --- /dev/null +++ b/trace_analyzer/src/parser/event_parser_base.h @@ -0,0 +1,38 @@ +/* + * 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 SRC_EVENT_PARSER_BASE_H +#define SRC_EVENT_PARSER_BASE_H +#include "trace_data_cache.h" +#include "trace_streamer_cfg.h" +#include "trace_streamer_filters.h" +namespace SysTuning { +namespace TraceStreamer { +using namespace SysTuning::TraceCfg; +class EventParserBase { +public: + EventParserBase(TraceDataCache* dataCache, const TraceStreamerFilters* filter); + +public: + const TraceStreamerFilters* streamFilters_; + TraceDataCache* traceDataCache_; + +protected: + TraceStreamConfig config_; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // SRC_PARSER_BASE_H diff --git a/trace_analyzer/src/parser/htrace_parser/BUILD.gn b/trace_analyzer/src/parser/htrace_parser/BUILD.gn new file mode 100644 index 000000000..9a6febcf2 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/BUILD.gn @@ -0,0 +1,70 @@ +# 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("//build/ohos.gni") +import("../../ts.gni") +ohos_source_set("htrace_parser_src") { + sources = [ + "../parser_base.cpp", + "htrace_clock_detail_parser.cpp", + "htrace_clock_detail_parser.h", + "htrace_cpu_parser/htrace_cpu_detail_parser.cpp", + "htrace_cpu_parser/htrace_cpu_detail_parser.h", + "htrace_event_parser/htrace_event_parser.cpp", + "htrace_event_parser/htrace_event_parser.h", + "htrace_mem_parser.cpp", + "htrace_mem_parser.h", + "htrace_parser.cpp", + "htrace_symbols_detail_parser.cpp", + "htrace_symbols_detail_parser.h", + ] + include_dirs = [ + "htrace_event_parser", + "htrace_cpu_parser", + ".", + "${OHOS_PROTO_GEN}", + "../../include", + "../../", + "../", + "../../trace_data", + "../../cfg", + "../../trace_streamer", + "//third_party/protobuf/src", + "../../filter", + "../../base", + ] + if (enable_ts_utest) { + cflags = [ + "-fprofile-arcs", + "-ftest-coverage", + ] + ldflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "--coverage", + ] + } + public_deps = [] + deps = [] +} +group("htrace_parser") { + print( + "--------------------------------start build htrace_parser ${OHOS_FTRACE_PROTO_DIR}:ftrace_data_cpp") + deps = [ + ":htrace_parser_src", + "${OHOS_FTRACE_PROTO_DIR}:ftrace_data_cpp", + "${OHOS_MEMORY_PROTO_DIR}:memory_data_cpp", + "${OHOS_SERVICE_PROTO_DIR}:proto_services_cpp", + "//third_party/protobuf:protobuf", + "//third_party/protobuf:protobuf_lite", + ] +} diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp new file mode 100644 index 000000000..66e4cef1a --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp @@ -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. + */ +#include "htrace_clock_detail_parser.h" +#include "clock_filter.h" +#include "htrace_event_parser.h" +#include "measure_filter.h" +#include "process_filter.h" +#include "stat_filter.h" +#include "symbols_filter.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceClockDetailParser::HtraceClockDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) + : streamFilters_(ctx), traceDataCache_(dataCache) +{ + for (auto i = 0; i < MEM_MAX; i++) { + memNameDictMap_.insert( + std::make_pair(static_cast(i), + traceDataCache_->GetDataIndex(config_.memNameMap_.at(static_cast(i))))); + } +} + +HtraceClockDetailParser::~HtraceClockDetailParser() = default; +void HtraceClockDetailParser::Parse(TracePluginResult& tracePacket) const +{ + if (!tracePacket.clocks_detail_size()) { + return; + } + std::vector snapShot; + for (int i = 0; i < tracePacket.clocks_detail_size(); i++) { + auto clockInfo = tracePacket.mutable_clocks_detail(i); + snapShot.push_back(SnapShot{static_cast(clockInfo->id()), + clockInfo->time().tv_nsec() + clockInfo->time().tv_sec() * SEC_TO_NS}); + streamFilters_->clockFilter_->AddClockSnapshot(snapShot); + } + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CLOCK_SYNC, STAT_EVENT_RECEIVED); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.h b/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.h new file mode 100644 index 000000000..6caf9cc16 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef HTRACE_CLOCKDETAIL_PARSER_H +#define HTRACE_CLOCKDETAIL_PARSER_H +#include +#include +#include +#include +#include +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_cfg.h" +#include "trace_streamer_filters.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" + +namespace SysTuning { +namespace TraceStreamer { +class HtraceClockDetailParser { +public: + HtraceClockDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); + ~HtraceClockDetailParser(); + void Parse(TracePluginResult& tracePacket) const; + +private: + const TraceStreamerFilters* streamFilters_; + TraceDataCache* traceDataCache_; + TraceStreamConfig config_; + std::map memNameDictMap_{}; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // HTRACE_CLOCKDETAIL_PARSER_H diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.cpp new file mode 100644 index 000000000..fbd2b8954 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "htrace_cpu_detail_parser.h" +#include "htrace_event_parser.h" +#include "stat_filter.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceCpuDetailParser::HtraceCpuDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) + : EventParserBase(dataCache, ctx), eventParser_(std::make_unique(dataCache, ctx)) +{ +} + +HtraceCpuDetailParser::~HtraceCpuDetailParser() = default; +void HtraceCpuDetailParser::Parse(TracePluginResult& tracePacket, BuiltinClocks clock) +{ + if (!tracePacket.ftrace_cpu_detail_size()) { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_INVALID); + return; + } + + for (int i = 0; i < tracePacket.ftrace_cpu_detail_size(); i++) { + FtraceCpuDetailMsg* cpuDetail = tracePacket.mutable_ftrace_cpu_detail(i); + eventParser_->ParseDataItem(cpuDetail, clock); + } +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/trace_streamer.h b/trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.h similarity index 54% rename from trace_analyzer/src/trace_streamer.h rename to trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.h index 5e1dfef2e..01929fc47 100644 --- a/trace_analyzer/src/trace_streamer.h +++ b/trace_analyzer/src/parser/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.h @@ -12,39 +12,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef TRACE_STREAMER_H -#define TRACE_STREAMER_H - -#include -#include +#ifndef HTRACE_CPU_DETAIL_PARSER_H +#define HTRACE_CPU_DETAIL_PARSER_H +#include +#include +#include +#include +#include +#include "event_parser_base.h" +#include "htrace_event_parser.h" +#include "log.h" +#include "parser_base.h" #include "trace_data/trace_data_cache.h" #include "trace_streamer_filters.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" namespace SysTuning { namespace TraceStreamer { -class BytraceParser; -constexpr size_t G_FILE_PERMISSION = 664; -constexpr int G_MIN_PARAM_NUM = 2; -enum FileType { BY_TRACE, PROTO, UN_KNOW }; -class TraceStreamer { +class HtraceCpuDetailParser : private EventParserBase { public: - TraceStreamer(); - ~TraceStreamer(); + HtraceCpuDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx); + ~HtraceCpuDetailParser(); + void Parse(TracePluginResult &tracePacket, BuiltinClocks clock); - bool Parse(std::unique_ptr, size_t); - int ExportDatabase(const std::string& outputName); private: - void InitFilter(); - void InitParser(); - FileType fileType_; - - std::unique_ptr streamFilters_; - std::unique_ptr traceDataCache_; - - std::unique_ptr bytraceParser_; + std::unique_ptr eventParser_; }; } // namespace TraceStreamer } // namespace SysTuning -#endif // TRACE_STREAMER_H +#endif // HTRACE_CPU_DETAIL_PARSER_H_ diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.cpp new file mode 100755 index 000000000..602a6a71e --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.cpp @@ -0,0 +1,336 @@ +/* + * 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 "htrace_event_parser.h" +#include +#include +#include "clock_filter.h" +#include "cpu_filter.h" +#include "log.h" +#include "measure_filter.h" +#include "process_filter.h" +#include "slice_filter.h" +#include "stat_filter.h" +#include "symbols_filter.h" +#include "thread_state.h" +#include "types/plugins/ftrace_data/binder.pb.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceEventParser::HtraceEventParser(TraceDataCache* dataCache, const TraceStreamerFilters* filter) + : EventParserBase(dataCache, filter), workQueueId_(dataCache->dataDict_.GetStringIndex("workqueue")) +{ + eventToFunctionMap_ = {{config_.eventNameMap_.at(TRACE_EVENT_SCHED_SWITCH), + std::bind(&HtraceEventParser::SchedSwitchEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_TASK_RENAME), + std::bind(&HtraceEventParser::TaskRenameEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_TASK_NEWTASK), + std::bind(&HtraceEventParser::TaskNewtaskEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_TRACING_MARK_WRITE), + std::bind(&HtraceEventParser::TracingMarkWriteEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP), + std::bind(&HtraceEventParser::SchedWakeupEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP_NEW), + std::bind(&HtraceEventParser::SchedWakeupNewEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_PROCESS_EXIT), + std::bind(&HtraceEventParser::ProcessExitEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKING), + std::bind(&HtraceEventParser::SchedWakingEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_CPU_IDLE), + std::bind(&HtraceEventParser::CpuIdleEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY), + std::bind(&HtraceEventParser::CpuFrequencyEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_START), + std::bind(&HtraceEventParser::WorkqueueExecuteStartEvent, this, std::placeholders::_1)}, + {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_END), + std::bind(&HtraceEventParser::WorkqueueExecuteEndEvent, this, std::placeholders::_1)}}; +} + +HtraceEventParser::~HtraceEventParser() = default; +void HtraceEventParser::ParseDataItem(const FtraceCpuDetailMsg* cpuDetail, BuiltinClocks clock) +{ + eventCpu_ = cpuDetail->cpu(); + auto events = cpuDetail->event(); + if (events.size()) { + if (cpuDetail->overwrite()) { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_LOST); + } + // parser cpu event + for (auto i = 0; i < events.size(); i++) { + auto event = cpuDetail->event(i); + eventTimestamp_ = event.timestamp(); + eventTimestamp_ = streamFilters_->clockFilter_->ToPrimaryTraceTime(clock, eventTimestamp_); + traceDataCache_->UpdateTraceTime(eventTimestamp_); + if (event.tgid() != INVALID_INT32) { + eventPid_ = event.tgid(); + streamFilters_->processFilter_->GetOrCreateThreadWithPid(eventPid_, eventPid_); + streamFilters_->processFilter_->UpdateOrCreateThreadWithPidAndName(eventPid_, eventPid_, "name"); + } + + if (event.has_binder_transaction_format()) { + InvokeFunc(TRACE_EVENT_BINDER_TRANSACTION, event.binder_transaction_format()); + } else if (event.has_binder_transaction_received_format()) { + InvokeFunc(TRACE_EVENT_BINDER_TRANSACTION_RECEIVED, event.binder_transaction_received_format()); + } else if (event.has_sched_switch_format()) { + InvokeFunc(TRACE_EVENT_SCHED_SWITCH, event.sched_switch_format()); + } else if (event.has_task_rename_format()) { + InvokeFunc(TRACE_EVENT_TASK_RENAME, event.task_rename_format()); + } else if (event.has_task_newtask_format()) { + InvokeFunc(TRACE_EVENT_TASK_NEWTASK, event.task_newtask_format()); + } else if (event.has_sched_wakeup_format()) { + InvokeFunc(TRACE_EVENT_SCHED_WAKEUP, event.sched_wakeup_format()); + } else if (event.has_sched_wakeup_new_format()) { + InvokeFunc(TRACE_EVENT_SCHED_WAKEUP, event.sched_wakeup_new_format()); + } else if (event.has_sched_process_exit_format()) { + InvokeFunc(TRACE_EVENT_PROCESS_EXIT, event.sched_process_exit_format()); + } else if (event.has_sched_waking_format()) { + InvokeFunc(TRACE_EVENT_SCHED_WAKING, event.sched_waking_format()); + } else if (event.has_cpu_idle_format()) { + InvokeFunc(TRACE_EVENT_CPU_IDLE, event.cpu_idle_format()); + } else if (event.has_cpu_frequency_format()) { + InvokeFunc(TRACE_EVENT_CPU_FREQUENCY, event.cpu_frequency_format()); + } else if (event.has_workqueue_execute_start_format()) { + InvokeFunc(TRACE_EVENT_WORKQUEUE_EXECUTE_START, event.workqueue_execute_start_format()); + } else if (event.has_workqueue_execute_end_format()) { + InvokeFunc(TRACE_EVENT_WORKQUEUE_EXECUTE_END, event.workqueue_execute_end_format()); + } + } + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_LOST); + } +} +bool HtraceEventParser::SchedSwitchEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + uint32_t prevPrioValue = msg.prev_prio(); + uint32_t nextPrioValue = msg.next_prio(); + uint32_t prevPidValue = msg.prev_pid(); + uint32_t nextPidValue = msg.next_pid(); + + std::string prevCommStr = msg.prev_comm(); + std::string nextCommStr = msg.next_comm(); + auto prevState = msg.prev_state(); + + auto nextInternalTid = + streamFilters_->processFilter_->UpdateOrCreateThreadWithName(eventTimestamp_, nextPidValue, nextCommStr); + auto uprevtid = + streamFilters_->processFilter_->UpdateOrCreateThreadWithName(eventTimestamp_, prevPidValue, prevCommStr); + streamFilters_->cpuFilter_->InsertSwitchEvent(eventTimestamp_, eventCpu_, uprevtid, + static_cast(prevPrioValue), prevState, nextInternalTid, + static_cast(nextPrioValue)); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_SWITCH, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::ProcessExitEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + uint32_t pidValue = msg.pid(); + std::string commStr = msg.comm(); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_PROCESS_EXIT, STAT_EVENT_RECEIVED); + auto iTid = streamFilters_->processFilter_->UpdateOrCreateThreadWithName(eventTimestamp_, pidValue, commStr); + if (streamFilters_->cpuFilter_->InsertProcessExitEvent(eventTimestamp_, eventCpu_, iTid)) { + return true; + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_PROCESS_EXIT, STAT_EVENT_NOTMATCH); + return false; + } +} +bool HtraceEventParser::TaskRenameEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + auto prevCommStr = msg.newcomm(); + auto pidValue = msg.pid(); + streamFilters_->processFilter_->UpdateOrCreateProcessWithName(pidValue, prevCommStr); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TASK_RENAME, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::TaskNewtaskEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + auto commonStr = msg.comm(); + auto pidValue = msg.pid(); + + uint32_t ftracePid = 0; + if (eventPid_ != INVALID_UINT32) { + ftracePid = eventPid_; + } + + static const uint32_t threadPid = 2; + static const uint32_t cloneThread = 0x00010000; + auto cloneFlags = msg.clone_flags(); + if ((cloneFlags & cloneThread) == 0 && ftracePid != threadPid) { + streamFilters_->processFilter_->UpdateOrCreateProcessWithName(pidValue, commonStr); + } else if (ftracePid == threadPid) { + streamFilters_->processFilter_->GetOrCreateThreadWithPid(pidValue, threadPid); + } + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TASK_NEWTASK, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::TracingMarkWriteEvent(const google::protobuf::MessageLite& event) const +{ + UNUSED(event); + TS_LOGE("TracingMarkWriteEvent"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_TRACING_MARK_WRITE, STAT_EVENT_NOTSUPPORTED); + return true; +} +bool HtraceEventParser::SchedWakeupEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_wakeup")); + auto instants = traceDataCache_->GetInstantsData(); + + InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(eventTimestamp_, msg.pid()); + instants->AppendInstantEventData(eventTimestamp_, name, internalTid); + + std::optional targetCpu = msg.target_cpu(); + if (targetCpu.has_value()) { + traceDataCache_->GetRawData()->AppendRawData(0, eventTimestamp_, RAW_SCHED_WAKEUP, targetCpu.value(), + internalTid); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_RECEIVED); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_DATA_INVALID); + } + return true; +} +bool HtraceEventParser::SchedWakeupNewEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_wakeup_new")); + auto instants = traceDataCache_->GetInstantsData(); + + InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(eventTimestamp_, msg.pid()); + instants->AppendInstantEventData(eventTimestamp_, name, internalTid); + + std::optional targetCpu = msg.target_cpu(); + if (targetCpu.has_value()) { + traceDataCache_->GetRawData()->AppendRawData(0, eventTimestamp_, RAW_SCHED_WAKEUP, targetCpu.value(), + internalTid); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP_NEW, STAT_EVENT_RECEIVED); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP_NEW, STAT_EVENT_DATA_INVALID); + } + return true; +} +bool HtraceEventParser::SchedWakingEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + std::optional wakePidValue = msg.pid(); + if (!wakePidValue.has_value()) { + TS_LOGD("Failed to convert wake_pid"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_DATA_INVALID); + return false; + } + DataIndex name = traceDataCache_->GetDataIndex(std::string_view("sched_waking")); + auto instants = traceDataCache_->GetInstantsData(); + InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(eventTimestamp_, eventPid_); + instants->AppendInstantEventData(eventTimestamp_, name, internalTid); + streamFilters_->cpuFilter_->InsertWakeingEvent(eventTimestamp_, internalTid); + std::optional targetCpu = msg.target_cpu(); + if (targetCpu.has_value()) { + traceDataCache_->GetRawData()->AppendRawData(0, eventTimestamp_, RAW_SCHED_WAKING, targetCpu.value(), + internalTid); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_RECEIVED); + } + return true; +} +bool HtraceEventParser::CpuIdleEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + std::optional eventCpuValue = msg.cpu_id(); + std::optional newStateValue = msg.state(); + if (!eventCpuValue.has_value()) { + TS_LOGW("Failed to convert event cpu"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_DATA_INVALID); + return false; + } + if (!newStateValue.has_value()) { + TS_LOGW("Failed to convert state"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_DATA_INVALID); + return false; + } + auto cpuIdleNameIndex = traceDataCache_->GetDataIndex(std::string_view("cpu_idle")); + + streamFilters_->cpuMeasureFilter_->AppendNewMeasureData(eventCpuValue.value(), cpuIdleNameIndex, eventTimestamp_, + newStateValue.value()); + + // Add cpu_idle event to raw_data_table + traceDataCache_->GetRawData()->AppendRawData(0, eventTimestamp_, RAW_CPU_IDLE, eventCpuValue.value(), 0); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_IDLE, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::CpuFrequencyEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + std::optional newStateValue = msg.state(); + std::optional eventCpuValue = msg.cpu_id(); + + if (!newStateValue.has_value()) { + TS_LOGW("Failed to convert state"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_DATA_INVALID); + return false; + } + if (!eventCpuValue.has_value()) { + TS_LOGW("Failed to convert event cpu"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_DATA_INVALID); + return false; + } + TS_LOGE("CPU FREQ"); + auto cpuidleNameIndex = traceDataCache_->GetDataIndex(std::string_view("cpu_frequency")); + + streamFilters_->cpuMeasureFilter_->AppendNewMeasureData(eventCpuValue.value(), cpuidleNameIndex, eventTimestamp_, + newStateValue.value()); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::WorkqueueExecuteStartEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + auto result = streamFilters_->sliceFilter_->BeginSlice(eventTimestamp_, eventPid_, eventPid_, workQueueId_, + streamFilters_->symbolsFilter_->GetFunc(msg.function())); + if (result) { + traceDataCache_->GetInternalSlicesData()->AppendDistributeInfo(); + } + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_START, STAT_EVENT_RECEIVED); + return true; +} +bool HtraceEventParser::WorkqueueExecuteEndEvent(const google::protobuf::MessageLite& event) const +{ + const auto msg = static_cast(event); + if (streamFilters_->sliceFilter_->EndSlice(eventTimestamp_, eventPid_, eventPid_)) { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_NOTMATCH); + } else { + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_RECEIVED); + } + return true; +} + +bool HtraceEventParser::InvokeFunc(const SupportedTraceEventType& eventType, + const google::protobuf::MessageLite& msgBase) +{ + auto eventName = config_.eventNameMap_.find(eventType); + if (eventName == config_.eventNameMap_.end()) { + // log warn + streamFilters_->statFilter_->IncreaseStat(eventType, STAT_EVENT_NOTSUPPORTED); + return false; + } + auto it = eventToFunctionMap_.find(eventName->second); + if (it == eventToFunctionMap_.end()) { + // log warn + streamFilters_->statFilter_->IncreaseStat(eventType, STAT_EVENT_NOTSUPPORTED); + return false; + } + it->second(msgBase); + return true; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.h b/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.h new file mode 100755 index 000000000..b8195d54f --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_event_parser/htrace_event_parser.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef HTRACE_EVENT_PARSER_H +#define HTRACE_EVENT_PARSER_H +#include +#include +#include +#include +#include +#include + +#include "base/common.h" +#include "event_parser_base.h" +#include "google/protobuf/message_lite.h" +#include "log.h" +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_filters.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" + +namespace SysTuning { +namespace TraceStreamer { +class HtraceEventParser : private EventParserBase { +public: + HtraceEventParser(TraceDataCache* dataCache, const TraceStreamerFilters* filter); + ~HtraceEventParser(); + void ParseDataItem(const FtraceCpuDetailMsg* cpuDetail, BuiltinClocks clock); + +private: + bool SchedSwitchEvent(const google::protobuf::MessageLite& event) const; + bool ProcessExitEvent(const google::protobuf::MessageLite& event) const; + bool TaskRenameEvent(const google::protobuf::MessageLite& event) const; + bool TaskNewtaskEvent(const google::protobuf::MessageLite& event) const; + bool TracingMarkWriteEvent(const google::protobuf::MessageLite& event) const; + bool SchedWakeupEvent(const google::protobuf::MessageLite& event) const; + bool SchedWakeupNewEvent(const google::protobuf::MessageLite& event) const; + bool SchedWakingEvent(const google::protobuf::MessageLite& event) const; + bool CpuIdleEvent(const google::protobuf::MessageLite& event) const; + bool CpuFrequencyEvent(const google::protobuf::MessageLite& event) const; + bool WorkqueueExecuteStartEvent(const google::protobuf::MessageLite& event) const; + bool WorkqueueExecuteEndEvent(const google::protobuf::MessageLite& event) const; + bool InvokeFunc(const SupportedTraceEventType& eventType, const google::protobuf::MessageLite& msgBase); + using FuncCall = std::function; + uint32_t eventCpu_ = INVALID_UINT32; + uint64_t eventTimestamp_ = INVALID_UINT64; + uint32_t eventPid_ = INVALID_UINT32; + std::map eventToFunctionMap_{}; + DataIndex workQueueId_ = 0; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // HTRACE_EVENT_PARSER_H_ diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.cpp new file mode 100644 index 000000000..b039e1f1f --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.cpp @@ -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. + */ +#include "htrace_mem_parser.h" +#include "clock_filter.h" +#include "htrace_event_parser.h" +#include "measure_filter.h" +#include "process_filter.h" +#include "stat_filter.h" +#include "symbols_filter.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceMemParser::HtraceMemParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) + : streamFilters_(ctx), traceDataCache_(dataCache) +{ + if (!traceDataCache_) { + TS_LOGF("traceDataCache_ should not be null"); + return; + } + for (auto i = 0; i < MEM_MAX; i++) { + memNameDictMap_.insert( + std::make_pair(static_cast(i), + traceDataCache_->GetDataIndex(config_.memNameMap_.at(static_cast(i))))); + } +} + +HtraceMemParser::~HtraceMemParser() = default; +void HtraceMemParser::Parse(const MemoryData& tracePacket, uint64_t timeStamp, BuiltinClocks clock) const +{ + if (!tracePacket.processesinfo_size()) { + return; + } + + if (!streamFilters_) { + TS_LOGF("streamFilters_ should not be null"); + return; + } + + timeStamp = streamFilters_->clockFilter_->ToPrimaryTraceTime(clock, timeStamp); + for (int i = 0; i < tracePacket.processesinfo_size(); i++) { + auto memInfo = tracePacket.processesinfo(i); + auto ipid = streamFilters_->processFilter_->UpdateOrCreateProcessWithName(memInfo.pid(), memInfo.name()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_SIZE), timeStamp, + memInfo.vm_size_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_RSS), timeStamp, + memInfo.vm_rss_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_ANON), timeStamp, + memInfo.rss_anon_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_RSS_FILE), timeStamp, + memInfo.rss_file_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_RSS_SHMEM), timeStamp, + memInfo.rss_shmem_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_SWAP), timeStamp, + memInfo.vm_swap_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_LOCKED), timeStamp, + memInfo.vm_locked_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_VM_HWM), timeStamp, + memInfo.vm_hwm_kb()); + streamFilters_->processMeasureFilter_->AppendNewMeasureData(ipid, memNameDictMap_.at(MEM_OOM_SCORE_ADJ), + timeStamp, memInfo.oom_score_adj()); + streamFilters_->statFilter_->IncreaseStat(TRACE_MEMORY, STAT_EVENT_RECEIVED); + } +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.h b/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.h new file mode 100644 index 000000000..384b0d8c8 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_mem_parser.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef HTRACE_MEM_PARSER_H +#define HTRACE_MEM_PARSER_H +#include +#include +#include +#include +#include +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_cfg.h" +#include "trace_streamer_filters.h" +#include "types/plugins/memory_data/memory_plugin_result.pb.h" + +namespace SysTuning { +namespace TraceStreamer { +class HtraceMemParser { +public: + HtraceMemParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx); + ~HtraceMemParser(); + void Parse(const MemoryData& tracePacket, uint64_t, BuiltinClocks clock) const; + +private: + const TraceStreamerFilters* streamFilters_; + TraceDataCache* traceDataCache_; + TraceStreamConfig config_; + std::map memNameDictMap_{}; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // HTRACE_MEM_PARSER_H diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_parser.cpp new file mode 100644 index 000000000..b46b0949d --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_parser.cpp @@ -0,0 +1,129 @@ +/* + * 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 "htrace_parser.h" +#include "log.h" +#include "services/common_types.pb.h" +#include "stat_filter.h" +#include "types/plugins/ftrace_data/ftrace_event.pb.h" +#include "types/plugins/ftrace_data/trace_plugin_config.pb.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" +#include "types/plugins/memory_data/memory_plugin_result.pb.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceParser::HtraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters) + : ParserBase(filters), + htraceCpuDetailParser_(std::make_unique(dataCache, filters)), + htraceSymbolsDetailParser_(std::make_unique(dataCache, filters)), + htraceMemParser_(std::make_unique(dataCache, filters)), + htraceClockDetailParser_(std::make_unique(dataCache, filters)) +{ +} + +HtraceParser::~HtraceParser() = default; + +void HtraceParser::ParseTraceDataItem(const std::string& buffer) +{ + ProfilerPluginData plugininData; + if (!plugininData.ParseFromArray(buffer.data(), static_cast(buffer.length()))) { + TS_LOGW("ProfilerPluginData ParseFromArray failed\n"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_INVALID); + return; + } + if (plugininData.name() == "memory-plugin") { + auto timeStamp = plugininData.tv_nsec() + plugininData.tv_sec() * SEC_TO_NS; + BuiltinClocks clockId = TS_CLOCK_REALTIME; + auto clockIdTemp = plugininData.clock_id(); + if (clockIdTemp == ProfilerPluginData_ClockId_CLOCKID_REALTIME) { + clockId = TS_CLOCK_REALTIME; + } + MemoryData memData; + if (!memData.ParseFromArray(plugininData.data().data(), static_cast(plugininData.data().size()))) { + TS_LOGW("tracePacketParseFromArray failed\n"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_INVALID); + return; + } + + if (memData.processesinfo_size()) { + htraceMemParser_->Parse(memData, timeStamp, clockId); + } + } else { + TS_LOGD("plugininData.name():%s", plugininData.name().c_str()); + TracePluginResult tracePacket; + if (!tracePacket.ParseFromArray(plugininData.data().data(), static_cast(plugininData.data().size()))) { + TS_LOGW("tracePacketParseFromArray failed\n"); + streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_OTHER, STAT_EVENT_DATA_INVALID); + return; + } + if (tracePacket.ftrace_cpu_stats_size()) { + auto cpuStats = tracePacket.ftrace_cpu_stats(0); + auto clock = cpuStats.trace_clock(); + if (clock == "boot") { + clock_ = TS_CLOCK_BOOTTIME; + } + } + + if (tracePacket.ftrace_cpu_detail_size()) { + htraceCpuDetailParser_->Parse(tracePacket, clock_); // has Event + } + if (tracePacket.symbols_detail_size()) { + htraceSymbolsDetailParser_->Parse(tracePacket); // has Event + } + if (tracePacket.clocks_detail_size()) { + htraceClockDetailParser_->Parse(tracePacket); // has Event + } + } +} +void HtraceParser::ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) +{ + packagesBuffer_.insert(packagesBuffer_.end(), &bufferStr[0], &bufferStr[size]); + auto packagesBegin = packagesBuffer_.begin(); + auto currentLength = packagesBuffer_.size(); + if (!hasGotHeader) { + std::string start(reinterpret_cast(bufferStr.get()), std::min(size, 20)); + if (start.compare(0, std::string("OHOSPROF").length(), "OHOSPROF") == 0) { + currentLength -= PACKET_HEADER_LENGTH; + packagesBegin += PACKET_HEADER_LENGTH; + } + hasGotHeader = true; + } + + while (1) { + if (!hasGotSegLength_) { + if (currentLength < PACKET_SEG_LENGTH) { + break; + } + std::string bufferLine(packagesBegin, packagesBegin + PACKET_SEG_LENGTH); + const uint32_t* len = reinterpret_cast(bufferLine.data()); + nextLength_ = *len; + hasGotSegLength_ = true; + currentLength -= PACKET_SEG_LENGTH; + packagesBegin += PACKET_SEG_LENGTH; + } + if (currentLength < nextLength_) { + break; + } + std::string bufferLine(packagesBegin, packagesBegin + nextLength_); + + ParseTraceDataItem(bufferLine); + hasGotSegLength_ = false; + packagesBegin += nextLength_; + currentLength -= nextLength_; + } + packagesBuffer_.erase(packagesBuffer_.begin(), packagesBegin); + return; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_parser.h b/trace_analyzer/src/parser/htrace_parser/htrace_parser.h new file mode 100644 index 000000000..9c2977b24 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_parser.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HTRACE_PARSER_H +#define HTRACE_PARSER_H + +#include +#include +#include +#include +#include +#include "htrace_clock_detail_parser.h" +#include "htrace_cpu_detail_parser.h" +#include "htrace_mem_parser.h" +#include "htrace_symbols_detail_parser.h" +#include "log.h" +#include "parser_base.h" +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +class HtraceParser : public ParserBase { +public: + HtraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); + ~HtraceParser(); + void ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) override; + +private: + void ParseTraceDataItem(const std::string& buffer) override; + bool hasGotSegLength_ = false; + bool hasGotHeader = false; + uint32_t nextLength_ = 0; + const size_t PACKET_SEG_LENGTH = 4; + const size_t PACKET_HEADER_LENGTH = 1024; + std::unique_ptr htraceCpuDetailParser_; + std::unique_ptr htraceSymbolsDetailParser_; + std::unique_ptr htraceMemParser_; + std::unique_ptr htraceClockDetailParser_; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // HTRACE_PARSER_H_ diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.cpp b/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.cpp new file mode 100644 index 000000000..0eadd1c8a --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.cpp @@ -0,0 +1,41 @@ +/* + * 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 "htrace_symbols_detail_parser.h" +#include "htrace_event_parser.h" +#include "symbols_filter.h" +namespace SysTuning { +namespace TraceStreamer { +HtraceSymbolsDetailParser::HtraceSymbolsDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) + : streamFilters_(ctx), traceDataCache_(dataCache) +{ + UNUSED(traceDataCache_); +} + +HtraceSymbolsDetailParser::~HtraceSymbolsDetailParser() = default; +void HtraceSymbolsDetailParser::Parse(const TracePluginResult& tracePacket) +{ + if (!tracePacket.symbols_detail_size()) { + return; + } + for (int i = 0; i < tracePacket.symbols_detail_size(); i++) { + auto symbol = const_cast(tracePacket).mutable_symbols_detail(i); + TS_LOGD("symbol_name:%s, symbol_addr:%lu", symbol->symbol_name().c_str(), symbol->symbol_addr()); + // symbol + streamFilters_->symbolsFilter_->RegisterFunc(symbol->symbol_addr(), + traceDataCache_->GetDataIndex(symbol->symbol_name())); + } +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.h b/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.h new file mode 100644 index 000000000..c04474ca7 --- /dev/null +++ b/trace_analyzer/src/parser/htrace_parser/htrace_symbols_detail_parser.h @@ -0,0 +1,41 @@ +/* + * 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 HTRACE_SYMBOLS_DETAIL_PARSER_H +#define HTRACE_SYMBOLS_DETAIL_PARSER_H +#include +#include +#include +#include +#include +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_filters.h" +#include "types/plugins/ftrace_data/trace_plugin_result.pb.h" + +namespace SysTuning { +namespace TraceStreamer { +class HtraceSymbolsDetailParser { +public: + HtraceSymbolsDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx); + ~HtraceSymbolsDetailParser(); + void Parse(const TracePluginResult& tracePacket); + +private: + const TraceStreamerFilters* streamFilters_; + TraceDataCache* traceDataCache_; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // HTRACE_SYMBOLS_DETAIL_PARSER_H diff --git a/trace_analyzer/src/parser/parser.pri b/trace_analyzer/src/parser/parser.pri new file mode 100755 index 000000000..1d58b6fce --- /dev/null +++ b/trace_analyzer/src/parser/parser.pri @@ -0,0 +1,43 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +INCLUDEPATH += $$PWD \ + $$PWD/bytrace_parser \ + $$PWD/htrace_parser/htrace_cpu_parser \ + $$PWD/htrace_parser/htrace_event_parser \ + $$PWD/htrace_parser/htrace_symbol_parser +HEADERS += \ + $$PWD/common_types.h \ + $$PWD/event_parser_base.h \ + $$PWD/thread_state.h \ + $$PWD/bytrace_parser/bytrace_parser.h \ + $$PWD/bytrace_parser/bytrace_event_parser.h \ + $$PWD/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.h \ + $$PWD/htrace_parser/htrace_event_parser/htrace_event_parser.h \ + $$PWD/htrace_parser/htrace_parser.h \ + $$PWD/htrace_parser/htrace_mem_parser.h \ + $$PWD/htrace_parser/htrace_clock_detail_parser.h \ + $$PWD/htrace_parser/htrace_symbols_detail_parser.h + +SOURCES += \ + $$PWD/parser_base.cpp \ + $$PWD/event_parser_base.cpp \ + $$PWD/thread_state.cpp \ + $$PWD/bytrace_parser/bytrace_parser.cpp \ + $$PWD/bytrace_parser/bytrace_event_parser.cpp \ + $$PWD/htrace_parser/htrace_cpu_parser/htrace_cpu_detail_parser.cpp \ + $$PWD/htrace_parser/htrace_event_parser/htrace_event_parser.cpp \ + $$PWD/htrace_parser/htrace_parser.cpp \ + $$PWD/htrace_parser/htrace_mem_parser.cpp \ + $$PWD/htrace_parser/htrace_clock_detail_parser.cpp \ + $$PWD/htrace_parser/htrace_symbols_detail_parser.cpp diff --git a/trace_analyzer/src/parser/parser_base.cpp b/trace_analyzer/src/parser/parser_base.cpp new file mode 100644 index 000000000..ad069faf4 --- /dev/null +++ b/trace_analyzer/src/parser/parser_base.cpp @@ -0,0 +1,21 @@ +/* + * 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 "parser_base.h" +namespace SysTuning { +namespace TraceStreamer { +ParserBase::ParserBase(const TraceStreamerFilters* filter) : streamFilters_(filter), clock_(TS_CLOCK_UNKNOW) {} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/parser/parser_base.h b/trace_analyzer/src/parser/parser_base.h new file mode 100644 index 000000000..ff6f9dcfb --- /dev/null +++ b/trace_analyzer/src/parser/parser_base.h @@ -0,0 +1,38 @@ +/* + * 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 SRC_PARSER_BASE_H +#define SRC_PARSER_BASE_H +#include +#include +#include "common.h" +#include "trace_streamer_filters.h" +namespace SysTuning { +namespace TraceStreamer { +class ParserBase { +public: + explicit ParserBase(const TraceStreamerFilters* filter); + virtual ~ParserBase() = default; + virtual void ParseTraceDataSegment(std::unique_ptr, size_t size) = 0; + +protected: + virtual void ParseTraceDataItem(const std::string& buffer) = 0; + std::deque packagesBuffer_; + const TraceStreamerFilters* streamFilters_; + BuiltinClocks clock_; +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif diff --git a/trace_analyzer/src/parser/thread_state.cpp b/trace_analyzer/src/parser/thread_state.cpp index fc6ba028d..22c771b7a 100755 --- a/trace_analyzer/src/parser/thread_state.cpp +++ b/trace_analyzer/src/parser/thread_state.cpp @@ -21,16 +21,8 @@ Direction ThreadState::SetStatByChar(char ch) { if (ch == 'R') { if (state_ == 0) { - SetIsRunnable(true); return NEED_CONTINUE; } - - SetInvalidChar(true); - return NEED_BREAK; - } - - if (ch == '|') { - return NEED_CONTINUE; } if (statMap_.find(ch) == statMap_.end()) { @@ -44,39 +36,24 @@ Direction ThreadState::SetStatByChar(char ch) void ThreadState::ProcessSate(const std::string& stateStr) { for (size_t i = 0; i < stateStr.size(); i++) { - if (state_ & MAXSTAT) { - SetInvalidChar(true); - break; - } else if (stateStr[i] == '+') { - SetStat(MAXSTAT); + if (stateStr[i] == '+') { + SetStat(TASKNEW); continue; } - if (isRunnable_) { - SetInvalidChar(true); - break; - } - Direction ret = SetStatByChar(stateStr[i]); if (ret == NEED_CONTINUE) { continue; } else if (ret == NEED_BREAK) { - SetInvalidChar(true); + TS_LOGE("Un supported state:%c", stateStr[i]); break; } } } -ThreadState::ThreadState(const std::string stateStr) +ThreadState::ThreadState(const std::string& stateStr) { ProcessSate(stateStr); - - bool noState = ((!isRunnable_) && (state_ == 0)); - if (invalidChar_ || noState || state_ > MAXSTAT) { - SetStatZero(); - } else { - SetStat(VALID); - } } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/parser/thread_state.h b/trace_analyzer/src/parser/thread_state.h index f2119af0c..9149d6ca6 100644 --- a/trace_analyzer/src/parser/thread_state.h +++ b/trace_analyzer/src/parser/thread_state.h @@ -26,19 +26,25 @@ enum Direction { NEED_GO = 0, NEED_CONTINUE, NEED_BREAK }; class ThreadState { public: - explicit ThreadState(const std::string stateStr); + explicit ThreadState(const std::string& stateStr); ~ThreadState() {} uint32_t State() const { - TUNING_ASSERT(state_ & VALID); return state_ & ~VALID; } +private: + void SetStat(Stat value) + { + state_ |= value; + } + + void ProcessSate(const std::string& stateStr); + Direction SetStatByChar(char ch); + private: uint32_t state_ = 0; - bool invalidChar_ = false; - bool isRunnable_ = false; std::map statMap_ = { {'R', RUNNABLE}, {'S', INTERRUPTABLESLEEP}, @@ -54,26 +60,6 @@ private: {'N', NOLOAD}, {'|', VALID}, }; - - void SetStatZero() - { - state_ = 0; - } - void SetStat(Stat value) - { - state_ |= value; - } - void SetInvalidChar(bool value) - { - invalidChar_ = value; - } - void SetIsRunnable(bool value) - { - isRunnable_ = value; - } - - void ProcessSate(const std::string& stateStr); - Direction SetStatByChar(char ch); }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/table/callstack_table.cpp b/trace_analyzer/src/table/callstack_table.cpp new file mode 100644 index 000000000..4247229a4 --- /dev/null +++ b/trace_analyzer/src/table/callstack_table.cpp @@ -0,0 +1,147 @@ +/* + * 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 "callstack_table.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +enum Index { + ID = 0, + TS, + DUR, + CALL_ID, + CAT, + NAME, + DEPTH, + COOKIE_ID, + PARENT_ID, + CHAIN_ID, + SPAN_ID, + PARENT_SPAN_ID, + FLAG, + ARGS +}; +} +CallStackTable::CallStackTable(const TraceDataCache* dataCache) : TableBase(dataCache) +{ + tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("ts", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("dur", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("callid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("cat", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("depth", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("cookie", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("parent_id", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("chainId", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("spanId", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("parentSpanId", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("flag", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("args", "STRING")); + tablePriKey_.push_back("callid"); + tablePriKey_.push_back("ts"); + tablePriKey_.push_back("depth"); +} + +CallStackTable::~CallStackTable() {} + +void CallStackTable::CreateCursor() +{ + cursor_ = std::make_unique(dataCache_); +} + +CallStackTable::Cursor::Cursor(const TraceDataCache* dataCache) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstInternalSlicesData().Size())), + slicesObj_(dataCache->GetConstInternalSlicesData()) +{ +} + +CallStackTable::Cursor::~Cursor() {} + +int CallStackTable::Cursor::Column(int column) const +{ + switch (column) { + case ID: + sqlite3_result_int64(context_, CurrentRow()); + break; + case TS: + sqlite3_result_int64(context_, static_cast(slicesObj_.TimeStamData()[CurrentRow()])); + break; + case DUR: + sqlite3_result_int64(context_, static_cast(slicesObj_.DursData()[CurrentRow()])); + break; + case CALL_ID: + sqlite3_result_int64(context_, static_cast(slicesObj_.CallIds()[CurrentRow()])); + break; + case CAT: { + if (slicesObj_.CatsData()[CurrentRow()] != INVALID_UINT64) { + auto catsDataIndex = static_cast(slicesObj_.CatsData()[CurrentRow()]); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(catsDataIndex).c_str(), STR_DEFAULT_LEN, + nullptr); + } + break; + } + case NAME: { + if (slicesObj_.NamesData()[CurrentRow()] != INVALID_UINT64) { + auto nameDataIndex = static_cast(slicesObj_.NamesData()[CurrentRow()]); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(nameDataIndex).c_str(), STR_DEFAULT_LEN, + nullptr); + } + break; + } + case DEPTH: + sqlite3_result_int64(context_, static_cast(slicesObj_.Depths()[CurrentRow()])); + break; + case COOKIE_ID: + if (slicesObj_.Cookies()[CurrentRow()] != INVALID_UINT64) { + sqlite3_result_int64(context_, static_cast(slicesObj_.Cookies()[CurrentRow()])); + } + break; + case PARENT_ID: { + if (slicesObj_.ParentIdData()[CurrentRow()].has_value()) { + sqlite3_result_int64(context_, static_cast(slicesObj_.ParentIdData()[CurrentRow()].value())); + } + break; + } + case CHAIN_ID: + sqlite3_result_text(context_, dataCache_->GetConstInternalSlicesData().ChainIds()[CurrentRow()].c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case SPAN_ID: + sqlite3_result_text(context_, dataCache_->GetConstInternalSlicesData().SpanIds()[CurrentRow()].c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case PARENT_SPAN_ID: + sqlite3_result_text(context_, + dataCache_->GetConstInternalSlicesData().ParentSpanIds()[CurrentRow()].c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case FLAG: + sqlite3_result_text(context_, dataCache_->GetConstInternalSlicesData().Flags()[CurrentRow()].c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case ARGS: + sqlite3_result_text(context_, dataCache_->GetConstInternalSlicesData().ArgsData()[CurrentRow()].c_str(), + STR_DEFAULT_LEN, nullptr); + break; + default: + TS_LOGF("Unregistered column : %d", column); + break; + } + return SQLITE_OK; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/table/internal_thread.h b/trace_analyzer/src/table/callstack_table.h old mode 100644 new mode 100755 similarity index 78% rename from trace_analyzer/src/table/internal_thread.h rename to trace_analyzer/src/table/callstack_table.h index 9729e25a4..f1ea29b97 --- a/trace_analyzer/src/table/internal_thread.h +++ b/trace_analyzer/src/table/callstack_table.h @@ -13,18 +13,18 @@ * limitations under the License. */ -#ifndef SRC_INTERNAL_THREAD_H -#define SRC_INTERNAL_THREAD_H +#ifndef CALL_STACK_TABLE_H +#define CALL_STACK_TABLE_H #include "table_base.h" #include "trace_data_cache.h" namespace SysTuning { namespace TraceStreamer { -class InternalThread : public TableBase { +class CallStackTable : public TableBase { public: - explicit InternalThread(const TraceDataCache*); - ~InternalThread() override; + explicit CallStackTable(const TraceDataCache* dataCache); + ~CallStackTable() override; void CreateCursor() override; private: @@ -33,9 +33,12 @@ private: explicit Cursor(const TraceDataCache*); ~Cursor() override; int Column(int) const override; + + private: + const CallStack& slicesObj_; }; }; } // namespace TraceStreamer } // namespace SysTuning -#endif // _INTERNAL_THREAD_H_ +#endif // CALL_STACK_TABLE_H diff --git a/trace_analyzer/src/table/clock_event_filter_table.cpp b/trace_analyzer/src/table/clock_event_filter_table.cpp new file mode 100644 index 000000000..a123ed86c --- /dev/null +++ b/trace_analyzer/src/table/clock_event_filter_table.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "clock_event_filter_table.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +enum Index { ID = 0, TYPE, NAME, CPU }; +} +ClockEventFilterTable::ClockEventFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) +{ + tableColumn_.push_back(TableBase::ColumnInfo("id", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("cpu", "INT")); + tablePriKey_.push_back("id"); +} + +ClockEventFilterTable::~ClockEventFilterTable() {} + +void ClockEventFilterTable::CreateCursor() +{ + cursor_ = std::make_unique(dataCache_); +} + +ClockEventFilterTable::Cursor::Cursor(const TraceDataCache* dataCache) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstClockEventFilterData().Size())) +{ +} + +ClockEventFilterTable::Cursor::~Cursor() {} + +int ClockEventFilterTable::Cursor::Column(int col) const +{ + switch (col) { + case ID: + sqlite3_result_int64(context_, static_cast( + dataCache_->GetConstClockEventFilterData().IdsData()[CurrentRow()])); + break; + case TYPE: { + size_t typeId = static_cast(dataCache_->GetConstClockEventFilterData().TypesData()[CurrentRow()]); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(typeId).c_str(), STR_DEFAULT_LEN, nullptr); + break; + } + case NAME: { + size_t strId = static_cast(dataCache_->GetConstClockEventFilterData().NamesData()[CurrentRow()]); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(strId).c_str(), STR_DEFAULT_LEN, nullptr); + break; + } + case CPU: + sqlite3_result_int64(context_, static_cast( + dataCache_->GetConstClockEventFilterData().CpusData()[CurrentRow()])); + break; + default: + TS_LOGF("Unregistered column : %d", col); + break; + } + return SQLITE_OK; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/table/internal_slice_table.h b/trace_analyzer/src/table/clock_event_filter_table.h old mode 100755 new mode 100644 similarity index 74% rename from trace_analyzer/src/table/internal_slice_table.h rename to trace_analyzer/src/table/clock_event_filter_table.h index ae0c208e8..a61795035 --- a/trace_analyzer/src/table/internal_slice_table.h +++ b/trace_analyzer/src/table/clock_event_filter_table.h @@ -13,32 +13,30 @@ * limitations under the License. */ -#ifndef INTERNAL_SLICE_TABLE_H -#define INTERNAL_SLICE_TABLE_H +#ifndef SRC_CLOCK_EVENT_FILTER_TABLE_H +#define SRC_CLOCK_EVENT_FILTER_TABLE_H + #include "table_base.h" #include "trace_data_cache.h" namespace SysTuning { namespace TraceStreamer { -class InternalSliceTable : public TableBase { +class ClockEventFilterTable : public TableBase { public: - explicit InternalSliceTable(const TraceDataCache*); - ~InternalSliceTable() override; + explicit ClockEventFilterTable(const TraceDataCache* dataCache); + ~ClockEventFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; - - private: - const InternalSlices& slicesObj_; }; }; } // namespace TraceStreamer } // namespace SysTuning -#endif // INTERNAL_SLICE_TABLE_H +#endif // SRC_CLOCK_EVENT_FILTER_TABLE_H diff --git a/trace_analyzer/src/table/cpu_measure_filter_table.cpp b/trace_analyzer/src/table/cpu_measure_filter_table.cpp index 7cf1a940e..ba89f946a 100755 --- a/trace_analyzer/src/table/cpu_measure_filter_table.cpp +++ b/trace_analyzer/src/table/cpu_measure_filter_table.cpp @@ -19,14 +19,13 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { ID = 0, TYPE, NAME, UNIT, CPU }; +enum Index { ID = 0, TYPE, NAME, CPU }; } CpuMeasureFilterTable::CpuMeasureFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("unit", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("cpu", "UNSIGNED INT")); tablePriKey_.push_back("id"); } @@ -39,8 +38,8 @@ void CpuMeasureFilterTable::CreateCursor() } CpuMeasureFilterTable::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstCpuCounterData().Size())), - cpuCounterObj_(dataCache->GetConstCpuCounterData()) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstCpuMeasureData().Size())), + cpuMeasureObj_(dataCache->GetConstCpuMeasureData()) { } @@ -50,25 +49,22 @@ int CpuMeasureFilterTable::Cursor::Column(int column) const { switch (column) { case ID: - sqlite3_result_int64(context_, static_cast(cpuCounterObj_.IdsData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast(cpuMeasureObj_.IdsData()[CurrentRow()])); break; case TYPE: - sqlite3_result_text(context_, "cpu_counter_track", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "cpu_measure_filter", STR_DEFAULT_LEN, nullptr); break; case NAME: { const std::string& str = - dataCache_->GetDataFromDict(static_cast(cpuCounterObj_.NameData()[CurrentRow()])); + dataCache_->GetDataFromDict(static_cast(cpuMeasureObj_.NameData()[CurrentRow()])); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case UNIT: - sqlite3_result_int64(context_, static_cast(cpuCounterObj_.UnitData()[CurrentRow()])); - break; case CPU: - sqlite3_result_int64(context_, static_cast(cpuCounterObj_.CpuData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast(cpuMeasureObj_.CpuData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/cpu_measure_filter_table.h b/trace_analyzer/src/table/cpu_measure_filter_table.h index 95956209e..de9275fc3 100755 --- a/trace_analyzer/src/table/cpu_measure_filter_table.h +++ b/trace_analyzer/src/table/cpu_measure_filter_table.h @@ -23,19 +23,19 @@ namespace SysTuning { namespace TraceStreamer { class CpuMeasureFilterTable : public TableBase { public: - explicit CpuMeasureFilterTable(const TraceDataCache*); + explicit CpuMeasureFilterTable(const TraceDataCache* dataCache); ~CpuMeasureFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache*); +public: + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; private: - const CpuCounter& cpuCounterObj_; + const CpuMeasureFilter& cpuMeasureObj_; }; }; } // namespace TraceStreamer diff --git a/trace_analyzer/src/table/data_dict_table.cpp b/trace_analyzer/src/table/data_dict_table.cpp index f9eed5301..6804bc28d 100644 --- a/trace_analyzer/src/table/data_dict_table.cpp +++ b/trace_analyzer/src/table/data_dict_table.cpp @@ -23,9 +23,9 @@ enum Index { ID = 0, STR }; } DataDictTable::DataDictTable(const TraceDataCache* dataCache) : TableBase(dataCache) { - tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("data", "STRING")); - tablePriKey_.push_back("id"); + tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("data", "STRING")); + tablePriKey_.push_back("id"); } DataDictTable::~DataDictTable() {} @@ -53,7 +53,7 @@ int DataDictTable::Cursor::Column(int col) const sqlite3_result_text(context_, dataCache_->GetDataFromDict(index).c_str(), STR_DEFAULT_LEN, nullptr); break; default: - TUNING_LOGF("Unknown column %d", col); + TS_LOGF("Unknown column %d", col); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/data_dict_table.h b/trace_analyzer/src/table/data_dict_table.h index afbc8dfd5..435eb4cc3 100644 --- a/trace_analyzer/src/table/data_dict_table.h +++ b/trace_analyzer/src/table/data_dict_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class DataDictTable : public TableBase { public: - explicit DataDictTable(const TraceDataCache*); + explicit DataDictTable(const TraceDataCache* dataCache); ~DataDictTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; diff --git a/trace_analyzer/src/table/filter_table.cpp b/trace_analyzer/src/table/filter_table.cpp index 98c612bcc..471cca7f7 100644 --- a/trace_analyzer/src/table/filter_table.cpp +++ b/trace_analyzer/src/table/filter_table.cpp @@ -25,7 +25,7 @@ FilterTable::FilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("source_arg_set_id", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("source_arg_set_id", "UNSIGNED BIG INT")); tablePriKey_.push_back("id"); } @@ -60,7 +60,7 @@ int FilterTable::Cursor::Column(int column) const sqlite3_result_int64(context_, static_cast(filterObj_.SourceArgSetIdData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/instants_table.cpp b/trace_analyzer/src/table/instants_table.cpp index e54c8c015..28af7d701 100644 --- a/trace_analyzer/src/table/instants_table.cpp +++ b/trace_analyzer/src/table/instants_table.cpp @@ -53,19 +53,19 @@ int InstantsTable::Cursor::Column(int column) const sqlite3_result_int64(context_, static_cast(InstantsObj_.TimeStamData()[CurrentRow()])); break; case NAME: { - sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), - STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), STR_DEFAULT_LEN, + nullptr); break; } case REF: sqlite3_result_int64(context_, static_cast(InstantsObj_.InternalTidsData()[CurrentRow()])); break; case REF_TYPE: { - sqlite3_result_text(context_, "utid", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "itid", STR_DEFAULT_LEN, nullptr); break; } default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/instants_table.h b/trace_analyzer/src/table/instants_table.h index 6048828d8..27b039234 100644 --- a/trace_analyzer/src/table/instants_table.h +++ b/trace_analyzer/src/table/instants_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class InstantsTable : public TableBase { public: - explicit InstantsTable(const TraceDataCache*); + explicit InstantsTable(const TraceDataCache* dataCache); ~InstantsTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; diff --git a/trace_analyzer/src/table/internal_slice_table.cpp b/trace_analyzer/src/table/internal_slice_table.cpp deleted file mode 100644 index fa059ce4d..000000000 --- a/trace_analyzer/src/table/internal_slice_table.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "internal_slice_table.h" - -namespace SysTuning { -namespace TraceStreamer { -namespace { -enum Index { ID = 0, TS, DUR, INTERNAL_TID, FILTER_ID, CAT, NAME, DEPTH, STACK_ID, PARENT_STACK_ID, PARENT_ID }; -} -InternalSliceTable::InternalSliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) -{ - tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("ts", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("dur", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("track_id", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("cat", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("depth", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("stack_id", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("parent_stack_id", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("parent_id", "UNSIGNED INT")); - tablePriKey_.push_back("utid"); - tablePriKey_.push_back("ts"); - tablePriKey_.push_back("depth"); -} - -InternalSliceTable::~InternalSliceTable() {} - -void InternalSliceTable::CreateCursor() -{ - cursor_ = std::make_unique(dataCache_); -} - -InternalSliceTable::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstInternalSlicesData().Size())), - slicesObj_(dataCache->GetConstInternalSlicesData()) -{ -} - -InternalSliceTable::Cursor::~Cursor() {} - -int InternalSliceTable::Cursor::Column(int column) const -{ - switch (column) { - case ID: - sqlite3_result_int64(context_, CurrentRow()); - break; - case TS: - sqlite3_result_int64(context_, static_cast(slicesObj_.TimeStamData()[CurrentRow()])); - break; - case DUR: - sqlite3_result_int64(context_, static_cast(slicesObj_.DursData()[CurrentRow()])); - break; - case INTERNAL_TID: - sqlite3_result_int64(context_, static_cast(slicesObj_.InternalTidsData()[CurrentRow()])); - break; - case FILTER_ID: - sqlite3_result_int64(context_, static_cast(slicesObj_.FilterIdData()[CurrentRow()])); - break; - case CAT: { - size_t stringIdentity = static_cast(slicesObj_.CatsData()[CurrentRow()]); - sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), - STR_DEFAULT_LEN, nullptr); - break; - } - case NAME: { - size_t stringIdentity = static_cast(slicesObj_.NamesData()[CurrentRow()]); - sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), - STR_DEFAULT_LEN, nullptr); - break; - } - case DEPTH: - sqlite3_result_int64(context_, static_cast(slicesObj_.Depths()[CurrentRow()])); - break; - case STACK_ID: - sqlite3_result_int64(context_, static_cast(slicesObj_.StackIdsData()[CurrentRow()])); - break; - case PARENT_STACK_ID: - sqlite3_result_int64(context_, static_cast(slicesObj_.ParentStackIds()[CurrentRow()])); - break; - case PARENT_ID: { - if (slicesObj_.ParentIdData()[CurrentRow()].has_value()) { - sqlite3_result_int64(context_, static_cast(slicesObj_.ParentIdData()[CurrentRow()].value())); - } - break; - } - default: - TUNING_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/table/internal_thread.cpp b/trace_analyzer/src/table/internal_thread.cpp deleted file mode 100644 index 766c5df53..000000000 --- a/trace_analyzer/src/table/internal_thread.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "internal_thread.h" - -namespace SysTuning { -namespace TraceStreamer { -namespace { -enum Index { ID = 0, TYPE, TID, NAME, START_TS, END_TS, INTERNAL_PID, IS_MAIN_THREAD }; -} -InternalThread::InternalThread(const TraceDataCache* dataCache) : TableBase(dataCache) -{ - tableColumn_.push_back(TableBase::ColumnInfo("id", "INT")); - tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("tid", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("start_ts", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("end_ts", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("upid", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("is_main_thread", "UNSIGNED INT")); - tablePriKey_.push_back("id"); -} - -InternalThread::~InternalThread() {} - -void InternalThread::CreateCursor() -{ - cursor_ = std::make_unique(dataCache_); -} - -InternalThread::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->ThreadSize())) -{ -} - -InternalThread::Cursor::~Cursor() {} - -int InternalThread::Cursor::Column(int column) const -{ - switch (column) { - case ID: { - sqlite3_result_int64(context_, CurrentRow()); - break; - } - case TYPE: { - sqlite3_result_text(context_, "internal_thread", strlen("internal_thread"), nullptr); - break; - } - case TID: { - const auto& process = dataCache_->GetConstThreadData(CurrentRow()); - sqlite3_result_int64(context_, static_cast(process.tid_)); - break; - } - case NAME: { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - const auto& name = dataCache_->GetDataFromDict(thread.nameIndex_); - sqlite3_result_text(context_, name.c_str(), static_cast(name.length()), nullptr); - break; - } - case START_TS: { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - sqlite3_result_int64(context_, static_cast(thread.startT_)); - break; - } - case END_TS: { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - sqlite3_result_int64(context_, static_cast(thread.endT_)); - break; - } - case INTERNAL_PID: { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - sqlite3_result_int(context_, static_cast(thread.internalPid_)); - break; - } - case IS_MAIN_THREAD: { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - const auto& process = dataCache_->GetConstProcessData(thread.internalPid_); - sqlite3_result_int(context_, thread.tid_ == process.pid_); - break; - } - default: - TUNING_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/table/measure_filter_table.cpp b/trace_analyzer/src/table/measure_filter_table.cpp index 29a944f3b..50882a940 100644 --- a/trace_analyzer/src/table/measure_filter_table.cpp +++ b/trace_analyzer/src/table/measure_filter_table.cpp @@ -25,7 +25,7 @@ MeasureFilterTable::MeasureFilterTable(const TraceDataCache* dataCache) : TableB tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("itid", "UNSIGNED INT")); tablePriKey_.push_back("id"); } @@ -37,7 +37,7 @@ void MeasureFilterTable::CreateCursor() } MeasureFilterTable::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->ThreadCounterFilterData()->Size())) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstThreadMeasureFilterData().Size())) { } @@ -47,24 +47,26 @@ int MeasureFilterTable::Cursor::Column(int column) const { switch (column) { case ID: - sqlite3_result_int64(context_, - static_cast(dataCache_->ThreadCounterFilterData()->FilterIdData()[CurrentRow()])); + sqlite3_result_int64( + context_, + static_cast(dataCache_->GetConstThreadMeasureFilterData().FilterIdData()[CurrentRow()])); break; case TYPE: - sqlite3_result_text(context_, "thread_counter_track", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "thread_measure_filter", STR_DEFAULT_LEN, nullptr); break; case NAME: { - const std::string& str = - dataCache_->GetDataFromDict(dataCache_->ThreadCounterFilterData()->NameIndexData()[CurrentRow()]); + const std::string& str = dataCache_->GetDataFromDict( + dataCache_->GetConstThreadMeasureFilterData().NameIndexData()[CurrentRow()]); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } case INTERNAL_TID: - sqlite3_result_int64(context_, - static_cast(dataCache_->ThreadCounterFilterData()->InternalTidData()[CurrentRow()])); + sqlite3_result_int64( + context_, + static_cast(dataCache_->GetConstThreadMeasureFilterData().InternalTidData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/measure_filter_table.h b/trace_analyzer/src/table/measure_filter_table.h index 39df53ce3..f07aeb784 100644 --- a/trace_analyzer/src/table/measure_filter_table.h +++ b/trace_analyzer/src/table/measure_filter_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class MeasureFilterTable : public TableBase { public: - explicit MeasureFilterTable(const TraceDataCache*); + explicit MeasureFilterTable(const TraceDataCache* dataCache); ~MeasureFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; diff --git a/trace_analyzer/src/table/measure_table.cpp b/trace_analyzer/src/table/measure_table.cpp index 24b4c5c46..2636dc70b 100644 --- a/trace_analyzer/src/table/measure_table.cpp +++ b/trace_analyzer/src/table/measure_table.cpp @@ -25,9 +25,9 @@ MeasureTable::MeasureTable(const TraceDataCache* dataCache) : TableBase(dataCach tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("ts", "UNSIGNED BIG INT")); tableColumn_.push_back(TableBase::ColumnInfo("value", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("track_id", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("filter_id", "UNSIGNED INT")); tablePriKey_.push_back("ts"); - tablePriKey_.push_back("track_id"); + tablePriKey_.push_back("filter_id"); } MeasureTable::~MeasureTable() {} @@ -38,8 +38,8 @@ void MeasureTable::CreateCursor() } MeasureTable::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstCounterData().Size())), - counterObj(dataCache->GetConstCounterData()) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstMeasureData().Size())), + measureObj(dataCache->GetConstMeasureData()) { } @@ -49,19 +49,19 @@ int MeasureTable::Cursor::Column(int column) const { switch (column) { case TYPE: - sqlite3_result_text(context_, "counter", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "measure", STR_DEFAULT_LEN, nullptr); break; case TS: - sqlite3_result_int64(context_, static_cast(counterObj.TimeStamData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast(measureObj.TimeStamData()[CurrentRow()])); break; case VALUE: - sqlite3_result_int64(context_, static_cast(counterObj.ValuesData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast(measureObj.ValuesData()[CurrentRow()])); break; case FILTER_ID: - sqlite3_result_int64(context_, static_cast(counterObj.FilterIdData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast(measureObj.FilterIdData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/measure_table.h b/trace_analyzer/src/table/measure_table.h index 3b3f604fb..b77875ffc 100644 --- a/trace_analyzer/src/table/measure_table.h +++ b/trace_analyzer/src/table/measure_table.h @@ -23,19 +23,19 @@ namespace SysTuning { namespace TraceStreamer { class MeasureTable : public TableBase { public: - explicit MeasureTable(const TraceDataCache*); + explicit MeasureTable(const TraceDataCache* dataCache); ~MeasureTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; private: - const Counter& counterObj; + const Measure& measureObj; }; }; } // namespace TraceStreamer diff --git a/trace_analyzer/src/table/meta_table.cpp b/trace_analyzer/src/table/meta_table.cpp new file mode 100644 index 000000000..4d9304cfd --- /dev/null +++ b/trace_analyzer/src/table/meta_table.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 "meta_table.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +enum Index { NAMEINDEX = 0, VALUE }; +} +MetaTable::MetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) +{ + tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("value", "STRING")); + tablePriKey_.push_back("name"); +} + +MetaTable::~MetaTable() {} + +void MetaTable::CreateCursor() +{ + cursor_ = std::make_unique(dataCache_); +} + +MetaTable::Cursor::Cursor(const TraceDataCache* dataCache) : TableBase::Cursor(dataCache, 0, METADATA_ITEM_MAX) {} + +MetaTable::Cursor::~Cursor() {} + +int MetaTable::Cursor::Column(int column) const +{ + switch (column) { + case NAMEINDEX: + sqlite3_result_text(context_, dataCache_->GetConstMetaData().Name(CurrentRow()).c_str(), STR_DEFAULT_LEN, + nullptr); + break; + case VALUE: + sqlite3_result_text(context_, dataCache_->GetConstMetaData().Value(CurrentRow()).c_str(), STR_DEFAULT_LEN, + nullptr); + break; + default: + TS_LOGF("Unregistered column : %d", column); + break; + } + return SQLITE_OK; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/table/bound_table.h b/trace_analyzer/src/table/meta_table.h similarity index 79% rename from trace_analyzer/src/table/bound_table.h rename to trace_analyzer/src/table/meta_table.h index ab3da9da5..4ca1f9f73 100644 --- a/trace_analyzer/src/table/bound_table.h +++ b/trace_analyzer/src/table/meta_table.h @@ -13,27 +13,27 @@ * limitations under the License. */ -#ifndef BOUND_TABLE_H -#define BOUND_TABLE_H +#ifndef META_TABLE_H +#define META_TABLE_H #include "table_base.h" #include "trace_data_cache.h" namespace SysTuning { namespace TraceStreamer { -class BoundTable : public TableBase { +class MetaTable : public TableBase { public: - explicit BoundTable(const TraceDataCache*); - ~BoundTable() override; + explicit MetaTable(const TraceDataCache* dataCache); + ~MetaTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; }; } // namespace TraceStreamer } // namespace SysTuning -#endif // BOUND_TABLE_H +#endif // META_TABLE_H diff --git a/trace_analyzer/src/table/process_filter_table.cpp b/trace_analyzer/src/table/process_filter_table.cpp index 9dd03efa0..63bba49ac 100644 --- a/trace_analyzer/src/table/process_filter_table.cpp +++ b/trace_analyzer/src/table/process_filter_table.cpp @@ -18,14 +18,14 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { ID = 0, TYPE, NAME, INTERNAL_PID}; +enum Index { ID = 0, TYPE, NAME, INTERNAL_PID }; } ProcessFilterTable::ProcessFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("upid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("ipid", "UNSIGNED INT")); tablePriKey_.push_back("id"); } @@ -51,19 +51,19 @@ int ProcessFilterTable::Cursor::Column(int col) const sqlite3_result_int64(context_, static_cast(processFilterObj_.IdsData()[CurrentRow()])); break; case TYPE: - sqlite3_result_text(context_, "process_track", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "process_filter", STR_DEFAULT_LEN, nullptr); break; case NAME: { DataIndex stringIdentity = static_cast(processFilterObj_.NamesData()[CurrentRow()]); - sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), - STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), STR_DEFAULT_LEN, + nullptr); break; } case INTERNAL_PID: sqlite3_result_int64(context_, static_cast(processFilterObj_.UpidsData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", col); + TS_LOGF("Unregistered column : %d", col); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/process_filter_table.h b/trace_analyzer/src/table/process_filter_table.h index a898b61fc..28a59a2ab 100644 --- a/trace_analyzer/src/table/process_filter_table.h +++ b/trace_analyzer/src/table/process_filter_table.h @@ -18,25 +18,24 @@ #include "table_base.h" #include "trace_data_cache.h" -#include "trace_streamer_filters.h" namespace SysTuning { namespace TraceStreamer { class ProcessFilterTable : public TableBase { public: - explicit ProcessFilterTable(const TraceDataCache*); + explicit ProcessFilterTable(const TraceDataCache* dataCache); ~ProcessFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; private: - const ProcessCounterFilter& processFilterObj_; + const ProcessMeasureFilter& processFilterObj_; }; }; } // namespace TraceStreamer diff --git a/trace_analyzer/src/table/process_measure_filter_table.cpp b/trace_analyzer/src/table/process_measure_filter_table.cpp index 56f4f0ba3..afd6e8073 100644 --- a/trace_analyzer/src/table/process_measure_filter_table.cpp +++ b/trace_analyzer/src/table/process_measure_filter_table.cpp @@ -25,7 +25,7 @@ ProcessMeasureFilterTable::ProcessMeasureFilterTable(const TraceDataCache* dataC tableColumn_.push_back(TableBase::ColumnInfo("id", "INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("upid", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("ipid", "INT")); tablePriKey_.push_back("id"); } @@ -37,7 +37,7 @@ void ProcessMeasureFilterTable::CreateCursor() } ProcessMeasureFilterTable::Cursor::Cursor(const TraceDataCache* dataCache) - : TableBase::Cursor(dataCache, 0, static_cast(dataCache->ProcessCounterFilterData().Size())) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstProcessMeasureFilterData().Size())) { } @@ -47,23 +47,25 @@ int ProcessMeasureFilterTable::Cursor::Column(int col) const { switch (col) { case ID: - sqlite3_result_int64(context_, - static_cast(dataCache_->ProcessCounterFilterData().IdsData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast( + dataCache_->GetConstProcessMeasureFilterData().IdsData()[CurrentRow()])); break; case TYPE: - sqlite3_result_text(context_, "process_counter_track", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "process_measure_filter", STR_DEFAULT_LEN, nullptr); break; case NAME: { - size_t strId = static_cast(dataCache_->ProcessCounterFilterData().NamesData()[CurrentRow()]); + size_t strId = + static_cast(dataCache_->GetConstProcessMeasureFilterData().NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(strId).c_str(), STR_DEFAULT_LEN, nullptr); break; } case INTERNAL_PID: - sqlite3_result_int64(context_, - static_cast(dataCache_->ProcessCounterFilterData().UpidsData()[CurrentRow()])); + sqlite3_result_int64( + context_, + static_cast(dataCache_->GetConstProcessMeasureFilterData().UpidsData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", col); + TS_LOGF("Unregistered column : %d", col); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/process_measure_filter_table.h b/trace_analyzer/src/table/process_measure_filter_table.h index 3ebe61ec5..e06adf4d1 100644 --- a/trace_analyzer/src/table/process_measure_filter_table.h +++ b/trace_analyzer/src/table/process_measure_filter_table.h @@ -19,20 +19,19 @@ #include "table_base.h" #include "trace_data_cache.h" -#include "trace_streamer_filters.h" namespace SysTuning { namespace TraceStreamer { class ProcessMeasureFilterTable : public TableBase { public: - explicit ProcessMeasureFilterTable(const TraceDataCache*); + explicit ProcessMeasureFilterTable(const TraceDataCache* dataCache); ~ProcessMeasureFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; diff --git a/trace_analyzer/src/table/process_table.cpp b/trace_analyzer/src/table/process_table.cpp index 73c19bcc9..f2df99bea 100644 --- a/trace_analyzer/src/table/process_table.cpp +++ b/trace_analyzer/src/table/process_table.cpp @@ -52,20 +52,20 @@ int ProcessTable::Cursor::Column(int column) const sqlite3_result_int64(context_, CurrentRow()); break; case TYPE: - sqlite3_result_text(context_, "internal_process", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "process", STR_DEFAULT_LEN, nullptr); break; case PID: sqlite3_result_int64(context_, process.pid_); break; case NAME: - sqlite3_result_text(context_, process.cmdLine_.c_str(), - static_cast(process.cmdLine_.length()), nullptr); + sqlite3_result_text(context_, process.cmdLine_.c_str(), static_cast(process.cmdLine_.length()), + nullptr); break; case START_TS: sqlite3_result_int64(context_, static_cast(process.startT_)); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/process_table.h b/trace_analyzer/src/table/process_table.h index bc0d9b056..2110d6997 100644 --- a/trace_analyzer/src/table/process_table.h +++ b/trace_analyzer/src/table/process_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class ProcessTable : public TableBase { public: - explicit ProcessTable(const TraceDataCache*); + explicit ProcessTable(const TraceDataCache* dataCache); ~ProcessTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; diff --git a/trace_analyzer/src/table/bound_table.cpp b/trace_analyzer/src/table/range_table.cpp similarity index 76% rename from trace_analyzer/src/table/bound_table.cpp rename to trace_analyzer/src/table/range_table.cpp index 90e3b7320..d6580bb80 100644 --- a/trace_analyzer/src/table/bound_table.cpp +++ b/trace_analyzer/src/table/range_table.cpp @@ -13,42 +13,42 @@ * limitations under the License. */ -#include "bound_table.h" +#include "range_table.h" namespace SysTuning { namespace TraceStreamer { namespace { enum Index { START_TS = 0, END_TS }; } -BoundTable::BoundTable(const TraceDataCache* dataCache) : TableBase(dataCache) +RangeTable::RangeTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("start_ts", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("end_ts", "INT")); tablePriKey_.push_back("start_ts"); } -BoundTable::~BoundTable() {} +RangeTable::~RangeTable() {} -void BoundTable::CreateCursor() +void RangeTable::CreateCursor() { cursor_ = std::make_unique(dataCache_); } -BoundTable::Cursor::Cursor(const TraceDataCache* dataCache) : TableBase::Cursor(dataCache, 0, 1) {} +RangeTable::Cursor::Cursor(const TraceDataCache* dataCache) : TableBase::Cursor(dataCache, 0, 1) {} -BoundTable::Cursor::~Cursor() {} +RangeTable::Cursor::~Cursor() {} -int BoundTable::Cursor::Column(int column) const +int RangeTable::Cursor::Column(int column) const { switch (column) { case START_TS: - sqlite3_result_int64(context_, static_cast(dataCache_->BoundStartTime())); + sqlite3_result_int64(context_, static_cast(dataCache_->TraceStartTime())); break; case END_TS: - sqlite3_result_int64(context_, static_cast(dataCache_->BoundEndTime())); + sqlite3_result_int64(context_, static_cast(dataCache_->TraceEndTime())); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/range_table.h b/trace_analyzer/src/table/range_table.h new file mode 100644 index 000000000..9679668e3 --- /dev/null +++ b/trace_analyzer/src/table/range_table.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RANGE_TABLE_H +#define RANGE_TABLE_H + +#include "table_base.h" +#include "trace_data_cache.h" + +namespace SysTuning { +namespace TraceStreamer { +class RangeTable : public TableBase { +public: + explicit RangeTable(const TraceDataCache* dataCache); + ~RangeTable() override; + void CreateCursor() override; +private: + class Cursor : public TableBase::Cursor { + public: + explicit Cursor(const TraceDataCache* dataCache); + ~Cursor() override; + int Column(int) const override; + }; +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif // RANGE_TABLE_H diff --git a/trace_analyzer/src/table/raw_table.cpp b/trace_analyzer/src/table/raw_table.cpp index 8c20f7134..6a1086c63 100644 --- a/trace_analyzer/src/table/raw_table.cpp +++ b/trace_analyzer/src/table/raw_table.cpp @@ -27,7 +27,7 @@ RawTable::RawTable(const TraceDataCache* dataCache) : TableBase(dataCache) tableColumn_.push_back(TableBase::ColumnInfo("ts", "UNSIGNED BIG INT")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("cpu", "UNSIGNED INT")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("itid", "UNSIGNED INT")); tablePriKey_.push_back("id"); } @@ -75,7 +75,7 @@ int RawTable::Cursor::Column(int column) const sqlite3_result_int64(context_, static_cast(rawObj_.InternalTidData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/raw_table.h b/trace_analyzer/src/table/raw_table.h index fbb60affd..78322a0e6 100644 --- a/trace_analyzer/src/table/raw_table.h +++ b/trace_analyzer/src/table/raw_table.h @@ -24,14 +24,14 @@ namespace TraceStreamer { class RawTable : public TableBase { public: enum EventName : uint32_t { CPU_IDLE = 1, SCHED_WAKEUP = 2, SCHED_WAKING = 3 }; - explicit RawTable(const TraceDataCache*); + explicit RawTable(const TraceDataCache* dataCache); ~RawTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; diff --git a/trace_analyzer/src/table/sched_slice_table.cpp b/trace_analyzer/src/table/sched_slice_table.cpp index 9ce0f9837..e87e3036d 100644 --- a/trace_analyzer/src/table/sched_slice_table.cpp +++ b/trace_analyzer/src/table/sched_slice_table.cpp @@ -27,7 +27,7 @@ SchedSliceTable::SchedSliceTable(const TraceDataCache* dataCache) : TableBase(da tableColumn_.push_back(TableBase::ColumnInfo("ts", "INT")); tableColumn_.push_back(TableBase::ColumnInfo("dur", "UNSIGNED BIG INT")); tableColumn_.push_back(TableBase::ColumnInfo("cpu", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("itid", "UNSIGNED BIG INT")); tableColumn_.push_back(TableBase::ColumnInfo("end_state", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("priority", "INT")); tablePriKey_.push_back("id"); @@ -78,7 +78,7 @@ int SchedSliceTable::Cursor::Column(int col) const sqlite3_result_int64(context_, static_cast(schedSliceObj_.PriorityData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", col); + TS_LOGF("Unregistered column : %d", col); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/sched_slice_table.h b/trace_analyzer/src/table/sched_slice_table.h index 2a36050e0..bbf2cf688 100644 --- a/trace_analyzer/src/table/sched_slice_table.h +++ b/trace_analyzer/src/table/sched_slice_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class SchedSliceTable : public TableBase { public: - explicit SchedSliceTable(const TraceDataCache*); + explicit SchedSliceTable(const TraceDataCache* dataCache); ~SchedSliceTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; diff --git a/trace_analyzer/src/table/stat_table.cpp b/trace_analyzer/src/table/stat_table.cpp new file mode 100644 index 000000000..ea2fc0fd1 --- /dev/null +++ b/trace_analyzer/src/table/stat_table.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_table.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +enum Index { EVENT_NAME = 0, STAT_EVENT_TYPE = 1, COUNT = 2, SEVERITY = 3, SOURCE = 4 }; +} +StatTable::StatTable(const TraceDataCache* dataCache) : TableBase(dataCache) +{ + tableColumn_.push_back(TableBase::ColumnInfo("event_name", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("stat_type", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("count", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("serverity", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("source", "STRING")); + tablePriKey_.push_back("event_name"); + tablePriKey_.push_back("stat_type"); +} + +StatTable::~StatTable() {} + +void StatTable::CreateCursor() +{ + cursor_ = std::make_unique(dataCache_); +} + +StatTable::Cursor::Cursor(const TraceDataCache* dataCache) + : TableBase::Cursor(dataCache, 0, STAT_EVENT_MAX * TRACE_EVENT_MAX) +{ +} + +StatTable::Cursor::~Cursor() {} + +int StatTable::Cursor::Column(int column) const +{ + const StatAndInfo stat = dataCache_->GetConstStatAndInfo(); + SupportedTraceEventType eventType = static_cast(CurrentRow() / STAT_EVENT_MAX); + StatType statType = static_cast(CurrentRow() % STAT_EVENT_MAX); + switch (column) { + case EVENT_NAME: + sqlite3_result_text(context_, dataCache_->GetConstStatAndInfo().GetEvent(eventType).c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case STAT_EVENT_TYPE: + sqlite3_result_text(context_, dataCache_->GetConstStatAndInfo().GetStat(statType).c_str(), STR_DEFAULT_LEN, + nullptr); + break; + case COUNT: + sqlite3_result_int64( + context_, static_cast(dataCache_->GetConstStatAndInfo().GetValue(eventType, statType))); + break; + case SEVERITY: + sqlite3_result_text(context_, + dataCache_->GetConstStatAndInfo().GetSeverityDesc(eventType, statType).c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case SOURCE: + sqlite3_result_text(context_, "trace", STR_DEFAULT_LEN, nullptr); + break; + default: + TS_LOGF("Unregistered column : %d", column); + break; + } + return SQLITE_OK; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/table/stat_table.h b/trace_analyzer/src/table/stat_table.h new file mode 100644 index 000000000..a9c43ccae --- /dev/null +++ b/trace_analyzer/src/table/stat_table.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STAT_TABLE_H +#define STAT_TABLE_H + +#include "table_base.h" +#include "trace_data_cache.h" + +namespace SysTuning { +namespace TraceStreamer { +class StatTable : public TableBase { +public: + explicit StatTable(const TraceDataCache* dataCache); + ~StatTable() override; + void CreateCursor() override; +private: + class Cursor : public TableBase::Cursor { + public: + explicit Cursor(const TraceDataCache* dataCache); + ~Cursor() override; + int Column(int) const override; + }; +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif // STAT_TABLE_H diff --git a/trace_analyzer/src/table/symbols_table.cpp b/trace_analyzer/src/table/symbols_table.cpp new file mode 100644 index 000000000..e538e8425 --- /dev/null +++ b/trace_analyzer/src/table/symbols_table.cpp @@ -0,0 +1,70 @@ +/* + * 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 "symbols_table.h" +#include "trace_data_cache.h" + +namespace SysTuning { +namespace TraceStreamer { +namespace { +enum Index { ID = 0, STR, ADDR }; +} +SymbolsTable::SymbolsTable(const TraceDataCache* dataCache) : TableBase(dataCache) +{ + tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("funcname", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("addr", "UNSIGNED BIG INT")); + tablePriKey_.push_back("id"); +} + +SymbolsTable::~SymbolsTable() {} + +void SymbolsTable::CreateCursor() +{ + cursor_ = std::make_unique(dataCache_); +} + +SymbolsTable::Cursor::Cursor(const TraceDataCache* dataCache) + : TableBase::Cursor(dataCache, 0, static_cast(dataCache->GetConstSymbolsData().Size())) +{ +} + +SymbolsTable::Cursor::~Cursor() {} + +int SymbolsTable::Cursor::Column(int col) const +{ + DataIndex index = static_cast(CurrentRow()); + switch (col) { + case ID: + sqlite3_result_int64(context_, static_cast(CurrentRow())); + break; + case STR: + sqlite3_result_text( + context_, + dataCache_->GetDataFromDict(dataCache_->GetConstSymbolsData().GetConstFuncNames()[index]).c_str(), + STR_DEFAULT_LEN, nullptr); + break; + case ADDR: + sqlite3_result_int64(context_, + static_cast(dataCache_->GetConstSymbolsData().GetConstAddrs()[index])); + break; + default: + TS_LOGF("Unknown column %d", col); + break; + } + return SQLITE_OK; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/table/symbols_table.h b/trace_analyzer/src/table/symbols_table.h new file mode 100644 index 000000000..6759d8a35 --- /dev/null +++ b/trace_analyzer/src/table/symbols_table.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYMBOLS_DICT_TABLE_H +#define SYMBOLS_DICT_TABLE_H + +#include "table_base.h" +#include "trace_data_cache.h" + +namespace SysTuning { +namespace TraceStreamer { +class SymbolsTable : public TableBase { +public: + explicit SymbolsTable(const TraceDataCache* dataCache); + ~SymbolsTable() override; + void CreateCursor() override; + +private: + class Cursor : public TableBase::Cursor { + public: + explicit Cursor(const TraceDataCache* dataCache); + ~Cursor() override; + int Column(int) const override; + }; +}; +} // namespace TraceStreamer +} // namespace SysTuning +#endif // SYMBOLS_DICT_TABLE_H diff --git a/trace_analyzer/src/table/table.pri b/trace_analyzer/src/table/table.pri new file mode 100755 index 000000000..f5cf32e3d --- /dev/null +++ b/trace_analyzer/src/table/table.pri @@ -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. + +INCLUDEPATH += $$PWD +HEADERS += \ + $$PWD/range_table.h \ + $$PWD/cpu_measure_filter_table.h \ + $$PWD/data_dict_table.h \ + $$PWD/filter_table.h \ + $$PWD/instants_table.h \ + $$PWD/callstack_table.h \ + $$PWD/thread_table.h \ + $$PWD/measure_filter_table.h \ + $$PWD/measure_table.h \ + $$PWD/process_filter_table.h \ + $$PWD/process_measure_filter_table.h \ + $$PWD/process_table.h \ + $$PWD/raw_table.h \ + $$PWD/sched_slice_table.h \ + $$PWD/table_base.h \ + $$PWD/thread_filter_table.h \ + $$PWD/thread_state_table.h \ + $$PWD/clock_event_filter_table.h \ + $$PWD/stat_table.h \ + $$PWD/meta_table.h \ + $$PWD/symbols_table.h + +SOURCES += \ + $$PWD/range_table.cpp \ + $$PWD/cpu_measure_filter_table.cpp \ + $$PWD/data_dict_table.cpp \ + $$PWD/filter_table.cpp \ + $$PWD/instants_table.cpp \ + $$PWD/callstack_table.cpp \ + $$PWD/thread_table.cpp \ + $$PWD/measure_filter_table.cpp \ + $$PWD/measure_table.cpp \ + $$PWD/process_filter_table.cpp \ + $$PWD/process_measure_filter_table.cpp \ + $$PWD/process_table.cpp \ + $$PWD/raw_table.cpp \ + $$PWD/sched_slice_table.cpp \ + $$PWD/table_base.cpp \ + $$PWD/thread_filter_table.cpp \ + $$PWD/thread_state_table.cpp \ + $$PWD/clock_event_filter_table.cpp \ + $$PWD/stat_table.cpp \ + $$PWD/meta_table.cpp \ + $$PWD/symbols_table.cpp diff --git a/trace_analyzer/src/table/table_base.cpp b/trace_analyzer/src/table/table_base.cpp index c6e44e9bd..bd37c7103 100755 --- a/trace_analyzer/src/table/table_base.cpp +++ b/trace_analyzer/src/table/table_base.cpp @@ -18,6 +18,11 @@ #include #include "log.h" +#define UNUSED(expr) \ + do { \ + static_cast(expr); \ + } while (0) + namespace SysTuning { namespace TraceStreamer { namespace { @@ -28,17 +33,26 @@ struct TableContext { }; } // namespace -TableBase::~TableBase() = default; +TableBase::~TableBase() +{ + dataCache_ = nullptr; + cursor_ = nullptr; +} -void TableBase::TableRegister(sqlite3& db, const TraceDataCache* cache, - const std::string& tableName, TabTemplate tmplate) +void TableBase::TableRegister(sqlite3& db, + const TraceDataCache* cache, + const std::string& tableName, + TabTemplate tmplate) { std::unique_ptr context(std::make_unique()); context->dataCache = cache; context->tmplate = tmplate; sqlite3_module& module = context->module; - auto createFn = [](sqlite3* xdb, void* arg, int, const char* const*, sqlite3_vtab** tab, char**) { + auto createFn = [](sqlite3* xdb, void* arg, int argc, const char* const* argv, sqlite3_vtab** tab, char** other) { + UNUSED(argc); + UNUSED(argv); + UNUSED(other); auto xdesc = static_cast(arg); auto table = xdesc->tmplate(xdesc->dataCache); std::string createStmt = table->CreateTableSql(); @@ -57,26 +71,23 @@ void TableBase::TableRegister(sqlite3& db, const TraceDataCache* cache, module.xCreate = createFn; module.xConnect = createFn; - module.xBestIndex = [](sqlite3_vtab*, sqlite3_index_info*) { - return SQLITE_OK; - }; + module.xBestIndex = [](sqlite3_vtab*, sqlite3_index_info*) { return SQLITE_OK; }; module.xDisconnect = destroyFn; module.xDestroy = destroyFn; - module.xOpen = [](sqlite3_vtab* t, sqlite3_vtab_cursor** c) { - return (static_cast(t))->Open(c); - }; - module.xClose = [](sqlite3_vtab_cursor*) { + module.xOpen = [](sqlite3_vtab* t, sqlite3_vtab_cursor** c) { return (static_cast(t))->Open(c); }; + module.xClose = [](sqlite3_vtab_cursor* c) { + UNUSED(c); return SQLITE_OK; }; - module.xFilter = [](sqlite3_vtab_cursor*, int, const char*, int, sqlite3_value**) { + module.xFilter = [](sqlite3_vtab_cursor* c, int arg1, const char* arg2, int, sqlite3_value** sqlite) { + UNUSED(c); + UNUSED(arg1); + UNUSED(arg2); + UNUSED(sqlite); return SQLITE_OK; }; - module.xNext = [](sqlite3_vtab_cursor* c) { - return static_cast(c)->Next(); - }; - module.xEof = [](sqlite3_vtab_cursor* c) { - return static_cast(c)->Eof(); - }; + module.xNext = [](sqlite3_vtab_cursor* c) { return static_cast(c)->Next(); }; + module.xEof = [](sqlite3_vtab_cursor* c) { return static_cast(c)->Eof(); }; module.xColumn = [](sqlite3_vtab_cursor* c, sqlite3_context* a, int b) { static_cast(c)->context_ = a; return static_cast(c)->Column(b); @@ -118,6 +129,7 @@ TableBase::Cursor::Cursor(const TraceDataCache* dataCache, uint32_t row, uint32_ TableBase::Cursor::~Cursor() { context_ = nullptr; + dataCache_ = nullptr; } int TableBase::Cursor::Next() diff --git a/trace_analyzer/src/table/table_base.h b/trace_analyzer/src/table/table_base.h index a5949ee0e..edf7fb6aa 100755 --- a/trace_analyzer/src/table/table_base.h +++ b/trace_analyzer/src/table/table_base.h @@ -26,20 +26,19 @@ namespace SysTuning { namespace TraceStreamer { class TableBase; constexpr int STR_DEFAULT_LEN = -1; -using TabTemplate = std::unique_ptr(*)(const TraceDataCache*); +using TabTemplate = std::unique_ptr (*)(const TraceDataCache* dataCache); class TableBase : public sqlite3_vtab { public: virtual ~TableBase(); TableBase(const TableBase&) = delete; TableBase& operator=(const TableBase&) = delete; - template + template static void TableDeclare(sqlite3& db, TraceDataCache* dataCache, const std::string& name) { - TableRegister(db, dataCache, name, - [](const TraceDataCache* cache) { - return std::unique_ptr(std::make_unique(cache)); - }); + TableRegister(db, dataCache, name, [](const TraceDataCache* cache) { + return std::unique_ptr(std::make_unique(cache)); + }); dataCache->AppendNewTable(name); } @@ -52,10 +51,16 @@ public: virtual int Next(); virtual int Eof(); virtual int Column(int) const = 0; + + public: sqlite3_context* context_; + protected: uint32_t CurrentRow() const; + + protected: const TraceDataCache* dataCache_; + private: uint32_t currentRow_; uint32_t rowsTotalNum_; @@ -70,13 +75,16 @@ public: protected: explicit TableBase(const TraceDataCache* dataCache) : dataCache_(dataCache), cursor_(nullptr) {} virtual void CreateCursor() = 0; - std::vector tableColumn_ {}; - std::vector tablePriKey_ {}; + +protected: + std::vector tableColumn_{}; + std::vector tablePriKey_{}; const TraceDataCache* dataCache_; std::unique_ptr cursor_; + private: - static void TableRegister(sqlite3& db, const TraceDataCache*, const std::string& name, TabTemplate); - int Open(sqlite3_vtab_cursor**); + static void TableRegister(sqlite3& db, const TraceDataCache* cache, const std::string& name, TabTemplate tmplate); + int Open(sqlite3_vtab_cursor** ppCursor); }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/table/thread_filter_table.cpp b/trace_analyzer/src/table/thread_filter_table.cpp index 12da1dc67..2019725ab 100644 --- a/trace_analyzer/src/table/thread_filter_table.cpp +++ b/trace_analyzer/src/table/thread_filter_table.cpp @@ -25,7 +25,7 @@ ThreadFilterTable::ThreadFilterTable(const TraceDataCache* dataCache) : TableBas tableColumn_.push_back(TableBase::ColumnInfo("id", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("itid", "UNSIGNED INT")); tablePriKey_.push_back("id"); } @@ -47,11 +47,11 @@ int ThreadFilterTable::Cursor::Column(int column) const { switch (column) { case ID: - sqlite3_result_int64(context_, - static_cast(dataCache_->GetConstThreadFilterData().FilterIdData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast( + dataCache_->GetConstThreadFilterData().FilterIdData()[CurrentRow()])); break; case TYPE: - sqlite3_result_text(context_, "thread_track", STR_DEFAULT_LEN, nullptr); + sqlite3_result_text(context_, "thread_filter", STR_DEFAULT_LEN, nullptr); break; case NAME: { std::string str = @@ -60,11 +60,11 @@ int ThreadFilterTable::Cursor::Column(int column) const break; } case INTERNAL_TID: - sqlite3_result_int64(context_, - static_cast(dataCache_->GetConstThreadFilterData().InternalTidData()[CurrentRow()])); + sqlite3_result_int64(context_, static_cast( + dataCache_->GetConstThreadFilterData().InternalTidData()[CurrentRow()])); break; default: - TUNING_LOGF("Unregistered column : %d", column); + TS_LOGF("Unregistered column : %d", column); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/thread_filter_table.h b/trace_analyzer/src/table/thread_filter_table.h index 491d8e7fb..61b468ac8 100644 --- a/trace_analyzer/src/table/thread_filter_table.h +++ b/trace_analyzer/src/table/thread_filter_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class ThreadFilterTable : public TableBase { public: - explicit ThreadFilterTable(const TraceDataCache*); + explicit ThreadFilterTable(const TraceDataCache* dataCache); ~ThreadFilterTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; diff --git a/trace_analyzer/src/table/thread_state_table.cpp b/trace_analyzer/src/table/thread_state_table.cpp index 142888766..97d26b2ad 100644 --- a/trace_analyzer/src/table/thread_state_table.cpp +++ b/trace_analyzer/src/table/thread_state_table.cpp @@ -27,7 +27,7 @@ ThreadStateTable::ThreadStateTable(const TraceDataCache* dataCache) : TableBase( tableColumn_.push_back(TableBase::ColumnInfo("ts", "INT")); tableColumn_.push_back(TableBase::ColumnInfo("dur", "UNSIGNED BIG INT")); tableColumn_.push_back(TableBase::ColumnInfo("cpu", "UNSIGNED BIG INT")); - tableColumn_.push_back(TableBase::ColumnInfo("utid", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("itid", "INT")); tableColumn_.push_back(TableBase::ColumnInfo("state", "STRING")); tablePriKey_.push_back("id"); } @@ -69,7 +69,7 @@ int ThreadStateTable::Cursor::Column(int col) const break; case INTERNAL_TID: sqlite3_result_int64(context_, - static_cast(threadStateObj_.InternalTidsData()[CurrentRow()])); + static_cast(threadStateObj_.InternalTidsData()[CurrentRow()])); break; case STATE: { const std::string& str = dataCache_->GetConstSchedStateData(threadStateObj_.StatesData()[CurrentRow()]); @@ -77,7 +77,7 @@ int ThreadStateTable::Cursor::Column(int col) const break; } default: - TUNING_LOGF("Unregistered column : %d", col); + TS_LOGF("Unregistered column : %d", col); break; } return SQLITE_OK; diff --git a/trace_analyzer/src/table/thread_state_table.h b/trace_analyzer/src/table/thread_state_table.h index 7ebf2137c..5fde36c55 100644 --- a/trace_analyzer/src/table/thread_state_table.h +++ b/trace_analyzer/src/table/thread_state_table.h @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class ThreadStateTable : public TableBase { public: - explicit ThreadStateTable(const TraceDataCache*); + explicit ThreadStateTable(const TraceDataCache* dataCache); ~ThreadStateTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; diff --git a/trace_analyzer/src/table/thread_table.cpp b/trace_analyzer/src/table/thread_table.cpp index 06524bec4..202a04190 100644 --- a/trace_analyzer/src/table/thread_table.cpp +++ b/trace_analyzer/src/table/thread_table.cpp @@ -18,15 +18,19 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { INTERNAL_TID = 0, INTERNAL_PID, NAME, TID }; +enum Index { ID = 0, TYPE, TID, NAME, START_TS, END_TS, INTERNAL_PID, IS_MAIN_THREAD }; } ThreadTable::ThreadTable(const TraceDataCache* dataCache) : TableBase(dataCache) { - tableColumn_.push_back(TableBase::ColumnInfo("utid", "INT")); - tableColumn_.push_back(TableBase::ColumnInfo("upid", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("id", "INT")); + tableColumn_.push_back(TableBase::ColumnInfo("type", "STRING")); + tableColumn_.push_back(TableBase::ColumnInfo("tid", "UNSIGNED INT")); tableColumn_.push_back(TableBase::ColumnInfo("name", "STRING")); - tableColumn_.push_back(TableBase::ColumnInfo("tid", "INT")); - tablePriKey_.push_back("utid"); + tableColumn_.push_back(TableBase::ColumnInfo("start_ts", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("end_ts", "UNSIGNED BIG INT")); + tableColumn_.push_back(TableBase::ColumnInfo("ipid", "UNSIGNED INT")); + tableColumn_.push_back(TableBase::ColumnInfo("is_main_thread", "UNSIGNED INT")); + tablePriKey_.push_back("id"); } ThreadTable::~ThreadTable() {} @@ -45,29 +49,50 @@ ThreadTable::Cursor::~Cursor() {} int ThreadTable::Cursor::Column(int column) const { - const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); switch (column) { - case INTERNAL_TID: { + case ID: { sqlite3_result_int64(context_, CurrentRow()); break; } - case INTERNAL_PID: { - sqlite3_result_int64(context_, thread.internalPid_); + case TYPE: { + sqlite3_result_text(context_, "thread", strlen("thread"), nullptr); + break; + } + case TID: { + const auto& process = dataCache_->GetConstThreadData(CurrentRow()); + sqlite3_result_int64(context_, static_cast(process.tid_)); break; } case NAME: { + const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); const auto& name = dataCache_->GetDataFromDict(thread.nameIndex_); sqlite3_result_text(context_, name.c_str(), static_cast(name.length()), nullptr); break; } - case TID: { - sqlite3_result_int64(context_, thread.tid_); + case START_TS: { + const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); + sqlite3_result_int64(context_, static_cast(thread.startT_)); break; } - default: { - TUNING_LOGF("Unregistered column : %d", column); + case END_TS: { + const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); + sqlite3_result_int64(context_, static_cast(thread.endT_)); break; } + case INTERNAL_PID: { + const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); + sqlite3_result_int(context_, static_cast(thread.internalPid_)); + break; + } + case IS_MAIN_THREAD: { + const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); + const auto& process = dataCache_->GetConstProcessData(thread.internalPid_); + sqlite3_result_int(context_, thread.tid_ == process.pid_); + break; + } + default: + TS_LOGF("Unregistered column : %d", column); + break; } return SQLITE_OK; } diff --git a/trace_analyzer/src/table/thread_table.h b/trace_analyzer/src/table/thread_table.h index 0a0cc2692..3e9fd7c2a 100644 --- a/trace_analyzer/src/table/thread_table.h +++ b/trace_analyzer/src/table/thread_table.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef THREAD_TABLE_H -#define THREAD_TABLE_H +#ifndef SRC_THREAD_TABLE_H +#define SRC_THREAD_TABLE_H #include "table_base.h" #include "trace_data_cache.h" @@ -23,14 +23,14 @@ namespace SysTuning { namespace TraceStreamer { class ThreadTable : public TableBase { public: - explicit ThreadTable(const TraceDataCache*); + explicit ThreadTable(const TraceDataCache* dataCache); ~ThreadTable() override; void CreateCursor() override; private: class Cursor : public TableBase::Cursor { public: - explicit Cursor(const TraceDataCache*); + explicit Cursor(const TraceDataCache* dataCache); ~Cursor() override; int Column(int) const override; }; @@ -38,4 +38,4 @@ private: } // namespace TraceStreamer } // namespace SysTuning -#endif // THREAD_TABLE_H +#endif // SRC_THREAD_TABLE_H diff --git a/trace_analyzer/src/trace_data/trace_data.pri b/trace_analyzer/src/trace_data/trace_data.pri new file mode 100644 index 000000000..910cc5227 --- /dev/null +++ b/trace_analyzer/src/trace_data/trace_data.pri @@ -0,0 +1,28 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +INCLUDEPATH +=$$PWD +HEADERS += \ + $$PWD/trace_data_cache.h \ + $$PWD/trace_data_cache_base.h \ + $$PWD/trace_data_cache_reader.h \ + $$PWD/trace_data_cache_writer.h \ + $$PWD/trace_data_db.h \ + $$PWD/trace_stdtype.h + +SOURCES += \ + $$PWD/trace_data_cache.cpp \ + $$PWD/trace_data_cache_base.cpp \ + $$PWD/trace_data_cache_reader.cpp \ + $$PWD/trace_data_cache_writer.cpp \ + $$PWD/trace_data_db.cpp \ + $$PWD/trace_stdtype.cpp diff --git a/trace_analyzer/src/trace_data/trace_data_cache.cpp b/trace_analyzer/src/trace_data/trace_data_cache.cpp index 36fb94a4a..0267658bf 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache.cpp +++ b/trace_analyzer/src/trace_data/trace_data_cache.cpp @@ -16,20 +16,23 @@ #include "trace_data_cache.h" #include -#include "bound_table.h" +#include "callstack_table.h" +#include "clock_event_filter_table.h" #include "cpu_measure_filter_table.h" #include "data_dict_table.h" #include "filter_table.h" #include "instants_table.h" -#include "internal_slice_table.h" -#include "internal_thread.h" #include "measure_filter_table.h" #include "measure_table.h" +#include "meta_table.h" #include "process_filter_table.h" #include "process_measure_filter_table.h" #include "process_table.h" +#include "range_table.h" #include "raw_table.h" #include "sched_slice_table.h" +#include "stat_table.h" +#include "symbols_table.h" #include "table_base.h" #include "thread_filter_table.h" #include "thread_state_table.h" @@ -45,25 +48,28 @@ TraceDataCache::TraceDataCache() TraceDataCache::~TraceDataCache() { } - void TraceDataCache::InitDB() { - TableBase::TableDeclare(*db_, this, "internal_process"); + if (dbInited) { + return; + } + TableBase::TableDeclare(*db_, this, "process"); TableBase::TableDeclare(*db_, this, "sched_slice"); - TableBase::TableDeclare(*db_, this, "internal_slice"); - TableBase::TableDeclare(*db_, this, "strings"); + TableBase::TableDeclare(*db_, this, "callstack"); + TableBase::TableDeclare(*db_, this, "data_dict"); TableBase::TableDeclare(*db_, this, "thread_state"); TableBase::TableDeclare(*db_, this, "instant"); - TableBase::TableDeclare(*db_, this, "counter"); - TableBase::TableDeclare(*db_, this, "trace_bounds"); - TableBase::TableDeclare(*db_, this, "internal_thread"); + TableBase::TableDeclare(*db_, this, "measure"); + TableBase::TableDeclare(*db_, this, "trace_range"); + TableBase::TableDeclare(*db_, this, "thread"); TableBase::TableDeclare(*db_, this, "raw"); - TableBase::TableDeclare(*db_, this, "cpu_counter_track"); - TableBase::TableDeclare(*db_, this, "track"); - TableBase::TableDeclare(*db_, this, "thread_track"); - TableBase::TableDeclare(*db_, this, "thread_counter_track"); - TableBase::TableDeclare(*db_, this, "process_counter_track"); - TableBase::TableDeclare(*db_, this, "process_track"); + TableBase::TableDeclare(*db_, this, "cpu_measure_filter"); + TableBase::TableDeclare(*db_, this, "measure_filter"); + TableBase::TableDeclare(*db_, this, "process_measure_filter"); + TableBase::TableDeclare(*db_, this, "stat"); + TableBase::TableDeclare(*db_, this, "clock_event_filter"); + TableBase::TableDeclare(*db_, this, "symbols"); + dbInited = true; } } // namespace trace_streamer } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_cache.h b/trace_analyzer/src/trace_data/trace_data_cache.h index 57c3e2113..e1f995d67 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache.h +++ b/trace_analyzer/src/trace_data/trace_data_cache.h @@ -16,20 +16,23 @@ #ifndef TRACE_DATA_CACHE_H #define TRACE_DATA_CACHE_H +#include "trace_data_cache_reader.h" #include "trace_data_cache_writer.h" #include "trace_data_db.h" namespace SysTuning { namespace TraceStreamer { using namespace TraceStdtype; -class TraceDataCache : public TraceDataCacheWriter, public TraceDataDB { +class TraceDataCache : public TraceDataCacheReader, public TraceDataCacheWriter, public TraceDataDB { public: TraceDataCache(); - TraceDataCache(const TraceDataCache*) = delete; - TraceDataCache* operator=(const TraceDataCache*) = delete; + TraceDataCache(const TraceDataCache* dataCache) = delete; + TraceDataCache* operator=(const TraceDataCache* dataCache) = delete; ~TraceDataCache() override; + private: - void InitDB(); + void InitDB() override; + bool dbInited = false; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_cache_base.cpp b/trace_analyzer/src/trace_data/trace_data_cache_base.cpp index 0bdf3b97a..62314ea41 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_base.cpp +++ b/trace_analyzer/src/trace_data/trace_data_cache_base.cpp @@ -25,7 +25,6 @@ TraceDataCacheBase::TraceDataCacheBase() GetDataIndex(""); } -TraceDataCacheBase::~TraceDataCacheBase() {} DataIndex TraceDataCacheBase::GetDataIndex(std::string_view str) { return dataDict_.GetStringIndex(str); diff --git a/trace_analyzer/src/trace_data/trace_data_cache_base.h b/trace_analyzer/src/trace_data/trace_data_cache_base.h index 1234f035b..e78868616 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_base.h +++ b/trace_analyzer/src/trace_data/trace_data_cache_base.h @@ -35,7 +35,7 @@ public: TraceDataCacheBase(); TraceDataCacheBase(const TraceDataCacheBase&) = delete; TraceDataCacheBase& operator=(const TraceDataCacheBase&) = delete; - virtual ~TraceDataCacheBase(); + virtual ~TraceDataCacheBase() = default; public: size_t ThreadSize() const { @@ -55,32 +55,36 @@ public: {TASK_RUNNABLE, "R"}, {TASK_INTERRUPTIBLE, "S"}, {TASK_UNINTERRUPTIBLE, "D"}, {TASK_RUNNING, "Running"}, {TASK_INTERRUPTED, "I"}, {TASK_EXIT_DEAD, "X"}, {TASK_ZOMBIE, "Z"}, {TASK_KILLED, "I"}, {TASK_WAKEKILL, "R"}, {TASK_INVALID, "U"}, {TASK_CLONE, "I"}, {TASK_DK, "DK"}, - {TASK_FOREGROUND, "R+"} + {TASK_FOREGROUND, "R+"}, {TASK_MAX, "S"} }; - uint64_t boundtimeStart_ = std::numeric_limits::max(); - uint64_t boundtimeEnd_ = 0; + uint64_t traceStartTime_ = std::numeric_limits::max(); + uint64_t traceEndTime_ = 0; Raw rawData_; ThreadState threadStateData_; Instants instantsData_; Filter filterData_; - ProcessCounterFilter processCounterFilterData_; - ProcessCounterFilter processFilterData_; - ThreadCounterFilter threadCounterFilterData_; - ThreadCounterFilter threadFilterData_; + ProcessMeasureFilter processMeasureFilterData_; + ClockEventData clockEventFilterData_; + ProcessMeasureFilter processFilterData_; + ThreadMeasureFilter threadMeasureFilterData_; + ThreadMeasureFilter threadFilterData_; DataDict dataDict_; - Slices slicesData_; SchedSlice schedSliceData_; - InternalSlices internalSlicesData_; + CallStack internalSlicesData_; std::deque internalProcessesData_ {}; std::deque internalThreadsData_ {}; - Counter counterData_; - CpuCounter cpuCounterData_; + Measure measureData_; + CpuMeasureFilter cpuMeasureData_; + + StatAndInfo stat_; + MetaData metaData_; + SymbolsData symbolsData_; }; } // namespace trace_data_cache_base } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_cache_reader.cpp b/trace_analyzer/src/trace_data/trace_data_cache_reader.cpp index 1e491e415..3999b5df3 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_reader.cpp +++ b/trace_analyzer/src/trace_data/trace_data_cache_reader.cpp @@ -36,15 +36,15 @@ const std::string& TraceDataCacheReader::GetDataFromDict(DataIndex id) const } const Process& TraceDataCacheReader::GetConstProcessData(InternalPid internalPid) const { - TUNING_ASSERT(internalPid < internalProcessesData_.size()); + TS_ASSERT(internalPid < internalProcessesData_.size()); return internalProcessesData_[internalPid]; } const Thread& TraceDataCacheReader::GetConstThreadData(InternalTid internalTid) const { - TUNING_ASSERT(internalTid < internalThreadsData_.size()); + TS_ASSERT(internalTid < internalThreadsData_.size()); return internalThreadsData_[internalTid]; } -const InternalSlices& TraceDataCacheReader::GetConstInternalSlicesData() const +const CallStack& TraceDataCacheReader::GetConstInternalSlicesData() const { return internalSlicesData_; } @@ -56,14 +56,14 @@ const Raw& TraceDataCacheReader::GetConstRawTableData() const { return rawData_; } -const Counter& TraceDataCacheReader::GetConstCounterData() const +const Measure& TraceDataCacheReader::GetConstMeasureData() const { - return counterData_; + return measureData_; } -const ThreadCounterFilter* TraceDataCacheReader::ThreadCounterFilterData() const +const ThreadMeasureFilter& TraceDataCacheReader::GetConstThreadMeasureFilterData() const { - return &threadCounterFilterData_; + return threadMeasureFilterData_; } const ThreadState& TraceDataCacheReader::GetConstThreadStateData() const { @@ -73,11 +73,11 @@ const SchedSlice& TraceDataCacheReader::GetConstSchedSliceData() const { return schedSliceData_; } -const CpuCounter& TraceDataCacheReader::GetConstCpuCounterData() const +const CpuMeasureFilter& TraceDataCacheReader::GetConstCpuMeasureData() const { - return cpuCounterData_; + return cpuMeasureData_; } -const ThreadCounterFilter& TraceDataCacheReader::GetConstThreadFilterData() const +const ThreadMeasureFilter& TraceDataCacheReader::GetConstThreadFilterData() const { return threadFilterData_; } @@ -85,26 +85,45 @@ const Instants& TraceDataCacheReader::GetConstInstantsData() const { return instantsData_; } -const ProcessCounterFilter& TraceDataCacheReader::GetConstProcessFilterData() const +const ProcessMeasureFilter& TraceDataCacheReader::GetConstProcessFilterData() const { return processFilterData_; } -const ProcessCounterFilter& TraceDataCacheReader::ProcessCounterFilterData() const +const ProcessMeasureFilter& TraceDataCacheReader::GetConstProcessMeasureFilterData() const { - return processCounterFilterData_; + return processMeasureFilterData_; +} + +const ClockEventData& TraceDataCacheReader::GetConstClockEventFilterData() const +{ + return clockEventFilterData_; } const std::string& TraceDataCacheReader::GetConstSchedStateData(uint64_t rowId) const { - TUNING_ASSERT(statusString_.find(rowId) != statusString_.end()); + TS_ASSERT(statusString_.find(rowId) != statusString_.end()); return statusString_.at(rowId); } -uint64_t TraceDataCacheReader::BoundStartTime() const +uint64_t TraceDataCacheReader::TraceStartTime() const { - return boundtimeStart_; + return traceStartTime_; } -uint64_t TraceDataCacheReader::BoundEndTime() const +uint64_t TraceDataCacheReader::TraceEndTime() const { - return boundtimeEnd_; + return traceEndTime_; +} + +const StatAndInfo& TraceDataCacheReader::GetConstStatAndInfo() const +{ + return stat_; +} +const MetaData& TraceDataCacheReader::GetConstMetaData() const +{ + return metaData_; +} + +const SymbolsData& TraceDataCacheReader::GetConstSymbolsData() const +{ + return symbolsData_; } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_cache_reader.h b/trace_analyzer/src/trace_data/trace_data_cache_reader.h index c81bed6e3..335680208 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_reader.h +++ b/trace_analyzer/src/trace_data/trace_data_cache_reader.h @@ -23,32 +23,37 @@ namespace SysTuning { namespace TraceStreamer { using namespace TraceStdtype; -class TraceDataCacheReader : public TraceDataCacheBase { +class TraceDataCacheReader : virtual public TraceDataCacheBase { public: TraceDataCacheReader() = default; TraceDataCacheReader(const TraceDataCacheReader&) = delete; TraceDataCacheReader& operator=(const TraceDataCacheReader&) = delete; ~TraceDataCacheReader() override; + public: const std::string& GetDataFromDict(DataIndex id) const; const Process& GetConstProcessData(InternalPid internalPid) const; const Thread& GetConstThreadData(InternalTid internalTid) const; - const InternalSlices& GetConstInternalSlicesData() const; + const CallStack& GetConstInternalSlicesData() const; const Filter& GetConstFilterData() const; const Raw& GetConstRawTableData() const; - const Counter& GetConstCounterData() const; - const ThreadCounterFilter* ThreadCounterFilterData() const; + const Measure& GetConstMeasureData() const; + const ThreadMeasureFilter& GetConstThreadMeasureFilterData() const; const ThreadState& GetConstThreadStateData() const; const SchedSlice& GetConstSchedSliceData() const; - const CpuCounter& GetConstCpuCounterData() const; - const ThreadCounterFilter& GetConstThreadFilterData() const; + const CpuMeasureFilter& GetConstCpuMeasureData() const; + const ThreadMeasureFilter& GetConstThreadFilterData() const; const Instants& GetConstInstantsData() const; - const ProcessCounterFilter& GetConstProcessFilterData() const; - const ProcessCounterFilter& ProcessCounterFilterData() const; + const ProcessMeasureFilter& GetConstProcessFilterData() const; + const ProcessMeasureFilter& GetConstProcessMeasureFilterData() const; + const ClockEventData& GetConstClockEventFilterData() const; const std::string& GetConstSchedStateData(uint64_t rowId) const; - uint64_t BoundStartTime() const; - uint64_t BoundEndTime() const; + uint64_t TraceStartTime() const; + uint64_t TraceEndTime() const; + const StatAndInfo& GetConstStatAndInfo() const; + const MetaData& GetConstMetaData() const; + const SymbolsData& GetConstSymbolsData() const; }; -} -} +} // namespace TraceStreamer +} // namespace SysTuning #endif diff --git a/trace_analyzer/src/trace_data/trace_data_cache_writer.cpp b/trace_analyzer/src/trace_data/trace_data_cache_writer.cpp index 84ef72eb3..9df417d6d 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_writer.cpp +++ b/trace_analyzer/src/trace_data/trace_data_cache_writer.cpp @@ -36,32 +36,28 @@ InternalPid TraceDataCacheWriter::GetProcessInternalPid(uint32_t pid) } Process* TraceDataCacheWriter::GetProcessData(InternalPid internalPid) { - TUNING_ASSERT(internalPid < internalProcessesData_.size()); + TS_ASSERT(internalPid < internalProcessesData_.size()); return &internalProcessesData_[internalPid]; } -InternalTid TraceDataCacheWriter::GetInternalThread(uint32_t tid) +InternalTid TraceDataCacheWriter::NewInternalThread(uint32_t tid) { internalThreadsData_.emplace_back(tid); return static_cast(internalThreadsData_.size() - 1); } Thread* TraceDataCacheWriter::GetThreadData(InternalTid internalTid) { - TUNING_ASSERT(internalTid < internalThreadsData_.size()); + TS_ASSERT(internalTid < internalThreadsData_.size()); return &internalThreadsData_[internalTid]; } -void TraceDataCacheWriter::UpdateBoundTime(uint64_t timestamp) +void TraceDataCacheWriter::UpdateTraceTime(uint64_t timestamp) { - boundtimeStart_ = std::min(boundtimeStart_, timestamp); - boundtimeEnd_ = std::max(boundtimeEnd_, timestamp); + traceStartTime_ = std::min(traceStartTime_, timestamp); + traceEndTime_ = std::max(traceEndTime_, timestamp); } -Slices* TraceDataCacheWriter::GetSlicesData() -{ - return &slicesData_; -} -InternalSlices* TraceDataCacheWriter::GetInternalSlicesData() +CallStack* TraceDataCacheWriter::GetInternalSlicesData() { return &internalSlicesData_; } @@ -76,9 +72,9 @@ Raw* TraceDataCacheWriter::GetRawData() return &rawData_; } -Counter* TraceDataCacheWriter::GetCounterData() +Measure* TraceDataCacheWriter::GetMeasureData() { - return &counterData_; + return &measureData_; } ThreadState* TraceDataCacheWriter::GetThreadStateData() @@ -91,17 +87,17 @@ SchedSlice* TraceDataCacheWriter::GetSchedSliceData() return &schedSliceData_; } -CpuCounter* TraceDataCacheWriter::GetCpuCountersData() +CpuMeasureFilter* TraceDataCacheWriter::GetCpuMeasuresData() { - return &cpuCounterData_; + return &cpuMeasureData_; } -ThreadCounterFilter* TraceDataCacheWriter::GetThreadCounterFilterData() +ThreadMeasureFilter* TraceDataCacheWriter::GetThreadMeasureFilterData() { - return &threadCounterFilterData_; + return &threadMeasureFilterData_; } -ThreadCounterFilter* TraceDataCacheWriter::GetThreadFilterData() +ThreadMeasureFilter* TraceDataCacheWriter::GetThreadFilterData() { return &threadFilterData_; } @@ -111,14 +107,33 @@ Instants* TraceDataCacheWriter::GetInstantsData() return &instantsData_; } -ProcessCounterFilter* TraceDataCacheWriter::GetProcessFilterData() +ProcessMeasureFilter* TraceDataCacheWriter::GetProcessFilterData() { return &processFilterData_; } -ProcessCounterFilter* TraceDataCacheWriter::GetProcessCounterFilterData() +ProcessMeasureFilter* TraceDataCacheWriter::GetProcessMeasureFilterData() { - return &processCounterFilterData_; + return &processMeasureFilterData_; +} + +ClockEventData* TraceDataCacheWriter::GetClockEventFilterData() +{ + return &clockEventFilterData_; +} +StatAndInfo* TraceDataCacheWriter::GetStatAndInfo() +{ + return &stat_; +} + +MetaData* TraceDataCacheWriter::GetMetaData() +{ + return &metaData_; +} + +SymbolsData* TraceDataCacheWriter::GetSymbolsData() +{ + return &symbolsData_; } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_cache_writer.h b/trace_analyzer/src/trace_data/trace_data_cache_writer.h index ad0503fe0..68aa332a7 100644 --- a/trace_analyzer/src/trace_data/trace_data_cache_writer.h +++ b/trace_analyzer/src/trace_data/trace_data_cache_writer.h @@ -21,7 +21,7 @@ namespace SysTuning { namespace TraceStreamer { using namespace TraceStdtype; -class TraceDataCacheWriter : public TraceDataCacheReader { +class TraceDataCacheWriter : virtual public TraceDataCacheBase { public: TraceDataCacheWriter() = default; TraceDataCacheWriter(const TraceDataCacheWriter&) = delete; @@ -30,22 +30,25 @@ public: public: InternalPid GetProcessInternalPid(uint32_t pid); Process* GetProcessData(InternalPid internalPid); - InternalTid GetInternalThread(uint32_t tid); + InternalTid NewInternalThread(uint32_t tid); Thread* GetThreadData(InternalTid internalTid); - void UpdateBoundTime(uint64_t timestamp); - Slices* GetSlicesData(); - InternalSlices* GetInternalSlicesData(); + void UpdateTraceTime(uint64_t timestamp); + CallStack* GetInternalSlicesData(); Filter* GetFilterData(); Raw* GetRawData(); - Counter* GetCounterData(); + Measure* GetMeasureData(); ThreadState* GetThreadStateData(); SchedSlice* GetSchedSliceData(); - CpuCounter* GetCpuCountersData(); - ThreadCounterFilter* GetThreadCounterFilterData(); - ThreadCounterFilter* GetThreadFilterData(); + CpuMeasureFilter* GetCpuMeasuresData(); + ThreadMeasureFilter* GetThreadMeasureFilterData(); + ThreadMeasureFilter* GetThreadFilterData(); Instants* GetInstantsData(); - ProcessCounterFilter* GetProcessFilterData(); - ProcessCounterFilter* GetProcessCounterFilterData(); + ProcessMeasureFilter* GetProcessFilterData(); + ProcessMeasureFilter* GetProcessMeasureFilterData(); + ClockEventData* GetClockEventFilterData(); + StatAndInfo* GetStatAndInfo(); + MetaData* GetMetaData(); + SymbolsData* GetSymbolsData(); }; } // namespace TraceStreamer } // namespace trace_data_cache diff --git a/trace_analyzer/src/trace_data/trace_data_db.cpp b/trace_analyzer/src/trace_data/trace_data_db.cpp index f8e7f408e..315f23605 100644 --- a/trace_analyzer/src/trace_data/trace_data_db.cpp +++ b/trace_analyzer/src/trace_data/trace_data_db.cpp @@ -21,14 +21,34 @@ #include #include +#include "codec_cov.h" #include "file.h" #include "log.h" +#define UNUSED(expr) \ + do { \ + static_cast(expr); \ + } while (0) namespace SysTuning { namespace TraceStreamer { +// sqlite defined function module +int PrintQueryResult(void* para, int column, char** columnValue, char** columnName) +{ + UNUSED(para); + int i; + printf("Query results include %d column\n", column); + for (i = 0; i < column; i++) { + printf("name : %s \t value : %s\n", columnName[i], columnValue[i]); + } + printf("------------------\n"); + return 0; +} + TraceDataDB::TraceDataDB() : db_(nullptr) { - sqlite3_open(":memory:", &db_); + if (sqlite3_open(":memory:", &db_)) { + TS_LOGF("open :memory db failed"); + } } TraceDataDB::~TraceDataDB() { @@ -39,6 +59,10 @@ void TraceDataDB::AppendNewTable(std::string tableName) { internalTables_.push_back(tableName); } +void TraceDataDB::EnableMetaTable(bool enabled) +{ + exportMetaTable_ = enabled; +} int TraceDataDB::ExportDatabase(const std::string& outputName) { { @@ -52,13 +76,17 @@ int TraceDataDB::ExportDatabase(const std::string& outputName) } std::string attachSql("ATTACH DATABASE '" + outputName + "' AS systuning_export"); +#ifdef _WIN32 + if (!base::GetCoding(reinterpret_cast(attachSql.c_str()), attachSql.length())) { + attachSql = base::GbkToUtf8(attachSql.c_str()); + } +#endif ExecuteSql(attachSql); for (auto itor = internalTables_.begin(); itor != internalTables_.end(); itor++) { std::string exportSql("CREATE TABLE systuning_export." + *itor + " AS SELECT * FROM " + *itor); ExecuteSql(exportSql); } - std::string detachSql("DETACH DATABASE systuning_export"); ExecuteSql(detachSql); return 0; @@ -81,5 +109,49 @@ void TraceDataDB::ExecuteSql(const std::string_view& sql) sqlite3_finalize(stmt); } + +int TraceDataDB::SearchData(const std::string& outputName) +{ + { + int fd(base::OpenFile(outputName, O_RDWR, 0600)); + if (!fd) { + fprintf(stdout, "Failed to open file: %s", outputName.c_str()); + return 1; + } + ftruncate(fd, 0); + close(fd); + } + + std::string attachSql("ATTACH DATABASE '" + outputName + "' AS systuning_export"); +#ifdef _WIN32 + if (!base::GetCoding(reinterpret_cast(attachSql.c_str()), attachSql.length())) { + attachSql = base::GbkToUtf8(attachSql.c_str()); + } +#endif + ExecuteSql(attachSql); + + int result; + char* errmsg = nullptr; + std::string line; + for (;;) { + std::cout << "> "; + getline(std::cin, line); + if (line.empty()) { + std::cout << "If you want to quit either type -q or press CTRL-Z" << std::endl; + continue; + } + if (!line.compare("-q") || !line.compare("-quit")) { + break; + } else if (!line.compare("-help") || !line.compare("-h")) { + std::cout << "use info" << std::endl; + continue; + } + result = sqlite3_exec(db_, line.c_str(), PrintQueryResult, NULL, &errmsg); + } + + std::string detachSql("DETACH DATABASE systuning_export"); + ExecuteSql(detachSql); + return 0; } -} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_data_db.h b/trace_analyzer/src/trace_data/trace_data_db.h index 6cf4e7699..fb2e4e3d8 100644 --- a/trace_analyzer/src/trace_data/trace_data_db.h +++ b/trace_analyzer/src/trace_data/trace_data_db.h @@ -19,11 +19,12 @@ #include #include -extern "C" { -struct sqlite3; -struct sqlite3_stmt; -extern int sqlite3_close(sqlite3*); -extern int sqlite3_finalize(sqlite3_stmt* pStmt); +extern "C" +{ + struct sqlite3; + struct sqlite3_stmt; + extern int sqlite3_close(sqlite3*); + extern int sqlite3_finalize(sqlite3_stmt*pStmt); } namespace SysTuning { @@ -34,14 +35,22 @@ public: TraceDataDB(const TraceDataDB&) = delete; TraceDataDB& operator=(const TraceDataDB&) = delete; virtual ~TraceDataDB(); + virtual void InitDB() = 0; + public: int ExportDatabase(const std::string& outputName); + int SearchData(const std::string& outputName); void AppendNewTable(std::string tableName); + void EnableMetaTable(bool enabled); + +public: sqlite3* db_; + private: void ExecuteSql(const std::string_view&); - std::list internalTables_ {}; + std::list internalTables_{}; + bool exportMetaTable_ = false; }; -} -} +} // namespace TraceStreamer +} // namespace SysTuning #endif diff --git a/trace_analyzer/src/trace_data/trace_stdtype.cpp b/trace_analyzer/src/trace_data/trace_stdtype.cpp old mode 100644 new mode 100755 index 236525a49..e8357a78a --- a/trace_analyzer/src/trace_data/trace_stdtype.cpp +++ b/trace_analyzer/src/trace_data/trace_stdtype.cpp @@ -14,11 +14,10 @@ */ #include "trace_stdtype.h" - +#include namespace SysTuning { namespace TraceStdtype { -size_t ThreadState::AppendThreadState(uint64_t ts, uint64_t dur, - uint64_t cpu, uint64_t internalTid, uint64_t state) +size_t ThreadState::AppendThreadState(uint64_t ts, uint64_t dur, uint64_t cpu, uint64_t internalTid, uint64_t state) { internalTids_.emplace_back(internalTid); states_.emplace_back(state); @@ -35,7 +34,9 @@ void ThreadState::SetDuration(size_t index, uint64_t duration) uint64_t ThreadState::UpdateDuration(size_t index, uint64_t timestamp) { - durs_[index] = timestamp - timeStamps_[index]; + if (durs_[index] == INVALID_UINT64) { + durs_[index] = timestamp - timeStamps_[index]; + } return internalTids_[index]; } @@ -57,8 +58,12 @@ uint64_t ThreadState::UpdateDuration(size_t index, uint64_t timestamp, uint64_t return internalTids_[index]; } -size_t SchedSlice::AppendSchedSlice(uint64_t ts, uint64_t dur, uint64_t cpu, - uint64_t internalTid, uint64_t endState, uint64_t priority) +size_t SchedSlice::AppendSchedSlice(uint64_t ts, + uint64_t dur, + uint64_t cpu, + uint64_t internalTid, + uint64_t endState, + uint64_t priority) { internalTids_.emplace_back(internalTid); endStates_.emplace_back(endState); @@ -81,45 +86,125 @@ void SchedSlice::Update(uint64_t index, uint64_t ts, uint64_t state, uint64_t pi priority_[index] = pior; } - -size_t Slices::AppendSliceData(uint32_t cpu, uint64_t startT, uint64_t durationNs, InternalTid internalTid) +size_t CallStack::AppendInternalAsyncSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + DataIndex name, + uint8_t depth, + uint64_t cookid, + const std::optional& parentId) { - durs_.emplace_back(durationNs); - internalTids_.emplace_back(internalTid); - cpus_.emplace_back(cpu); - timeStamps_.emplace_back(startT); - return Size() - 1; -} - -size_t InternalSlices::AppendInternalSlice(uint64_t startT, uint64_t durationNs, - InternalTid internalTid, uint32_t filterId, DataIndex cat, DataIndex name, - uint8_t depth, uint64_t stackId, uint64_t parentStackId, std::optional parentId) -{ - AppendCommonInfo(startT, durationNs, internalTid, filterId); - AppendCallStack(cat, name, depth, stackId, - parentStackId, parentId); + AppendCommonInfo(startT, durationNs, internalTid); + AppendCallStack(cat, name, depth, parentId); + AppendDistributeInfo(); + cookies_.emplace_back(cookid); ids_.emplace_back(ids_.size()); return Size() - 1; } +size_t CallStack::AppendInternalSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + DataIndex name, + uint8_t depth, + const std::optional& parentId) +{ + AppendCommonInfo(startT, durationNs, internalTid); + AppendCallStack(cat, name, depth, parentId); + ids_.emplace_back(ids_.size()); + cookies_.emplace_back(INVALID_UINT64); + return Size() - 1; +} -void InternalSlices::AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid, uint32_t filterId) +void CallStack::AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid) { timeStamps_.emplace_back(startT); durs_.emplace_back(durationNs); - internalTids_.emplace_back(internalTid); - filterIds_.emplace_back(filterId); + callIds_.emplace_back(internalTid); } -void InternalSlices::AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, uint64_t stackId, - uint64_t parentStackId, std::optional parentId) +void CallStack::AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId) { - stackIds_.emplace_back(stackId); - parentStackIds_.emplace_back(parentStackId); parentIds_.emplace_back(parentId); cats_.emplace_back(cat); names_.emplace_back(name); depths_.emplace_back(depth); } -size_t Filter::AppendNewFilterData(std::string type, std::string name, uint32_t sourceArgSetId) +void CallStack::AppendDistributeInfo(const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args) +{ + chainIds_.emplace_back(chainId); + spanIds_.emplace_back(spanId); + parentSpanIds_.emplace_back(parentSpanId); + flags_.emplace_back(flag); + args_.emplace_back(args); +} +void CallStack::AppendDistributeInfo() +{ + chainIds_.emplace_back(""); + spanIds_.emplace_back(""); + parentSpanIds_.emplace_back(""); + flags_.emplace_back(""); + args_.emplace_back(""); +} +void CallStack::SetDuration(size_t index, uint64_t timestamp) +{ + durs_[index] = timestamp - timeStamps_[index]; +} +void CallStack::SetTimeStamp(size_t index, uint64_t timestamp) +{ + timeStamps_[index] = timestamp; +} + +const std::deque>& CallStack::ParentIdData() const +{ + return parentIds_; +} +const std::deque& CallStack::CatsData() const +{ + return cats_; +} +const std::deque& CallStack::NamesData() const +{ + return names_; +} +const std::deque& CallStack::Depths() const +{ + return depths_; +} +const std::deque& CallStack::Cookies() const +{ + return cookies_; +} +const std::deque& CallStack::CallIds() const +{ + return callIds_; +} +const std::deque& CallStack::ChainIds() const +{ + return chainIds_; +} +const std::deque& CallStack::SpanIds() const +{ + return spanIds_; +} +const std::deque& CallStack::ParentSpanIds() const +{ + return parentSpanIds_; +} +const std::deque& CallStack::Flags() const +{ + return flags_; +} +const std::deque& CallStack::ArgsData() const +{ + return args_; +} + +size_t Filter::AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId) { nameDeque_.emplace_back(name); sourceArgSetId_.emplace_back(sourceArgSetId); @@ -128,7 +213,7 @@ size_t Filter::AppendNewFilterData(std::string type, std::string name, uint32_t return Size() - 1; } -size_t Counter::AppendCounterData(uint32_t type, uint64_t timestamp, double value, uint32_t filterId) +size_t Measure::AppendMeasureData(uint32_t type, uint64_t timestamp, int64_t value, uint32_t filterId) { valuesDeque_.emplace_back(value); filterIdDeque_.emplace_back(filterId); @@ -143,11 +228,11 @@ size_t Raw::AppendRawData(uint32_t id, uint64_t timestamp, uint32_t name, uint32 timeStamps_.emplace_back(timestamp); nameDeque_.emplace_back(name); cpuDeque_.emplace_back(cpu); - utidDeque_.emplace_back(internalTid); + itidDeque_.emplace_back(internalTid); return Size() - 1; } -size_t ThreadCounterFilter::AppendNewData(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid) +size_t ThreadMeasureFilter::AppendNewFilter(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid) { filterId_.emplace_back(filterId); nameIndex_.emplace_back(nameIndex); @@ -163,20 +248,157 @@ size_t Instants::AppendInstantEventData(uint64_t timestamp, DataIndex nameIndex, return Size() - 1; } -size_t ProcessCounterFilter::AppendProcessCounterFilterData(uint32_t id, DataIndex name, uint32_t internalPid) +size_t ProcessMeasureFilter::AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid) { internalPids_.emplace_back(internalPid); ids_.emplace_back(id); names_.emplace_back(name); return Size() - 1; } +size_t ClockEventData::AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu) +{ + cpus_.emplace_back(cpu); + ids_.emplace_back(id); + types_.emplace_back(type); + names_.emplace_back(name); + return Size() - 1; +} +StatAndInfo::StatAndInfo() +{ + // sched_switch_received | sched_switch_not_match | sched_switch_not_not_supported etc. + for (int i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + event_[i] = config_.eventNameMap_.at(static_cast(i)); + } + for (int j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + stat_[j] = config_.eventErrorDescMap_.at(static_cast(j)); + } -size_t ProcessCounterFilter::AppendProcessFilterData(uint32_t id, DataIndex name, uint32_t internalPid) -{ - internalPids_.emplace_back(internalPid); - ids_.emplace_back(id); - names_.emplace_back(name); - return Size() - 1; + for (int i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statSeverity_[i][j] = config_.eventParserStatSeverityDescMap_.at(static_cast(i)) + .at(static_cast(j)); + } + } + + for (int i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statSeverityDesc_[i][j] = config_.serverityLevelDescMap_.at(statSeverity_[i][j]); + } + } + + for (int i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statCount_[i][j] = 0; + } + } } -} // namespace TraceStreamer +void StatAndInfo::IncreaseStat(SupportedTraceEventType eventType, StatType type) +{ + statCount_[eventType][type]++; +} +const uint32_t& StatAndInfo::GetValue(SupportedTraceEventType eventType, StatType type) const +{ + return statCount_[eventType][type]; +} +const std::string& StatAndInfo::GetEvent(SupportedTraceEventType eventType) const +{ + return event_[eventType]; +} +const std::string& StatAndInfo::GetStat(StatType type) const +{ + return stat_[type]; +} +const std::string& StatAndInfo::GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const +{ + return statSeverityDesc_[eventType][type]; +} +const StatSeverityLevel& StatAndInfo::GetSeverity(SupportedTraceEventType eventType, StatType type) const +{ + return statSeverity_[eventType][type]; +} +uint64_t SymbolsData::Size() const +{ + return addrs_.size(); +} +void SymbolsData::InsertSymbol(const DataIndex& name, const uint64_t& addr) +{ + addrs_.emplace_back(addr); + funcName_.emplace_back(name); +} +const std::deque& SymbolsData::GetConstFuncNames() const +{ + return funcName_; +} +const std::deque& SymbolsData::GetConstAddrs() const +{ + return addrs_; +} +MetaData::MetaData() +{ + columnNames_.resize(METADATA_ITEM_MAX); + values_.resize(METADATA_ITEM_MAX); + columnNames_[METADATA_ITEM_DATASIZE] = METADATA_ITEM_DATASIZE_COLNAME; + columnNames_[METADATA_ITEM_PARSETOOL_NAME] = METADATA_ITEM_PARSETOOL_NAME_COLNAME; + columnNames_[METADATA_ITEM_PARSERTOOL_VERSION] = METADATA_ITEM_PARSERTOOL_VERSION_COLNAME; + columnNames_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME; + columnNames_[METADATA_ITEM_SOURCE_FILENAME] = METADATA_ITEM_SOURCE_FILENAME_COLNAME; + columnNames_[METADATA_ITEM_OUTPUT_FILENAME] = METADATA_ITEM_OUTPUT_FILENAME_COLNAME; + columnNames_[METADATA_ITEM_PARSERTIME] = METADATA_ITEM_PARSERTIME_COLNAME; + columnNames_[METADATA_ITEM_SOURCE_DATETYPE] = METADATA_ITEM_SOURCE_DATETYPE_COLNAME; + values_[METADATA_ITEM_PARSETOOL_NAME] = "trace_streamer"; +} +void MetaData::SetTraceType(const std::string& traceType) +{ + values_[METADATA_ITEM_SOURCE_DATETYPE] = traceType; +} +void MetaData::SetSourceFileName(const std::string& fileName) +{ + MetaData::values_[METADATA_ITEM_SOURCE_FILENAME] = fileName; +} +void MetaData::SetOutputFileName(const std::string& fileName) +{ + MetaData::values_[METADATA_ITEM_OUTPUT_FILENAME] = fileName; +} +void MetaData::SetParserToolVersion(const std::string& version) +{ + values_[METADATA_ITEM_PARSERTOOL_VERSION] = version; +} +void MetaData::SetParserToolPublishDateTime(const std::string& datetime) +{ + values_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = datetime; +} +void MetaData::SetTraceDataSize(uint64_t dataSize) +{ + std::stringstream ss; + ss << dataSize; + values_[METADATA_ITEM_DATASIZE] = ss.str(); + // Function 'time' may return error. It is not allowed to do anything that might fail inside the constructor. + time_t rawtime; + struct tm* timeinfo = nullptr; + void(time(&rawtime)); + timeinfo = localtime(&rawtime); + values_[METADATA_ITEM_PARSERTIME] = asctime(timeinfo); +} +const std::string& MetaData::Value(uint64_t row) const +{ + return values_[row]; +} +const std::string& MetaData::Name(uint64_t row) const +{ + return columnNames_[row]; +} +DataIndex DataDict::GetStringIndex(std::string_view str) +{ + auto hashValue = hashFun(str); + auto itor = dataDictInnerMap_.find(hashValue); + if (itor != dataDictInnerMap_.end()) { + TS_ASSERT(std::string_view(dataDict_[itor->second]) == str); + return itor->second; + } + dataDict_.emplace_back(std::string(str)); + DataIndex stringIdentity = dataDict_.size() - 1; + dataDictInnerMap_.emplace(hashValue, stringIdentity); + return stringIdentity; +} +} // namespace TraceStdtype } // namespace SysTuning diff --git a/trace_analyzer/src/trace_data/trace_stdtype.h b/trace_analyzer/src/trace_data/trace_stdtype.h index 82e1dc9ba..c7530a258 100644 --- a/trace_analyzer/src/trace_data/trace_stdtype.h +++ b/trace_analyzer/src/trace_data/trace_stdtype.h @@ -21,34 +21,22 @@ #include #include #include +#include #include #include #include #include +#include "base/common.h" +#include "cfg/trace_streamer_cfg.h" #include "log.h" -#include "src/base/common.h" namespace SysTuning { namespace TraceStdtype { -enum EndState { - TASK_RUNNABLE = 0, // R - TASK_INTERRUPTIBLE = 1, // S - TASK_UNINTERRUPTIBLE = 2, // D - TASK_RUNNING = 3, // Running - TASK_INTERRUPTED = 4, // I - TASK_EXIT_DEAD = 16, // X - TASK_ZOMBIE = 32, // Z - TASK_CLONE = 64, // I - TASK_KILLED = 128, // K - TASK_DK = 130, // DK - TASK_WAKEKILL = 256, // W - TASK_INVALID = 9999, - TASK_FOREGROUND = 2048 // R+ -}; - +using namespace SysTuning::TraceCfg; class CacheBase { public: + virtual ~CacheBase() = default; size_t Size() const { return std::max(timeStamps_.size(), ids_.size()); @@ -65,6 +53,7 @@ public: { return internalTids_; } + public: std::deque internalTids_; std::deque timeStamps_; @@ -73,6 +62,7 @@ public: class CpuCacheBase { public: + virtual ~CpuCacheBase() = default; const std::deque& DursData() const { return durs_; @@ -82,6 +72,7 @@ public: { return cpus_; } + public: std::deque durs_; std::deque cpus_; @@ -113,7 +104,7 @@ public: void UpdateDuration(size_t index, uint64_t timestamp, uint64_t state); uint64_t UpdateDuration(size_t index, uint64_t timestamp, uint64_t cpu, uint64_t state); const std::deque& StatesData() const -{ + { return states_; } @@ -123,8 +114,12 @@ private: class SchedSlice : public CacheBase, public CpuCacheBase { public: - size_t AppendSchedSlice(uint64_t ts, uint64_t dur, uint64_t cpu, - uint64_t internalTid, uint64_t endState, uint64_t priority); + size_t AppendSchedSlice(uint64_t ts, + uint64_t dur, + uint64_t cpu, + uint64_t internalTid, + uint64_t endState, + uint64_t priority); void SetDuration(size_t index, uint64_t duration); void Update(uint64_t index, uint64_t ts, uint64_t state, uint64_t pior); @@ -143,82 +138,66 @@ private: std::deque priority_; }; -class Slices : public CacheBase, public CpuCacheBase { -public: - size_t AppendSliceData(uint32_t cpu, uint64_t startT, uint64_t durationNs, InternalTid internalTid); - - void SetDuration(size_t index, uint64_t durationNs) - { - durs_[index] = durationNs; - } -}; - -class InternalSlices : public CacheBase, public CpuCacheBase { +class CallStack : public CacheBase, public CpuCacheBase { public: + size_t AppendInternalAsyncSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + DataIndex name, + uint8_t depth, + uint64_t cookid, + const std::optional& parentId); size_t AppendInternalSlice(uint64_t startT, - uint64_t durationNs, - InternalTid internalTid, - uint32_t filterId, - DataIndex cat, - DataIndex name, - uint8_t depth, - uint64_t stackId, - uint64_t parentStackId, - std::optional parentId); - void SetDuration(size_t index, uint64_t durationNs) - { - durs_[index] = durationNs; - } + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + DataIndex name, + uint8_t depth, + const std::optional& parentId); + void AppendDistributeInfo(const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args); + void AppendDistributeInfo(); + void SetDuration(size_t index, uint64_t timestamp); + void SetTimeStamp(size_t index, uint64_t timestamp); + + const std::deque>& ParentIdData() const; + const std::deque& CatsData() const; + const std::deque& NamesData() const; + const std::deque& Depths() const; + const std::deque& Cookies() const; + const std::deque& CallIds() const; + const std::deque& ChainIds() const; + const std::deque& SpanIds() const; + const std::deque& ParentSpanIds() const; + const std::deque& Flags() const; + const std::deque& ArgsData() const; - void SetStackId(size_t index, uint64_t stackId) - { - stackIds_[index] = stackId; - } - const std::deque>& ParentIdData() const - { - return parentIds_; - } - const std::deque& FilterIdData() const - { - return filterIds_; - } - const std::deque& CatsData() const - { - return cats_; - } - const std::deque& StackIdsData() const - { - return stackIds_; - } - const std::deque& ParentStackIds() const - { - return parentStackIds_; - } - const std::deque& NamesData() const - { - return names_; - } - const std::deque& Depths() const - { - return depths_; - } private: - void AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid, uint32_t filterId); - void AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, uint64_t stackId, - uint64_t parentStackId, std::optional parentId); + void AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid); + void AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId); + private: std::deque> parentIds_; - std::deque filterIds_; std::deque cats_; - std::deque stackIds_; - std::deque parentStackIds_; + std::deque cookies_; + std::deque callIds_; std::deque names_; std::deque depths_; + + std::deque chainIds_; + std::deque spanIds_; + std::deque parentSpanIds_; + std::deque flags_; + std::deque args_; }; class Filter : public CacheBase { public: - size_t AppendNewFilterData(std::string type, std::string name, uint32_t sourceArgSetId); + size_t AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId); const std::deque& NameData() const { return nameDeque_; @@ -227,7 +206,7 @@ public: { return typeDeque_; } - const std::deque& SourceArgSetIdData() const + const std::deque& SourceArgSetIdData() const { return sourceArgSetId_; } @@ -235,12 +214,12 @@ public: private: std::deque nameDeque_; std::deque typeDeque_; - std::deque sourceArgSetId_; + std::deque sourceArgSetId_; }; -class Counter : public CacheBase { +class Measure : public CacheBase { public: - size_t AppendCounterData(uint32_t type, uint64_t timestamp, double value, uint32_t filterId); + size_t AppendMeasureData(uint32_t type, uint64_t timestamp, int64_t value, uint32_t filterId); const std::deque& TypeData() const { return typeDeque_; @@ -273,18 +252,18 @@ public: } const std::deque& InternalTidData() const { - return utidDeque_; + return itidDeque_; } private: std::deque nameDeque_; std::deque cpuDeque_; - std::deque utidDeque_; + std::deque itidDeque_; }; -class ThreadCounterFilter { +class ThreadMeasureFilter { public: - size_t AppendNewData(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid); + size_t AppendNewFilter(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid); size_t Size() const { return filterId_.size(); @@ -308,19 +287,13 @@ private: std::deque nameIndex_; }; -class CpuCounter : public CacheBase { +class CpuMeasureFilter : public CacheBase { public: - inline size_t AppendCpuCounter(uint64_t filterId, - DataIndex name, - uint64_t cpu, - uint64_t sourceArgSetId = 0, - DataIndex unit = 0) + inline size_t AppendNewFilter(uint64_t filterId, DataIndex name, uint64_t cpu) { ids_.emplace_back(filterId); - unit_.emplace_back(unit); cpu_.emplace_back(cpu); name_.emplace_back(name); - sourceArgSetId_.emplace_back(sourceArgSetId); return Size() - 1; } @@ -334,27 +307,15 @@ public: return type_; } - const std::deque& UnitData() const - { - return unit_; - } - const std::deque& NameData() const { return name_; } - const std::deque& SourceArgSetIdData() const - { - return sourceArgSetId_; - } - private: std::deque cpu_; std::deque type_; - std::deque unit_; std::deque name_; - std::deque sourceArgSetId_; }; class Instants : public CacheBase { @@ -370,10 +331,9 @@ private: std::deque NameIndexs_; }; -class ProcessCounterFilter : public CacheBase { +class ProcessMeasureFilter : public CacheBase { public: - size_t AppendProcessCounterFilterData(uint32_t id, DataIndex name, uint32_t internalPid); - size_t AppendProcessFilterData(uint32_t id, DataIndex name, uint32_t internalPid); + size_t AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid); const std::deque& UpidsData() const { @@ -389,37 +349,108 @@ private: std::deque internalPids_; std::deque names_; }; +class ClockEventData : public CacheBase { +public: + size_t AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu); + + const std::deque& CpusData() const + { + return cpus_; + } + + const std::deque& NamesData() const + { + return names_; + } + const std::deque& TypesData() const + { + return types_; + } + +private: + std::deque cpus_; // in clock_set_rate event, it save cpu + std::deque names_; + std::deque types_; +}; +class StatAndInfo { +public: + StatAndInfo(); + ~StatAndInfo() = default; + void IncreaseStat(SupportedTraceEventType eventType, StatType type); + const uint32_t& GetValue(SupportedTraceEventType eventType, StatType type) const; + const std::string& GetEvent(SupportedTraceEventType eventType) const; + const std::string& GetStat(StatType type) const; + const std::string& GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const; + const StatSeverityLevel& GetSeverity(SupportedTraceEventType eventType, StatType type) const; + +private: + uint32_t statCount_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + std::string event_[TRACE_EVENT_MAX]; + std::string stat_[STAT_EVENT_MAX]; + std::string statSeverityDesc_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + StatSeverityLevel statSeverity_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + TraceStreamConfig config_; +}; +class SymbolsData { +public: + SymbolsData() = default; + ~SymbolsData() = default; + uint64_t Size() const; + void InsertSymbol(const DataIndex& name, const uint64_t& addr); + const std::deque& GetConstFuncNames() const; + const std::deque& GetConstAddrs() const; + +private: + std::deque addrs_; + std::deque funcName_; +}; +class MetaData { +public: + MetaData(); + ~MetaData() = default; + void SetTraceType(const std::string& traceType); + void SetSourceFileName(const std::string& fileName); + void SetOutputFileName(const std::string& fileName); + void SetParserToolVersion(const std::string& version); + void SetParserToolPublishDateTime(const std::string& datetime); + void SetTraceDataSize(uint64_t dataSize); + const std::string& Value(uint64_t row) const; + const std::string& Name(uint64_t row) const; + +private: + const std::string METADATA_ITEM_DATASIZE_COLNAME = "datasize"; + const std::string METADATA_ITEM_PARSETOOL_NAME_COLNAME = "parse_tool"; + const std::string METADATA_ITEM_PARSERTOOL_VERSION_COLNAME = "tool_version"; + const std::string METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME = "tool_publish_time"; + const std::string METADATA_ITEM_SOURCE_FILENAME_COLNAME = "source_name"; + const std::string METADATA_ITEM_OUTPUT_FILENAME_COLNAME = "output_name"; + const std::string METADATA_ITEM_PARSERTIME_COLNAME = "runtime"; + const std::string METADATA_ITEM_SOURCE_DATETYPE_COLNAME = "source_type"; + + std::deque columnNames_; + std::deque values_; +}; class DataDict { public: std::deque dataDict_; std::unordered_map dataDictInnerMap_; + public: size_t Size() const { return dataDict_.size(); } - DataIndex GetStringIndex(std::string_view str) - { - auto hashValue = hashFun(str); - auto itor = dataDictInnerMap_.find(hashValue); - if (itor != dataDictInnerMap_.end()) { - TUNING_ASSERT(std::string_view(dataDict_[itor->second]) == str); - return itor->second; - } - dataDict_.emplace_back(std::string(str)); - DataIndex stringIdentity = dataDict_.size() - 1; - dataDictInnerMap_.emplace(hashValue, stringIdentity); - return stringIdentity; - } + DataIndex GetStringIndex(std::string_view str); const std::string& GetDataFromDict(DataIndex id) const { - TUNING_ASSERT(id < dataDict_.size()); + TS_ASSERT(id < dataDict_.size()); return dataDict_[id]; } + private: std::hash hashFun; }; -} // namespace TraceStreamer +} // namespace TraceStdtype } // namespace SysTuning #endif // TRACE_STDTYPE_H diff --git a/trace_analyzer/src/trace_streamer.cpp b/trace_analyzer/src/trace_streamer.cpp deleted file mode 100644 index 023a1471e..000000000 --- a/trace_analyzer/src/trace_streamer.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "trace_streamer.h" - -#include -#include -#include - -#include "clock_filter.h" -#include "cpu_filter.h" -#include "event_filter.h" -#include "file.h" -#include "filter_filter.h" -#include "measure_filter.h" -#include "parser/bytrace_parser.h" -#include "process_filter.h" -#include "slice_filter.h" - -namespace SysTuning { -namespace TraceStreamer { -namespace { -FileType ParseFileType(const uint8_t* data, size_t size) -{ - if (size == 0) { - return UN_KNOW; - } - std::string start(reinterpret_cast(data), std::min(size, 20)); - if (start.find("# tracer") != std::string::npos) { - return BY_TRACE; - } - if ((start.compare(0, std::string("").length(), "") == 0) || - (start.compare(0, std::string("").length(), "") == 0)) { - return BY_TRACE; - } - if (start.compare(0, std::string("\x0a").length(), "\x0a") == 0) { - return PROTO; - } - return UN_KNOW; -} -} // namespace - -TraceStreamer::TraceStreamer() : fileType_(UN_KNOW), bytraceParser_(nullptr) -{ - InitFilter(); - InitParser(); -} -TraceStreamer::~TraceStreamer() -{ -} - -void TraceStreamer::InitFilter() -{ - streamFilters_ = std::make_unique(); - traceDataCache_ = std::make_unique(); - streamFilters_ = std::make_unique(); - traceDataCache_ = std::make_unique(); - streamFilters_->sliceFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - streamFilters_->cpuFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - streamFilters_->eventFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - - streamFilters_->processFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - streamFilters_->clockFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - streamFilters_->filterFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - - streamFilters_->threadCounterFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREADMEASURE_FILTER); - streamFilters_->threadFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREAD_FILTER); - streamFilters_->cpuCounterFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CPU_MEASURE_FILTER); - streamFilters_->processCounterFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_MEASURE_FILTER); - streamFilters_->processFilterFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_FILTER_FILTER); -} -void TraceStreamer::InitParser() -{ - bytraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); -} -bool TraceStreamer::Parse(std::unique_ptr data, size_t size) -{ - if (size == 0) { - return true; - } - if (fileType_ == UN_KNOW) { - fileType_ = ParseFileType(data.get(), size); - if (fileType_ == UN_KNOW) { - base::SetAnalysisResult(base::FILE_TYPE_ERROR); - fprintf(stdout, "File type is not supported!"); - return false; - } - } - if (fileType_ == PROTO) { - base::SetAnalysisResult(base::FILE_TYPE_ERROR); - fprintf(stdout, "File type is not supported!"); - return false; - } - if (fileType_ == BY_TRACE) { - if (!bytraceParser_->Parse(std::move(data), size)) { - base::SetAnalysisResult(base::PARSE_ERROR); - return false; - } - } - base::SetAnalysisResult(base::NORMAL); - return true; -} - -int TraceStreamer::ExportDatabase(const std::string& outputName) -{ - return traceDataCache_->ExportDatabase(outputName); -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_analyzer/src/trace_streamer.pro b/trace_analyzer/src/trace_streamer.pro new file mode 100755 index 000000000..2e80a5a0b --- /dev/null +++ b/trace_analyzer/src/trace_streamer.pro @@ -0,0 +1,55 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +QT -= gui core +TEMPLATE = app +CONFIG += c++17 console +#CONFIG += c++14 +TARGET = trace_streamer + +#CONFIG += release + +DEFINES += HAVE_PTHREAD +DEFINES += _LIBCPP_DISABLE_AVAILABILITY + +DEFINES += HAVE_PTHREAD +ROOTSRCDIR = $$PWD/../ + +include($$PWD/../global.pri) +INCLUDEPATH += $$PWD/include \ + $$PWD/../third_party/protobuf/src \ + $$PWD/../third_party/sqlite/include \ + $$PWD/../third_party/protogen/gen + + +include($$PWD/trace_streamer/trace_streamer.pri) +include($$PWD/base/base.pri) +include($$PWD/filter/filter.pri) +include($$PWD/parser/parser.pri) +include($$PWD/../third_party/protogen/gen.pri) +include($$PWD/table/table.pri) +include($$PWD/trace_data/trace_data.pri) +include($$PWD/cfg/cfg.pri) + +#LIBS += -lrt -ldl +unix{ +LIBS += -L$$DESTDIR/ -lstdc++ \ + -L$${ROOTSRCDIR}/lib/$${DESTFOLDER} -lprotobuf -lsqlite -ldl +} else { +LIBS += -L$$DESTDIR/ -lstdc++ \ + -L$${ROOTSRCDIR}/lib/$${DESTFOLDER} -lprotobuf -lsqlite +} +INCLUDEPATH +=$$PWD/include + +SOURCES += \ + main.cpp diff --git a/trace_analyzer/src/trace_streamer/trace_streamer.pri b/trace_analyzer/src/trace_streamer/trace_streamer.pri new file mode 100644 index 000000000..f2804faa2 --- /dev/null +++ b/trace_analyzer/src/trace_streamer/trace_streamer.pri @@ -0,0 +1,21 @@ +# 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. + +INCLUDEPATH += $$PWD +HEADERS += \ + $$PWD/trace_streamer_selector.h \ + $$PWD/trace_streamer_filters.h + +SOURCES += \ + $$PWD/trace_streamer_selector.cpp \ + $$PWD/trace_streamer_filters.cpp diff --git a/trace_analyzer/src/trace_streamer_filters.cpp b/trace_analyzer/src/trace_streamer/trace_streamer_filters.cpp similarity index 92% rename from trace_analyzer/src/trace_streamer_filters.cpp rename to trace_analyzer/src/trace_streamer/trace_streamer_filters.cpp index 16f3b6d6a..5ae6721c4 100755 --- a/trace_analyzer/src/trace_streamer_filters.cpp +++ b/trace_analyzer/src/trace_streamer/trace_streamer_filters.cpp @@ -17,11 +17,12 @@ #include "clock_filter.h" #include "cpu_filter.h" -#include "event_filter.h" #include "filter_filter.h" #include "measure_filter.h" #include "process_filter.h" #include "slice_filter.h" +#include "stat_filter.h" +#include "symbols_filter.h" namespace SysTuning { namespace TraceStreamer { diff --git a/trace_analyzer/src/trace_streamer_filters.h b/trace_analyzer/src/trace_streamer/trace_streamer_filters.h similarity index 72% rename from trace_analyzer/src/trace_streamer_filters.h rename to trace_analyzer/src/trace_streamer/trace_streamer_filters.h index dc1294770..350bce1c5 100755 --- a/trace_analyzer/src/trace_streamer_filters.h +++ b/trace_analyzer/src/trace_streamer/trace_streamer_filters.h @@ -22,11 +22,12 @@ namespace SysTuning { namespace TraceStreamer { class SliceFilter; class ProcessFilter; -class EventFilter; class CpuFilter; class MeasureFilter; class FilterFilter; class ClockFilter; +class SymbolsFilter; +class StatFilter; class TraceStreamerFilters { public: @@ -38,12 +39,16 @@ public: std::unique_ptr sliceFilter_; std::unique_ptr processFilter_; std::unique_ptr cpuFilter_; - std::unique_ptr eventFilter_; - std::unique_ptr cpuCounterFilter_; - std::unique_ptr threadCounterFilter_; + std::unique_ptr cpuMeasureFilter_; + std::unique_ptr threadMeasureFilter_; std::unique_ptr threadFilter_; - std::unique_ptr processCounterFilter_; + std::unique_ptr processMeasureFilter_; std::unique_ptr processFilterFilter_; + std::unique_ptr symbolsFilter_; + std::unique_ptr statFilter_; + std::unique_ptr clockRateFilter_; + std::unique_ptr clockEnableFilter_; + std::unique_ptr clockDisableFilter_; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_analyzer/src/trace_streamer/trace_streamer_selector.cpp b/trace_analyzer/src/trace_streamer/trace_streamer_selector.cpp new file mode 100755 index 000000000..6373d978f --- /dev/null +++ b/trace_analyzer/src/trace_streamer/trace_streamer_selector.cpp @@ -0,0 +1,159 @@ +/* + * 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 "trace_streamer_selector.h" + +#include +#include +#include + +#include "clock_filter.h" +#include "cpu_filter.h" +#include "file.h" +#include "filter_filter.h" +#include "measure_filter.h" +#include "parser/bytrace_parser/bytrace_parser.h" +#include "parser/htrace_parser/htrace_parser.h" +#include "process_filter.h" +#include "slice_filter.h" +#include "stat_filter.h" +#include "symbols_filter.h" +using namespace SysTuning::base; +namespace SysTuning { +namespace TraceStreamer { +namespace { +TraceFileType GuessFileType(const uint8_t* data, size_t size) +{ + if (size == 0) { + return TRACE_FILETYPE_UN_KNOW; + } + std::string start(reinterpret_cast(data), std::min(size, 20)); + if (start.find("# tracer") != std::string::npos) { + return TRACE_FILETYPE_BY_TRACE; + } + if (start.find("# TRACE") != std::string::npos) { + return TRACE_FILETYPE_BY_TRACE; + } + if ((start.compare(0, std::string("").length(), "") == 0) || + (start.compare(0, std::string("").length(), "") == 0)) { + return TRACE_FILETYPE_BY_TRACE; + } + if (start.compare(0, std::string("\x0a").length(), "\x0a") == 0) { + return TRACE_FILETYPE_H_TRACE; + } + if (start.compare(0, std::string("OHOSPROF").length(), "OHOSPROF") == 0) { + return TRACE_FILETYPE_H_TRACE; + } + if (start.compare(0, std::string("\x0a").length(), "\x0a") == 0) { + return TRACE_FILETYPE_UN_KNOW; + } + return TRACE_FILETYPE_UN_KNOW; +} +} // namespace + +TraceStreamerSelector::TraceStreamerSelector() + : fileType_(TRACE_FILETYPE_UN_KNOW), bytraceParser_(nullptr), htraceParser_(nullptr) +{ + InitFilter(); + InitParser(); +} +TraceStreamerSelector::~TraceStreamerSelector() {} + +void TraceStreamerSelector::InitFilter() +{ + streamFilters_ = std::make_unique(); + traceDataCache_ = std::make_unique(); + streamFilters_->sliceFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + streamFilters_->cpuFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + + streamFilters_->processFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + streamFilters_->clockFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + streamFilters_->filterFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + + streamFilters_->threadMeasureFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREADMEASURE_FILTER); + streamFilters_->threadFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREAD_FILTER); + streamFilters_->cpuMeasureFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CPU_MEASURE_FILTER); + streamFilters_->processMeasureFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_MEASURE_FILTER); + streamFilters_->processFilterFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_FILTER_FILTER); + streamFilters_->symbolsFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + streamFilters_->statFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + streamFilters_->clockRateFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CLOCK_RATE_FILTER); + streamFilters_->clockEnableFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CLOCK_ENABLE_FILTER); + streamFilters_->clockDisableFilter_ = + std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CLOCK_DISABLE_FILTER); +} +void TraceStreamerSelector::InitParser() +{ + bytraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + htraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); +} + +void TraceStreamerSelector::WaitForParserEnd() +{ + if (fileType_ == TRACE_FILETYPE_H_TRACE) { + return; + } + if (fileType_ == TRACE_FILETYPE_BY_TRACE) { + bytraceParser_->WaitForParserEnd(); + } +} + +MetaData* TraceStreamerSelector::GetMetaData() +{ + return traceDataCache_->GetMetaData(); +} +bool TraceStreamerSelector::ParseTraceDataSegment(std::unique_ptr data, size_t size) +{ + if (size == 0) { + return true; + } + if (fileType_ == TRACE_FILETYPE_UN_KNOW) { + fileType_ = GuessFileType(data.get(), size); + if (fileType_ == TRACE_FILETYPE_UN_KNOW) { + SetAnalysisResult(TRACE_PARSER_FILE_TYPE_ERROR); + fprintf(stdout, "File type is not supported!"); + return false; + } + } + if (fileType_ == TRACE_FILETYPE_H_TRACE) { + htraceParser_->ParseTraceDataSegment(std::move(data), size); + } + if (fileType_ == TRACE_FILETYPE_BY_TRACE) { + bytraceParser_->ParseTraceDataSegment(std::move(data), size); + } + SetAnalysisResult(TRACE_PARSER_NORMAL); + return true; +} +void TraceStreamerSelector::EnableMetaTable(bool enabled) +{ + traceDataCache_->EnableMetaTable(enabled); +} +int TraceStreamerSelector::ExportDatabase(const std::string& outputName) const +{ + return traceDataCache_->ExportDatabase(outputName); +} +int TraceStreamerSelector::SearchData(const std::string& outputName) +{ + return traceDataCache_->SearchData(outputName); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/src/trace_streamer/trace_streamer_selector.h b/trace_analyzer/src/trace_streamer/trace_streamer_selector.h new file mode 100755 index 000000000..a46f85c91 --- /dev/null +++ b/trace_analyzer/src/trace_streamer/trace_streamer_selector.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TRACE_STREAMER_SELECTOR_H +#define TRACE_STREAMER_SELECTOR_H + +#include +#include +#include "trace_data/trace_data_cache.h" +#include "trace_streamer_filters.h" + +namespace SysTuning { +namespace TraceStreamer { +class BytraceParser; +class HtraceParser; +enum TraceFileType { TRACE_FILETYPE_BY_TRACE, TRACE_FILETYPE_H_TRACE, TRACE_FILETYPE_UN_KNOW }; +class TraceStreamerSelector { +public: + TraceStreamerSelector(); + ~TraceStreamerSelector(); + bool ParseTraceDataSegment(std::unique_ptr data, size_t size); + void EnableMetaTable(bool enabled); + int ExportDatabase(const std::string& outputName) const; + int SearchData(const std::string& outputName); + void WaitForParserEnd(); + MetaData* GetMetaData(); + TraceFileType DataType() + { + return fileType_; + } + +private: + void InitFilter(); + void InitParser(); + TraceFileType fileType_; + std::unique_ptr streamFilters_{}; + std::unique_ptr traceDataCache_{}; + + std::unique_ptr bytraceParser_; + std::unique_ptr htraceParser_; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // TRACE_STREAMER_SELECTOR_H diff --git a/trace_analyzer/src/ts.gni b/trace_analyzer/src/ts.gni new file mode 100644 index 000000000..ca1cb0a1e --- /dev/null +++ b/trace_analyzer/src/ts.gni @@ -0,0 +1,29 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +OHOS_PROTO_DIR = "" + +if (target_os == "linux" || target_os == "windows") { + OHOS_FTRACE_PROTO_DIR = "//third_party/protogen" + OHOS_MEMORY_PROTO_DIR = "//third_party/protogen" + OHOS_PROTO_GEN = "//third_party/protogen/gen" + OHOS_SERVICE_PROTO_DIR = "//third_party/protogen" + enable_ts_utest = false +} else { + enable_ts_utest = true + OHOS_FTRACE_PROTO_DIR = + "//developtools/profiler/protos/types/plugins/ftrace_data" + OHOS_MEMORY_PROTO_DIR = + "//developtools/profiler/protos/types/plugins/memory_data" + OHOS_SERVICE_PROTO_DIR = "//developtools/profiler/protos/services" + OHOS_PROTO_GEN = "//out/aosp-arm-release/gen/cpp/developtools/profiler/protos" +} diff --git a/trace_analyzer/test/BUILD.gn b/trace_analyzer/test/BUILD.gn new file mode 100755 index 000000000..f435b4767 --- /dev/null +++ b/trace_analyzer/test/BUILD.gn @@ -0,0 +1,97 @@ +# 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("//build/ohos.gni") +import("//build/test.gni") +import("../../device/base/config.gni") +import("test_ts.gni") + +module_output_path = "${OHOS_PROFILER_TEST_MODULE_OUTPUT_PATH}/trace_analyzer" +config("module_private_config") { + visibility = [ ":*" ] + if (current_toolchain != host_toolchain) { + defines = [ "HAVE_HILOG" ] + } +} + +ohos_unittest("hiprofiler_ts_ut") { + module_out_path = module_output_path + sources = [ + "unittest/bytrace_parser_test.cpp", + "unittest/clock_filter_test.cpp", + "unittest/cpu_filter_test.cpp", + "unittest/event_parser_test.cpp", + "unittest/filter_filter_test.cpp", + "unittest/htrace_event_parser_test.cpp", + "unittest/htrace_mem_parser_test.cpp", + "unittest/measure_filter_test.cpp", + "unittest/parser_test.cpp", + "unittest/process_filter_test.cpp", + "unittest/slice_filter_test.cpp", + ] + deps = [ + "${OHOS_FTRACE_PROTO_DIR}:ftrace_data_cpp", + "${OHOS_MEMORY_PROTO_DIR}:memory_data_cpp", + "${OHOS_SERVICE_PROTO_DIR}:proto_services_cpp", + "../src:trace_streamer_source", + "//third_party/googletest:gtest_main", + "//third_party/protobuf:protobuf", + "//third_party/protobuf:protobuf_lite", + "//third_party/sqlite:sqlite", + "//utils/native/base:utilsecurec", + ] + include_dirs = [ + "../src", + "../src/trace_data", + "../src/table", + "../src/filter", + "../src/base", + "../src/include", + "../src/trace_streamer", + "../src/parser/bytrace_parser", + "../src/parser", + "../src/cfg", + "../src/parser/htrace_parser", + "../src/parser/htrace_parser/htrace_event_parser", + "../src/parser/htrace_parser/htrace_cpu_parser", + "..", + "//third_party/googletest/googletest/include/gtest", + "//utils/native/base/include", + "//third_party/protobuf/src", + "${OHOS_PROTO_GEN}", + ] + cflags = [ + "-Wno-inconsistent-missing-override", + "-Dprivate=public", #allow test code access private members + "-fprofile-arcs", + "-ftest-coverage", + "-Wno-unused-command-line-argument", + "-Wno-format", + "-Wno-unused-const-variable", + "-Wno-unused-variable", + ] + ldflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "--coverage", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] + configs = [ ":module_private_config" ] + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" +} + +group("unittest") { + testonly = true + deps = [ ":hiprofiler_ts_ut" ] +} diff --git a/trace_analyzer/test/bytrace/bytrace_parser_test.cpp b/trace_analyzer/test/bytrace/bytrace_parser_test.cpp deleted file mode 100755 index ddc81ed1a..000000000 --- a/trace_analyzer/test/bytrace/bytrace_parser_test.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include -#include - -#include "bytrace_parser.h" - -static std::string g_str = "TRACE: - #tracer : nop - # - #entries - in - buffer / entries - written : 1585855 / 1585855 #P : 4 - # - #_-- -- -= > irqs - off - #/ _ -- -- => need - resched - #| / _ -- -=> hardirq / softirq - #|| / _ -- => preempt - depth - #|| | / delay - #TASK - PID TGID CPU # || || TIMESTAMP FUNCTION - #| | | | || || | | - atrace - 12728(12728)[003]... 1 174330.280300 : tracing_mark_write : trace_event_clock_sync - : parent_ts = 23139.998047 atrace - 12728(12728)[003]... 1 174330.280316 : tracing_mark_write - : trace_event_clock_sync : realtime_ts = 1616439852302 ACCS0 - 2716(2519)[000] d.h1 174330.280362 - : irq_handler_entry : irq = 19 name = 408000.qcom, cpu - bwmon ACCS0 - - 2716(2519)[000] d.h1 174330.280382 : irq_handler_exit - : irq = 19 ret = handled atrace - 12728(12728)[003] d..3 174330.280387 : sched_switch - : prev_comm = atrace prev_pid = 12728 prev_prio = 120 prev_state = - S == > next_comm = swapper / 3 next_pid = 0 next_prio = 120 < idle > -0(-----)[003] d..4 174330.280435 - : sched_waking : comm = rcu_preempt pid = 7 prio = 98 target_cpu = 000 ACCS0 - - 2716(2519)[000] d..1 174330.280449 : ipi_entry - : (Rescheduling interrupts) - 0(-----)[003] d..2 174330.280450 : softirq_raise - : vec = 9 [action = RCU] - 0(-----)[003] d..3 174330.280453 : sched_waking - : comm = ksoftirqd / 3 pid = 29 prio = 120 target_cpu = 003 ACCS0 - 2716(2519)[000] dnh2 174330.280459 - : sched_wakeup : comm = rcu_preempt pid = 7 prio = 98 target_cpu = 000 ACCS0 - - 2716(2519)[000] dn .1 174330.280461 : ipi_exit - : (Rescheduling interrupts) - 0(-----)[003] dn .4 174330.280468 : sched_wakeup - : comm = ksoftirqd / 3 pid = 29 prio = 120 target_cpu = 003 ACCS0 - 2716(2519)[000] d..3 174330.280472 - : sched_switch - : prev_comm = ACCS0 prev_pid = 2716 prev_prio = 120 prev_state = R == - > next_comm = rcu_preempt next_pid = 7 next_prio = 98 rcu_preempt - 7(7)[000] d..3 174330.280485 - : sched_switch - : prev_comm = rcu_preempt prev_pid = 7 prev_prio = 98 prev_state = S == - > next_comm = ACCS0 next_pid = 2716 next_prio = 120 < idle > -0(-----)[003] d..3 174330.280494 - : sched_switch - : prev_comm = swapper / 3 prev_pid = 0 prev_prio = 120 prev_state = - R == > next_comm = ksoftirqd / 3 next_pid = 29 next_prio = 120 ksoftirqd / 3 - 29(29)[003]..s1 174330.280504 - : softirq_entry : vec = 9 [action = RCU] ksoftirqd / 3 - 29(29)[003] d.s3 174330.280510 : sched_waking - : comm = rcu_preempt pid = 7 prio = 98 target_cpu = 000 ACCS0 - 2716(2519)[000] d..1 174330.280519 : ipi_entry - : (Rescheduling interrupts)ksoftirqd / 3 - 29(29)[003]..s1 174330.280521 : softirq_exit - : vec = 9 [action = RCU] ACCS0 - 2716(2519)[000] dnh2 174330.280523 : sched_wakeup - : comm = rcu_preempt pid = 7 prio = 98 target_cpu = 000 ACCS0 - 2716(2519)[000] dn .1 174330.280524 : ipi_exit - : (Rescheduling interrupts) "; - -namespace SysTuning { -namespace trace_analyzer { -// TestSuite: -class BytraceParserTest : public ::testing::Test { -public: - static void SetUpTestCase() {} - static void TearDownTestCase() {} - void SetUp() override {} - - void TearDown() override {} -}; - -HWTEST_F(BytraceParserTest, Parse) -{ - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(g_str.c_str(), g_str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(BytraceParserTest, Parse_no_data1) -{ - std::string str; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(BytraceParserTest, Parse_no_data2) -{ - std::string str = " "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(BytraceParserTest, Parse_error_data) -{ - std::string str = "1111111111111111111111111111111111111111111111"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(BytraceParserTest, Parse_error_data1) -{ - std::string str = - "TRACE: - # tracer: nop - # "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(BytraceParserTest, Parse_error_data2) -{ - std::string str = "\nafafda "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} -} // namespace trace_analyzer -} diff --git a/trace_analyzer/test/bytrace/event_parser_test.cpp b/trace_analyzer/test/bytrace/event_parser_test.cpp deleted file mode 100755 index 21afebc4b..000000000 --- a/trace_analyzer/test/bytrace/event_parser_test.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include -#include - -#include "bytrace_parser.h" -#include "event_parser.h" - -namespace SysTuning { -namespace trace_analyzer { -// TestSuite: -class EventParserTest : public ::testing::Test { -public: - static void SetUpTestCase() {} - static void TearDownTestCase() {} - void SetUp() override {} - - void TearDown() override {} -}; - -HWTEST_F(EventParserTest, ParseLine) -{ - BytraceLine bytraceLine; - bytraceLine.ts = 1616439852302; - bytraceLine.pid = 1; - bytraceLine.cpu = 0; - bytraceLine.task = "ACCS0-2716"; - bytraceLine.pidStr = "12"; - bytraceLine.tGidStr = "12"; - bytraceLine.tGidStr = "softirq_raise"; - bytraceLine.argsStr = "vec=9 [action=RCU]"; - - TraceAnalyzerContext ctx; - EventParser eventParser(ctx); - - int result = eventParser.ParseLine(bytraceLine); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, ParseLine_error) -{ - BytraceLine bytraceLine; - TraceAnalyzerContext ctx; - EventParser eventParser(ctx); - - int result = eventParser.ParseLine(bytraceLine); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, trace_event_clock_sync) -{ - std::string str = - "atrace-12728 (12728) [003] ...1 174330.280300: tracing_mark_write: trace_event_clock_sync: " - "parent_ts=23139.998047 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, trace_event_clock_sync) -{ - std::string str = - "atrace-12728 (12728) [003] ...1 174330.280300: tracing_mark_write: trace_event_clock_sync: " - "parent_ts=23139.998047 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_C) -{ - std::string str = "ACCS0-2716 ( 2519) [000] ...1 174330.284808: tracing_mark_write: C|2519|Heap size (KB)|2906"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_BE) -{ - std::string str = "system-1298 ( 1298) [001] ...1 174330.287420: tracing_mark_write: B|1298|Choreographer#doFrame - system - 1298(1298)[001]... 1 174330.287622 : tracing_mark_write : E | 1298 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_SF) -{ - std::string str = - "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: S|1298|animator:translateX|18888109 - system - - 1298(1298)[001]... 1 174330.287514 : tracing_mark_write : F | 1298 | animator : translateX | 18888109 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_point) -{ - std::string str = - "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: G|1298|animator:translateX|18888109 - system - - 1298(1298)[001]... 1 174330.287514 : tracing_mark_write : F | 1298 | animator : translateX | 18888109 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_length) -{ - std::string str = "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: B|2"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_formart) -{ - std::string str = "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: B2ggg"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_formart1) -{ - std::string str = "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write:aaaaffff B2ggg"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, cpu_idle) -{ - std::string str = "-0 (-----) [003] d..2 174330.280761: cpu_idle: state=2 cpu_id=3 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, irq_handler_entry) -{ - std::string str = - "ACCS0-2716 ( 2519) [000] d.h1 174330.280362: irq_handler_entry: irq=19 name=408000.qcom,cpu-bwmon"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, irq_handler_exit) -{ - std::string str = "ACCS0-2716 ( 2519) [000] d.h1 174330.280382: irq_handler_exit: irq=19 ret=handled"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, sched_waking) -{ - std::string str = - "ACCS0-2716 ( 2519) [000] d..5 174330.280567: sched_waking: comm=Binder:924_6 pid=1332 prio=120 " - "target_cpu=000"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, sched_wakeup) -{ - std::string str = - "ACCS0-2716 ( 2519) [000] d..6 174330.280575: sched_wakeup: comm=Binder:924_6 pid=1332 prio=120 " - "target_cpu=000"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, trace_event_clock_sync) -{ - std::string str = - " atrace-12728 (12728) [003] ...1 174330.280300: tracing_mark_write: trace_event_clock_sync: " - "parent_ts=23139.998047 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_C) -{ - std::string str = " ACCS0-2716 ( 2519) [000] ...1 174330.284808: tracing_mark_write: C|2519|Heap size (KB)|2906"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_BE) -{ - std::string str = - "system-1298 ( 1298) [001] ...1 174330.287420: tracing_mark_write: B|1298|Choreographer#doFrame - system - 1298(1298)[001]... 1 174330.287622 : tracing_mark_write : E | 1298 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_SF) -{ - std::string str = - "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: S|1298|animator:translateX|18888109 - system - 1298(1298)[001]... 1 174330.287514 : tracing_mark_write : F | 1298 | animator : translateX | - 18888109 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_point) -{ - std::string str = - "system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: G|1298|animator:translateX|18888109 - system - 1298(1298)[001]... 1 174330.287514 : tracing_mark_write : F | - 1298 | animator : translateX | 18888109 "; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_length) -{ - std::string str = " system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: B|2"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_formart) -{ - std::string str = " system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: B2ggg"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, tracing_mark_write_error_formart1) -{ - std::string str = " system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write:aaaaffff B2ggg"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, false); -} - -HWTEST_F(EventParserTest, binder_transaction) -{ - std::string str = - " ACCS0-2716 ( 2519) [000] ...1 174330.280558: binder_transaction: transaction=28562407 dest_node=4336 " - "dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, binder_lock) -{ - std::string str = " <...>-1332 (-----) [000] ...1 174330.289231: binder_lock: transaction=28562426"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, binder_locked) -{ - std::string str = " <...>-1332 (-----) [000] ...1 174330.289232: binder_locked: transaction=28562426"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, binder_unlock) -{ - std::string str = " <...>-1332 (-----) [000] ...1 174330.289233: binder_unlock: transaction=28562426"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, binder_transaction_alloc_buf) -{ - std::string str = - " ACCS0-2716 ( 2519) [000] ...1 174330.290071: binder_transaction_alloc_buf: transaction=28562428 " - "data_size=80 offsets_size=0"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, sched_switch) -{ - std::string str = - " ACCS0-2716 ( 2519) [000] d..3 174330.289220: sched_switch: prev_comm=ACCS0 prev_pid=2716 prev_prio=120 " - "prev_state=R+ ==> next_comm=Binder:924_6 next_pid=1332 next_prio=120"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, task_rename) -{ - std::string str = - "<...>-2093 (-----) [001] ...2 174332.792290: task_rename: pid=12729 oldcomm=perfd newcomm=POSIX timer 249" - "oom_score_adj=-1000"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, task_newtask) -{ - std::string str = - "<...>-2 (-----) [003] ...1 174332.825588: task_newtask: pid=12730 comm=kthreadd clone_flags=800711" - "oom_score_adj=0"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, workqueue_execute_start) -{ - std::string str = - " <...>-12180 (-----) [001] ...1 174332.827595: workqueue_execute_start: work struct 0000000000000000: " - "function pm_runtime_work"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(EventParserTest, workqueue_execute_end) -{ - std::string str = - " <...>-12180 (-----) [001] ...1 174332.828056: workqueue_execute_end: work struct 0000000000000000"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} -} // namespace trace_analyzer -} // namespace SysTuning diff --git a/trace_analyzer/test/bytrace/thread_state_test.cpp b/trace_analyzer/test/bytrace/thread_state_test.cpp deleted file mode 100755 index 806fb6cb7..000000000 --- a/trace_analyzer/test/bytrace/thread_state_test.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include -#include - -#include "bytrace_parser.h" - -namespace SysTuning { -namespace trace_analyzer { -// TestSuite: -class ThreadStateTest : public ::testing::Test { -public: - static void SetUpTestCase() {} - static void TearDownTestCase() {} - void SetUp() override {} - - void TearDown() override {} -}; - -HWTEST_F(ThreadStateTest, ThreadState) -{ - std::string str = - "<...>-968 (-----) [003] d..3 174332.828058: sched_switch: prev_comm=anim prev_pid=968 prev_prio=116 " - "prev_state=S ==> next_comm=display next_pid=966 next_prio=117"; - ThreadState threadState(str); - - uint32_t result = threadState.State(); - - EXPECT_EQ(result, 0x10); -} - -HWTEST_F(ThreadStateTest, ThreadState1) -{ - std::string str = - "<...>-968 (-----) [003] d..3 174332.828058: sched_switch: prev_comm=anim prev_pid=968 prev_prio=116 " - "prev_state=S ==> next_comm=display next_pid=966 next_prio=117"; - TraceAnalyzerContext ctx; - BytraceParser bytraceParser(ctx); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} - -HWTEST_F(ThreadStateTest, ThreadState2) -{ - std::string str = - "< ... > -968(-----)[003] d..3 174332.828058 : sched_switch - : prev_comm = anim prev_pid = 968 prev_prio = 116 prev_state = - S == > next_comm = display next_pid = 966 next_prio = - 117 < ... > -1823(-----)[002] dn .4 174332.828061 : sched_wakeup : comm = system pid = - 1298 prio = 110 target_cpu = - 002 < ... > -966(-----)[003]... 1 174332.828062 : tracing_mark_write : B | 924 | - com.server.wm.RootWindowContainer$MyHandler : #1 < ... > -1823(-----)[002] dn .2 174332.828064 - : ipi_entry : (Rescheduling interrupts)<...> - 966(-----)[003] d..3 174332.828064 : sched_waking : comm = - Binder : 924_11 pid = 3672 prio = 120 target_cpu = - 002 < ... > -12180(-----)[001] d..3 174332.828065 : sched_switch : prev_comm = - kworker / 1 : 0 prev_pid = 12180 prev_prio = 120 prev_state = - S == > next_comm = Binder : 924_C next_pid = 2183 next_prio = - 120 < ... > -1823(-----)[002] dnh3 174332.828067 : sched_blocked_reason - : pid = 569 iowait = 0 caller = rpm_resume + 0x138 / 0x63c < ... > -1823(-----)[002] dnh3 174332.828069 - : sched_wakeup : comm = HwBinder : 508_1 pid = 569 prio = 112 target_cpu = - 002 < ... > -1823(-----)[002] dn .2 174332.828070 : ipi_exit - : (Rescheduling interrupts)<...> - 1823(-----)[002] dn .2 174332.828073 : ipi_entry - : (Single function call interrupts)<...> - - 1823(-----)[002] dnh3 174332.828074 : sched_waking : comm = kschedfreq : 2 pid = 12391 prio = 49 target_cpu = - 002 < ... > -964(-----)[000] d..1 174332.828075 : ipi_entry - : (Rescheduling interrupts)<...> - 2183(-----)[001] d..3 174332.828080 : sched_waking : comm = - PowerManagerSer pid = 987 prio = 116 target_cpu = - 001 < ... > -1823(-----)[002] dnh4 174332.828080 : sched_wakeup - : comm = kschedfreq : 2 pid = 12391 prio = 49 target_cpu = 002 < ... > -964(-----)[000] d.h2 174332.828082 - : sched_blocked_reason - : pid = 3672 iowait = 0 caller = __fdget_pos + 0x5c / 0x9c < ... > -1823(-----)[002] dn .2 174332.828082 - : ipi_exit : (Single function call interrupts)<...> - 2183(-----)[001] dn .4 174332.828086 : sched_wakeup - : comm = PowerManagerSer pid = 987 prio = 116 target_cpu = 001 < ... > -1823(-----)[002] d..3 174332.828086 - : sched_switch : prev_comm = Binder : 924_A prev_pid = 1823 prev_prio = 110 prev_state = - R + == > next_comm = kschedfreq : 2 next_pid = 12391 next_prio = 49 "; - TraceAnalyzerContext context; - BytraceParser bytraceParser(context); - - int result = bytraceParser.Parse(str.c_str(), str.size()); - - EXPECT_EQ(result, true); -} -} // namespace trace_analyzer -} // namespace SysTuning diff --git a/trace_analyzer/test/clock_tracker_test.cpp b/trace_analyzer/test/clock_tracker_test.cpp deleted file mode 100644 index 9a63e554c..000000000 --- a/trace_analyzer/test/clock_tracker_test.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include - -#include "src/trace_analyzer/tracker/clock_tracker.h" - -using namespace testing::ext; - -class ClockTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.clockTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(ClockTrackerTest, ConvertTimestamp, TestSize.Level1) -{ - std::vector snapShot0; - SysTuning::trace_analyzer::SnapShot a{1, 100}; - SysTuning::trace_analyzer::SnapShot b{2, 200}; - SysTuning::trace_analyzer::SnapShot c{3, 300}; - SysTuning::trace_analyzer::SnapShot d{4, 400}; - snapShot0.push_back(a); - snapShot0.push_back(b); - snapShot0.push_back(c); - snapShot0.push_back(d); - context_.clockTracker_->AddClockSnapshot(snapShot0); - - std::vector snapShot1; - SysTuning::trace_analyzer::SnapShot a1{1, 200}; - SysTuning::trace_analyzer::SnapShot b1{2, 350}; - SysTuning::trace_analyzer::SnapShot c1{3, 400}; - SysTuning::trace_analyzer::SnapShot d1{4, 800}; - snapShot1.push_back(a1); - snapShot1.push_back(b1); - snapShot1.push_back(c1); - snapShot1.push_back(d1); - context_.clockTracker_->AddClockSnapshot(snapShot1); - - EXPECT_EQ(context_.clockTracker_->Convert(1, 150, 2), 250); - EXPECT_EQ(context_.clockTracker_->Convert(1, 200, 2), 350); - EXPECT_EQ(context_.clockTracker_->Convert(1, 101, 3), 301); - EXPECT_EQ(context_.clockTracker_->Convert(1, 102, 4), 402); - EXPECT_EQ(context_.clockTracker_->Convert(2, 101, 3), 201); - - EXPECT_EQ(context_.clockTracker_->Convert(3, 351, 2), 251); - EXPECT_EQ(context_.clockTracker_->Convert(3, 401, 2), 351); - EXPECT_EQ(context_.clockTracker_->Convert(2, 150, 1), 50); - EXPECT_EQ(context_.clockTracker_->Convert(2, 250, 1), 150); - EXPECT_EQ(context_.clockTracker_->Convert(2, 351, 1), 201); -} - -HWTEST_F(ClockTrackerTest, ConvertToPrimary, TestSize.Level1) -{ - std::vector snapShot0; - SysTuning::trace_analyzer::SnapShot a{1, 100}; - SysTuning::trace_analyzer::SnapShot b{2, 200}; - SysTuning::trace_analyzer::SnapShot c{3, 300}; - SysTuning::trace_analyzer::SnapShot d{4, 400}; - snapShot0.push_back(a); - snapShot0.push_back(b); - snapShot0.push_back(c); - snapShot0.push_back(d); - context_.clockTracker_->AddClockSnapshot(snapShot0); - - std::vector snapShot1; - SysTuning::trace_analyzer::SnapShot a1{1, 200}; - SysTuning::trace_analyzer::SnapShot b1{2, 350}; - SysTuning::trace_analyzer::SnapShot c1{3, 400}; - SysTuning::trace_analyzer::SnapShot d1{4, 800}; - snapShot1.push_back(a1); - snapShot1.push_back(b1); - snapShot1.push_back(c1); - snapShot1.push_back(d1); - context_.clockTracker_->AddClockSnapshot(snapShot1); - - context_.clockTracker_->SetPrimaryClock(3); - - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(1, 150), 350); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(1, 101), 301); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(2, 101), 201); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(2, 351), 401); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(4, 350), 250); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(4, 420), 320); - EXPECT_EQ(context_.clockTracker_->ToPrimaryTraceTime(4, 801), 401); -} diff --git a/trace_analyzer/test/counter_tracker_test.cpp b/trace_analyzer/test/counter_tracker_test.cpp deleted file mode 100644 index 42bdff60f..000000000 --- a/trace_analyzer/test/counter_tracker_test.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "src/trace_analyzer/tracker/counter_tracker.h" -#include "src/trace_analyzer/tracker/track_tracker.h" - -using namespace testing::ext; - -class CounterTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.storage->InternString("test0"); - context_.storage->InternString("test1"); - context_.storage->InternString("test2"); - context_.storage->InternString("test3"); - - context_.trackTracker_ = std::make_unique(&context_); - context_.threadCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_THREADCOUNTER_TRACK); - context_.threadTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_THREAD_TRACK); - context_.cpuCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_CPU_COUNTER_TRACK); - context_.processCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_PROCESS_COUNTER_TRACK); - context_.processTrackTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_PROCESS_TRACK_TRACK); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(CounterTrackerTest, ThreadCounterTracker, TestSize.Level1) -{ - uint32_t trackId = context_.threadCounterTracker_->GetOrCreateCertainTrackId(100, 0); - EXPECT_EQ(trackId, 0); - - trackId = context_.threadCounterTracker_->GetOrCreateCertainTrackId(101, 2); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - SysTuning::trace_analyzer::ThreaCounterTrack* threadCounterTable = - context_->storage->mutable_thread_counter_track(); - EXPECT_EQ(threadCounterTable->count(), 2); - EXPECT_EQ(threadCounterTable->trackId(0), 0); - EXPECT_EQ(threadCounterTable->trackId(1), 1); - EXPECT_EQ(threadCounterTable->utid(0), 100); - EXPECT_EQ(threadCounterTable->utid(1), 101); - EXPECT_EQ(threadCounterTable->nameId(0), 0); - EXPECT_EQ(threadCounterTable->nameId(1), 2); -} - -HWTEST_F(CounterTrackerTest, ThreadTracker, TestSize.Level1) -{ - uint32_t trackId = context_.threadTracker_->GetOrCreateCertainTrackId(201, 2); - EXPECT_EQ(trackId, 0); - - trackId = context_.threadTracker_->GetOrCreateCertainTrackId(202, 3); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - SysTuning::trace_analyzer::ThreaCounterTrack* threadTable = context_->storage->mutable_thread_track(); - EXPECT_EQ(threadTable->count(), 2); - EXPECT_EQ(threadTable->trackId(0), 0); - EXPECT_EQ(threadTable->trackId(1), 1); - EXPECT_EQ(threadTable->utid(0), 201); - EXPECT_EQ(threadTable->utid(1), 202); - EXPECT_EQ(threadTable->nameId(0), 2); - EXPECT_EQ(threadTable->nameId(1), 3); -} - -HWTEST_F(CounterTrackerTest, CpuTracker, TestSize.Level1) -{ - uint32_t trackId = context_.cpuCounterTracker_->GetOrCreateCertainTrackId(0, 0); - EXPECT_EQ(trackId, 0); - - trackId = context_.cpuCounterTracker_->GetOrCreateCertainTrackId(1, 1); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - SysTuning::trace_analyzer::CpuCounter* cpuCounterTable = context_->storage->mutable_cpu_counters(); - EXPECT_EQ(cpuCounterTable->cpu_counter_count(), 2); - EXPECT_EQ(cpuCounterTable->id(0), 0); - EXPECT_EQ(cpuCounterTable->id(1), 1); - EXPECT_EQ(cpuCounterTable->cpu(0), 201); - EXPECT_EQ(cpuCounterTable->cpu(1), 202); -} - -HWTEST_F(CounterTrackerTest, ProcessCounterTracker, TestSize.Level1) -{ - uint32_t trackId = context_.process_counter_track->GetOrCreateCertainTrackId(300, 0); - EXPECT_EQ(trackId, 0); - - trackId = context_.process_counter_track->GetOrCreateCertainTrackId(301, 1); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - SysTuning::trace_analyzer::ProcessCounterTrack* processCounterTable = - context_->storage->mutable_process_counter_track(); - EXPECT_EQ(processCounterTable->process_counter_track_count(), 2); - EXPECT_EQ(processCounterTable->id(0), 0); - EXPECT_EQ(processCounterTable->id(1), 1); - EXPECT_EQ(processCounterTable->upids(0), 300); - EXPECT_EQ(processCounterTable->upids(1), 301); -} - -HWTEST_F(CounterTrackerTest, ProcessTracker, TestSize.Level1) -{ - uint32_t trackId = context_.processTrackTracker_->GetOrCreateCertainTrackId(400, 0); - EXPECT_EQ(trackId, 0); - - trackId = context_.processTrackTracker_->GetOrCreateCertainTrackId(401, 1); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - SysTuning::trace_analyzer::ProcessCounterTrack* processTrackTable = context_->storage->mutable_process_track(); - EXPECT_EQ(processTrackTable->process_track_count(), 2); -} diff --git a/trace_analyzer/test/cpu_tracker_test.cpp b/trace_analyzer/test/cpu_tracker_test.cpp deleted file mode 100644 index 2d2693ce3..000000000 --- a/trace_analyzer/test/cpu_tracker_test.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "src/trace_analyzer/tracker/cpu_tracker.h" - -using namespace testing::ext; - -class CpuTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.cpuTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(CpuTrackerTest, GenThreadStateTable, TestSize.Level1) -{ - context_.cpuTracker_->InsertWakeingEvent(10000, 200); - context_.cpuTracker_->InsertSwitchEvent(10500, 0, 105, 120, 1, 200, 120); - context_.cpuTracker_->InsertSwitchEvent(10700, 0, 200, 120, 1, 210, 120); - context_.cpuTracker_->InsertWakeingEvent(11000, 200); - context_.cpuTracker_->InsertSwitchEvent(11100, 0, 110, 120, 1, 200, 120); - context_.cpuTracker_->InsertSwitchEvent(11500, 0, 200, 120, 1, 210, 120); - context_.cpuTracker_->InsertWakeingEvent(12000, 200); - context_.cpuTracker_->InsertSwitchEvent(12600, 0, 120, 120, 1, 200, 120); - context_.cpuTracker_->InsertSwitchEvent(12800, 0, 200, 120, 16, 210, 120); - - SysTuning::trace_analyzer::ThreadStateStorage* threadStateTable = context_->storage->mutable_ThreadStateObj(); - - EXPECT_GT(threadStateTable->thread_state_count(), 6); - EXPECT_EQ(context_.cpuTracker_->FindUtidInThreadStateTableByCpu(0), 210); -} diff --git a/trace_analyzer/test/event_tracker_test.cpp b/trace_analyzer/test/event_tracker_test.cpp deleted file mode 100644 index b2025cebe..000000000 --- a/trace_analyzer/test/event_tracker_test.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "src/trace_analyzer/tracker/cpu_tracker.h" - -using namespace testing::ext; - -class EventTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.storage->InternString("process0"); - context_.storage->InternString("process1"); - context_.storage->InternString("process2"); - context_.storage->InternString("process3"); - context_.storage->InternString("thread4"); - context_.storage->InternString("thread5"); - context_.storage->InternString("thread6"); - - context_.trackTracker_ = std::make_unique(&context_); - context_.process_tracker = std::make_unique(&context_); - context_.eventTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(EventTrackerTest, PushSchedSwitch, TestSize.Level1) -{ - context_.eventTracker_->PushSchedSwitch(0, 100000, 101, 200, "threadTest0"); - context_.eventTracker_->PushSchedSwitch(0, 110000, 200, 201, "threadTest1"); - context_.eventTracker_->PushSchedSwitch(0, 120000, 201, 203, "threadTest2"); - context_.eventTracker_->PushSchedSwitch(0, 140000, 203, 205, "threadTest3"); - context_.eventTracker_->PushSchedSwitch(0, 170000, 205, 207, "threadTest4"); - context_.eventTracker_->PushSchedSwitch(0, 200000, 207, 209, "threadTest5"); - - SysTuning::trace_analyzer::Slices* slices = context_->storage->mutable_slices(); - - EXPECT_GT(slices->slice_count(), 6); -} diff --git a/trace_analyzer/test/process_tracker_test.cpp b/trace_analyzer/test/process_tracker_test.cpp deleted file mode 100644 index 3e653e219..000000000 --- a/trace_analyzer/test/process_tracker_test.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include - -#include "src/trace_analyzer/tracker/process_tracker.h" - -using namespace testing::ext; - -class ProcessTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.storage->InternString("process0"); - context_.storage->InternString("process1"); - context_.storage->InternString("process2"); - context_.storage->InternString("process3"); - context_.storage->InternString("thread4"); - context_.storage->InternString("thread5"); - context_.storage->InternString("thread6"); - - context_.processTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(ProcessTrackerTest, UpdateThread, TestSize.Level1) -{ - uint32_t utid0 = context_.processTracker_->UpdateThread(1000, 101, 4); - EXPECT_EQ(utid0, 1); - - uint32_t utid1 = context_.processTracker_->UpdateThread(100, 95); - EXPECT_EQ(utid1, 2); - - SysTuning::trace_analyzer::Thread* thread = context_->storage->GetMutableThread(utid0); - EXPECT_EQ(thread->tid, 101); - EXPECT_EQ(thread->start_ns, 10000); - - thread = context_->storage->GetMutableThread(utid0); - EXPECT_EQ(thread->tid, 100); - EXPECT_EQ(thread->upid, 1); -} - -HWTEST_F(ProcessTrackerTest, UpdateProcess, TestSize.Level1) -{ - uint32_t upid0 = context_.processTracker_->UpdateProcess(1000); - EXPECT_EQ(upid0, 1); - - SysTuning::trace_analyzer::Process* process = context_->storage->GetMutableProcess(upid0); - EXPECT_EQ(process->pid, 1000); - - process = context_->storage->GetMutableProcess(upid1); - EXPECT_EQ(process->pid, 1001); -} - -HWTEST_F(ProcessTrackerTest, Update, TestSize.Level1) -{ - uint32_t upid0 = context_.processTracker_->UpdateProcess(2000); - EXPECT_EQ(upid0, 1); - - SysTuning::trace_analyzer::Process* process = context_->storage->GetMutableProcess(upid0); - EXPECT_EQ(process->pid, 2000); - - SysTuning::trace_analyzer::Thread* thread = context_->storage->GetMutableThread(1); - EXPECT_EQ(thread->tid, 2000); - - SysTuning::trace_analyzer::Thread* thread = context_->storage->GetMutableThread(2); - EXPECT_EQ(thread->tid, 2001); -} diff --git a/trace_analyzer/test/resource/htrace.bin b/trace_analyzer/test/resource/htrace.bin new file mode 100644 index 000000000..8afa3b9f3 --- /dev/null +++ b/trace_analyzer/test/resource/htrace.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b546804c5e7e43fc39d0a26e6204181a798fd7038c8727dc068728ae0150446 +size 11438327 diff --git a/trace_analyzer/test/resource/htrace_gold.db b/trace_analyzer/test/resource/htrace_gold.db new file mode 100644 index 000000000..b0a183930 Binary files /dev/null and b/trace_analyzer/test/resource/htrace_gold.db differ diff --git a/trace_analyzer/test/resource/ut_bytrace_input_full.txt b/trace_analyzer/test/resource/ut_bytrace_input_full.txt new file mode 100755 index 000000000..0a0588c46 --- /dev/null +++ b/trace_analyzer/test/resource/ut_bytrace_input_full.txt @@ -0,0 +1,75 @@ +# TRACE: +# tracer: nop +# +# entries-in-buffer/entries-written: 1373949/1373949 #P:4 +# +# _-----=> irqs-off +# / _----=> need-resched +# | / _---=> hardirq/softirq +# || / _--=> preempt-depth +# ||| / delay +# TASK-PID TGID CPU# |||| TIMESTAMP FUNCTION +# | | | | |||| | | + ACCS0-2716 ( 2519) [000] ...1 168758.662861: binder_transaction: transaction=25137708 dest_node=4336 dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3 + ACCS0-2716 ( 2519) [000] ...1 168758.662869: binder_transaction_alloc_buf: transaction=25137708 data_size=80 offsets_size=0 + ACCS0-2716 ( 2519) [000] d..5 168758.662877: sched_waking: comm=Binder:924_3 pid=1200 prio=120 target_cpu=001 + ACCS0-2716 ( 2519) [000] d..6 168758.662898: sched_wakeup: comm=Binder:924_3 pid=1200 prio=120 target_cpu=001 + ACCS0-2716 ( 2519) [000] d..3 168758.662919: sched_switch: prev_comm=ACCS0 prev_pid=2716 prev_prio=120 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + HeapTaskDaemon-2532 ( 2519) [000] ...1 168758.662947: tracing_mark_write: E|2519 + HeapTaskDaemon-2532 ( 2519) [000] ...1 168758.662957: tracing_mark_write: B|2519|VisitNonThreadRoots + atrace-8528 ( 8528) [003] ...1 168758.662972: tracing_mark_write: trace_event_clock_sync: parent_ts=20445.875000 + atrace-8528 ( 8528) [003] ...1 168758.662986: tracing_mark_write: trace_event_clock_sync: realtime_ts=1616434280685 + -0 (-----) [001] dn.2 168758.662989: ipi_entry: (Rescheduling interrupts) + -0 (-----) [001] dn.2 168758.662992: ipi_exit: (Rescheduling interrupts) + -0 (-----) [001] .n.2 168758.662996: cpu_idle: state=4294967295 cpu_id=1 + HeapTaskDaemon-2532 ( 2519) [000] ...1 168758.663011: tracing_mark_write: E|2519 + -0 (-----) [001] d..3 168758.663017: sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=Binder:924_3 next_pid=1200 next_prio=120 + HeapTaskDaemon-2532 ( 2519) [000] ...1 168758.663018: tracing_mark_write: B|2519|ProcessMarkStack + <...>-1200 (-----) [001] ...1 168758.663028: binder_transaction_received: transaction=25137708 + atrace-8528 ( 8528) [003] d..3 168758.663039: sched_switch: prev_comm=atrace prev_pid=8528 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..4 168758.663078: sched_waking: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] d..1 168758.663089: ipi_entry: (Rescheduling interrupts) + -0 (-----) [003] d..2 168758.663089: softirq_raise: vec=9 [action=RCU] + -0 (-----) [003] d..3 168758.663092: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663097: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] dn.1 168758.663100: ipi_exit: (Rescheduling interrupts) + -0 (-----) [003] dn.4 168758.663104: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663107: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663126: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663126: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663134: softirq_entry: vec=9 [action=RCU] + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663141: softirq_exit: vec=9 [action=RCU] + ksoftirqd/3-29 ( 29) [003] d..3 168758.663159: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..4 168758.663181: sched_waking: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + -0 (-----) [003] d..2 168758.663188: softirq_raise: vec=9 [action=RCU] + HeapTaskDaemon-2532 ( 2519) [000] d..1 168758.663190: ipi_entry: (Rescheduling interrupts) + -0 (-----) [003] d..3 168758.663190: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663194: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] dn.1 168758.663195: ipi_exit: (Rescheduling interrupts) + -0 (-----) [003] dn.4 168758.663198: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663199: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R+ ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663209: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663212: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663218: softirq_entry: vec=9 [action=RCU] + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663222: softirq_exit: vec=9 [action=RCU] + ksoftirqd/3-29 ( 29) [003] d..3 168758.663239: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..4 168758.663261: sched_waking: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] d..1 168758.663270: ipi_entry: (Rescheduling interrupts) + -0 (-----) [003] d..2 168758.663270: softirq_raise: vec=9 [action=RCU] + -0 (-----) [003] d..3 168758.663272: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663274: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] dn.1 168758.663276: ipi_exit: (Rescheduling interrupts) + -0 (-----) [003] dn.4 168758.663279: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663280: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663290: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663294: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663298: softirq_entry: vec=9 [action=RCU] + ksoftirqd/3-29 ( 29) [003] ..s1 168758.663301: softirq_exit: vec=9 [action=RCU] + <...>-1200 (-----) [001] ...1 168758.663302: binder_transaction: transaction=25137709 dest_node=0 dest_proc=2519 dest_thread=2716 reply=1 flags=0x0 code=0x0 + <...>-1200 (-----) [001] ...1 168758.663307: binder_transaction_alloc_buf: transaction=25137709 data_size=8 offsets_size=0 + <...>-1200 (-----) [001] d..3 168758.663312: sched_waking: comm=ACCS0 pid=2716 prio=120 target_cpu=000 + ksoftirqd/3-29 ( 29) [003] d..3 168758.663316: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + HeapTaskDaemon-2532 ( 2519) [000] dn.1 168758.663324: ipi_entry: (Rescheduling interrupts) + <...>-1200 (-----) [001] d..4 168758.663324: sched_wakeup: comm=ACCS0 pid=2716 prio=120 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] dn.1 168758.663325: ipi_exit: (Rescheduling interrupts) + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663329: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=ACCS0 next_pid=2716 next_prio=120 \ No newline at end of file diff --git a/trace_analyzer/test/resource/ut_bytrace_input_full_gold.db b/trace_analyzer/test/resource/ut_bytrace_input_full_gold.db new file mode 100644 index 000000000..249b8e63d Binary files /dev/null and b/trace_analyzer/test/resource/ut_bytrace_input_full_gold.db differ diff --git a/trace_analyzer/test/resource/ut_bytrace_input_thread.txt b/trace_analyzer/test/resource/ut_bytrace_input_thread.txt new file mode 100755 index 000000000..1e6486754 --- /dev/null +++ b/trace_analyzer/test/resource/ut_bytrace_input_thread.txt @@ -0,0 +1,43 @@ +# TRACE: +# tracer: nop +# +# entries-in-buffer/entries-written: 1373949/1373949 #P:4 +# +# _-----=> irqs-off +# / _----=> need-resched +# | / _---=> hardirq/softirq +# || / _--=> preempt-depth +# ||| / delay +# TASK-PID TGID CPU# |||| TIMESTAMP FUNCTION +# | | | | |||| | | + ACCS0-2716 ( 2519) [000] d..5 168758.662877: sched_waking: comm=Binder:924_3 pid=1200 prio=120 target_cpu=001 + ACCS0-2716 ( 2519) [000] d..6 168758.662898: sched_wakeup: comm=Binder:924_3 pid=1200 prio=120 target_cpu=001 + -0 (-----) [001] d..3 168758.663017: sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=Binder:924_3 next_pid=1200 next_prio=120 + atrace-8528 ( 8528) [003] d..3 168758.663039: sched_switch: prev_comm=atrace prev_pid=8528 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..3 168758.663092: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663097: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000) + -0 (-----) [003] dn.4 168758.663104: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663107: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663126: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663126: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + ksoftirqd/3-29 ( 29) [003] d..3 168758.663159: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..4 168758.663181: sched_waking: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + -0 (-----) [003] d..3 168758.663190: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663194: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + -0 (-----) [003] dn.4 168758.663198: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663199: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R+ ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663209: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663212: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + ksoftirqd/3-29 ( 29) [003] d..3 168758.663239: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + -0 (-----) [003] d..4 168758.663261: sched_waking: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + -0 (-----) [003] d..3 168758.663272: sched_waking: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] dnh2 168758.663274: sched_wakeup: comm=rcu_preempt pid=7 prio=98 target_cpu=000 + -0 (-----) [003] dn.4 168758.663279: sched_wakeup: comm=ksoftirqd/3 pid=29 prio=120 target_cpu=003 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663280: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=rcu_preempt next_pid=7 next_prio=98 + rcu_preempt-7 ( 7) [000] d..3 168758.663290: sched_switch: prev_comm=rcu_preempt prev_pid=7 prev_prio=98 prev_state=S ==> next_comm=HeapTaskDaemon next_pid=2532 next_prio=124 + -0 (-----) [003] d..3 168758.663294: sched_switch: prev_comm=swapper/3 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=ksoftirqd/3 next_pid=29 next_prio=120 + <...>-1200 (-----) [001] d..3 168758.663312: sched_waking: comm=ACCS0 pid=2716 prio=120 target_cpu=000 + ksoftirqd/3-29 ( 29) [003] d..3 168758.663316: sched_switch: prev_comm=ksoftirqd/3 prev_pid=29 prev_prio=120 prev_state=S ==> next_comm=swapper/3 next_pid=0 next_prio=120 + <...>-1200 (-----) [001] d..4 168758.663324: sched_wakeup: comm=ACCS0 pid=2716 prio=120 target_cpu=000 + HeapTaskDaemon-2532 ( 2519) [000] d..3 168758.663329: sched_switch: prev_comm=HeapTaskDaemon prev_pid=2532 prev_prio=124 prev_state=R ==> next_comm=ACCS0 next_pid=2716 next_prio=120 + \ No newline at end of file diff --git a/trace_analyzer/test/resource/ut_bytrace_input_thread_gold.db b/trace_analyzer/test/resource/ut_bytrace_input_thread_gold.db new file mode 100644 index 000000000..8e4299724 Binary files /dev/null and b/trace_analyzer/test/resource/ut_bytrace_input_thread_gold.db differ diff --git a/trace_analyzer/test/slice_tracker_test.cpp b/trace_analyzer/test/slice_tracker_test.cpp deleted file mode 100644 index 301ece1f3..000000000 --- a/trace_analyzer/test/slice_tracker_test.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "src/trace_analyzer/tracker/counter_tracker.h" -#include "src/trace_analyzer/tracker/process_tracker.h" -#include "src/trace_analyzer/tracker/slice_tracker.h" -#include "src/trace_analyzer/tracker/track_tracker.h" - -using namespace testing::ext; - -class SliceTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.storage->InternString("category0"); - context_.storage->InternString("category1"); - context_.storage->InternString("name0"); - context_.storage->InternString("name1"); - - context_.trackTracker_ = std::make_unique(&context_); - context_.processTracker_ = std::make_unique(&context_); - context_.threadCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_THREADCOUNTER_TRACK); - context_.threadTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_THREAD_TRACK); - context_.cpuCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_CPU_COUNTER_TRACK); - context_.processCounterTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_PROCESS_COUNTER_TRACK); - context_.processTrackTracker_ = std::make_unique( - &context_, SysTuning::trace_analyzer::TrackType::E_PROCESS_TRACK_TRACK); - context_.sliceTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(SliceTrackerTest, SliceTest, TestSize.Level1) -{ - context_.sliceTracker_->BeginSlice(100000, 200, 200, 0, 2); - context_.sliceTracker_->EndSlice(105000, 200, 200); - - SysTuning::trace_analyzer::Slices* slices = context_->storage->mutable_slices(); - EXPECT_GT(slices->slice_count(), 0); -} diff --git a/trace_analyzer/test/test_ts.gni b/trace_analyzer/test/test_ts.gni new file mode 100644 index 000000000..c98a8ae39 --- /dev/null +++ b/trace_analyzer/test/test_ts.gni @@ -0,0 +1,29 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +OHOS_PROTO_DIR = "" + +if (target_os == "linux" || target_os == "windows") { + OHOS_FTRACE_PROTO_DIR = "//third_party/protogen" + OHOS_MEMORY_PROTO_DIR = "//third_party/protogen" + OHOS_PROTO_GEN = "//third_party/protogen/gen" + OHOS_SERVICE_PROTO_DIR = "//third_party/protogen" +} else { + OHOS_FTRACE_PROTO_DIR = + "//developtools/profiler/protos/types/plugins/ftrace_data" + OHOS_MEMORY_PROTO_DIR = + "//developtools/profiler/protos/types/plugins/memory_data" + OHOS_SERVICE_PROTO_DIR = "//developtools/profiler/protos/services" + OHOS_PROTO_GEN = "//out/aosp-arm-release/gen/cpp/developtools/profiler/protos" +} +enable_ts_utest = true diff --git a/trace_analyzer/test/trace_analyzer_test.cpp b/trace_analyzer/test/trace_analyzer_test.cpp deleted file mode 100755 index ef6432a7d..000000000 --- a/trace_analyzer/test/trace_analyzer_test.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include -#include - -#include "file.h" -#include "log.h" -#include "trace_analyzer.h" - -static char g_argv[3][100] = {"./test.systrace.txt", "-e", "./test.db"}; - -using namespace SysTuning; -using namespace base; -using namespace trace_analyzer; - -// TestSuite: -class TraceAnalyzerTest : public ::testing::Test { -public: - static void SetUpTestCase() {} - static void TearDownTestCase() {} - void SetUp() override {} - - void TearDown() override {} -}; - -HWTEST_F(TraceAnalyzerTest, EnterTraceAnalyzer) -{ - int argc = 3; - ExportStatusToLog(ABNORMAL); - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &g_argv); - ExportStatusToLog(GetAnalysisResult()); - EXPECT_EQ(result, 1); -} - -HWTEST_F(TraceAnalyzerTest, EnterTraceAnalyzer_args_too_short) -{ - int argc = 1; - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &argv); - EXPECT_EQ(result, 0); -} - -HWTEST_F(TraceAnalyzerTest, EnterTraceAnalyzer_version) -{ - int argc = 1; - char argv[3][100] = {"-v"}; - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &argv); - EXPECT_EQ(result, 1); - - char argv1[3][100] = {"--v"}; - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &1argv); - EXPECT_EQ(result, 1); - - char argv2[3][100] = {"--version"}; - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &2argv); - EXPECT_EQ(result, 1); - - char argv3[3][100] = {"-version"}; - int result = SysTuning::trace_analyzer::EnterTraceAnalyzer(argc, &3argv); - EXPECT_EQ(result, 1); -} diff --git a/trace_analyzer/test/track_tracker_test.cpp b/trace_analyzer/test/track_tracker_test.cpp deleted file mode 100644 index 444a92342..000000000 --- a/trace_analyzer/test/track_tracker_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "src/trace_analyzer/tracker/track_tracker.h" - -using namespace testing::ext; - -class TrackTrackerTest : public ::testing::Test { -protected: - void SetUp() override - { - context_.storage = std::make_unique(); - context_.trackTracker_ = std::make_unique(&context_); - } - - void TearDown() override {} - -private: - SysTuning::trace_analyzer::TraceAnalyzerContext context_; -}; - -HWTEST_F(TrackTrackerTest, AddCpuCounterTrack, TestSize.Level1) -{ - uint32_t trackId = context_.trackTracker_->AddTrack("cpu_counter_track", "cpu1"); - EXPECT_EQ(trackId, 0); - - trackId = context_.trackTracker_->AddTrack("cpu_counter_track", "cpu2"); - EXPECT_EQ(trackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); -} - -HWTEST_F(TrackTrackerTest, AddThreadTrack, TestSize.Level1) -{ - uint32_t threadTrackId = context_.trackTracker_->AddTrack("thread_counter_track", "threadCount1"); - EXPECT_EQ(threadTrackId, 0); - - threadTrackId = context_.trackTracker_->AddTrack("thread_counter_track", "threadCount2"); - EXPECT_EQ(threadTrackId, 1); - - SysTuning::trace_analyzer::Track* trackTable = context_->storage->mutable_track_table(); - EXPECT_EQ(trackTable->count(), 2); - - threadTrackId = context_.trackTracker_->AddTrack("thread_track", "thread1"); - EXPECT_EQ(threadTrackId, 2); - - threadTrackId = context_.trackTracker_->AddTrack("thread_track", "thread2"); - EXPECT_EQ(threadTrackId, 3); - - EXPECT_EQ(trackTable->count(), 4); -} diff --git a/trace_analyzer/test/unittest/bytrace_parser_test.cpp b/trace_analyzer/test/unittest/bytrace_parser_test.cpp new file mode 100755 index 000000000..32174660c --- /dev/null +++ b/trace_analyzer/test/unittest/bytrace_parser_test.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include "parser/bytrace_parser/bytrace_parser.h" +#include "parser/common_types.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; + +namespace SysTuning { +namespace TraceStreamer { +class BytraceParserTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} + +public: + SysTuning::TraceStreamer::TraceStreamerSelector stream_{}; + const char* dbPath = "/data/resource/out.db"; +}; + +HWTEST_F(BytraceParserTest, ParseNoData, TestSize.Level1) +{ + TS_LOGI("test1-1"); + std::unique_ptr buf = std::make_unique(1); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + printf("xxx\n"); + bytraceParser.ParseTraceDataSegment(std::move(buf), 1); + printf("xxx2\n"); + bytraceParser.WaitForParserEnd(); + printf("xxx3\n"); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 0); +} + +HWTEST_F(BytraceParserTest, ParseNoDataWhithLineFlag, TestSize.Level1) +{ + TS_LOGI("test1-2"); + constexpr uint32_t bufSize = 1024; + std::unique_ptr buf{new uint8_t[bufSize]{" \n"}}; + + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), bufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + +HWTEST_F(BytraceParserTest, ParseInvalidData, TestSize.Level1) +{ + TS_LOGI("test1-3"); + constexpr uint32_t bufSize = 1024; + std::unique_ptr buf{new uint8_t[bufSize]{"0123456789\n"}}; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), bufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + +HWTEST_F(BytraceParserTest, ParseComment, TestSize.Level1) +{ + TS_LOGI("test1-4"); + constexpr uint32_t bufSize = 1024; + std::unique_ptr buf{new uint8_t[bufSize]{"TRACE: \n# tracer: nop \n# \n"}}; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), bufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 2); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + +HWTEST_F(BytraceParserTest, ParseInvalidLines, TestSize.Level1) +{ + TS_LOGI("test1-5"); + constexpr uint32_t bufSize = 1024; + std::unique_ptr buf{new uint8_t[bufSize]{"\nafafda\n"}}; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), bufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 2); +} + +HWTEST_F(BytraceParserTest, ParseNormal, TestSize.Level1) +{ + TS_LOGI("test1-6"); + std::string str( + "ACCS0-2716 ( 2519) [000] ...1 168758.662861: binder_transaction: \ + transaction=25137708 dest_node=4336 dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3\n"); + // BytraceLine line; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataItem(str); + bytraceParser.WaitForParserEnd(); + + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 1); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 0); +} + +HWTEST_F(BytraceParserTest, LineParser_abnormal_pid_err, TestSize.Level1) +{ + TS_LOGI("test1-7"); + std::string str( + "ACCS0-27X6 ( 2519) [000] ...1 168758.662861: binder_transaction: \ + transaction=25137708 dest_node=4336 dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3\n"); + // BytraceLine line; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataItem(str); + bytraceParser.WaitForParserEnd(); + + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + +HWTEST_F(BytraceParserTest, LineParserWithInvalidCpu, TestSize.Level1) +{ + TS_LOGI("test1-8"); + std::string str( + "ACCS0-2716 ( 2519) [00X] ...1 168758.662861: binder_transaction: \ + transaction=25137708 dest_node=4336 dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3\n"); + // BytraceLine line; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataItem(str); + bytraceParser.WaitForParserEnd(); + + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + +HWTEST_F(BytraceParserTest, LineParserWithInvalidTs, TestSize.Level1) +{ + TS_LOGI("test1-9"); + std::string str( + "ACCS0-2716 ( 2519) [000] ...1 168758.662X61: binder_transaction: \ + transaction=25137708 dest_node=4336 dest_proc=924 dest_thread=0 reply=0 flags=0x10 code=0x3\n"); + // BytraceLine line; + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataItem(str); + bytraceParser.WaitForParserEnd(); + + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/clock_filter_test.cpp b/trace_analyzer/test/unittest/clock_filter_test.cpp new file mode 100755 index 000000000..39b70014a --- /dev/null +++ b/trace_analyzer/test/unittest/clock_filter_test.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "clock_filter.h" +#include "trace_data_cache.h" +#include "trace_streamer_filters.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class ClockFilterTest : public ::testing::Test { +public: + void SetUp() + { + streamFilters_.clockFilter_ = std::make_unique(&traceDataCache_, &streamFilters_); + } + + void TearDown() {} + +public: + SysTuning::TraceStreamer::TraceStreamerFilters streamFilters_; + SysTuning::TraceStreamer::TraceDataCache traceDataCache_; +}; +HWTEST_F(ClockFilterTest, ConvertTimestamp, TestSize.Level1) +{ + TS_LOGI("test2-1"); + std::vector snapShot0; + snapShot0.push_back({TS_CLOCK_BOOTTIME, 100}); + snapShot0.push_back({TS_MONOTONIC, 200}); + snapShot0.push_back({TS_CLOCK_REALTIME, 300}); + snapShot0.push_back({TS_CLOCK_REALTIME_COARSE, 400}); + streamFilters_.clockFilter_->AddClockSnapshot(snapShot0); + + std::vector snapShot1; + snapShot1.push_back({TS_CLOCK_BOOTTIME, 200}); + snapShot1.push_back({TS_MONOTONIC, 350}); + snapShot1.push_back({TS_CLOCK_REALTIME, 400}); + snapShot1.push_back({TS_CLOCK_REALTIME_COARSE, 800}); + streamFilters_.clockFilter_->AddClockSnapshot(snapShot1); + + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_BOOTTIME, 150, TS_MONOTONIC), static_cast(250)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_BOOTTIME, 200, TS_MONOTONIC), static_cast(350)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_BOOTTIME, 101, TS_CLOCK_REALTIME), + static_cast(301)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_BOOTTIME, 102, TS_CLOCK_REALTIME_COARSE), + static_cast(402)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_MONOTONIC, 101, TS_CLOCK_REALTIME), static_cast(201)); + + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_REALTIME, 351, TS_MONOTONIC), static_cast(251)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_CLOCK_REALTIME, 401, TS_MONOTONIC), static_cast(351)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_MONOTONIC, 150, TS_CLOCK_BOOTTIME), static_cast(50)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_MONOTONIC, 250, TS_CLOCK_BOOTTIME), static_cast(150)); + EXPECT_EQ(streamFilters_.clockFilter_->Convert(TS_MONOTONIC, 351, TS_CLOCK_BOOTTIME), static_cast(201)); +} + +HWTEST_F(ClockFilterTest, ConvertToPrimary, TestSize.Level1) +{ + TS_LOGI("test2-2"); + std::vector snapShot0; + snapShot0.push_back({TS_CLOCK_BOOTTIME, 100}); + snapShot0.push_back({TS_CLOCK_REALTIME, 200}); + snapShot0.push_back({CLOCK_REALTIME, 300}); + snapShot0.push_back({TS_CLOCK_REALTIME_COARSE, 400}); + streamFilters_.clockFilter_->AddClockSnapshot(snapShot0); + + std::vector snapShot1; + snapShot1.push_back({TS_CLOCK_BOOTTIME, 200}); + snapShot1.push_back({TS_CLOCK_REALTIME, 350}); + snapShot1.push_back({CLOCK_REALTIME, 400}); + snapShot1.push_back({TS_CLOCK_REALTIME_COARSE, 800}); + streamFilters_.clockFilter_->AddClockSnapshot(snapShot1); + + streamFilters_.clockFilter_->SetPrimaryClock(CLOCK_REALTIME); + + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_BOOTTIME, 150), static_cast(350)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_BOOTTIME, 101), static_cast(301)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_REALTIME, 101), static_cast(201)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_REALTIME, 351), static_cast(401)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_REALTIME_COARSE, 350), + static_cast(250)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_REALTIME_COARSE, 420), + static_cast(320)); + EXPECT_EQ(streamFilters_.clockFilter_->ToPrimaryTraceTime(TS_CLOCK_REALTIME_COARSE, 801), + static_cast(401)); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/cpu_filter_test.cpp b/trace_analyzer/test/unittest/cpu_filter_test.cpp new file mode 100755 index 000000000..08454171f --- /dev/null +++ b/trace_analyzer/test/unittest/cpu_filter_test.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "common.h" +#include "cpu_filter.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class CpuFilterTest : public ::testing::Test { +public: + void SetUp() + { + streamFilters_.cpuFilter_ = std::make_unique(&traceDataCache_, &streamFilters_); + } + + void TearDown() {} + +public: + TraceStreamerFilters streamFilters_; + TraceDataCache traceDataCache_; +}; + +HWTEST_F(CpuFilterTest, CpufilterTest1, TestSize.Level1) +{ + TS_LOGI("test3-1"); + /* InsertWakeingEvent ts, internalTid */ + /* InsertSwitchEvent ts, cpu, prevPid, prevPior, prevState, nextPid, nextPior */ + streamFilters_.cpuFilter_->InsertWakeingEvent(168758662877000, 1); // 1st waking + + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(1) == INVALID_UINT64); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(1) == TASK_INVALID); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 0); // 0 thread state only + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758662919000, 0, 1, 120, TASK_INTERRUPTIBLE, 2, 124); // 1st switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(1) == TASK_INVALID); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 0); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 1); // 1 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663017000, 0, 0, 120, TASK_RUNNABLE, 4, 120); // 2nd switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(4) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(4) == 1); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 2); // 2 thread state + + streamFilters_.cpuFilter_->InsertWakeingEvent(168758663078000, 0); // 2nd waking + + streamFilters_.cpuFilter_->InsertWakeingEvent(168758663092000, 0); // 3rd waking + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663107000, 0, 2, 124, TASK_RUNNABLE, 5, 98); // 3rd switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(5) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNABLE); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(5) == 2); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 3); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 4); // 4 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663126000, 0, 5, 98, TASK_INTERRUPTIBLE, 2, 124); // 4th switch + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(5) == TASK_INTERRUPTIBLE); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 4); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(5) == 5); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 6); // 6 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663136000, 3, 5, 120, TASK_RUNNABLE, 6, 120); // 5th switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(6) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(6) == 6); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 8); // 8 thread state + + // after 3rd switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[0] == 168758663107000 - 168758662919000); + // after 4th switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[2] == 168758663126000 - 168758663107000); + // after 5th switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[5] == 168758663136000 - 168758663126000); +} + +HWTEST_F(CpuFilterTest, GenThreadStateTable, TestSize.Level1) +{ + TS_LOGI("test3-1"); + /* InsertWakeingEvent ts, internalTid */ + /* InsertSwitchEvent ts, cpu, prevPid, prevPior, prevState, nextPid, nextPior */ + streamFilters_.cpuFilter_->InsertWakeingEvent(168758662877000, 1); // 1st waking + + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(1) == INVALID_UINT64); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(1) == TASK_INVALID); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 0); // 0 thread state only + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758662919000, 0, 1, 120, TASK_INTERRUPTIBLE, 2, 124); // 1st switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(1) == TASK_INVALID); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 0); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 1); // 1 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663017000, 0, 0, 120, TASK_RUNNABLE, 4, 120); // 2nd switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(4) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(4) == 1); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 2); // 2 thread state + + streamFilters_.cpuFilter_->InsertWakeingEvent(168758663078000, 0); // 2nd waking + + streamFilters_.cpuFilter_->InsertWakeingEvent(168758663092000, 0); // 3rd waking + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663107000, 0, 2, 124, TASK_RUNNABLE, 5, 98); // 3rd switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(5) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNABLE); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(5) == 2); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 3); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 4); // 4 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663126000, 0, 5, 98, TASK_INTERRUPTIBLE, 2, 124); // 4th switch + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(2) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(5) == TASK_INTERRUPTIBLE); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(2) == 4); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(5) == 5); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 6); // 6 thread state + + streamFilters_.cpuFilter_->InsertSwitchEvent(168758663136000, 3, 5, 120, TASK_RUNNABLE, 6, 120); // 5th switch + + EXPECT_TRUE(streamFilters_.cpuFilter_->StateOfInternalTidThreadState(6) == TASK_RUNNING); + EXPECT_TRUE(streamFilters_.cpuFilter_->RowOfInternalTidThreadState(6) == 6); + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->Size() == 8); // 8 thread state + + // after 3rd switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[0] == 168758663107000 - 168758662919000); + // after 4th switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[2] == 168758663126000 - 168758663107000); + // after 5th switch + EXPECT_TRUE(traceDataCache_.GetThreadStateData()->DursData()[5] == 168758663136000 - 168758663126000); +} +} +} diff --git a/trace_analyzer/test/unittest/event_parser_test.cpp b/trace_analyzer/test/unittest/event_parser_test.cpp new file mode 100755 index 000000000..e673fa387 --- /dev/null +++ b/trace_analyzer/test/unittest/event_parser_test.cpp @@ -0,0 +1,806 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include "parser/bytrace_parser/bytrace_event_parser.h" +#include "parser/bytrace_parser/bytrace_parser.h" +#include "parser/common_types.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +const uint32_t G_BUF_SIZE = 1024; +// TestSuite: +class EventParserTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} + +public: + TraceStreamerSelector stream_{}; + const char* dbPath = "/data/resource/out.db"; +}; + +HWTEST_F(EventParserTest, ParseLine, TestSize.Level1) +{ + TS_LOGI("test4-1"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.cpu = 0; + bytraceLine.task = "ACCS0-2716"; + bytraceLine.pidStr = "12"; + bytraceLine.tGidStr = "12"; + bytraceLine.eventName = "sched_switch"; + ArgsMap args; + args.insert(std::make_pair("prev_comm", "ACCS0")); + args.insert(std::make_pair("prev_pid", "2716")); + args.insert(std::make_pair("prev_prio", "120")); + args.insert(std::make_pair("prev_state", "R")); + args.insert(std::make_pair("next_comm", "kworker/0:0")); + args.insert(std::make_pair("next_pid", "8326")); + args.insert(std::make_pair("next_prio", "120")); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.ParseDataItem(bytraceLine, args, 2519); + + EXPECT_EQ(result, true); +} +HWTEST_F(EventParserTest, ParseLineNotEnoughArgs, TestSize.Level1) +{ + TS_LOGI("test4-1"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.cpu = 0; + bytraceLine.task = "ACCS0-2716"; + bytraceLine.pidStr = "12"; + bytraceLine.tGidStr = "12"; + bytraceLine.eventName = "sched_switch"; + ArgsMap args; + args.insert(std::make_pair("prev_prio", "120")); + args.insert(std::make_pair("prev_state", "R")); + args.insert(std::make_pair("next_comm", "kworker/0:0")); + args.insert(std::make_pair("next_pid", "8326")); + args.insert(std::make_pair("next_prio", "120")); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.ParseDataItem(bytraceLine, args, 2519); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, ParseLineUnCognizableEventname, TestSize.Level1) +{ + TS_LOGI("test4-2"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.cpu = 0; + bytraceLine.task = "ACCS0-2716"; + bytraceLine.pidStr = "12"; + bytraceLine.tGidStr = "12"; + bytraceLine.eventName = "ThisEventNameDoNotExist"; // UnRecognizable event name + ArgsMap args; + args.insert(std::make_pair("prev_comm", "ACCS0")); + args.insert(std::make_pair("prev_pid", "2716")); + args.insert(std::make_pair("prev_prio", "120")); + args.insert(std::make_pair("prev_state", "R")); + args.insert(std::make_pair("next_comm", "kworker/0:0")); + args.insert(std::make_pair("next_pid", "8326")); + args.insert(std::make_pair("next_prio", "120")); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.ParseDataItem(bytraceLine, args, 2519); + + EXPECT_EQ(result, false); +} +HWTEST_F(EventParserTest, ParseLineNoArgs, TestSize.Level1) +{ + TS_LOGI("test4-4"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.cpu = 0; + bytraceLine.task = "ACCS0-2716"; + bytraceLine.pidStr = "12"; + bytraceLine.tGidStr = "12"; + bytraceLine.eventName = "sched_switch"; + ArgsMap args; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.ParseDataItem(bytraceLine, args, 2519); + + EXPECT_EQ(result, false); +} +HWTEST_F(EventParserTest, ParseLineNoArgs2, TestSize.Level1) +{ + TS_LOGI("test4-4"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.cpu = 0; + bytraceLine.task = "ACCS0-2716"; + bytraceLine.pidStr = "12"; + bytraceLine.tGidStr = "12"; + bytraceLine.eventName = "sched_wakeup"; + ArgsMap args; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.ParseDataItem(bytraceLine, args, 2519); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, TracingMarkWriteC, TestSize.Level1) +{ + TS_LOGI("test4-7"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "ACCS0-2716 ( 2519) [000] ...1 174330.284808: tracing_mark_write: C|2519|Heap size (KB)|2906\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TracingMarkWriteBE, TestSize.Level1) +{ + TS_LOGI("test4-8"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "system-1298 ( 1298) [001] ...1 174330.287420: tracing_mark_write: B|1298|Choreographer#doFrame\n \ + system - 1298(1298)[001]... 1 174330.287622 : tracing_mark_write : E | 1298\n" // E | 1298 wrong format + }); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + EXPECT_EQ(bytraceParser.ParsedTraceInvalidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TracingMarkWriteSF, TestSize.Level1) +{ + TS_LOGI("test4-9"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: S|1298|animator:\ + translateX|18888109\n system-1298(1298)[001]... 1 174330.287514 : tracing_mark_write : \ + F | 1298 | animator : translateX | 18888109\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + EXPECT_EQ(bytraceParser.ParsedTraceInvalidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TracingMarkWriteErrorPoint, TestSize.Level1) +{ + TS_LOGI("test4-10"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: G|1298|animator: \ + translateX|18888109\n system-1298(1298)[001]... 1 174330.287514 : tracing_mark_write : \ + F | 1298 | animator : translateX | 18888109\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + EXPECT_EQ(bytraceParser.ParsedTraceInvalidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, CpuIdle, TestSize.Level1) +{ + TS_LOGI("test4-14"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"-0 (-----) [003] d..2 174330.280761: cpu_idle: state=2 cpu_id=3\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, IrqHandlerEntry, TestSize.Level1) +{ + TS_LOGI("test4-15"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "ACCS0-2716 ( 2519) [000] d.h1 174330.280362: irq_handler_entry: irq=19 name=408000.qcom,cpu-bwmon\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, IrqHandlerExit, TestSize.Level1) +{ + TS_LOGI("test4-16"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "ACCS0-2716 ( 2519) [000] d.h1 174330.280382: irq_handler_exit: irq=19 ret=handled\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, SchedWaking, TestSize.Level1) +{ + TS_LOGI("test4-17"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"ACCS0-2716 ( 2519) [000] d..5 174330.280567: sched_waking: \ + comm=Binder:924_6 pid=1332 prio=120 target_cpu=000\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, SchedWakeup, TestSize.Level1) +{ + TS_LOGI("test4-18"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"ACCS0-2716 ( 2519) [000] d..6 174330.280575: sched_wakeup: \ + comm=Binder:924_6 pid=1332 prio=120 target_cpu=000\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TraceEventClockSync, TestSize.Level1) +{ + TS_LOGI("test4-19"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"athread-12728 (12728) [003] ...1 174330.280300: tracing_mark_write: \ + trace_event_clock_sync:parent_ts=23139.998047\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TracingMarkWriteErrorPoint2, TestSize.Level1) +{ + TS_LOGI("test4-23"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"system-1298 ( 1298) [001] ...1 174330.287478: tracing_mark_write: \ + G|1298|animator:translateX|18888109 system - 1298(1298)[001]... 1 174330.287514 : \ + tracing_mark_write : F | 1298 | animator : translateX | 18888109 \n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, SchedSwitch, TestSize.Level1) +{ + TS_LOGI("test4-27"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "ACCS0-2716 ( 2519) [000] d..3 174330.289220: sched_switch: prev_comm=ACCS0 prev_pid=2716 prev_prio=120 \ + prev_state=R+ ==> next_comm=Binder:924_6 next_pid=1332 next_prio=120\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TaskRename, TestSize.Level1) +{ + TS_LOGI("test4-28"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"<...>-2093 (-----) [001] ...2 174332.792290: task_rename: pid=12729 oldcomm=perfd \ + newcomm=POSIX timer 249 oom_score_adj=-1000\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, TaskNewtask, TestSize.Level1) +{ + TS_LOGI("test4-29"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"<...>-2 (-----) [003] ...1 174332.825588: task_newtask: pid=12730 \ + comm=kthreadd clone_flags=800711 oom_score_adj=0\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, WorkqueueExecuteStart, TestSize.Level1) +{ + TS_LOGI("test4-30"); + std::unique_ptr buf( + new uint8_t[G_BUF_SIZE]{"<...>-12180 (-----) [001] ...1 174332.827595: workqueue_execute_start: \ + work struct 0000000000000000: function pm_runtime_work\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, WorkqueueExecuteEnd, TestSize.Level1) +{ + TS_LOGI("test4-31"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "<...>-12180 (-----) [001] ...1 174332.828056: workqueue_execute_end: work struct 0000000000000000\n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} +HWTEST_F(EventParserTest, Distribute, TestSize.Level1) +{ + TS_LOGI("test4-31"); + std::unique_ptr buf(new uint8_t[G_BUF_SIZE]{ + "system-1298 ( 1298) [001] ...1 174330.287420: tracing_mark_write: B|1298|[8b00e96b2,2,1]:C$#decodeFrame$#" + "{\"Process\":\"DecodeVideoFrame\",\"frameTimestamp\":37313484466} \ + system - 1298(1298)[001]... 1 174330.287622 : tracing_mark_write : E | 1298 \n"}); + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), G_BUF_SIZE); + bytraceParser.WaitForParserEnd(); + + EXPECT_EQ(bytraceParser.ParsedTraceValidLines(), static_cast(1)); + stream_.traceDataCache_->ExportDatabase(dbPath); + EXPECT_TRUE(access(dbPath, F_OK) == 0); +} + +HWTEST_F(EventParserTest, SchedSwitchEvent, TestSize.Level1) +{ + TS_LOGI("test4-32"); + BytraceLine bytraceLine; + static std::unordered_map args{{"prev_comm", "ACCS0"}, {"next_comm", "HeapTaskDaemon"}, + {"prev_prio", "120"}, {"next_prio", "124"}, + {"prev_pid", "2716"}, {"next_pid", "2532"}, + {"prev_state", "S"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedSwitchEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, SchedSwitchEventAbnormal, TestSize.Level1) +{ + TS_LOGI("test4-33"); + BytraceLine bytraceLine; + static std::unordered_map args{{"prev_comm", "ACCS0"}, {"next_comm", "HeapTaskDaemon"}, + {"prev_prio", ""}, {"next_prio", ""}, + {"prev_pid", ""}, {"next_pid", ""}, + {"prev_state", "S"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedSwitchEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, TaskRenameEvent, TestSize.Level1) +{ + TS_LOGI("test4-34"); + BytraceLine bytraceLine; + static std::unordered_map args{{"newcomm", "POSIX"}, {"pid", "8542"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.TaskRenameEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, TaskNewtaskEvent, TestSize.Level1) +{ + TS_LOGI("test4-35"); + BytraceLine bytraceLine; + bytraceLine.tGidStr = "12"; + static std::unordered_map args{{"comm", "POSIX"}, {"pid", "8542"}, {"clone_flags", "1"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.TaskNewtaskEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, TracingMarkWriteEvent, TestSize.Level1) +{ + TS_LOGI("test4-36"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + bytraceLine.argsStr = "vec=9 [action=RCU]"; + static std::unordered_map args{}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.TracingMarkWriteEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, SchedWakeupEvent, TestSize.Level1) +{ + TS_LOGI("test4-37"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + static std::unordered_map args{{"pid", "1200"}, {"target_cpu", "1"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedWakeupEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, SchedWakeupEventAbromal, TestSize.Level1) +{ + TS_LOGI("test4-38"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + static std::unordered_map args{{"pid", ""}, {"target_cpu", "1"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedWakeupEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, SchedWakingEvent, TestSize.Level1) +{ + TS_LOGI("test4-39"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + static std::unordered_map args{{"pid", "1200"}, {"target_cpu", "1"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedWakingEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, SchedWakingEventAbnormal, TestSize.Level1) +{ + TS_LOGI("test4-40"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1; + static std::unordered_map args{{"pid", ""}, {"target_cpu", "1"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.SchedWakingEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, CpuIdleEvent, TestSize.Level1) +{ + TS_LOGI("test4-41"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", "3"}, {"state", "4294967295"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuIdleEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, CpuIdleEventAbnormal1, TestSize.Level1) +{ + TS_LOGI("test4-42"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", ""}, {"state", "4294967295"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuIdleEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, CpuIdleEventAbnormal2, TestSize.Level1) +{ + TS_LOGI("test4-43"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", "1"}, {"state", ""}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuIdleEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, CpuFrequencyEvent, TestSize.Level1) +{ + TS_LOGI("test4-44"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", "3"}, {"state", "4294967295"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuFrequencyEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, CpuFrequencyEventAbnormal1, TestSize.Level1) +{ + TS_LOGI("test4-45"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", ""}, {"state", "4294967295"}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuFrequencyEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, CpuFrequencyEventAbnormal2, TestSize.Level1) +{ + TS_LOGI("test4-46"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.eventName = "POSIX"; + static std::unordered_map args{{"cpu_id", "3"}, {"state", ""}}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CpuFrequencyEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, WorkqueueExecuteStartEvent, TestSize.Level1) +{ + TS_LOGI("test4-47"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1355; + bytraceLine.argsStr = "vec=9 [action=RCU]"; + static std::unordered_map args{}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.WorkqueueExecuteStartEvent(args, bytraceLine); + + EXPECT_EQ(result, true); +} + +HWTEST_F(EventParserTest, WorkqueueExecuteEndEvent, TestSize.Level1) +{ + TS_LOGI("test4-48"); + BytraceLine bytraceLine; + bytraceLine.ts = 1616439852302; + bytraceLine.pid = 1355; + static std::unordered_map args{}; + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.WorkqueueExecuteEndEvent(args, bytraceLine); + + EXPECT_EQ(result, false); +} + +HWTEST_F(EventParserTest, CheckTracePoint, TestSize.Level1) +{ + TS_LOGI("test4-49"); + std::string str("B|924|FullSuspendCheck"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == SUCCESS); +} + +HWTEST_F(EventParserTest, CheckTracePointAbnormal1, TestSize.Level1) +{ + TS_LOGI("test4-50"); + std::string str(""); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, CheckTracePointAbnormal2, TestSize.Level1) +{ + TS_LOGI("test4-51"); + std::string str("trace_event_clock_sync"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, CheckTracePointAbnormal3, TestSize.Level1) +{ + TS_LOGI("test4-52"); + std::string str("BECSF|924|FullSuspendCheck"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, CheckTracePointAbnormal4, TestSize.Level1) +{ + TS_LOGI("test4-53"); + std::string str("X"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, CheckTracePointAbnormal5, TestSize.Level1) +{ + TS_LOGI("test4-54"); + std::string str("B&924|FullSuspendCheck"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.CheckTracePoint(str); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, GetTracePoint, TestSize.Level1) +{ + TS_LOGI("test4-55"); + TracePoint point; + std::string str("B|924|SuspendThreadByThreadId suspended Binder:924_8 id=39"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.GetTracePoint(str, point); + + EXPECT_TRUE(result == SUCCESS); +} + +HWTEST_F(EventParserTest, GetTracePointAbnormal1, TestSize.Level1) +{ + TS_LOGI("test4-56"); + TracePoint point; + std::string str(""); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.GetTracePoint(str, point); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, GetTracePointAbnormal2, TestSize.Level1) +{ + TS_LOGI("test4-57"); + TracePoint point; + std::string str("X|924|SuspendThreadByThreadId suspended Binder:924_8 id=39"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.GetTracePoint(str, point); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, GetThreadGroupId, TestSize.Level1) +{ + TS_LOGI("test4-58"); + size_t length{0}; + std::string str("E|924"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.GetThreadGroupId(str, length); + + EXPECT_TRUE(result == 924); +} + +HWTEST_F(EventParserTest, GetThreadGroupIdAbnormal, TestSize.Level1) +{ + TS_LOGI("test4-59"); + size_t length{0}; + std::string str("E|abc"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.GetThreadGroupId(str, length); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, HandlerB, TestSize.Level1) +{ + TS_LOGI("test4-60"); + size_t length{3}; + TracePoint outPoint; + std::string str("B|924|HIDL::ISensors::batch::client"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.HandlerB(str, outPoint, length); + + EXPECT_TRUE(result == SUCCESS); +} + +HWTEST_F(EventParserTest, HandlerBAbnormal, TestSize.Level1) +{ + TS_LOGI("test4-61"); + size_t length{3}; + TracePoint outPoint; + std::string str("B|924|"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.HandlerB(str, outPoint, length); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, HandlerCsf, TestSize.Level1) +{ + TS_LOGI("test4-62"); + size_t length{4}; + TracePoint outPoint; + std::string str("C|2519|Heap size (KB)|2363"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.HandlerCSF(str, outPoint, length); + + EXPECT_TRUE(result == SUCCESS); +} + +HWTEST_F(EventParserTest, HandlerCsfAbnormal1, TestSize.Level1) +{ + TS_LOGI("test4-63"); + size_t length{4}; + TracePoint outPoint; + std::string str(""); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.HandlerCSF(str, outPoint, length); + + EXPECT_TRUE(result == ERROR); +} + +HWTEST_F(EventParserTest, HandlerCsfAbnormal2, TestSize.Level1) +{ + TS_LOGI("test4-64"); + size_t length{4}; + TracePoint outPoint; + std::string str("C|2519|Heap size (KB)|"); + BytraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + int result = eventParser.HandlerCSF(str, outPoint, length); + + EXPECT_TRUE(result == ERROR); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/filter_filter_test.cpp b/trace_analyzer/test/unittest/filter_filter_test.cpp new file mode 100755 index 000000000..1f6af9c1c --- /dev/null +++ b/trace_analyzer/test/unittest/filter_filter_test.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "filter_filter.h" +#include "trace_data_cache.h" +#include "trace_streamer_filters.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class FilterFilterTest : public ::testing::Test { +public: + void SetUp() + { + streamFilters_.filterFilter_ = std::make_unique(&traceDataCache_, &streamFilters_); + } + + void TearDown() {} + +public: + TraceStreamerFilters streamFilters_; + TraceDataCache traceDataCache_; +}; + +HWTEST_F(FilterFilterTest, AddCpuCounterFilter, TestSize.Level1) +{ + TS_LOGI("test5-1"); + uint32_t filterId = streamFilters_.filterFilter_->AddFilter("cpu_counter_filter", "cpu1", 1); + EXPECT_EQ(filterId, static_cast(0)); + + filterId = streamFilters_.filterFilter_->AddFilter("cpu_counter_filter", "cpu2", 2); + EXPECT_EQ(filterId, static_cast(1)); + + Filter* filterTable = traceDataCache_.GetFilterData(); + EXPECT_EQ(filterTable->Size(), static_cast(2)); +} + +HWTEST_F(FilterFilterTest, AddThreadFilter, TestSize.Level1) +{ + TS_LOGI("test5-2"); + uint32_t threadFilterId = streamFilters_.filterFilter_->AddFilter("thread_counter_filter", "threadCount1", 1); + EXPECT_EQ(threadFilterId, static_cast(0)); + + threadFilterId = streamFilters_.filterFilter_->AddFilter("thread_counter_filter", "threadCount2", 2); + EXPECT_EQ(threadFilterId, static_cast(1)); + + Filter* filterTable = traceDataCache_.GetFilterData(); + EXPECT_EQ(filterTable->Size(), static_cast(2)); + + threadFilterId = streamFilters_.filterFilter_->AddFilter("thread_filter", "thread1", 1); + EXPECT_EQ(threadFilterId, static_cast(2)); + + threadFilterId = streamFilters_.filterFilter_->AddFilter("thread_filter", "thread2", 2); + EXPECT_EQ(threadFilterId, static_cast(3)); + + EXPECT_EQ(filterTable->Size(), static_cast(4)); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/htrace_event_parser_test.cpp b/trace_analyzer/test/unittest/htrace_event_parser_test.cpp new file mode 100644 index 000000000..071bad2c8 --- /dev/null +++ b/trace_analyzer/test/unittest/htrace_event_parser_test.cpp @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include "htrace_cpu_detail_parser.h" +#include "parser/common_types.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +const uint64_t TIMESTAMP = 1616439852302; +const std::string THREAD_NAME_01 = "ACCS0"; +const std::string THREAD_NAME_02 = "HeapTaskDaemon"; +const uint32_t PRIORITY_01 = 120; +const uint32_t PRIORITY_02 = 124; +const uint32_t PID_01 = 2716; +const uint32_t PID_02 = 2532; +class HtraceEventParserTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} +public: + SysTuning::TraceStreamer::TraceStreamerSelector stream_; +}; + +// schedSwitch event +HWTEST_F(HtraceEventParserTest, ParseDataItem01, TestSize.Level1) +{ + SchedSwitchFormat* event = new SchedSwitchFormat(); + event->set_prev_prio(PRIORITY_01); + event->set_next_prio(PRIORITY_02); + event->set_prev_pid(PID_01); + event->set_next_pid(PID_02); + event->set_prev_comm(THREAD_NAME_01); + event->set_next_comm(THREAD_NAME_02); + event->set_prev_state(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->unsafe_arena_set_allocated_sched_switch_format(event); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + EXPECT_TRUE(1); + auto realTimeStamp = stream_.traceDataCache_->GetConstSchedSliceData().TimeStamData()[0]; + EXPECT_TRUE(TIMESTAMP == realTimeStamp); + auto realCpu = stream_.traceDataCache_->GetConstSchedSliceData().CpusData()[0]; + EXPECT_TRUE(0 == realCpu); +} + +// FtraceCpuDetailMsg has no ftrace event +HWTEST_F(HtraceEventParserTest, ParseDataItem02, TestSize.Level1) +{ + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_OTHER, STAT_EVENT_DATA_LOST); + EXPECT_TRUE(1 == eventCount); +} + +HWTEST_F(HtraceEventParserTest, ParseDataItem03, TestSize.Level1) +{ + SchedSwitchFormat* event = new SchedSwitchFormat(); + event->set_prev_prio(PRIORITY_01); + event->set_next_prio(PRIORITY_02); + event->set_prev_pid(PID_01); + event->set_next_pid(PID_02); + event->set_prev_comm(THREAD_NAME_01); + event->set_next_comm(THREAD_NAME_02); + event->set_prev_state(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(1); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_sched_switch_format(event); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_OTHER, STAT_EVENT_DATA_LOST); + EXPECT_TRUE(1 == eventCount); +} + +// task_rename event +HWTEST_F(HtraceEventParserTest, ParseDataItem04, TestSize.Level1) +{ + TaskRenameFormat* taskRenameEvent = new TaskRenameFormat(); + taskRenameEvent->set_pid(PID_01); + taskRenameEvent->set_oldcomm(THREAD_NAME_01); + taskRenameEvent->set_newcomm(THREAD_NAME_02); + taskRenameEvent->set_oom_score_adj(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_task_rename_format(taskRenameEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_TASK_RENAME, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// task_newtask event +HWTEST_F(HtraceEventParserTest, ParseDataItem05, TestSize.Level1) +{ + TaskNewtaskFormat* newTaskEvent = new TaskNewtaskFormat(); + newTaskEvent->set_pid(PID_01); + newTaskEvent->set_comm(THREAD_NAME_01); + newTaskEvent->set_clone_flags(0); + newTaskEvent->set_oom_score_adj(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_task_newtask_format(newTaskEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_TASK_NEWTASK, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// sched_wakeup event +HWTEST_F(HtraceEventParserTest, ParseDataItem06, TestSize.Level1) +{ + SchedWakeupFormat* wakeupEvent = new SchedWakeupFormat(); + wakeupEvent->set_comm(THREAD_NAME_01); + wakeupEvent->set_pid(PRIORITY_02); + wakeupEvent->set_prio(PID_01); + wakeupEvent->set_target_cpu(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_sched_wakeup_format(wakeupEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// sched_waking event +HWTEST_F(HtraceEventParserTest, ParseDataItem07, TestSize.Level1) +{ + SchedWakingFormat* wakingEvent = new SchedWakingFormat(); + wakingEvent->set_comm(THREAD_NAME_01); + wakingEvent->set_pid(PRIORITY_02); + wakingEvent->set_prio(PID_01); + wakingEvent->set_target_cpu(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_sched_waking_format(wakingEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +HWTEST_F(HtraceEventParserTest, ParseDataItem08, TestSize.Level1) +{ + CpuIdleFormat* cpuIdleEvent = new CpuIdleFormat(); + cpuIdleEvent->set_cpu_id(0); + cpuIdleEvent->set_state(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_cpu_idle_format(cpuIdleEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_CPU_IDLE, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// CpuFrequency event +HWTEST_F(HtraceEventParserTest, ParseDataItem09, TestSize.Level1) +{ + CpuFrequencyFormat* cpuFrequencyEvent = new CpuFrequencyFormat(); + cpuFrequencyEvent->set_cpu_id(0); + cpuFrequencyEvent->set_state(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(2); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_cpu_frequency_format(cpuFrequencyEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_CPU_FREQUENCY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// WorkqueueExecuteStart event +HWTEST_F(HtraceEventParserTest, ParseDataItem10, TestSize.Level1) +{ + WorkqueueExecuteStartFormat* workqueueExecuteStartEvent = new WorkqueueExecuteStartFormat(); + workqueueExecuteStartEvent->set_work(0); + workqueueExecuteStartEvent->set_function(1); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_workqueue_execute_start_format(workqueueExecuteStartEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_WORKQUEUE_EXECUTE_START, + STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +// WorkqueueExecuteEnd event +HWTEST_F(HtraceEventParserTest, ParseDataItem11, TestSize.Level1) +{ + WorkqueueExecuteEndFormat* workqueueExecuteEndEvent = new WorkqueueExecuteEndFormat(); + workqueueExecuteEndEvent->set_work(0); + + FtraceCpuDetailMsg ftraceCpuDetail; + ftraceCpuDetail.set_cpu(0); + ftraceCpuDetail.set_overwrite(0); + auto ftraceEvent = ftraceCpuDetail.add_event(); + + ftraceEvent->set_timestamp(TIMESTAMP); + ftraceEvent->set_tgid(1); + ftraceEvent->set_comm(THREAD_NAME_02); + ftraceEvent->set_allocated_workqueue_execute_end_format(workqueueExecuteEndEvent); + + HtraceEventParser eventParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + eventParser.ParseDataItem(&ftraceCpuDetail, TS_CLOCK_BOOTTIME); + auto eventCount = + stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/htrace_mem_parser_test.cpp b/trace_analyzer/test/unittest/htrace_mem_parser_test.cpp new file mode 100644 index 000000000..5c2f6992e --- /dev/null +++ b/trace_analyzer/test/unittest/htrace_mem_parser_test.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include "htrace_mem_parser.h" +#include "parser/common_types.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +class HtraceMemParserTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} + +public: + SysTuning::TraceStreamer::TraceStreamerSelector stream_; + const char* dbPath_ = "out.db"; +}; + +HWTEST_F(HtraceMemParserTest, ParseMemParse, TestSize.Level1) +{ + TS_LOGI("test7-1"); + HtraceMemParser* memParser = new HtraceMemParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + + MemoryData tracePacket; + ProcessMemoryInfo* memoryInfo = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo != nullptr); + int size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 1); + uint64_t timeStamp = 1616439852302; + BuiltinClocks clock = TS_CLOCK_REALTIME; + + memParser->Parse(tracePacket, timeStamp, clock); + stream_.traceDataCache_->ExportDatabase(dbPath_); + + EXPECT_TRUE(access(dbPath_, F_OK) == 0); + tracePacket.clear_processesinfo(); + delete memParser; + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_MEMORY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); +} + +HWTEST_F(HtraceMemParserTest, ParseMemParseTestMeasureDataSize, TestSize.Level1) +{ + TS_LOGI("test7-1"); + HtraceMemParser* memParser = new HtraceMemParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + + MemoryData tracePacket; + ProcessMemoryInfo* memoryInfo = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo != nullptr); + int size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 1); + uint64_t timeStamp = 1616439852302; + BuiltinClocks clock = TS_CLOCK_REALTIME; + memoryInfo->set_pid(12); + memoryInfo->set_name("Process1"); + memoryInfo->set_vm_size_kb(1024); + memoryInfo->set_vm_rss_kb(512); + memoryInfo->set_rss_anon_kb(128); + memoryInfo->set_rss_file_kb(128); + + memParser->Parse(tracePacket, timeStamp, clock); + stream_.traceDataCache_->ExportDatabase(dbPath_); + + EXPECT_TRUE(access(dbPath_, F_OK) == 0); + tracePacket.clear_processesinfo(); + delete memParser; + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_MEMORY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(1 == eventCount); + + EXPECT_TRUE(stream_.traceDataCache_->GetConstProcessData(1).pid_ == 12); +} + +HWTEST_F(HtraceMemParserTest, ParseMemParseTestMeasureDataSize2, TestSize.Level1) +{ + TS_LOGI("test7-1"); + HtraceMemParser* memParser = new HtraceMemParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + + MemoryData tracePacket; + ProcessMemoryInfo* memoryInfo = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo != nullptr); + int size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 1); + uint64_t timeStamp = 1616439852302; + BuiltinClocks clock = TS_CLOCK_REALTIME; + memoryInfo->set_pid(12); + memoryInfo->set_name("Process1"); + memoryInfo->set_vm_size_kb(1024); + memoryInfo->set_vm_rss_kb(512); + memoryInfo->set_rss_anon_kb(128); + memoryInfo->set_rss_file_kb(128); + + ProcessMemoryInfo* memoryInfo2 = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo2 != nullptr); + size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 2); + timeStamp = 1616439852402; + memoryInfo2->set_pid(13); + memoryInfo2->set_name("Process2"); + memoryInfo2->set_vm_size_kb(1024); + memoryInfo2->set_vm_rss_kb(512); + memoryInfo2->set_rss_anon_kb(128); + memoryInfo2->set_rss_file_kb(128); + + memParser->Parse(tracePacket, timeStamp, clock); + stream_.traceDataCache_->ExportDatabase(dbPath_); + + EXPECT_TRUE(access(dbPath_, F_OK) == 0); + tracePacket.clear_processesinfo(); + delete memParser; + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_MEMORY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(2 == eventCount); + + EXPECT_TRUE(stream_.traceDataCache_->GetConstProcessData(1).pid_ == 12); + EXPECT_TRUE(stream_.traceDataCache_->GetConstProcessData(2).pid_ == 13); +} + +HWTEST_F(HtraceMemParserTest, ParseMemParseTestMeasureDataSize3, TestSize.Level1) +{ + TS_LOGI("test7-1"); + HtraceMemParser* memParser = new HtraceMemParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + + MemoryData tracePacket; + ProcessMemoryInfo* memoryInfo = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo != nullptr); + int size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 1); + uint64_t timeStamp = 1616439852302; + BuiltinClocks clock = TS_CLOCK_REALTIME; + + ProcessMemoryInfo* memoryInfo2 = tracePacket.add_processesinfo(); + EXPECT_TRUE(memoryInfo2 != nullptr); + size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 2); + + memParser->Parse(tracePacket, timeStamp, clock); + stream_.traceDataCache_->ExportDatabase(dbPath_); + + EXPECT_TRUE(access(dbPath_, F_OK) == 0); + tracePacket.clear_processesinfo(); + delete memParser; + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_MEMORY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(2 == eventCount); + + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == MEM_MAX * 2); +} + +HWTEST_F(HtraceMemParserTest, ParseMemParseInvalidData, TestSize.Level1) +{ + TS_LOGI("test7-1"); + HtraceMemParser* memParser = new HtraceMemParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + + MemoryData tracePacket; + int size = tracePacket.processesinfo_size(); + EXPECT_TRUE(size == 0); + uint64_t timeStamp = 1616439852302; + BuiltinClocks clock = TS_CLOCK_REALTIME; + + memParser->Parse(tracePacket, timeStamp, clock); + delete memParser; + + auto eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_MEMORY, STAT_EVENT_RECEIVED); + EXPECT_TRUE(0 == eventCount); +} \ No newline at end of file diff --git a/trace_analyzer/test/unittest/measure_filter_test.cpp b/trace_analyzer/test/unittest/measure_filter_test.cpp new file mode 100755 index 000000000..fdf634047 --- /dev/null +++ b/trace_analyzer/test/unittest/measure_filter_test.cpp @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "filter_filter.h" +#include "measure_filter.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +constexpr int CPU_ID_0 = 0; +constexpr int CPU_ID_1 = 1; +constexpr std::string_view CPU_TYPE_0 = "cpu_idle"; +constexpr std::string_view CPU_TYPE_1 = "cpu_frequency"; +constexpr int INTERNAL_THREAD_ID_0 = 1; +constexpr int INTERNAL_THREAD_ID_1 = 2; +constexpr int INTERNAL_PROCESS_ID_0 = 1; +constexpr int INTERNAL_PROCESS_ID_1 = 2; +constexpr std::string_view TASK_NAME_0 = "softbus_server"; +constexpr std::string_view TASK_NAME_1 = "hiprofilerd"; + +class MeasureFilterTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} + +public: + SysTuning::TraceStreamer::TraceStreamerSelector stream_; +}; + +HWTEST_F(MeasureFilterTest, ThreadMeasureFilter, TestSize.Level1) +{ + TS_LOGI("test8-1"); + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = + stream_.streamFilters_->threadMeasureFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_0, nameIndex0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->threadMeasureFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_1, nameIndex1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ThreadMeasureFilter* threadMeasureTable = stream_.traceDataCache_->GetThreadMeasureFilterData(); + EXPECT_TRUE(threadMeasureTable->Size() == 2); + EXPECT_TRUE(threadMeasureTable->FilterIdData()[0] == 0); + EXPECT_TRUE(threadMeasureTable->FilterIdData()[1] == 1); + EXPECT_TRUE(threadMeasureTable->InternalTidData()[0] == INTERNAL_THREAD_ID_0); + EXPECT_TRUE(threadMeasureTable->InternalTidData()[1] == INTERNAL_THREAD_ID_1); +} + +HWTEST_F(MeasureFilterTest, ThreadFilter, TestSize.Level1) +{ + TS_LOGI("test8-2"); + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = stream_.streamFilters_->threadFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_0, nameIndex0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->threadFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_1, nameIndex1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ThreadMeasureFilter* threadTable = stream_.traceDataCache_->GetThreadFilterData(); + EXPECT_TRUE(threadTable->Size() == 2); + EXPECT_TRUE(threadTable->FilterIdData()[0] == 0); + EXPECT_TRUE(threadTable->FilterIdData()[1] == 1); + EXPECT_TRUE(threadTable->InternalTidData()[0] == INTERNAL_THREAD_ID_0); + EXPECT_TRUE(threadTable->InternalTidData()[1] == INTERNAL_THREAD_ID_1); +} + +HWTEST_F(MeasureFilterTest, CpuFilter, TestSize.Level1) +{ + TS_LOGI("test8-3"); + auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(CPU_TYPE_0); + uint32_t filterId = stream_.streamFilters_->cpuMeasureFilter_->GetOrCreateFilterId(CPU_ID_0, nameIndex_0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(CPU_TYPE_1); + filterId = stream_.streamFilters_->cpuMeasureFilter_->GetOrCreateFilterId(CPU_ID_1, nameIndex_1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + CpuMeasureFilter* cpuMeasureTable = stream_.traceDataCache_->GetCpuMeasuresData(); + EXPECT_TRUE(cpuMeasureTable->Size() == 2); + EXPECT_TRUE(cpuMeasureTable->IdsData()[0] == 0); + EXPECT_TRUE(cpuMeasureTable->IdsData()[1] == 1); + EXPECT_TRUE(cpuMeasureTable->CpuData()[0] == CPU_ID_0); + EXPECT_TRUE(cpuMeasureTable->CpuData()[1] == CPU_ID_1); +} + +HWTEST_F(MeasureFilterTest, ProcessFilter, TestSize.Level1) +{ + TS_LOGI("test8-4"); + auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = + stream_.streamFilters_->processFilterFilter_->GetOrCreateFilterId(INTERNAL_PROCESS_ID_0, nameIndex_0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->processFilterFilter_->GetOrCreateFilterId(INTERNAL_PROCESS_ID_1, nameIndex_1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ProcessMeasureFilter* processFilterTable = stream_.traceDataCache_->GetProcessFilterData(); + EXPECT_TRUE(processFilterTable->Size() == 2); +} + +HWTEST_F(MeasureFilterTest, ClockRateFilter, TestSize.Level1) +{ + TS_LOGI("test8-5"); + auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = stream_.streamFilters_->clockRateFilter_->GetOrCreateFilterId(CPU_ID_0, nameIndex_0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->clockRateFilter_->GetOrCreateFilterId(CPU_ID_1, nameIndex_1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ClockEventData* clockEventTable = stream_.traceDataCache_->GetClockEventFilterData(); + EXPECT_TRUE(clockEventTable->Size() == 2); + EXPECT_TRUE(clockEventTable->CpusData()[0] == CPU_ID_0); + EXPECT_TRUE(clockEventTable->CpusData()[1] == CPU_ID_1); + EXPECT_TRUE(clockEventTable->NamesData()[0] == nameIndex_0); + EXPECT_TRUE(clockEventTable->NamesData()[1] == nameIndex_1); +} + +HWTEST_F(MeasureFilterTest, ClockEnableFilter, TestSize.Level1) +{ + TS_LOGI("test8-6"); + auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = stream_.streamFilters_->clockEnableFilter_->GetOrCreateFilterId(CPU_ID_0, nameIndex_0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->clockEnableFilter_->GetOrCreateFilterId(CPU_ID_1, nameIndex_1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ClockEventData* clockEventTable = stream_.traceDataCache_->GetClockEventFilterData(); + EXPECT_TRUE(clockEventTable->Size() == 2); + EXPECT_TRUE(clockEventTable->CpusData()[0] == CPU_ID_0); + EXPECT_TRUE(clockEventTable->CpusData()[1] == CPU_ID_1); + EXPECT_TRUE(clockEventTable->NamesData()[0] == nameIndex_0); + EXPECT_TRUE(clockEventTable->NamesData()[1] == nameIndex_1); +} + +HWTEST_F(MeasureFilterTest, ClockDisableFilter, TestSize.Level1) +{ + TS_LOGI("test8-7"); + auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); + uint32_t filterId = stream_.streamFilters_->clockDisableFilter_->GetOrCreateFilterId(CPU_ID_0, nameIndex_0); + EXPECT_TRUE(filterId == 0); + + auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); + filterId = stream_.streamFilters_->clockDisableFilter_->GetOrCreateFilterId(CPU_ID_1, nameIndex_1); + EXPECT_TRUE(filterId == 1); + + Filter* filterTable = stream_.traceDataCache_->GetFilterData(); + EXPECT_TRUE(filterTable->Size() == 2); + + ClockEventData* clockEventTable = stream_.traceDataCache_->GetClockEventFilterData(); + EXPECT_TRUE(clockEventTable->Size() == 2); + EXPECT_TRUE(clockEventTable->CpusData()[0] == CPU_ID_0); + EXPECT_TRUE(clockEventTable->CpusData()[1] == CPU_ID_1); + EXPECT_TRUE(clockEventTable->NamesData()[0] == nameIndex_0); + EXPECT_TRUE(clockEventTable->NamesData()[1] == nameIndex_1); +} + +HWTEST_F(MeasureFilterTest, MeasureFilterTest, TestSize.Level1) +{ + TS_LOGI("test8-7"); + uint64_t itid = 1; + const std::string_view MEASURE_ITEM_NAME = "mem_rss"; + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME); + auto threadMeasureFilter = stream_.streamFilters_->processMeasureFilter_.get(); + threadMeasureFilter->AppendNewMeasureData(itid, nameIndex0, 168758682476000, 1200); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == 1); +} + +HWTEST_F(MeasureFilterTest, MeasureFilterTest2, TestSize.Level1) +{ + TS_LOGI("test8-7"); + uint64_t itid = 1; + auto threadMeasureFilter = stream_.streamFilters_->processMeasureFilter_.get(); + const std::string_view MEASURE_ITEM_NAME = "mem_rss"; + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME); + threadMeasureFilter->AppendNewMeasureData(itid, nameIndex0, 168758682476000, 1200); + const std::string_view MEASURE_ITEM_NAME2 = "mem_vm"; + auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME2); + threadMeasureFilter->AppendNewMeasureData(itid, nameIndex1, 168758682477000, 9200); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == 2); +} + +HWTEST_F(MeasureFilterTest, MeasureFilterTest3, TestSize.Level1) +{ + TS_LOGI("test8-7"); + uint64_t itid = 1; + uint64_t itid2 = 2; + auto threadMeasureFilter = stream_.streamFilters_->processMeasureFilter_.get(); + const std::string_view MEASURE_ITEM_NAME = "mem_rss"; + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME); + threadMeasureFilter->AppendNewMeasureData(itid, nameIndex0, 168758682476000, 1200); + const std::string_view MEASURE_ITEM_NAME2 = "mem_vm"; + auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME2); + threadMeasureFilter->AppendNewMeasureData(itid2, nameIndex1, 168758682477000, 9200); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == 2); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().ValuesData()[0] == 1200); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().ValuesData()[1] == 9200); +} + +HWTEST_F(MeasureFilterTest, MeasureFilterTest4, TestSize.Level1) +{ + TS_LOGI("test8-7"); + uint64_t cpuId = 1; + int64_t state = 0; + auto threadMeasureFilter = stream_.streamFilters_->clockDisableFilter_.get(); + const std::string_view MEASURE_ITEM_NAME = "perfcl_lf_mux"; + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME); + threadMeasureFilter->AppendNewMeasureData(cpuId, nameIndex0, 168758682476000, state); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == 1); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().ValuesData()[0] == state); +} + +HWTEST_F(MeasureFilterTest, MeasureFilterTest5, TestSize.Level1) +{ + TS_LOGI("test8-7"); + uint64_t cpuId = 1; + int64_t state = 1747200000; + auto threadMeasureFilter = stream_.streamFilters_->clockRateFilter_.get(); + const std::string_view MEASURE_ITEM_NAME = "perfcl_pll"; + auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(MEASURE_ITEM_NAME); + threadMeasureFilter->AppendNewMeasureData(cpuId, nameIndex0, 168758682476000, state); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().Size() == 1); + EXPECT_TRUE(stream_.traceDataCache_->GetConstMeasureData().ValuesData()[0] == state); +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_analyzer/test/unittest/parser_test.cpp b/trace_analyzer/test/unittest/parser_test.cpp new file mode 100755 index 000000000..3587d8fde --- /dev/null +++ b/trace_analyzer/test/unittest/parser_test.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include +#include + +#include "file.h" +#include "trace_streamer_selector.h" +constexpr size_t G_FILE_PERMISSION = 664; + +using namespace testing::ext; +using namespace SysTuning; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class ParserTest : public testing::Test { +protected: + static void SetUpTestCase() {} + static void TearDownTestCase() {} +}; + +HWTEST_F(ParserTest, BytraceParserTest, TestSize.Level1) +{ + TS_LOGI("test9-1"); + const char tracePath[] = "/data/resource/ut_bytrace_input_full.txt"; + const char utGoldDb[] = "/data/resource/ut_bytrace_input_full_gold.db"; + const char dbPath[] = "/data/resource/out1.db"; + constexpr size_t readSize = 1024 * 1024; + constexpr uint32_t lineLength = 256; + + if (access(tracePath, F_OK) == 0) { + std::string traceFilePath(tracePath); + std::unique_ptr ta = + std::make_unique(); + int fd(base::OpenFile(traceFilePath, O_RDONLY, G_FILE_PERMISSION)); + while (true) { + std::unique_ptr buf = std::make_unique(std::move(readSize)); + auto rsize = base::Read(fd, buf.get(), readSize); + if (rsize == 0) { + break; + } + if (rsize < 0) { + TS_LOGD("Reading trace file failed (errno: %d, %s)", errno, strerror(errno)); + break; + } + if (!ta->ParseTraceDataSegment(std::move(buf), rsize)) { + break; + }; + } + ta->WaitForParserEnd(); + close(fd); + ta->ExportDatabase(std::string(dbPath)); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + } else { + EXPECT_TRUE(false); + } + + if (access(utGoldDb, F_OK) == 0) { + FILE* file1 = nullptr; + FILE* file2 = nullptr; + char line1[lineLength]; + char line2[lineLength]; + const char command1[] = "md5sum /data/resource/ut_bytrace_input_full_gold.db"; + const char command2[] = "md5sum /data/resource/out1.db"; + file1 = popen(command1, "r"); + file2 = popen(command2, "r"); + if (file1 && file2) { + if (fgets(line1, lineLength, file1) != nullptr && + fgets(line2, lineLength, file2) != nullptr) { + std::string str1(line1); + std::string str2(line2); + str1 = str1.substr(0, str1.find_first_of(' ')); + str2 = str2.substr(0, str2.find_first_of(' ')); + EXPECT_TRUE(str1.compare(str2) == 0); + } + } + } else { + EXPECT_TRUE(false); + } + + if (access(dbPath, F_OK) == 0) { + remove(dbPath); + } +} + +HWTEST_F(ParserTest, HtraceParserTest, TestSize.Level1) +{ + TS_LOGI("test9-2"); + const char tracePath[] = "/data/resource/htrace.bin"; + const char utGoldDb[] = "/data/resource/htrace_gold.db"; + const char dbPath[] = "/data/resource/out2.db"; + constexpr size_t readSize = 1024; + constexpr uint32_t lineLength = 256; + + if (access(tracePath, F_OK) == 0) { + std::string traceFilePath(tracePath); + std::unique_ptr ta = + std::make_unique(); + int fd(base::OpenFile(traceFilePath, O_RDONLY, G_FILE_PERMISSION)); + while (true) { + std::unique_ptr buf = std::make_unique(std::move(readSize)); + auto rsize = base::Read(fd, buf.get(), readSize); + + if (rsize == 0) { + break; + } + if (rsize < 0) { + TS_LOGD("Reading trace file over (errno: %d, %s)", errno, strerror(errno)); + break; + } + if (!ta->ParseTraceDataSegment(std::move(buf), rsize)) { + break; + }; + } + ta->WaitForParserEnd(); + close(fd); + ta->ExportDatabase(std::string(dbPath)); + EXPECT_TRUE(access(dbPath, F_OK) == 0); + } else { + EXPECT_TRUE(false); + } + + if (access(utGoldDb, F_OK) == 0) { + FILE* file1 = nullptr; + FILE* file2 = nullptr; + char line1[lineLength]; + char line2[lineLength]; + const char command1[] = "md5sum /data/resource/htrace_gold.db"; + const char command2[] = "md5sum /data/resource/out2.db"; + file1 = popen(command1, "r"); + file2 = popen(command2, "r"); + if (file1 && file2) { + if (fgets(line1, lineLength, file1) != nullptr && + fgets(line2, lineLength, file2) != nullptr) { + std::string str1(line1); + std::string str2(line2); + str1 = str1.substr(0, str1.find_first_of(' ')); + str2 = str2.substr(0, str2.find_first_of(' ')); + EXPECT_TRUE(str1.compare(str2) == 0); + } + } + } else { + EXPECT_TRUE(false); + } + + if (access(dbPath, F_OK) == 0) { + remove(dbPath); + } +} +} +} diff --git a/trace_analyzer/test/unittest/process_filter_test.cpp b/trace_analyzer/test/unittest/process_filter_test.cpp new file mode 100755 index 000000000..0d47e5f9e --- /dev/null +++ b/trace_analyzer/test/unittest/process_filter_test.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "process_filter.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class ProcessFilterTest : public ::testing::Test { +public: + void SetUp() + { + streamFilters_.processFilter_ = std::make_unique(&traceDataCache_, &streamFilters_); + } + + void TearDown() {} + +public: + TraceStreamerFilters streamFilters_; + TraceDataCache traceDataCache_; +}; + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThread, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 = streamFilters_.processFilter_->UpdateOrCreateThread(168758662877000, 2716); + EXPECT_TRUE(iTid0 == 1); + + uint32_t iTid1 = streamFilters_.processFilter_->UpdateOrCreateThread(2716, 2519); + EXPECT_TRUE(iTid1 == 2); + + Thread* thread = traceDataCache_.GetThreadData(iTid0); + EXPECT_TRUE(thread->tid_ == 2716); + EXPECT_TRUE(thread->startT_ == 168758662877000); + + thread = traceDataCache_.GetThreadData(iTid1); + EXPECT_TRUE(thread->tid_ == 2519); + EXPECT_TRUE(thread->internalPid_ == 0); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateProcessWithName, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iPid0 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8629, "RenderThread"); + EXPECT_TRUE(iPid0 == 1); + + uint32_t iPid1 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8709, "RenderThread"); + EXPECT_TRUE(iPid1 == 2); + + Process* process = traceDataCache_.GetProcessData(iPid0); + EXPECT_TRUE(process->pid_ == 8629); + + process = traceDataCache_.GetProcessData(iPid1); + EXPECT_TRUE(process->pid_ == 8709); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateProcessWithName2, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iPid0 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8629, "RenderThread"); + EXPECT_TRUE(iPid0 == 1); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateProcessWithName3, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iPid0 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8629, "RenderThread"); + EXPECT_TRUE(iPid0 == 1); + + uint32_t iPid1 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8709, "RenderThread"); + EXPECT_TRUE(iPid1 == 2); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateProcessWithName4, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iPid0 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8629, "RenderThread"); + EXPECT_TRUE(iPid0 == 1); + + Process* process = traceDataCache_.GetProcessData(iPid0); + EXPECT_TRUE(process->pid_ == 8629); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateProcessWithName5, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iPid0 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8629, "RenderThread"); + EXPECT_TRUE(iPid0 == 1); + + uint32_t iPid1 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(8709, "RenderThread"); + EXPECT_TRUE(iPid1 == 2); + + uint32_t iPid2 = streamFilters_.processFilter_->UpdateOrCreateProcessWithName(87091, "RenderThread"); + EXPECT_TRUE(iPid2 == 3); + + Process* process = traceDataCache_.GetProcessData(iPid0); + EXPECT_TRUE(process->pid_ == 8629); + + process = traceDataCache_.GetProcessData(iPid1); + EXPECT_TRUE(process->pid_ == 8709); + + process = traceDataCache_.GetProcessData(iPid2); + EXPECT_TRUE(process->pid_ == 87091); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithName, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 =streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758662957020, 123, "RenderThread"); + EXPECT_TRUE(iTid0 == 1); + uint32_t iTid1 = streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758663957020, 2519, + "RenderThread2"); + EXPECT_TRUE(iTid1 == 2); + + Thread* thread = traceDataCache_.GetThreadData(iTid0); + EXPECT_TRUE(thread->tid_ == 123); + EXPECT_TRUE(thread->startT_ == 168758662957020); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread")); + + thread = traceDataCache_.GetThreadData(iTid1); + EXPECT_TRUE(thread->tid_ == 2519); + EXPECT_TRUE(thread->internalPid_ == 0); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread2")); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithName2, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 =streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758662957020, 123, "RenderThread"); + EXPECT_TRUE(iTid0 == 1); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithName3, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 =streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758662957020, 123, "RenderThread2"); + EXPECT_TRUE(iTid0 == 1); + Thread* thread = traceDataCache_.GetThreadData(iTid0); + EXPECT_TRUE(thread->tid_ == 123); + EXPECT_TRUE(thread->startT_ == 168758662957020); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread2")); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithName4, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 =streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758662957020, 123, "RenderThread"); + EXPECT_TRUE(iTid0 == 1); + uint32_t iTid1 = streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758663957020, 2519, + "RenderThread2"); + EXPECT_TRUE(iTid1 == 2); + auto thread = traceDataCache_.GetThreadData(iTid1); + EXPECT_TRUE(thread->tid_ == 2519); + EXPECT_TRUE(thread->internalPid_ == 0); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread2")); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithName5, TestSize.Level1) +{ + TS_LOGI("test10-1"); + uint32_t iTid0 =streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758662957020, 123, "RenderThread"); + EXPECT_TRUE(iTid0 == 1); + uint32_t iTid1 = streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758663957020, 2519, + "RenderThread2"); + EXPECT_TRUE(iTid1 == 2); + uint32_t iTid2 = streamFilters_.processFilter_->UpdateOrCreateThreadWithName(168758663957020, 25191, + "RenderThread3"); + EXPECT_TRUE(iTid2 == 3); + auto thread = traceDataCache_.GetThreadData(iTid2); + EXPECT_TRUE(thread->tid_ == 25191); + EXPECT_TRUE(thread->internalPid_ == 0); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread3")); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithPidAndName, TestSize.Level1) +{ + TS_LOGI("test10-1"); + streamFilters_.processFilter_->UpdateOrCreateThreadWithPidAndName(869, 123, "RenderThread"); + auto itid = streamFilters_.processFilter_->GetInternalTid(869); + EXPECT_TRUE(itid != INVALID_ID); + + Thread* thread = traceDataCache_.GetThreadData(itid); + EXPECT_TRUE(thread->nameIndex_ == traceDataCache_.GetDataIndex("RenderThread")); +} +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithPidAndName2, TestSize.Level1) +{ + TS_LOGI("test10-1"); + streamFilters_.processFilter_->UpdateOrCreateThreadWithPidAndName(869, 123, "RenderThread"); + auto itid = streamFilters_.processFilter_->GetInternalTid(969); + EXPECT_TRUE(itid == INVALID_ID); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithPidAndName3, TestSize.Level1) +{ + TS_LOGI("test10-1"); + streamFilters_.processFilter_->UpdateOrCreateThreadWithPidAndName(869, 123, "RenderThread"); + auto itid = streamFilters_.processFilter_->GetInternalPid(123); + EXPECT_TRUE(itid != INVALID_ID); +} + +HWTEST_F(ProcessFilterTest, UpdateOrCreateThreadWithPidAndName4, TestSize.Level1) +{ + TS_LOGI("test10-1"); + streamFilters_.processFilter_->UpdateOrCreateThreadWithPidAndName(869, 123, "RenderThread"); + auto itid = streamFilters_.processFilter_->GetInternalPid(124); + EXPECT_TRUE(itid == INVALID_ID); +} +} +} diff --git a/trace_analyzer/test/unittest/slice_filter_test.cpp b/trace_analyzer/test/unittest/slice_filter_test.cpp new file mode 100755 index 000000000..844dce97b --- /dev/null +++ b/trace_analyzer/test/unittest/slice_filter_test.cpp @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "filter_filter.h" +#include "measure_filter.h" +#include "process_filter.h" +#include "slice_filter.h" +#include "trace_streamer_selector.h" + +using namespace testing::ext; +using namespace SysTuning::TraceStreamer; +namespace SysTuning { +namespace TraceStreamer { +class SliceFilterTest : public ::testing::Test { +public: + void SetUp() + { + stream_.InitFilter(); + } + + void TearDown() {} +public: + TraceStreamerSelector stream_; +}; + +HWTEST_F(SliceFilterTest, SliceTest1, TestSize.Level1) +{ + TS_LOGI("test1"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758662957000, 2532, 2519, 0, splitStrIndex); + stream_.streamFilters_->sliceFilter_->EndSlice(168758663011000, 2532, 2519); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 1); + EXPECT_TRUE(slices->DursData()[0] == 168758663011000 - 168758662957000); +} + +HWTEST_F(SliceFilterTest, SliceTest2, TestSize.Level1) +{ + TS_LOGI("test2"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758670506000, 1298, 1298, 0, splitStrIndex); + splitStrIndex = stream_.traceDataCache_->GetDataIndex("call_function_two"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758670523000, 1298, 1298, 0, splitStrIndex); + stream_.streamFilters_->sliceFilter_->EndSlice(168758670720000, 1298, 1298); + stream_.streamFilters_->sliceFilter_->EndSlice(168758670732000, 1298, 1298); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 2); + EXPECT_TRUE(slices->DursData()[0] == 168758670732000 - 168758670506000); + EXPECT_TRUE(slices->DursData()[1] == 168758670720000 - 168758670523000); + EXPECT_TRUE(slices->Depths()[1] == 1); +} + +HWTEST_F(SliceFilterTest, SliceTest3, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663028000, 2533, 2529, 0, splitStrIndex); + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_two"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758679303000, 2532, 2519, 0, splitStrIndex); // slice 2 + // end thread_one_call_function_two + stream_.streamFilters_->sliceFilter_->EndSlice(168758682466000, 2532, 2519); + // end thread_one_call_function_one + stream_.streamFilters_->sliceFilter_->EndSlice(168758682476000, 2532, 2519); + // end thread_two_call_function_one slice 1 + stream_.streamFilters_->sliceFilter_->EndSlice(168758689323000, 2533, 2529); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 3); + EXPECT_TRUE(slices->DursData()[0] == 168758682476000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758689323000 - 168758663028000); // slice 1 + EXPECT_TRUE(slices->Depths()[1] == 0); + EXPECT_TRUE(slices->DursData()[2] == 168758682466000 - 168758679303000); // slice 2 + EXPECT_TRUE(slices->Depths()[2] == 1); +} + +HWTEST_F(SliceFilterTest, SliceTest4, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663028000, 2532, 2519, 0, splitStrIndex); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->EndSlice(168758682456000, 2532, 2519); + // end thread_one_call_function_two + stream_.streamFilters_->sliceFilter_->EndSlice(168758682466000, 2532, 2519); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 2); + EXPECT_TRUE(slices->DursData()[0] == 168758682466000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758682456000 - 168758663028000); // slice 1 + EXPECT_TRUE(slices->Depths()[1] == 1); +} +HWTEST_F(SliceFilterTest, SliceTest5, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758663028000, 2533, 2529, 0, splitStrIndex); + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_two"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758679303000, 2532, 2519, 0, splitStrIndex); // slice 2 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_two"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758679312000, 2533, 2529, 0, splitStrIndex); + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_three"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758679313000, 2532, 2519, 0, splitStrIndex); // slice 4 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_three"); + stream_.streamFilters_->sliceFilter_->BeginSlice(168758679323000, 2533, 2529, 0, splitStrIndex); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->EndSlice(168758682456000, 2532, 2519); + // end thread_one_call_function_two + stream_.streamFilters_->sliceFilter_->EndSlice(168758682466000, 2532, 2519); + // end thread_one_call_function_one + stream_.streamFilters_->sliceFilter_->EndSlice(168758682476000, 2532, 2519); + // end thread_two_call_function_three slice 5 + stream_.streamFilters_->sliceFilter_->EndSlice(168758679343000, 2533, 2529); + // end thread_two_call_function_two slice 3 + stream_.streamFilters_->sliceFilter_->EndSlice(168758679344000, 2533, 2529); + // end thread_two_call_function_one slice 1 + stream_.streamFilters_->sliceFilter_->EndSlice(168758689323000, 2533, 2529); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 6); + EXPECT_TRUE(slices->DursData()[0] == 168758682476000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758689323000 - 168758663028000); // slice 1 + EXPECT_TRUE(slices->Depths()[1] == 0); + EXPECT_TRUE(slices->DursData()[2] == 168758682466000 - 168758679303000); // slice 2 + EXPECT_TRUE(slices->Depths()[2] == 1); + EXPECT_TRUE(slices->DursData()[3] == 168758679344000 - 168758679312000); // slice 3 + EXPECT_TRUE(slices->Depths()[3] == 1); + EXPECT_TRUE(slices->DursData()[4] == 168758682456000 - 168758679313000); // slice 4 + EXPECT_TRUE(slices->DursData()[5] == 168758679343000 - 168758679323000); // slice 5 +} + +HWTEST_F(SliceFilterTest, SyncTest1, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("async_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("async_call_function_one"); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682456000, 2532, 2519, 0, splitStrIndex); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 1); + EXPECT_TRUE(slices->DursData()[0] == 168758682456000 - 168758663018000); // slice 0 +} + +HWTEST_F(SliceFilterTest, SyncTest2, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("async_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + splitStrIndex = stream_.traceDataCache_->GetDataIndex("async_call_function_one"); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682456000, 2532, 2519, 0, splitStrIndex); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 1); + EXPECT_TRUE(slices->DursData()[0] == 168758682456000 - 168758663018000); // slice 0 +} + +HWTEST_F(SliceFilterTest, BeginSliceMulti3, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + DataIndex splitStrIndex2 = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663028000, 2533, 2529, 0, splitStrIndex2); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682456000, 2532, 2519, 0, splitStrIndex); + // end thread_two_call_function_three slice 5 + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758679343000, 2533, 2529, 0, splitStrIndex2); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 2); + EXPECT_TRUE(slices->DursData()[0] == 168758682456000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758679343000 - 168758663028000); // slice 1 +} + +HWTEST_F(SliceFilterTest, BeginSliceMulti4, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + DataIndex splitStrIndex2 = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663028000, 2533, 2529, 0, splitStrIndex2); + DataIndex splitStrIndex3 = stream_.traceDataCache_->GetDataIndex("thread_three_call_function_two"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758679303000, 2532, 2519, 1, splitStrIndex3); // slice 2 + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682456000, 2532, 2519, 0, splitStrIndex); + // end thread_one_call_function_two + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682466000, 2532, 2519, 1, splitStrIndex3); + // end thread_two_call_function_three slice 5 + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758679343000, 2533, 2529, 0, splitStrIndex2); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 3); + EXPECT_TRUE(slices->DursData()[0] == 168758682456000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758679343000 - 168758663028000); // slice 1 + EXPECT_TRUE(slices->Depths()[1] == 0); + EXPECT_TRUE(slices->DursData()[2] == 168758682466000 - 168758679303000); // slice 2 +} + +HWTEST_F(SliceFilterTest, BeginSliceMulti5, TestSize.Level1) +{ + TS_LOGI("test3"); + DataIndex splitStrIndex = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663018000, 2532, 2519, 0, splitStrIndex); // slice 0 + DataIndex splitStrIndex2 = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_one"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758663028000, 2533, 2529, 0, splitStrIndex2); + DataIndex splitStrIndex3 = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_two"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758679303000, 2532, 2519, 1, splitStrIndex3); // slice 2 + DataIndex splitStrIndex4 = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_two"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758679312000, 2533, 2529, 1, splitStrIndex4); + DataIndex splitStrIndex5 = stream_.traceDataCache_->GetDataIndex("thread_one_call_function_three"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758679313000, 2532, 2519, 2, splitStrIndex5); // slice 4 + DataIndex splitStrIndex6 = stream_.traceDataCache_->GetDataIndex("thread_two_call_function_three"); + stream_.streamFilters_->sliceFilter_->StartAsyncSlice(168758679323000, 2533, 2529, 1, splitStrIndex6); + // end thread_one_call_function_three + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682456000, 2532, 2519, 0, splitStrIndex); + // end thread_one_call_function_two + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682466000, 2532, 2519, 1, splitStrIndex3); + // end thread_one_call_function_one + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758682476000, 2532, 2519, 2, splitStrIndex5); + // end thread_two_call_function_three slice 5 + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758679343000, 2533, 2529, 0, splitStrIndex2); + // end thread_two_call_function_two slice 3 + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758679344000, 2533, 2529, 1, splitStrIndex4); + // end thread_two_call_function_one slice 1 + stream_.streamFilters_->sliceFilter_->FinishAsyncSlice(168758689323000, 2533, 2529, 1, splitStrIndex6); + auto slices = stream_.traceDataCache_->GetInternalSlicesData(); + EXPECT_TRUE(slices->Size() == 6); + EXPECT_TRUE(slices->DursData()[0] == 168758682456000 - 168758663018000); // slice 0 + EXPECT_TRUE(slices->Depths()[0] == 0); + EXPECT_TRUE(slices->DursData()[1] == 168758679343000 - 168758663028000); // slice 1 + EXPECT_TRUE(slices->Depths()[1] == 0); + EXPECT_TRUE(slices->DursData()[2] == 168758682466000 - 168758679303000); // slice 2 + EXPECT_TRUE(slices->Depths()[2] == 0); + EXPECT_TRUE(slices->DursData()[3] == 168758679344000 - 168758679312000); // slice 3 + EXPECT_TRUE(slices->Depths()[3] == 0); + EXPECT_TRUE(slices->DursData()[4] == 168758682476000 - 168758679313000); // slice 4 + EXPECT_TRUE(slices->DursData()[5] == 168758689323000 - 168758679323000); // slice 5 +} + +} +}