Debian Codegraph @

src/libsysprof/sysprof-memory-usage.c

raw
1 /* sysprof-memory-usage.c
2 *
3 * Copyright 2023 Christian Hergert <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21 #include "config.h"
22
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30
31 #include <glib-unix.h>
32 #include <glib/gstdio.h>
33
34 #include "line-reader-private.h"
35
36 #include "sysprof-memory-usage.h"
37 #include "sysprof-instrument-private.h"
38 #include "sysprof-recording-private.h"
39
40 struct _SysprofMemoryUsage
41 {
42 SysprofInstrument parent_instance;
43 };
44
45 struct _SysprofMemoryUsageClass
46 {
47 SysprofInstrumentClass parent_class;
48 };
49
50 static const char *counter_names[] = {
51 "Used",
52 "Total",
53 "Available",
54 "Free",
55 "Buffers",
56 "Cached",
57 "Swap Cached",
58 "Mapped",
59 "Shmem",
60 "Swap Total",
61 "Swap Free",
62 };
63
64 typedef struct _MemStat
65 {
66 int stat_fd;
67
68 union {
69 struct {
70 gint64 used;
71 gint64 total;
72 gint64 avail;
73 gint64 free;
74 gint64 buffers;
75 gint64 cached;
76 gint64 swap_cached;
77 gint64 mapped;
78 gint64 shmem;
79 gint64 swap_total;
80 gint64 swap_free;
81 } sys;
82 SysprofCaptureCounterValue values[11];
83 };
84 } MemStat;
85
86 G_DEFINE_FINAL_TYPE (SysprofMemoryUsage, sysprof_memory_usage, SYSPROF_TYPE_INSTRUMENT)
87
88 static GHashTable *keys;
89
90 static gboolean
91 mem_stat_open (MemStat *st,
92 GError **error)
93 {
94 memset (st, 0, sizeof *st);
95
96 st->stat_fd = open ("/proc/meminfo", O_RDONLY|O_CLOEXEC);
97
98 if (st->stat_fd == -1)
99 {
100 int errsv = errno;
101 g_set_error_literal (error,
102 G_IO_ERROR,
103 g_io_error_from_errno (errsv),
104 g_strerror (errsv));
105 return FALSE;
106 }
107
108 return TRUE;
109 }
110
111 static gboolean
112 mem_stat_close (MemStat *st,
113 GError **error)
114 {
115 g_assert (st != NULL);
116
117 return g_clear_fd (&st->stat_fd, error);
118 }
119
120 static void
121 mem_stat_parse (MemStat *st,
122 char *buf)
123 {
124 char *bufptr = buf;
125 char *save = NULL;
126
127 g_assert (st != NULL);
128 g_assert (buf != NULL);
129
130 for (;;)
131 {
132 gssize off;
133 char *key;
134 char *value;
135 char *unit;
136 gint64 v64;
137 gint64 *v64ptr;
138
139 /* Get the data key name */
140 if (!(key = strtok_r (bufptr, " \n\t:", &save)))
141 break;
142
143 bufptr = NULL;
144
145 /* Offset from self to save value. Stop after getting to
146 * last value we care about.
147 */
148 if (!g_hash_table_lookup_extended (keys, key, NULL, (gpointer *)&off))
149 off = -1;
150
151 /* Get the data value */
152 if (!(value = strtok_r (bufptr, " \n\t:", &save)))
153 break;
154
155 /* Parse the numeric value of this column */
156 v64 = g_ascii_strtoll (value, NULL, 10);
157 if ((v64 == G_MININT64 || v64 == G_MAXINT64) && errno == ERANGE)
158 break;
159
160 /* Get the data unit */
161 unit = strtok_r (bufptr, " \n\t:", &save);
162
163 if (g_strcmp0 (unit, "kB") == 0)
164 v64 *= 1024L;
165 else if (g_strcmp0 (unit, "mB") == 0)
166 v64 *= 1024L * 1024L;
167 else if (g_strcmp0 (unit, "gB") == 0)
168 v64 *= 1024L * 1024L * 1024L;
169
170 if (off >= 0)
171 {
172 v64ptr = (gint64 *)(gpointer)(((gchar *)st) + off);
173 *v64ptr = v64;
174 }
175 }
176
177 /* Create pre-compiled value for used to simplify display */
178 st->sys.used = (gdouble)st->sys.total - (gdouble)st->sys.avail;
179 }
180
181 typedef struct _Record
182 {
183 SysprofRecording *recording;
184 DexFuture *cancellable;
185 } Record;
186
187 static void
188 record_free (gpointer data)
189 {
190 Record *record = data;
191
192 g_clear_object (&record->recording);
193 dex_clear (&record->cancellable);
194 g_free (record);
195 }
196
197 static DexFuture *
198 sysprof_memory_usage_record_fiber (gpointer user_data)
199 {
200 g_autoptr(GByteArray) buf = NULL;
201 Record *record = user_data;
202 SysprofCaptureWriter *writer;
203 g_autoptr(GError) error = NULL;
204 SysprofCaptureCounter counters[11];
205 MemStat st;
206 guint counter_base;
207 g_autofree guint *counter_ids = g_new0 (guint, 11);
208 g_autofree SysprofCaptureCounterValue *values = g_new0 (SysprofCaptureCounterValue, 11);
209
210 g_assert (record != NULL);
211 g_assert (SYSPROF_IS_RECORDING (record->recording));
212 g_assert (DEX_IS_FUTURE (record->cancellable));
213
214 buf = g_byte_array_new ();
215 g_byte_array_set_size (buf, 4096);
216
217 writer = _sysprof_recording_writer (record->recording);
218
219 if (!mem_stat_open (&st, &error))
220 return dex_future_new_for_error (g_steal_pointer (&error));
221
222 counter_base = sysprof_capture_writer_request_counter (writer, 11);
223
224 for (guint i = 0; i < 11; i++)
225 {
226 g_strlcpy (counters[i].category, "Memory", sizeof counters[i].category);
227 g_strlcpy (counters[i].name, counter_names[i], sizeof counters[i].name);
228 g_strlcpy (counters[i].description, "", sizeof counters[0].description);
229 counters[i].id = counter_base + i;
230 counters[i].type = SYSPROF_CAPTURE_COUNTER_INT64;
231 counters[i].value.v64 = 0;
232 }
233
234 sysprof_capture_writer_define_counters (writer,
235 SYSPROF_CAPTURE_CURRENT_TIME,
236 -1,
237 -1,
238 counters,
239 11);
240
241 for (guint i = 0; i < 11; i++)
242 counter_ids[i] = counter_base + i;
243
244 for (;;)
245 {
246 g_autoptr(DexFuture) read_future = dex_aio_read (NULL, st.stat_fd, buf->data, buf->len-1, 0);
247 gssize n_read;
248
249 dex_await (dex_future_first (dex_ref (read_future),
250 dex_ref (record->cancellable),
251 NULL),
252 NULL);
253
254 if (dex_future_get_status (read_future) != DEX_FUTURE_STATUS_RESOLVED)
255 break;
256
257 n_read = dex_await_int64 (dex_ref (read_future), NULL);
258 if (n_read <= 0)
259 break;
260
261 if (n_read > 0)
262 {
263 buf->data[n_read] = 0;
264
265 mem_stat_parse (&st, (char *)buf->data);
266
267 sysprof_capture_writer_set_counters (writer,
268 SYSPROF_CAPTURE_CURRENT_TIME,
269 -1,
270 -1,
271 counter_ids,
272 st.values,
273 11);
274 }
275
276 dex_await (dex_future_first (dex_ref (record->cancellable),
277 dex_timeout_new_usec (G_USEC_PER_SEC / 2),
278 NULL),
279 NULL);
280
281 if (dex_future_get_status (record->cancellable) == DEX_FUTURE_STATUS_REJECTED)
282 break;
283 }
284
285 if (!mem_stat_close (&st, &error))
286 return dex_future_new_for_error (g_steal_pointer (&error));
287
288 return dex_future_new_for_boolean (TRUE);
289 }
290
291 static DexFuture *
292 sysprof_memory_usage_record (SysprofInstrument *instrument,
293 SysprofRecording *recording,
294 GCancellable *cancellable)
295 {
296 Record *record;
297
298 g_assert (SYSPROF_IS_MEMORY_USAGE (instrument));
299 g_assert (SYSPROF_IS_RECORDING (recording));
300 g_assert (G_IS_CANCELLABLE (cancellable));
301
302 record = g_new0 (Record, 1);
303 record->recording = g_object_ref (recording);
304 record->cancellable = dex_cancellable_new_from_cancellable (cancellable);
305
306 return dex_scheduler_spawn (NULL, 0,
307 sysprof_memory_usage_record_fiber,
308 record,
309 record_free);
310 }
311
312 static void
313 sysprof_memory_usage_class_init (SysprofMemoryUsageClass *klass)
314 {
315 SysprofInstrumentClass *instrument_class = SYSPROF_INSTRUMENT_CLASS (klass);
316
317 instrument_class->record = sysprof_memory_usage_record;
318
319 keys = g_hash_table_new (g_str_hash, g_str_equal);
320
321 #define ADD_OFFSET(n,o) \
322 g_hash_table_insert (keys, (gchar *)n, GUINT_TO_POINTER (o))
323 ADD_OFFSET ("MemTotal", G_STRUCT_OFFSET (MemStat, sys.total));
324 ADD_OFFSET ("MemFree", G_STRUCT_OFFSET (MemStat, sys.free));
325 ADD_OFFSET ("MemAvailable", G_STRUCT_OFFSET (MemStat, sys.avail));
326 ADD_OFFSET ("Buffers", G_STRUCT_OFFSET (MemStat, sys.buffers));
327 ADD_OFFSET ("Cached", G_STRUCT_OFFSET (MemStat, sys.cached));
328 ADD_OFFSET ("SwapCached", G_STRUCT_OFFSET (MemStat, sys.swap_cached));
329 ADD_OFFSET ("Mapped", G_STRUCT_OFFSET (MemStat, sys.mapped));
330 ADD_OFFSET ("Shmem", G_STRUCT_OFFSET (MemStat, sys.shmem));
331 ADD_OFFSET ("SwapTotal", G_STRUCT_OFFSET (MemStat, sys.swap_total));
332 ADD_OFFSET ("SwapFree", G_STRUCT_OFFSET (MemStat, sys.swap_free));
333 #undef ADD_OFFSET
334 }
335
336 static void
337 sysprof_memory_usage_init (SysprofMemoryUsage *self)
338 {
339 }
340
341 SysprofInstrument *
342 sysprof_memory_usage_new (void)
343 {
344 return g_object_new (SYSPROF_TYPE_MEMORY_USAGE, NULL);
345 }