main.cpp 8.8 KB

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