main.cpp 11 KB

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