main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/CircularQueue.h>
  9. #include <AK/JsonObject.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/System.h>
  12. #include <LibGUI/Application.h>
  13. #include <LibGUI/Frame.h>
  14. #include <LibGUI/Painter.h>
  15. #include <LibGUI/Process.h>
  16. #include <LibGUI/Window.h>
  17. #include <LibGfx/Palette.h>
  18. #include <LibMain/Main.h>
  19. #include <stdio.h>
  20. enum class GraphType {
  21. CPU,
  22. Memory,
  23. Network,
  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_style(Gfx::FrameStyle::SunkenPanel);
  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 = DeprecatedString::formatted("CPU usage: {:.1}%", 100 * cpu);
  51. } else {
  52. m_history.enqueue(-1);
  53. m_tooltip = "Unable to determine CPU usage"sv;
  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 = DeprecatedString::formatted("Memory: {} MiB of {:.1} MiB in use", allocated / MiB, total_memory / MiB);
  64. } else {
  65. m_history.enqueue(-1);
  66. m_tooltip = "Unable to determine memory usage"sv;
  67. }
  68. break;
  69. }
  70. case GraphType::Network: {
  71. u64 tx, rx, link_speed;
  72. if (get_network_usage(tx, rx, link_speed)) {
  73. u64 recent_tx = tx - m_last_total;
  74. m_last_total = tx;
  75. if (recent_tx > m_current_scale) {
  76. u64 m_old_scale = m_current_scale;
  77. // Scale in multiples of 1000 kB/s
  78. m_current_scale = (recent_tx / scale_unit) * scale_unit;
  79. rescale_history(m_old_scale, m_current_scale);
  80. } else {
  81. // Figure out if we can scale back down.
  82. float max = static_cast<float>(recent_tx) / static_cast<float>(m_current_scale);
  83. for (auto const value : m_history) {
  84. if (value > max)
  85. max = value;
  86. }
  87. if (max < 0.5f && m_current_scale > scale_unit) {
  88. u64 m_old_scale = m_current_scale;
  89. m_current_scale = ::max((static_cast<u64>(max * m_current_scale) / scale_unit) * scale_unit, scale_unit);
  90. rescale_history(m_old_scale, m_current_scale);
  91. }
  92. }
  93. m_history.enqueue(static_cast<float>(recent_tx) / static_cast<float>(m_current_scale));
  94. m_tooltip = DeprecatedString::formatted("Network: TX {} / RX {} ({:.1} kbit/s)", tx, rx, static_cast<double>(recent_tx) * 8.0 / 1000.0);
  95. } else {
  96. m_history.enqueue(-1);
  97. m_tooltip = "Unable to determine network usage"sv;
  98. }
  99. break;
  100. }
  101. default:
  102. VERIFY_NOT_REACHED();
  103. }
  104. set_tooltip(m_tooltip);
  105. update();
  106. }
  107. virtual void paint_event(GUI::PaintEvent& event) override
  108. {
  109. GUI::Frame::paint_event(event);
  110. GUI::Painter painter(*this);
  111. painter.add_clip_rect(event.rect());
  112. painter.add_clip_rect(frame_inner_rect());
  113. painter.fill_rect(event.rect(), Color::Black);
  114. int i = m_history.capacity() - m_history.size();
  115. auto rect = frame_inner_rect();
  116. for (auto value : m_history) {
  117. if (value >= 0) {
  118. painter.draw_line(
  119. { rect.x() + i, rect.bottom() - 1 },
  120. { rect.x() + i, rect.top() + (int)(roundf(rect.height() - (value * rect.height()))) },
  121. m_graph_color);
  122. } else {
  123. painter.draw_line(
  124. { rect.x() + i, rect.top() },
  125. { rect.x() + i, rect.bottom() - 1 },
  126. m_graph_error_color);
  127. }
  128. ++i;
  129. }
  130. }
  131. virtual void mousedown_event(GUI::MouseEvent& event) override
  132. {
  133. if (event.button() != GUI::MouseButton::Primary)
  134. return;
  135. GUI::Process::spawn_or_show_error(window(), "/bin/SystemMonitor"sv, Array { "-t", m_graph_type == GraphType::Network ? "network" : "graphs" });
  136. }
  137. ErrorOr<JsonValue> get_data_as_json(OwnPtr<Core::File>& file, StringView filename)
  138. {
  139. if (file) {
  140. // Seeking to the beginning causes a data refresh!
  141. TRY(file->seek(0, SeekMode::SetPosition));
  142. } else {
  143. file = TRY(Core::File::open(filename, Core::File::OpenMode::Read));
  144. }
  145. auto file_contents = TRY(file->read_until_eof());
  146. return TRY(JsonValue::from_string(file_contents));
  147. }
  148. bool get_cpu_usage(u64& total, u64& idle)
  149. {
  150. total = 0;
  151. idle = 0;
  152. auto json = get_data_as_json(m_proc_stat, "/sys/kernel/stats"sv);
  153. if (json.is_error())
  154. return false;
  155. auto const& obj = json.value().as_object();
  156. total = obj.get_u64("total_time"sv).value_or(0);
  157. idle = obj.get_u64("idle_time"sv).value_or(0);
  158. return true;
  159. }
  160. bool get_memory_usage(u64& allocated, u64& available)
  161. {
  162. auto json = get_data_as_json(m_proc_mem, "/sys/kernel/memstat"sv);
  163. if (json.is_error())
  164. return false;
  165. auto const& obj = json.value().as_object();
  166. unsigned kmalloc_allocated = obj.get_u32("kmalloc_allocated"sv).value_or(0);
  167. unsigned kmalloc_available = obj.get_u32("kmalloc_available"sv).value_or(0);
  168. auto physical_allocated = obj.get_u64("physical_allocated"sv).value_or(0);
  169. auto physical_committed = obj.get_u64("physical_committed"sv).value_or(0);
  170. auto physical_uncommitted = obj.get_u64("physical_uncommitted"sv).value_or(0);
  171. unsigned kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
  172. unsigned kmalloc_pages_total = (kmalloc_bytes_total + PAGE_SIZE - 1) / PAGE_SIZE;
  173. u64 total_userphysical_and_swappable_pages = kmalloc_pages_total + physical_allocated + physical_committed + physical_uncommitted;
  174. allocated = kmalloc_allocated + ((physical_allocated + physical_committed) * PAGE_SIZE);
  175. available = (total_userphysical_and_swappable_pages * PAGE_SIZE) - allocated;
  176. return true;
  177. }
  178. bool get_network_usage(u64& tx, u64& rx, u64& link_speed)
  179. {
  180. tx = rx = link_speed = 0;
  181. auto json = get_data_as_json(m_proc_net, "/sys/kernel/net/adapters"sv);
  182. if (json.is_error())
  183. return false;
  184. auto const& array = json.value().as_array();
  185. for (auto const& adapter_value : array.values()) {
  186. auto const& adapter_obj = adapter_value.as_object();
  187. if (!adapter_obj.has_string("ipv4_address"sv) || !adapter_obj.get_bool("link_up"sv).value())
  188. continue;
  189. tx += adapter_obj.get_u64("bytes_in"sv).value_or(0);
  190. rx += adapter_obj.get_u64("bytes_out"sv).value_or(0);
  191. // Link speed data is given in megabits, but we want all return values to be in bytes.
  192. link_speed += adapter_obj.get_u64("link_speed"sv).value_or(0) * 8'000'000;
  193. }
  194. link_speed /= 8;
  195. return tx != 0;
  196. }
  197. void rescale_history(u64 old_scale, u64 new_scale)
  198. {
  199. float factor = static_cast<float>(old_scale) / static_cast<float>(new_scale);
  200. for (auto& value : m_history)
  201. value *= factor;
  202. }
  203. GraphType m_graph_type;
  204. Gfx::Color m_graph_color;
  205. Gfx::Color m_graph_error_color;
  206. CircularQueue<float, history_size> m_history;
  207. u64 m_last_idle { 0 };
  208. u64 m_last_total { 0 };
  209. static constexpr u64 const scale_unit = 8000;
  210. u64 m_current_scale { scale_unit };
  211. DeprecatedString m_tooltip;
  212. OwnPtr<Core::File> m_proc_stat;
  213. OwnPtr<Core::File> m_proc_mem;
  214. OwnPtr<Core::File> m_proc_net;
  215. };
  216. ErrorOr<int> serenity_main(Main::Arguments arguments)
  217. {
  218. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath unix"));
  219. auto app = TRY(GUI::Application::create(arguments));
  220. TRY(Core::System::pledge("stdio recvfd sendfd proc exec rpath"));
  221. StringView cpu {};
  222. StringView memory {};
  223. StringView network {};
  224. Core::ArgsParser args_parser;
  225. args_parser.add_option(cpu, "Create CPU graph", "cpu", 'C', "cpu");
  226. args_parser.add_option(memory, "Create memory graph", "memory", 'M', "memory");
  227. args_parser.add_option(network, "Create network graph", "network", 'N', "network");
  228. args_parser.parse(arguments);
  229. if (cpu.is_empty() && memory.is_empty() && network.is_empty()) {
  230. printf("At least one of --cpu, --memory, or --network must be used");
  231. return 1;
  232. }
  233. Vector<NonnullRefPtr<GUI::Window>> applet_windows;
  234. auto create_applet = [&](GraphType graph_type, StringView spec) -> ErrorOr<void> {
  235. auto parts = spec.split_view(',');
  236. dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
  237. if (parts.size() != 2)
  238. return Error::from_string_literal("ResourceGraph: Applet spec is not composed of exactly 2 comma-separated parts");
  239. auto name = parts[0];
  240. auto graph_color = Gfx::Color::from_string(parts[1]);
  241. auto window = GUI::Window::construct();
  242. window->set_title(name);
  243. window->set_window_type(GUI::WindowType::Applet);
  244. window->resize(GraphWidget::history_size + 2, 15);
  245. auto graph_widget = TRY(window->set_main_widget<GraphWidget>(graph_type, graph_color, Optional<Gfx::Color> {}));
  246. window->show();
  247. applet_windows.append(move(window));
  248. return {};
  249. };
  250. if (!cpu.is_empty())
  251. TRY(create_applet(GraphType::CPU, cpu));
  252. if (!memory.is_empty())
  253. TRY(create_applet(GraphType::Memory, memory));
  254. if (!network.is_empty())
  255. TRY(create_applet(GraphType::Network, network));
  256. TRY(Core::System::unveil("/res", "r"));
  257. TRY(Core::System::unveil("/sys/kernel/stats", "r"));
  258. TRY(Core::System::unveil("/sys/kernel/memstat", "r"));
  259. TRY(Core::System::unveil("/sys/kernel/net/adapters", "r"));
  260. TRY(Core::System::unveil("/bin/SystemMonitor", "x"));
  261. TRY(Core::System::unveil(nullptr, nullptr));
  262. return app->exec();
  263. }