aboutsummaryrefslogtreecommitdiffstats
path: root/src/systemd_manager.c
blob: e6d67f804dbdf9e233567b8875ec3a4880aa5e02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// SPDX-License-Identifier: Apache-2.0
/*
 * Copyright (C) 2022 Konsulko Group
 */

#include <stdbool.h>
#include "systemd_manager.h"
#include "utils.h"

// Pull in for sd_bus_path_encode, as there's no obvious alternative
// other than coding up a duplicate.  No other sd_bus functions should
// be used!
#include <systemd/sd-bus.h>

// gdbus generated headers
#include "systemd1_manager_interface.h"
#include "systemd1_unit_interface.h"

extern GMainLoop *main_loop;

// Object data
struct _SystemdManager {
    GObject parent_instance;

    GDBusConnection *conn;
    Systemd1Manager *proxy;

    GList *apps_list;
};

G_DEFINE_TYPE(SystemdManager, systemd_manager, G_TYPE_OBJECT);

enum {
  STARTED,
  TERMINATED,
  N_SIGNALS
};
static guint signals[N_SIGNALS];

/*
 * Application info structure, used for storing relevant data
 * in the `running_apps` list
 */
struct systemd_runtime_data {
    gchar *esc_service;
    SystemdManager *mgr;
    Systemd1Unit *proxy;
};

/*
 * Internal functions
 */

/*
 * Get app unit list
 */
static gboolean systemd_manager_enumerate_app_units(SystemdManager *self,
						    GList **units)
{
    g_return_val_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self), FALSE);
    g_return_val_if_fail(units != NULL, FALSE);

    GVariant *matched_units = NULL;
    GError *error = NULL;
    const gchar *const states[1] = { NULL }; 
    const gchar *const patterns[2] = { "agl-app*@*.service", NULL }; 
    if (!systemd1_manager_call_list_unit_files_by_patterns_sync(self->proxy,
								states,
								patterns,
								&matched_units,
								NULL,
								&error)) {
        g_critical("Failed to issue method call: %s", error ? error->message : "unspecified");
	g_error_free(error);
        goto finish;
    }

    // We expect the response GVariant to be format "a(ss)"
    GVariantIter *array;
    g_variant_get(matched_units, "a(ss)", &array);
    const char *unit;
    const char *status;
    while (g_variant_iter_loop(array, "(ss)", &unit, &status)) {
        if (!g_str_has_suffix(unit, "@.service"))
            *units = g_list_prepend(*units, g_strdup(unit));
    }
    g_variant_iter_free(array);
    g_variant_unref(matched_units);

    return TRUE;

finish:
    g_list_free_full(*units, g_free);
    *units = NULL;
    return FALSE;
}

/*
 * Get app unit description property
 */
static gboolean systemd_manager_get_app_description(SystemdManager *self,
                                                    gchar *service,
                                                    gchar **description)
{
    g_return_val_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self), FALSE);
    g_return_val_if_fail(service != NULL, FALSE);
    g_return_val_if_fail(description != NULL, FALSE);

    // Get the escaped unit name in the systemd hierarchy
    gchar *esc_service = NULL;
    sd_bus_path_encode("/org/freedesktop/systemd1/unit", service, &esc_service);

    GError *error = NULL;
    Systemd1Unit *proxy = systemd1_unit_proxy_new_sync(self->conn,
						       G_DBUS_PROXY_FLAGS_NONE,
						       "org.freedesktop.systemd1",
						       esc_service,
						       NULL,
						       &error);
    if (!proxy) {
        g_critical("Failed to create org.freedesktop.systemd1.Unit proxy: %s",
		   error ? error->message : "unspecified");
	g_error_free(error);
	goto finish;
    }

    gchar *value = systemd1_unit_dup_description(proxy);
    if (value) {
	*description = value;
    }

    g_object_unref(proxy);
    return TRUE;

finish:
    g_free(*description);
    *description = NULL;
    return FALSE;
}

/*
 * This function is executed during the object initialization. It goes through
 * all available applications on the system and creates a static list
 * containing all the relevant info (ID, name, unit, icon...) for further
 * processing.
 */
