main.cpp 12 KB

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