main.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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/ProcessStatisticsReader.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 <serenity.h>
  18. #include <spawn.h>
  19. #include <stdio.h>
  20. enum class GraphType {
  21. CPU,
  22. Memory,
  23. };
  24. class GraphWidget final : public GUI::Frame {
  25. C_OBJECT(GraphWidget);
  26. public:
  27. static constexpr size_t history_size = 24;
  28. GraphWidget(GraphType graph_type, Optional<Gfx::Color> graph_color, Optional<Gfx::Color> graph_error_color)
  29. : m_graph_type(graph_type)
  30. {
  31. set_frame_thickness(1);
  32. m_graph_color = graph_color.value_or(palette().menu_selection());
  33. m_graph_error_color = graph_error_color.value_or(Color::Red);
  34. start_timer(1000);
  35. }
  36. private:
  37. virtual void timer_event(Core::TimerEvent&) override
  38. {
  39. switch (m_graph_type) {
  40. case GraphType::CPU: {
  41. u64 busy, idle, scheduled_diff;
  42. if (get_cpu_usage(busy, idle, scheduled_diff)) {
  43. auto busy_diff = busy - m_last_cpu_busy;
  44. m_last_cpu_busy = busy;
  45. m_last_cpu_idle = idle;
  46. float cpu = scheduled_diff > 0 ? (float)busy_diff / (float)scheduled_diff : 0;
  47. m_history.enqueue(cpu);
  48. m_tooltip = String::formatted("CPU usage: {:.1}%", 100 * cpu);
  49. } else {
  50. m_history.enqueue(-1);
  51. m_tooltip = StringView("Unable to determine CPU usage");
  52. }
  53. break;
  54. }
  55. case GraphType::Memory: {
  56. u64 allocated, available;
  57. if (get_memory_usage(allocated, available)) {
  58. double total_memory = allocated + available;
  59. double memory = (double)allocated / total_memory;
  60. m_history.enqueue(memory);
  61. m_tooltip = String::formatted("Memory: {} MiB of {:.1} MiB in use", allocated / MiB, total_memory / MiB);
  62. } else {
  63. m_history.enqueue(-1);
  64. m_tooltip = StringView("Unable to determine memory usage");
  65. }
  66. break;
  67. }
  68. default:
  69. VERIFY_NOT_REACHED();
  70. }
  71. set_tooltip(m_tooltip);
  72. update();
  73. }
  74. virtual void paint_event(GUI::PaintEvent& event) override
  75. {
  76. GUI::Frame::paint_event(event);
  77. GUI::Painter painter(*this);
  78. painter.add_clip_rect(event.rect());
  79. painter.add_clip_rect(frame_inner_rect());
  80. painter.fill_rect(event.rect(), Color::Black);
  81. int i = m_history.capacity() - m_history.size();
  82. auto rect = frame_inner_rect();
  83. for (auto value : m_history) {
  84. if (value >= 0) {
  85. painter.draw_line(
  86. { rect.x() + i, rect.bottom() },
  87. { rect.x() + i, rect.top() + (int)(roundf(rect.height() - (value * rect.height()))) },
  88. m_graph_color);
  89. } else {
  90. painter.draw_line(
  91. { rect.x() + i, rect.top() },
  92. { rect.x() + i, rect.bottom() },
  93. m_graph_error_color);
  94. }
  95. ++i;
  96. }
  97. }
  98. virtual void mousedown_event(GUI::MouseEvent& event) override
  99. {
  100. if (event.button() != GUI::MouseButton::Left)
  101. return;
  102. pid_t child_pid;
  103. const char* argv[] = { "SystemMonitor", "-t", "graphs", nullptr };
  104. if ((errno = posix_spawn(&child_pid, "/bin/SystemMonitor", nullptr, nullptr, const_cast<char**>(argv), environ))) {
  105. perror("posix_spawn");
  106. } else {
  107. if (disown(child_pid) < 0)
  108. perror("disown");
  109. }
  110. }
  111. bool get_cpu_usage(u64& busy, u64& idle, u64& scheduled_diff)
  112. {
  113. busy = 0;
  114. idle = 0;
  115. scheduled_diff = 0;
  116. auto all_processes = Core::ProcessStatisticsReader::get_all(m_proc_all);
  117. if (!all_processes.has_value() || all_processes.value().processes.is_empty())
  118. return false;
  119. if (m_last_total_sum.has_value())
  120. scheduled_diff = all_processes->total_time_scheduled - m_last_total_sum.value();
  121. m_last_total_sum = all_processes->total_time_scheduled;
  122. for (auto& it : all_processes.value().processes) {
  123. for (auto& jt : it.threads) {
  124. if (it.pid == 0)
  125. idle += jt.time_user + jt.time_kernel;
  126. else
  127. busy += jt.time_user + jt.time_kernel;
  128. }
  129. }
  130. return true;
  131. }
  132. bool get_memory_usage(u64& allocated, u64& available)
  133. {
  134. if (m_proc_mem) {
  135. // Seeking to the beginning causes a data refresh!
  136. if (!m_proc_mem->seek(0, Core::SeekMode::SetPosition))
  137. return false;
  138. } else {
  139. auto proc_memstat = Core::File::construct("/proc/memstat");
  140. if (!proc_memstat->open(Core::OpenMode::ReadOnly))
  141. return false;
  142. m_proc_mem = move(proc_memstat);
  143. }
  144. auto file_contents = m_proc_mem->read_all();
  145. auto json = JsonValue::from_string(file_contents);
  146. VERIFY(json.has_value());
  147. auto& obj = json.value().as_object();
  148. unsigned kmalloc_allocated = obj.get("kmalloc_allocated").to_u32();
  149. unsigned kmalloc_available = obj.get("kmalloc_available").to_u32();
  150. auto user_physical_allocated = obj.get("user_physical_allocated").to_u64();
  151. auto user_physical_committed = obj.get("user_physical_committed").to_u64();
  152. auto user_physical_uncommitted = obj.get("user_physical_uncommitted").to_u64();
  153. unsigned kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
  154. unsigned kmalloc_pages_total = (kmalloc_bytes_total + PAGE_SIZE - 1) / PAGE_SIZE;
  155. u64 total_userphysical_and_swappable_pages = kmalloc_pages_total + user_physical_allocated + user_physical_committed + user_physical_uncommitted;
  156. allocated = kmalloc_allocated + ((user_physical_allocated + user_physical_committed) * PAGE_SIZE);
  157. available = (total_userphysical_and_swappable_pages * PAGE_SIZE) - allocated;
  158. return true;
  159. }
  160. GraphType m_graph_type;
  161. Gfx::Color m_graph_color;
  162. Gfx::Color m_graph_error_color;
  163. CircularQueue<float, history_size> m_history;
  164. u64 m_last_cpu_busy { 0 };
  165. u64 m_last_cpu_idle { 0 };
  166. Optional<u64> m_last_total_sum;
  167. String m_tooltip;
  168. RefPtr<Core::File> m_proc_all;
  169. RefPtr<Core::File> m_proc_mem;
  170. };
  171. int main(int argc, char** argv)
  172. {
  173. if (pledge("stdio recvfd sendfd proc exec rpath unix", nullptr) < 0) {
  174. perror("pledge");
  175. return 1;
  176. }
  177. auto app = GUI::Application::construct(argc, argv);
  178. if (pledge("stdio recvfd sendfd proc exec rpath", nullptr) < 0) {
  179. perror("pledge");
  180. return 1;
  181. }
  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(argc, argv);
  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. if (unveil("/res", "r") < 0) {
  213. perror("unveil");
  214. return 1;
  215. }
  216. // FIXME: This is required by Core::ProcessStatisticsReader.
  217. // It would be good if we didn't depend on that.
  218. if (unveil("/etc/passwd", "r") < 0) {
  219. perror("unveil");
  220. return 1;
  221. }
  222. if (unveil("/proc/all", "r") < 0) {
  223. perror("unveil");
  224. return 1;
  225. }
  226. if (unveil("/proc/memstat", "r") < 0) {
  227. perror("unveil");
  228. return 1;
  229. }
  230. if (unveil("/bin/SystemMonitor", "x") < 0) {
  231. perror("unveil");
  232. return 1;
  233. }
  234. unveil(nullptr, nullptr);
  235. return app->exec();
  236. }