static void systemd_manager_update_applications_list(SystemdManager *self)
{
    g_auto(GStrv) dirlist = NULL;

    char *xdg_data_dirs = getenv("XDG_DATA_DIRS");
    if (xdg_data_dirs)
        dirlist = g_strsplit(getenv("XDG_DATA_DIRS"), ":", -1);

    GList *units = NULL;
    if (!systemd_manager_enumerate_app_units(self, &units)) {
        return;
    }

    GList *iterator;
    for (iterator = units; iterator != NULL; iterator = iterator->next) {
        g_autofree const gchar *app_id = NULL;
        g_autofree const gchar *icon_path = NULL;
        gchar *service = NULL;
        AppInfo *app_info = NULL;

        if (!iterator->data)
            continue;

        // Parse service and app id out of unit filename
        gchar *p = g_strrstr(iterator->data, "/");
        if (!p)
            service = iterator->data;
        else
            service = p + 1;

        g_autofree char *tmp = g_strdup(service);
        char *end = tmp + strlen(tmp);
        while (end > tmp && *end != '.') {
            --end;
        }
        if (end > tmp) {
            *end = '\0';
        } else {
            g_free(tmp);
            continue;
        }
        while (end > tmp && *end != '@') {
            --end;
        }
        if (end > tmp) {
            app_id = g_strdup(end + 1);
        }
        // Potentially handle non-template agl-app-foo.service units here

        // Try getting display name from unit Description property
        g_autofree gchar *name = NULL;
        if (!systemd_manager_get_app_description(self,
                                                 service,
                                                 &name) ||
            name == NULL) {

            // Fall back to the application ID
            g_warning("Could not retrieve Description of '%s'", service);
            name = g_strdup(app_id);
        }

        /*
         * GAppInfo retrieves the icon data but doesn't provide a way to retrieve
         * the corresponding file name, so we have to look it up by ourselves.
         */
        if (app_id && dirlist)
            icon_path = applaunchd_utils_get_icon(dirlist, app_id);

        app_info = app_info_new(app_id,
				name,
				icon_path ? icon_path : "",
				service);

        g_debug("Adding application '%s' with display name '%s'", app_id, name);
        self->apps_list = g_list_append(self->apps_list, app_info);
    }
    g_list_free_full(units, g_free);
}


/*
 * Initialization & cleanup functions
 */

static void systemd_manager_dispose(GObject *object)
{
    SystemdManager *self = APPLAUNCHD_SYSTEMD_MANAGER(object);

    g_return_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self));

    if (self->apps_list)
        g_list_free_full(g_steal_pointer(&self->apps_list), g_object_unref);

    g_object_unref(self->proxy);
    g_object_unref(self->conn);

    G_OBJECT_CLASS(systemd_manager_parent_class)->dispose(object);
}

static void systemd_manager_finalize(GObject *object)
{
    G_OBJECT_CLASS(systemd_manager_parent_class)->finalize(object);
}

static void systemd_manager_class_init(SystemdManagerClass *klass)
{
    GObjectClass *object_class = (GObjectClass *)klass;

    object_class->dispose = systemd_manager_dispose;
    object_class->finalize = systemd_manager_finalize;

    signals[STARTED] = g_signal_new("started", G_TYPE_FROM_CLASS (klass),
                                    G_SIGNAL_RUN_LAST, 0 ,
                                    NULL, NULL, NULL, G_TYPE_NONE,
                                    1, G_TYPE_STRING);

    signals[TERMINATED] = g_signal_new("terminated", G_TYPE_FROM_CLASS (klass),
                                       G_SIGNAL_RUN_LAST, 0 ,
                                       NULL, NULL, NULL, G_TYPE_NONE,
                                       1, G_TYPE_STRING);
}

