main.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors();
  129. auto const& obj = json.as_object();
  130. total = obj.get("total_time").to_u64();
  131. idle = obj.get("idle_time").to_u64();
  132. return true;
  133. }
  134. bool get_memory_usage(u64& allocated, u64& available)
  135. {
  136. if (m_proc_mem) {
  137. // Seeking to the beginning causes a data refresh!
  138. if (!m_proc_mem->seek(0, Core::SeekMode::SetPosition))
  139. return false;
  140. } else {
  141. auto proc_memstat = Core::File::construct("/proc/memstat");
  142. if (!proc_memstat->open(Core::OpenMode::ReadOnly))
  143. return false;
  144. m_proc_mem = move(proc_memstat);
  145. }
  146. auto file_contents = m_proc_mem->read_all();
  147. auto json = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors();
  148. auto const& obj = json.as_object();
  149. unsigned kmalloc_allocated = obj.get("kmalloc_allocated").to_u32();
  150. unsigned kmalloc_available = obj.get("kmalloc_available").to_u32();
  151. auto user_physical_allocated = obj.get("user_physical_allocated").to_u64();
  152. auto user_physical_committed = obj.get("user_physical_committed").to_u64();
  153. auto user_physical_uncommitted = obj.get("user_physical_uncommitted").to_u64();
  154. unsigned kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
  155. unsigned kmalloc_pages_total = (kmalloc_bytes_total + PAGE_SIZE - 1) / PAGE_SIZE;
  156. u64 total_userphysical_and_swappable_pages = kmalloc_pages_total + user_physical_allocated + user_physical_committed + user_physical_uncommitted;
  157. allocated = kmalloc_allocated + ((user_physical_allocated + user_physical_committed) * PAGE_SIZE);
  158. available = (total_userphysical_and_swappable_pages * PAGE_SIZE) - allocated;
  159. return true;
  160. }
  161. GraphType m_graph_type;
  162. Gfx::Color m_graph_color;
  163. Gfx::Color m_graph_error_color;
  164. CircularQueue<float, history_size> m_history;
  165. u64 m_last_idle { 0 };
  166. u64 m_last_total { 0 };
  167. String m_tooltip;
  168. RefPtr<Core::File> m_proc_stat;
  169. RefPtr<Core::File> m_proc_mem;
  170. };
  171. ErrorOr<int> serenity_main(Main::Arguments arguments)
  172. {
  173. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath unix", nullptr));
  174. auto app = GUI::Application::construct(arguments);
  175. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath", nullptr));
  176. const char* cpu = nullptr;
  177. const char* memory = nullptr;
  178. Core::ArgsParser args_parser;
  179. args_parser.add_option(cpu, "Create CPU graph", "cpu", 'C', "cpu");
  180. args_parser.add_option(memory, "Create memory graph", "memory", 'M', "memory");
  181. args_parser.parse(arguments);
  182. if (!cpu && !memory) {
  183. printf("At least one of --cpu or --memory must be used");
  184. return 1;
  185. }
  186. NonnullRefPtrVector<GUI::Window> applet_windows;
  187. auto create_applet = [&](GraphType graph_type, StringView spec) {
  188. auto parts = spec.split_view(',');
  189. dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
  190. if (parts.size() != 2)
  191. return;
  192. auto name = parts[0];
  193. auto graph_color = Gfx::Color::from_string(parts[1]);
  194. auto window = GUI::Window::construct();
  195. window->set_title(name);
  196. window->set_window_type(GUI::WindowType::Applet);
  197. window->resize(GraphWidget::history_size + 2, 15);
  198. window->set_main_widget<GraphWidget>(graph_type, graph_color, Optional<Gfx::Color> {});
  199. window->show();
  200. applet_windows.append(move(window));
  201. };
  202. if (cpu)
  203. create_applet(GraphType::CPU, cpu);
  204. if (memory)
  205. create_applet(GraphType::Memory, memory);
  206. TRY(Core::System::unveil("/res", "r"));
  207. TRY(Core::System::unveil("/proc/stat", "r"));
  208. TRY(Core::System::unveil("/proc/memstat", "r"));
  209. TRY(Core::System::unveil("/bin/SystemMonitor", "x"));
  210. TRY(Core::System::unveil(nullptr, nullptr));
  211. return app->exec();
  212. }