main.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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/ByteBuffer.h>
  8. #include <AK/CircularQueue.h>
  9. #include <AK/JsonObject.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/File.h>
  12. #include <LibCore/ProcessStatisticsReader.h>
  13. #include <LibGUI/Application.h>
  14. #include <LibGUI/Frame.h>
  15. #include <LibGUI/Painter.h>
  16. #include <LibGUI/Window.h>
  17. #include <LibGfx/Palette.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. GraphWidget(GraphType graph_type, Optional<Gfx::Color> graph_color, Optional<Gfx::Color> graph_error_color)
  30. : m_graph_type(graph_type)
  31. {
  32. set_frame_thickness(1);
  33. m_graph_color = graph_color.value_or(palette().menu_selection());
  34. m_graph_error_color = graph_error_color.value_or(Color::Red);
  35. start_timer(1000);
  36. }
  37. private:
  38. virtual void timer_event(Core::TimerEvent&) override
  39. {
  40. switch (m_graph_type) {
  41. case GraphType::CPU: {
  42. u64 busy, idle, scheduled_diff;
  43. if (get_cpu_usage(busy, idle, scheduled_diff)) {
  44. auto busy_diff = busy - m_last_cpu_busy;
  45. m_last_cpu_busy = busy;
  46. m_last_cpu_idle = idle;
  47. float cpu = scheduled_diff > 0 ? (float)busy_diff / (float)scheduled_diff : 0;
  48. m_history.enqueue(cpu);
  49. m_tooltip = String::formatted("CPU usage: {:.1}%", 100 * cpu);
  50. } else {
  51. m_history.enqueue(-1);
  52. m_tooltip = StringView("Unable to determine CPU usage");
  53. }
  54. break;
  55. }
  56. case GraphType::Memory: {
  57. u64 allocated, available;
  58. if (get_memory_usage(allocated, available)) {
  59. double total_memory = allocated + available;
  60. double memory = (double)allocated / total_memory;
  61. m_history.enqueue(memory);
  62. m_tooltip = String::formatted("Memory: {} MiB of {:.1} MiB in use", allocated / MiB, total_memory / MiB);
  63. } else {
  64. m_history.enqueue(-1);
  65. m_tooltip = StringView("Unable to determine memory usage");
  66. }
  67. break;
  68. }
  69. default:
  70. VERIFY_NOT_REACHED();
  71. }
  72. set_tooltip(m_tooltip);
  73. update();
  74. }
  75. virtual void paint_event(GUI::PaintEvent& event) override
  76. {
  77. GUI::Frame::paint_event(event);
  78. GUI::Painter painter(*this);
  79. painter.add_clip_rect(event.rect());
  80. painter.add_clip_rect(frame_inner_rect());
  81. painter.fill_rect(event.rect(), Color::Black);
  82. int i = m_history.capacity() - m_history.size();
  83. auto rect = frame_inner_rect();
  84. for (auto value : m_history) {
  85. if (value >= 0) {
  86. painter.draw_line(
  87. { rect.x() + i, rect.bottom() },
  88. { rect.x() + i, rect.top() + (int)(roundf(rect.height() - (value * rect.height()))) },
  89. m_graph_color);
  90. } else {
  91. painter.draw_line(
  92. { rect.x() + i, rect.top() },
  93. { rect.x() + i, rect.bottom() },
  94. m_graph_error_color);
  95. }
  96. ++i;
  97. }
  98. }
  99. virtual void mousedown_event(GUI::MouseEvent& event) override
  100. {
  101. if (event.button() != GUI::MouseButton::Left)
  102. return;
  103. pid_t child_pid;
  104. const char* argv[] = { "SystemMonitor", "-t", "graphs", nullptr };
  105. if ((errno = posix_spawn(&child_pid, "/bin/SystemMonitor", nullptr, nullptr, const_cast<char**>(argv), environ))) {
  106. perror("posix_spawn");
  107. } else {
  108. if (disown(child_pid) < 0)
  109. perror("disown");
  110. }
  111. }
  112. bool get_cpu_usage(u64& busy, u64& idle, u64& scheduled_diff)
  113. {
  114. busy = 0;
  115. idle = 0;
  116. scheduled_diff = 0;
  117. auto all_processes = Core::ProcessStatisticsReader::get_all(m_proc_all);
  118. if (!all_processes.has_value() || all_processes.value().processes.is_empty())
  119. return false;
  120. if (m_last_total_sum.has_value())
  121. scheduled_diff = all_processes->total_ticks_scheduled - m_last_total_sum.value();
  122. m_last_total_sum = all_processes->total_ticks_scheduled;
  123. for (auto& it : all_processes.value().processes) {
  124. for (auto& jt : it.threads) {
  125. if (it.pid == 0)
  126. idle += jt.ticks_user + jt.ticks_kernel;
  127. else
  128. busy += jt.ticks_user + jt.ticks_kernel;
  129. }
  130. }
  131. return true;
  132. }
  133. bool get_memory_usage(u64& allocated, u64& available)
  134. {
  135. if (m_proc_mem) {
  136. // Seeking to the beginning causes a data refresh!
  137. if (!m_proc_mem->seek(0, Core::SeekMode::SetPosition))
  138. return false;
  139. } else {
  140. auto proc_memstat = Core::File::construct("/proc/memstat");
  141. if (!proc_memstat->open(Core::OpenMode::ReadOnly))
  142. return false;
  143. m_proc_mem = move(proc_memstat);
  144. }
  145. auto file_contents = m_proc_mem->read_all();
  146. auto json = JsonValue::from_string(file_contents);
  147. VERIFY(json.has_value());
  148. auto& obj = json.value().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_cpu_busy { 0 };
  166. u64 m_last_cpu_idle { 0 };
  167. Optional<u64> m_last_total_sum;
  168. String m_tooltip;
  169. RefPtr<Core::File> m_proc_all;
  170. RefPtr<Core::File> m_proc_mem;
  171. };
  172. int main(int argc, char** argv)
  173. {
  174. if (pledge("stdio recvfd sendfd proc exec rpath unix", nullptr) < 0) {
  175. perror("pledge");
  176. return 1;
  177. }
  178. auto app = GUI::Application::construct(argc, argv);
  179. if (pledge("stdio recvfd sendfd proc exec rpath", nullptr) < 0) {
  180. perror("pledge");
  181. return 1;
  182. }
  183. const char* cpu = nullptr;
  184. const char* memory = nullptr;
  185. Core::ArgsParser args_parser;
  186. args_parser.add_option(cpu, "Create CPU graph", "cpu", 'C', "cpu");
  187. args_parser.add_option(memory, "Create memory graph", "memory", 'M', "memory");
  188. args_parser.parse(argc, argv);
  189. if (!cpu && !memory) {
  190. printf("At least one of --cpu or --memory must be used");
  191. return 1;
  192. }
  193. NonnullRefPtrVector<GUI::Window> applet_windows;
  194. auto create_applet = [&](GraphType graph_type, StringView spec) {
  195. auto parts = spec.split_view(',');
  196. dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
  197. if (parts.size() != 2)
  198. return;
  199. auto name = parts[0];
  200. auto graph_color = Gfx::Color::from_string(parts[1]);
  201. auto window = GUI::Window::construct();
  202. window->set_title(name);
  203. window->set_window_type(GUI::WindowType::Applet);
  204. window->resize(GraphWidget::history_size + 2, 15);
  205. window->set_main_widget<GraphWidget>(graph_type, graph_color, Optional<Gfx::Color> {});
  206. window->show();
  207. applet_windows.append(move(window));
  208. };
  209. if (cpu)
  210. create_applet(GraphType::CPU, cpu);
  211. if (memory)
  212. create_applet(GraphType::Memory, memory);
  213. if (unveil("/res", "r") < 0) {
  214. perror("unveil");
  215. return 1;
  216. }
  217. // FIXME: This is required by Core::ProcessStatisticsReader.
  218. // It would be good if we didn't depend on that.
  219. if (unveil("/etc/passwd", "r") < 0) {
  220. perror("unveil");
  221. return 1;
  222. }
  223. if (unveil("/proc/all", "r") < 0) {
  224. perror("unveil");
  225. return 1;
  226. }
  227. if (unveil("/proc/memstat", "r") < 0) {
  228. perror("unveil");
  229. return 1;
  230. }
  231. if (unveil("/bin/SystemMonitor", "x") < 0) {
  232. perror("unveil");
  233. return 1;
  234. }
  235. unveil(nullptr, nullptr);
  236. return app->exec();
  237. }