static void systemd_manager_init(SystemdManager *self)
{
    GError *error = NULL;
    GDBusConnection *conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
    if (!conn) {
        g_critical("Failed to connect to D-Bus: %s", error ? error->message : "unspecified");
	g_error_free(error);
	return;
    }
    self->conn = conn;

    Systemd1Manager *proxy = systemd1_manager_proxy_new_sync(conn,
							     G_DBUS_PROXY_FLAGS_NONE,
							     "org.freedesktop.systemd1",
							     "/org/freedesktop/systemd1",
							     NULL,
							     &error);
    if (!proxy) {
        g_critical("Failed to create org.freedesktop.systemd1.Manager proxy: %s",
		   error ? error->message : "unspecified");
	g_error_free(error);
	return;
    }
    self->proxy = proxy;

    systemd_manager_update_applications_list(self);
}


/*
 * Internal callbacks
 */

/*
 * This function is called when "PropertiesChanged" signal happens for
 * the matched Unit - check its "ActiveState" to update the app status
 */
static void unit_properties_changed_cb(GDBusProxy *proxy,
				       GVariant *changed_properties,
				       const gchar* const *invalidated_properties,
				       gpointer user_data)
{
    AppInfo *app_info = user_data;
    struct systemd_runtime_data *data;

    data = app_info_get_runtime_data(app_info);
    if(!data) {
        g_critical("Couldn't find runtime data for %s!", app_info_get_app_id(app_info));
        return;
    }

    // NOTE: changed_properties and invalidated_properties are guaranteed to never be NULL
    gchar *new_state = NULL;
    bool found = false;
    if (g_variant_n_children(changed_properties) > 0) {
	GVariantIter *iter;
	const gchar *key;
	GVariant *value;

	g_variant_get(changed_properties, "a{sv}", &iter);
	while (g_variant_iter_loop (iter, "{&sv}", &key, &value)) {
	    if (!g_strcmp0(key, "ActiveState")) {
		    new_state = g_variant_dup_string(value, NULL);
		    found = true;
	    }
	}
	g_variant_iter_free(iter);
    }

    // Ignore invalidated_properties for now

    // Return if the changed property isn't "ActiveState"
    if (!found)
	return;

    if(!g_strcmp0(new_state, "inactive"))
    {
        if(app_info_get_status(app_info) != APP_STATUS_STARTING)
        {
	    g_debug("Application %s has terminated", app_info_get_app_id(app_info));
            app_info_set_status(app_info, APP_STATUS_INACTIVE);
            app_info_set_runtime_data(app_info, NULL);

            g_signal_emit(data->mgr, signals[TERMINATED], 0, app_info_get_app_id(app_info));
            systemd_manager_free_runtime_data(data);
	}
    }
    else if(!g_strcmp0(new_state, "active"))
    {
        // PropertiesChanged signal gets triggered multiple times, only handle it once
        if(app_info_get_status(app_info) != APP_STATUS_RUNNING)
        {
            g_debug("Application %s has started", app_info_get_app_id(app_info));
            app_info_set_status(app_info, APP_STATUS_RUNNING);
            g_signal_emit(data->mgr, signals[STARTED], 0, app_info_get_app_id(app_info));
        }
    }
    g_free(new_state);
}


/*
 * Public functions
 */

SystemdManager *systemd_manager_get_default(void)
{
    static SystemdManager *manager;

    /*
    * SystemdManager is a singleton, only create the object if it doesn't
    * exist already.
    */
    if (manager == NULL) {
        g_debug("Initializing app launcher service...");
        manager = g_object_new(APPLAUNCHD_TYPE_SYSTEMD_MANAGER, NULL);
        g_object_add_weak_pointer(G_OBJECT(manager), (gpointer*) &manager);
    }

    return manager;
}

void systemd_manager_connect_callbacks(SystemdManager *self,
                                       GCallback started_cb,
                                       GCallback terminated_cb,
                                       void *data)
{
    if (started_cb)
        g_signal_connect_swapped(self, "started", started_cb, data);

    if (terminated_cb)
        g_signal_connect_swapped(self, "terminated", terminated_cb, data);
}

/*
 * Search the applications list for an app which matches the provided app-id
 * and return the corresponding AppInfo object.
 */
