main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/CircularQueue.h>
  29. #include <AK/JsonObject.h>
  30. #include <LibCore/ArgsParser.h>
  31. #include <LibCore/File.h>
  32. #include <LibCore/ProcessStatisticsReader.h>
  33. #include <LibGUI/Application.h>
  34. #include <LibGUI/Frame.h>
  35. #include <LibGUI/Painter.h>
  36. #include <LibGUI/Window.h>
  37. #include <LibGfx/Palette.h>
  38. #include <serenity.h>
  39. #include <spawn.h>
  40. #include <stdio.h>
  41. enum class GraphType {
  42. CPU,
  43. Memory,
  44. };
  45. class GraphWidget final : public GUI::Frame {
  46. C_OBJECT(GraphWidget);
  47. public:
  48. static constexpr size_t history_size = 24;
  49. GraphWidget(GraphType graph_type, Optional<Gfx::Color> graph_color, Optional<Gfx::Color> graph_error_color)
  50. : m_graph_type(graph_type)
  51. {
  52. set_frame_thickness(1);
  53. m_graph_color = graph_color.value_or(palette().menu_selection());
  54. m_graph_error_color = graph_error_color.value_or(Color::Red);
  55. start_timer(1000);
  56. }
  57. private:
  58. virtual void timer_event(Core::TimerEvent&) override
  59. {
  60. switch (m_graph_type) {
  61. case GraphType::CPU: {
  62. unsigned busy;
  63. unsigned idle;
  64. if (get_cpu_usage(busy, idle)) {
  65. unsigned busy_diff = busy - m_last_cpu_busy;
  66. unsigned idle_diff = idle - m_last_cpu_idle;
  67. m_last_cpu_busy = busy;
  68. m_last_cpu_idle = idle;
  69. float cpu = (float)busy_diff / (float)(busy_diff + idle_diff);
  70. m_history.enqueue(cpu);
  71. m_tooltip = String::formatted("CPU usage: {:.1}%", 100 * cpu);
  72. } else {
  73. m_history.enqueue(-1);
  74. m_tooltip = StringView("Unable to determine CPU usage");
  75. }
  76. break;
  77. }
  78. case GraphType::Memory: {
  79. u64 allocated, available;
  80. if (get_memory_usage(allocated, available)) {
  81. double total_memory = allocated + available;
  82. double memory = (double)allocated / total_memory;
  83. m_history.enqueue(memory);
  84. m_tooltip = String::formatted("Memory: {} MiB of {:.1} MiB in use", allocated / MiB, total_memory / MiB);
  85. } else {
  86. m_history.enqueue(-1);
  87. m_tooltip = StringView("Unable to determine memory usage");
  88. }
  89. break;
  90. }
  91. default:
  92. VERIFY_NOT_REACHED();
  93. }
  94. set_tooltip(m_tooltip);
  95. update();
  96. }
  97. virtual void paint_event(GUI::PaintEvent& event) override
  98. {
  99. GUI::Frame::paint_event(event);
  100. GUI::Painter painter(*this);
  101. painter.add_clip_rect(event.rect());
  102. painter.add_clip_rect(frame_inner_rect());
  103. painter.fill_rect(event.rect(), Color::Black);
  104. int i = m_history.capacity() - m_history.size();
  105. auto rect = frame_inner_rect();
  106. for (auto value : m_history) {
  107. if (value >= 0) {
  108. painter.draw_line(
  109. { rect.x() + i, rect.bottom() },
  110. { rect.x() + i, rect.top() + (int)(round(rect.height() - (value * rect.height()))) },
  111. m_graph_color);
  112. } else {
  113. painter.draw_line(
  114. { rect.x() + i, rect.top() },
  115. { rect.x() + i, rect.bottom() },
  116. m_graph_error_color);
  117. }
  118. ++i;
  119. }
  120. }
  121. virtual void mousedown_event(GUI::MouseEvent& event) override
  122. {
  123. if (event.button() != GUI::MouseButton::Left)
  124. return;
  125. pid_t child_pid;
  126. const char* argv[] = { "SystemMonitor", "-t", "graphs", nullptr };
  127. if ((errno = posix_spawn(&child_pid, "/bin/SystemMonitor", nullptr, nullptr, const_cast<char**>(argv), environ))) {
  128. perror("posix_spawn");
  129. } else {
  130. if (disown(child_pid) < 0)
  131. perror("disown");
  132. }
  133. }
  134. bool get_cpu_usage(unsigned& busy, unsigned& idle)
  135. {
  136. busy = 0;
  137. idle = 0;
  138. auto all_processes = Core::ProcessStatisticsReader::get_all(m_proc_all);
  139. if (!all_processes.has_value() || all_processes.value().is_empty())
  140. return false;
  141. for (auto& it : all_processes.value()) {
  142. for (auto& jt : it.value.threads) {
  143. if (it.value.pid == 0)
  144. idle += jt.ticks_user + jt.ticks_kernel;
  145. else
  146. busy += jt.ticks_user + jt.ticks_kernel;
  147. }
  148. }
  149. return true;
  150. }
  151. bool get_memory_usage(u64& allocated, u64& available)
  152. {
  153. if (m_proc_mem) {
  154. // Seeking to the beginning causes a data refresh!
  155. if (!m_proc_mem->seek(0, Core::File::SeekMode::SetPosition))
  156. return false;
  157. } else {
  158. auto proc_memstat = Core::File::construct("/proc/memstat");
  159. if (!proc_memstat->open(Core::IODevice::OpenMode::ReadOnly))
  160. return false;
  161. m_proc_mem = move(proc_memstat);
  162. }
  163. auto file_contents = m_proc_mem->read_all();
  164. auto json = JsonValue::from_string(file_contents);
  165. VERIFY(json.has_value());
  166. auto& obj = json.value().as_object();
  167. unsigned kmalloc_allocated = obj.get("kmalloc_allocated").to_u32();
  168. unsigned kmalloc_available = obj.get("kmalloc_available").to_u32();
  169. unsigned user_physical_allocated = obj.get("user_physical_allocated").to_u32();
  170. unsigned user_physical_committed = obj.get("user_physical_committed").to_u32();
  171. unsigned user_physical_uncommitted = obj.get("user_physical_uncommitted").to_u32();
  172. unsigned kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
  173. unsigned kmalloc_pages_total = (kmalloc_bytes_total + PAGE_SIZE - 1) / PAGE_SIZE;
  174. unsigned total_userphysical_and_swappable_pages = kmalloc_pages_total + user_physical_allocated + user_physical_committed + user_physical_uncommitted;
  175. allocated = kmalloc_allocated + ((u64)(user_physical_allocated + user_physical_committed) * PAGE_SIZE);
  176. available = (u64)(total_userphysical_and_swappable_pages * PAGE_SIZE) - allocated;
  177. return true;
  178. }
  179. GraphType m_graph_type;
  180. Gfx::Color m_graph_color;
  181. Gfx::Color m_graph_error_color;
  182. CircularQueue<float, history_size> m_history;
  183. unsigned m_last_cpu_busy { 0 };
  184. unsigned m_last_cpu_idle { 0 };
  185. String m_tooltip;
  186. RefPtr<Core::File> m_proc_all;
  187. RefPtr<Core::File> m_proc_mem;
  188. };
  189. int main(int argc, char** argv)
  190. {
  191. if (pledge("stdio recvfd sendfd accept proc exec rpath unix cpath fattr", nullptr) < 0) {
  192. perror("pledge");
  193. return 1;
  194. }
  195. auto app = GUI::Application::construct(argc, argv);
  196. if (pledge("stdio recvfd sendfd accept proc exec rpath", nullptr) < 0) {
  197. perror("pledge");
  198. return 1;
  199. }
  200. const char* cpu = nullptr;
  201. const char* memory = nullptr;
  202. Core::ArgsParser args_parser;
  203. args_parser.add_option(cpu, "Create CPU graph", "cpu", 'C', "cpu");
  204. args_parser.add_option(memory, "Create memory graph", "memory", 'M', "memory");
  205. args_parser.parse(argc, argv);
  206. if (!cpu && !memory) {
  207. printf("At least one of --cpu or --memory must be used");
  208. return 1;
  209. }
  210. NonnullRefPtrVector<GUI::Window> applet_windows;
  211. auto create_applet = [&](GraphType graph_type, StringView spec) {
  212. auto parts = spec.split_view(',');
  213. dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
  214. if (parts.size() != 2)
  215. return;
  216. auto name = parts[0];
  217. auto graph_color = Gfx::Color::from_string(parts[1]);
  218. auto window = GUI::Window::construct();
  219. window->set_title(name);
  220. window->set_window_type(GUI::WindowType::Applet);
  221. window->resize(GraphWidget::history_size + 2, 15);
  222. window->set_main_widget<GraphWidget>(graph_type, graph_color, Optional<Gfx::Color> {});
  223. window->show();
  224. applet_windows.append(move(window));
  225. };
  226. if (cpu)
  227. create_applet(GraphType::CPU, cpu);
  228. if (memory)
  229. create_applet(GraphType::Memory, memory);
  230. if (unveil("/res", "r") < 0) {
  231. perror("unveil");
  232. return 1;
  233. }
  234. // FIXME: This is required by Core::ProcessStatisticsReader.
  235. // It would be good if we didn't depend on that.
  236. if (unveil("/etc/passwd", "r") < 0) {
  237. perror("unveil");
  238. return 1;
  239. }
  240. if (unveil("/proc/all", "r") < 0) {
  241. perror("unveil");
  242. return 1;
  243. }
  244. if (unveil("/proc/memstat", "r") < 0) {
  245. perror("unveil");
  246. return 1;
  247. }
  248. if (unveil("/bin/SystemMonitor", "x") < 0) {
  249. perror("unveil");
  250. return 1;
  251. }
  252. unveil(nullptr, nullptr);
  253. return app->exec();
  254. }