main.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CircularQueue.h>
  8. #include <AK/JsonObject.h>
  9. #include <LibCore/ArgsParser.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/System.h>
  12. #include <LibGUI/Application.h>
  13. #include <LibGUI/Frame.h>
  14. #include <LibGUI/Painter.h>
  15. #include <LibGUI/Window.h>
  16. #include <LibGfx/Palette.h>
  17. #include <LibMain/Main.h>
  18. #include <serenity.h>
  19. #include <spawn.h>
  20. #include <stdio.h>
  21. enum class GraphType {
  22. CPU,
  23. Memory,
  24. };
  25. class GraphWidget final : public GUI::Frame {
  26. C_OBJECT(GraphWidget);
  27. public:
  28. static constexpr size_t history_size = 24;
  29. private:
  30. GraphWidget(GraphType graph_type, Optional<Gfx::Color> graph_color, Optional<Gfx::Color> graph_error_color)
  31. : m_graph_type(graph_type)
  32. {
  33. set_frame_thickness(1);
  34. m_graph_color = graph_color.value_or(palette().menu_selection());
  35. m_graph_error_color = graph_error_color.value_or(Color::Red);
  36. start_timer(1000);
  37. }
  38. virtual void timer_event(Core::TimerEvent&) override
  39. {
  40. switch (m_graph_type) {
  41. case GraphType::CPU: {
  42. u64 total, idle;
  43. if (get_cpu_usage(total, idle)) {
  44. auto total_diff = total - m_last_total;
  45. m_last_total = total;
  46. auto idle_diff = idle - m_last_idle;
  47. m_last_idle = idle;
  48. float cpu = total_diff > 0 ? (float)(total_diff - idle_diff) / (float)total_diff : 0;
  49. m_history.enqueue(cpu);
  50. m_tooltip = String::formatted("CPU usage: {:.1}%", 100 * cpu);
  51. } else {
  52. m_history.enqueue(-1);
  53. m_tooltip = StringView("Unable to determine CPU usage");
  54. }
  55. break;
  56. }
  57. case GraphType::Memory: {
  58. u64 allocated, available;
  59. if (get_memory_usage(allocated, available)) {
  60. double total_memory = allocated + available;
  61. double memory = (double)allocated / total_memory;
  62. m_history.enqueue(memory);
  63. m_tooltip = String::formatted("Memory: {} MiB of {:.1} MiB in use", allocated / MiB, total_memory / MiB);
  64. } else {
  65. m_history.enqueue(-1);
  66. m_tooltip = StringView("Unable to determine memory usage");
  67. }
  68. break;
  69. }
  70. default:
  71. VERIFY_NOT_REACHED();
  72. }
  73. set_tooltip(m_tooltip);
  74. update();
  75. }
  76. virtual void paint_event(GUI::PaintEvent& event) override
  77. {
  78. GUI::Frame::paint_event(event);
  79. GUI::Painter painter(*this);
  80. painter.add_clip_rect(event.rect());
  81. painter.add_clip_rect(frame_inner_rect());
  82. painter.fill_rect(event.rect(), Color::Black);
  83. int i = m_history.capacity() - m_history.size();
  84. auto rect = frame_inner_rect();
  85. for (auto value : m_history) {
  86. if (value >= 0) {
  87. painter.draw_line(
  88. { rect.x() + i, rect.bottom() },
  89. { rect.x() + i, rect.top() + (int)(roundf(rect.height() - (value * rect.height()))) },
  90. m_graph_color);
  91. } else {
  92. painter.draw_line(
  93. { rect.x() + i, rect.top() },
  94. { rect.x() + i, rect.bottom() },
  95. m_graph_error_color);
  96. }
  97. ++i;
  98. }
  99. }
  100. virtual void mousedown_event(GUI::MouseEvent& event) override
  101. {
  102. if (event.button() != GUI::MouseButton::Primary)
  103. return;
  104. pid_t child_pid;
  105. const char* argv[] = { "SystemMonitor", "-t", "graphs", nullptr };
  106. if ((errno = posix_spawn(&child_pid, "/bin/SystemMonitor", nullptr, nullptr, const_cast<char**>(argv), environ))) {
  107. perror("posix_spawn");
  108. } else {
  109. if (disown(child_pid) < 0)
  110. perror("disown");
  111. }
  112. }
  113. bool get_cpu_usage(u64& total, u64& idle)
  114. {
  115. total = 0;
  116. idle = 0;
  117. if (m_proc_stat) {
  118. // Seeking to the beginning causes a data refresh!
  119. if (!m_proc_stat->seek(0, Core::SeekMode::SetPosition))
  120. return false;
  121. } else {
  122. auto proc_stat = Core::File::construct("/proc/stat");
  123. if (!proc_stat->open(Core::OpenMode::ReadOnly))
  124. return false;
  125. m_proc_stat = move(proc_stat);
  126. }
  127. auto file_contents = m_proc_stat->read_all();
  128. auto json_or_error = JsonValue::from_string(file_contents);
  129. if (json_or_error.is_error())
  130. return false;
  131. auto json = json_or_error.release_value();
  132. auto const& obj = json.as_object();
  133. total = obj.get("total_time").to_u64();
  134. idle = obj.get("idle_time").to_u64();
  135. return true;
  136. }
  137. bool get_memory_usage(u64& allocated, u64& available)
  138. {
  139. if (m_proc_mem) {
  140. // Seeking to the beginning causes a data refresh!
  141. if (!m_proc_mem->seek(0, Core::SeekMode::SetPosition))
  142. return false;
  143. } else {
  144. auto proc_memstat = Core::File::construct("/proc/memstat");
  145. if (!proc_memstat->open(Core::OpenMode::ReadOnly))
  146. return false;
  147. m_proc_mem = move(proc_memstat);
  148. }
  149. auto file_contents = m_proc_mem->read_all();
  150. auto json_or_error = JsonValue::from_string(file_contents);
  151. if (json_or_error.is_error())
  152. return false;
  153. auto json = json_or_error.release_value();
  154. auto const& obj = json.as_object();
  155. unsigned kmalloc_allocated = obj.get("kmalloc_allocated").to_u32();
  156. unsigned kmalloc_available = obj.get("kmalloc_available").to_u32();
  157. auto user_physical_allocated = obj.get("user_physical_allocated").to_u64();
  158. auto user_physical_committed = obj.get("user_physical_committed").to_u64();
  159. auto user_physical_uncommitted = obj.get("user_physical_uncommitted").to_u64();
  160. unsigned kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
  161. unsigned kmalloc_pages_total = (kmalloc_bytes_total + PAGE_SIZE - 1) / PAGE_SIZE;
  162. u64 total_userphysical_and_swappable_pages = kmalloc_pages_total + user_physical_allocated + user_physical_committed + user_physical_uncommitted;
  163. allocated = kmalloc_allocated + ((user_physical_allocated + user_physical_committed) * PAGE_SIZE);
  164. available = (total_userphysical_and_swappable_pages * PAGE_SIZE) - allocated;
  165. return true;
  166. }
  167. GraphType m_graph_type;
  168. Gfx::Color m_graph_color;
  169. Gfx::Color m_graph_error_color;
  170. CircularQueue<float, history_size> m_history;
  171. u64 m_last_idle { 0 };
  172. u64 m_last_total { 0 };
  173. String m_tooltip;
  174. RefPtr<Core::File> m_proc_stat;
  175. RefPtr<Core::File> m_proc_mem;
  176. };
  177. ErrorOr<int> serenity_main(Main::Arguments arguments)
  178. {
  179. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath unix"));
  180. auto app = GUI::Application::construct(arguments);
  181. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath"));
  182. const char* cpu = nullptr;
  183. const char* memory = nullptr;
  184. Core::ArgsParser args_parser;
  185. args_parser.add_option(cpu, "Create CPU graph", "cpu", 'C', "cpu");
  186. args_parser.add_option(memory, "Create memory graph", "memory", 'M', "memory");
  187. args_parser.parse(arguments);
  188. if (!cpu && !memory) {
  189. printf("At least one of --cpu or --memory must be used");
  190. return 1;
  191. }
  192. NonnullRefPtrVector<GUI::Window> applet_windows;
  193. auto create_applet = [&](GraphType graph_type, StringView spec) {
  194. auto parts = spec.split_view(',');
  195. dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
  196. if (parts.size() != 2)
  197. return;
  198. auto name = parts[0];
  199. auto graph_color = Gfx::Color::from_string(parts[1]);
  200. auto window = GUI::Window::construct();
  201. window->set_title(name);
  202. window->set_window_type(GUI::WindowType::Applet);
  203. window->resize(GraphWidget::history_size + 2, 15);
  204. window->set_main_widget<GraphWidget>(graph_type, graph_color, Optional<Gfx::Color> {});
  205. window->show();
  206. applet_windows.append(move(window));
  207. };
  208. if (cpu)
  209. create_applet(GraphType::CPU, cpu);
  210. if (memory)
  211. create_applet(GraphType::Memory, memory);
  212. TRY(Core::System::unveil("/res", "r"));
  213. TRY(Core::System::unveil("/proc/stat", "r"));
  214. TRY(Core::System::unveil("/proc/memstat", "r"));
  215. TRY(Core::System::unveil("/bin/SystemMonitor", "x"));
  216. TRY(Core::System::unveil(nullptr, nullptr));
  217. return app->exec();
  218. }