AppInfo *systemd_manager_get_app_info(SystemdManager *self, const gchar *app_id)
{
    g_return_val_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self), NULL);

    guint len = g_list_length(self->apps_list);

    for (guint i = 0; i < len; i++) {
        AppInfo *app_info = g_list_nth_data(self->apps_list, i);

        if (g_strcmp0(app_info_get_app_id(app_info), app_id) == 0)
            return app_info;
    }

    g_warning("Unable to find application with ID '%s'", app_id);

    return NULL;
}

GList *systemd_manager_get_app_list(SystemdManager *self)
{
    g_return_val_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self), NULL);

    return self->apps_list;
}

/*
 * Start an application by executing its service.
 */
gboolean systemd_manager_start_app(SystemdManager *self,
                                   AppInfo *app_info)
{
    g_return_val_if_fail(APPLAUNCHD_IS_SYSTEMD_MANAGER(self), FALSE);
    g_return_val_if_fail(APPLAUNCHD_IS_APP_INFO(app_info), FALSE);

    AppStatus app_status = app_info_get_status(app_info);
    const gchar *app_id = app_info_get_app_id(app_info);

    switch (app_status) {
    case APP_STATUS_STARTING:
        g_debug("Application '%s' is already starting", app_id);
        return TRUE;
    case APP_STATUS_RUNNING:
        g_debug("Application '%s' is already running", app_id);

        /*
        * The application may be running in the background, notify
        * subscribers it should be activated/brought to the foreground.
        */
        g_signal_emit(self, signals[STARTED], 0, app_id);
        return TRUE;
    case APP_STATUS_INACTIVE:
        // Fall through and start the application
        break;
    default:
        g_critical("Unknown status %d for application '%s'", app_status, app_id);
        return FALSE;
    }

    gchar *esc_service = NULL;
    const gchar *service = app_info_get_service(app_info);
    struct systemd_runtime_data *runtime_data;

    runtime_data = g_new0(struct systemd_runtime_data, 1);
    if (!runtime_data) {
        g_critical("Unable to allocate runtime data structure for '%s'", app_id);
        return FALSE;
    }

    // Get the escaped unit name in the systemd hierarchy
    sd_bus_path_encode("/org/freedesktop/systemd1/unit", service, &esc_service);
    g_debug("Trying to start service '%s', unit path '%s'", service, esc_service);

    runtime_data->mgr = self;
    runtime_data->esc_service = esc_service;

    GError *error = NULL;
    Systemd1Unit *proxy = systemd1_unit_proxy_new_sync(self->conn,
						       G_DBUS_PROXY_FLAGS_NONE,
						       "org.freedesktop.systemd1",
						       esc_service,
						       NULL,
						       &error);
    if (!proxy) {
        g_critical("Failed to create org.freedesktop.systemd1.Unit proxy: %s",
		   error ? error->message : "unspecified");
	g_error_free(error);
	goto finish;
    }
    runtime_data->proxy = proxy;

    app_info_set_runtime_data(app_info, runtime_data);
    g_signal_connect(proxy,
		     "g-properties-changed",
		     G_CALLBACK(unit_properties_changed_cb),
		     app_info);

    // The application is now starting, wait for notification to mark it running
    g_debug("Application %s is now being started", app_info_get_app_id(app_info));
    app_info_set_status(app_info, APP_STATUS_STARTING);

    if (!systemd1_manager_call_start_unit_sync(self->proxy,
					       service,
					       "replace",
					       NULL,
					       NULL,
					       &error)) {

        g_critical("Failed to issue method call: %s", error ? error->message : "unspecified");
	g_error_free(error);
        goto finish;
    }

    return TRUE;

finish:
    if(runtime_data->esc_service)
        g_free(runtime_data->esc_service);
    g_free(runtime_data);
    return FALSE;
}

void systemd_manager_free_runtime_data(gpointer data)
{
    struct systemd_runtime_data *runtime_data = data;

    g_return_if_fail(runtime_data != NULL);

    g_free(runtime_data->esc_service);
    g_free(runtime_data);
}