virsystemd.c 14.1 KB
Newer Older
1 2 3
/*
 * virsystemd.c: helpers for using systemd APIs
 *
4
 * Copyright (C) 2013, 2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 */

#include <config.h>

24 25 26 27
#ifdef WITH_SYSTEMD_DAEMON
# include <systemd/sd-daemon.h>
#endif

28
#include "virsystemd.h"
29
#include "viratomic.h"
30 31 32 33
#include "virdbus.h"
#include "virstring.h"
#include "viralloc.h"
#include "virutil.h"
34
#include "virlog.h"
35
#include "virerror.h"
36 37 38

#define VIR_FROM_THIS VIR_FROM_SYSTEMD

39
VIR_LOG_INIT("util.systemd");
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

static void virSystemdEscapeName(virBufferPtr buf,
                                 const char *name)
{
    static const char hextable[16] = "0123456789abcdef";

#define ESCAPE(c)                                                       \
    do {                                                                \
        virBufferAddChar(buf, '\\');                                    \
        virBufferAddChar(buf, 'x');                                     \
        virBufferAddChar(buf, hextable[(c >> 4) & 15]);                 \
        virBufferAddChar(buf, hextable[c & 15]);                        \
    } while (0)

#define VALID_CHARS                             \
        "0123456789"                            \
        "abcdefghijklmnopqrstuvwxyz"            \
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            \
        ":-_.\\"

    if (*name == '.') {
        ESCAPE(*name);
        name++;
    }

    while (*name) {
        if (*name == '/')
            virBufferAddChar(buf, '-');
        else if (*name == '-' ||
                 *name == '\\' ||
                 !strchr(VALID_CHARS, *name))
            ESCAPE(*name);
        else
            virBufferAddChar(buf, *name);
        name++;
    }

#undef ESCAPE
#undef VALID_CHARS
}


char *virSystemdMakeScopeName(const char *name,
                              const char *drivername,
                              const char *partition)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (*partition == '/')
        partition++;

    virSystemdEscapeName(&buf, partition);
    virBufferAddChar(&buf, '-');
    virSystemdEscapeName(&buf, drivername);
    virBufferAddLit(&buf, "\\x2d");
    virSystemdEscapeName(&buf, name);
    virBufferAddLit(&buf, ".scope");

98
    if (virBufferCheckError(&buf) < 0)
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        return NULL;

    return virBufferContentAndReset(&buf);
}


char *virSystemdMakeSliceName(const char *partition)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (*partition == '/')
        partition++;

    virSystemdEscapeName(&buf, partition);
    virBufferAddLit(&buf, ".slice");

115
    if (virBufferCheckError(&buf) < 0)
116 117 118 119 120
        return NULL;

    return virBufferContentAndReset(&buf);
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
char *virSystemdMakeMachineName(const char *name,
                                const char *drivername,
                                bool privileged)
{
    char *machinename = NULL;
    char *username = NULL;
    if (privileged) {
        if (virAsprintf(&machinename, "%s-%s", drivername, name) < 0)
            goto cleanup;
    } else {
        if (!(username = virGetUserName(geteuid())))
            goto cleanup;
        if (virAsprintf(&machinename, "%s-%s-%s", username, drivername, name) < 0)
            goto cleanup;
    }

137
 cleanup:
138 139 140 141
    VIR_FREE(username);

    return machinename;
}
142

143 144 145 146 147 148 149 150
/**
 * virSystemdCreateMachine:
 * @name: driver unique name of the machine
 * @drivername: name of the virt driver
 * @privileged: whether driver is running privileged or per user
 * @uuid: globally unique UUID of the machine
 * @rootdir: root directory of machine filesystem
 * @pidleader: PID of the leader process
151 152 153 154
 * @iscontainer: true if a container, false if a VM
 * @nnicindexes: number of network interface indexes in list
 * @nicindexes: list of network interface indexes
 * @partition: name of the slice to place the machine in
155 156
 *
 * Returns 0 on success, -1 on fatal error, or -2 if systemd-machine is not available
157 158 159 160 161 162 163 164
 */
int virSystemdCreateMachine(const char *name,
                            const char *drivername,
                            bool privileged,
                            const unsigned char *uuid,
                            const char *rootdir,
                            pid_t pidleader,
                            bool iscontainer,
165 166
                            size_t nnicindexes,
                            int *nicindexes,
167 168
                            const char *partition)
{
169
    int ret;
170 171 172 173
    DBusConnection *conn;
    char *machinename = NULL;
    char *creatorname = NULL;
    char *slicename = NULL;
174
    static int hasCreateWithNetwork = 1;
175

176 177 178
    ret = virDBusIsServiceEnabled("org.freedesktop.machine1");
    if (ret < 0)
        return ret;
179

180 181 182
    if ((ret = virDBusIsServiceRegistered("org.freedesktop.systemd1")) < 0)
        return ret;

183 184
    if (!(conn = virDBusGetSystemBus()))
        return -1;
185

186
    ret = -1;
187 188
    if (!(machinename = virSystemdMakeMachineName(name, drivername, privileged)))
        goto cleanup;
189 190 191 192 193

    if (virAsprintf(&creatorname, "libvirt-%s", drivername) < 0)
        goto cleanup;

    if (partition) {
194 195
        if (!(slicename = virSystemdMakeSliceName(partition)))
             goto cleanup;
196 197 198 199 200 201
    } else {
        if (VIR_STRDUP(slicename, "") < 0)
            goto cleanup;
    }

    /*
202 203 204 205 206 207 208 209 210 211 212 213
     * The systemd DBus APIs we're invoking have the
     * following signature(s)
     *
     * CreateMachineWithNetwork(in  s name,
     *                          in  ay id,
     *                          in  s service,
     *                          in  s class,
     *                          in  u leader,
     *                          in  s root_directory,
     *                          in  ai nicindexes
     *                          in  a(sv) scope_properties,
     *                          out o path);
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
     *
     * CreateMachine(in  s name,
     *               in  ay id,
     *               in  s service,
     *               in  s class,
     *               in  u leader,
     *               in  s root_directory,
     *               in  a(sv) scope_properties,
     *               out o path);
     *
     * @name a host unique name for the machine. shows up
     * in 'ps' listing & similar
     *
     * @id: a UUID of the machine, ideally matching /etc/machine-id
     * for containers
     *
     * @service: identifier of the client ie "libvirt-lxc"
     *
     * @class: either the string "container" or "vm" depending
     * on the type of machine
     *
     * @leader: main PID of the machine, either the host emulator
     * process, or the 'init' PID of the container
     *
     * @root_directory: the root directory of the container, if
     * this is known & visible in the host filesystem, or empty string
     *
241 242 243
     * @nicindexes: list of network interface indexes for the
     * host end of the VETH device pairs.
     *
244 245 246 247 248 249
     * @scope_properties:an array (not a dict!) of properties that are
     * passed on to PID 1 when creating a scope unit for your machine.
     * Will allow initial settings for the cgroup & similar.
     *
     * @path: a bus path returned for the machine object created, to
     * allow further API calls to be made against the object.
250
     *
251 252
     */

253
    VIR_DEBUG("Attempting to create machine via systemd");
254
    if (virAtomicIntGet(&hasCreateWithNetwork)) {
255 256
        virError error;
        memset(&error, 0, sizeof(error));
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

        if (virDBusCallMethod(conn,
                              NULL,
                              &error,
                              "org.freedesktop.machine1",
                              "/org/freedesktop/machine1",
                              "org.freedesktop.machine1.Manager",
                              "CreateMachineWithNetwork",
                              "sayssusa&ia(sv)",
                              machinename,
                              16,
                              uuid[0], uuid[1], uuid[2], uuid[3],
                              uuid[4], uuid[5], uuid[6], uuid[7],
                              uuid[8], uuid[9], uuid[10], uuid[11],
                              uuid[12], uuid[13], uuid[14], uuid[15],
                              creatorname,
                              iscontainer ? "container" : "vm",
                              (unsigned int)pidleader,
                              rootdir ? rootdir : "",
                              nnicindexes, nicindexes,
                              3,
                              "Slice", "s", slicename,
                              "After", "as", 1, "libvirtd.service",
                              "Before", "as", 1, "libvirt-guests.service") < 0)
            goto cleanup;

283
        if (error.level == VIR_ERR_ERROR) {
284
            if (virDBusErrorIsUnknownMethod(&error)) {
285 286
                VIR_INFO("CreateMachineWithNetwork isn't supported, switching "
                         "to legacy CreateMachine method for systemd-machined");
287
                virResetError(&error);
288 289 290 291 292 293
                virAtomicIntSet(&hasCreateWithNetwork, 0);
                /* Could re-structure without Using goto, but this
                 * avoids another atomic read which would trigger
                 * another memory barrier */
                goto fallback;
            }
294 295
            virReportErrorObject(&error);
            virResetError(&error);
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
            goto cleanup;
        }
    } else {
    fallback:
        if (virDBusCallMethod(conn,
                              NULL,
                              NULL,
                              "org.freedesktop.machine1",
                              "/org/freedesktop/machine1",
                              "org.freedesktop.machine1.Manager",
                              "CreateMachine",
                              "sayssusa(sv)",
                              machinename,
                              16,
                              uuid[0], uuid[1], uuid[2], uuid[3],
                              uuid[4], uuid[5], uuid[6], uuid[7],
                              uuid[8], uuid[9], uuid[10], uuid[11],
                              uuid[12], uuid[13], uuid[14], uuid[15],
                              creatorname,
                              iscontainer ? "container" : "vm",
                              (unsigned int)pidleader,
                              rootdir ? rootdir : "",
                              3,
                              "Slice", "s", slicename,
                              "After", "as", 1, "libvirtd.service",
                              "Before", "as", 1, "libvirt-guests.service") < 0)
            goto cleanup;
    }
324 325 326

    ret = 0;

327
 cleanup:
328 329
    VIR_FREE(creatorname);
    VIR_FREE(machinename);
330
    VIR_FREE(slicename);
331 332
    return ret;
}
333 334 335 336 337 338 339 340

int virSystemdTerminateMachine(const char *name,
                               const char *drivername,
                               bool privileged)
{
    int ret;
    DBusConnection *conn;
    char *machinename = NULL;
341 342 343
    virError error;

    memset(&error, 0, sizeof(error));
344 345 346

    ret = virDBusIsServiceEnabled("org.freedesktop.machine1");
    if (ret < 0)
347
        goto cleanup;
348

349
    if ((ret = virDBusIsServiceRegistered("org.freedesktop.systemd1")) < 0)
350 351 352
        goto cleanup;

    ret = -1;
353

354
    if (!(conn = virDBusGetSystemBus()))
355
        goto cleanup;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

    if (!(machinename = virSystemdMakeMachineName(name, drivername, privileged)))
        goto cleanup;

    /*
     * The systemd DBus API we're invoking has the
     * following signature
     *
     * TerminateMachine(in  s name);
     *
     * @name a host unique name for the machine. shows up
     * in 'ps' listing & similar
     */

    VIR_DEBUG("Attempting to terminate machine via systemd");
    if (virDBusCallMethod(conn,
372
                          NULL,
373
                          &error,
374 375 376 377 378 379 380 381
                          "org.freedesktop.machine1",
                          "/org/freedesktop/machine1",
                          "org.freedesktop.machine1.Manager",
                          "TerminateMachine",
                          "s",
                          machinename) < 0)
        goto cleanup;

382 383 384 385 386 387 388
    if (error.code == VIR_ERR_ERROR &&
        !STREQ_NULLABLE("org.freedesktop.machine1.NoSuchMachine",
                        error.str1)) {
        virReportErrorObject(&error);
        goto cleanup;
    }

389 390
    ret = 0;

391
 cleanup:
392 393
    virResetError(&error);

394 395 396
    VIR_FREE(machinename);
    return ret;
}
397 398 399 400 401 402 403 404

void
virSystemdNotifyStartup(void)
{
#ifdef WITH_SYSTEMD_DAEMON
    sd_notify(0, "READY=1");
#endif
}
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

static int
virSystemdPMSupportTarget(const char *methodName, bool *result)
{
    int ret;
    DBusConnection *conn;
    DBusMessage *message = NULL;
    char *response;

    ret = virDBusIsServiceEnabled("org.freedesktop.login1");
    if (ret < 0)
        return ret;

    if ((ret = virDBusIsServiceRegistered("org.freedesktop.login1")) < 0)
        return ret;

    if (!(conn = virDBusGetSystemBus()))
        return -1;

    ret = -1;

    if (virDBusCallMethod(conn,
                          &message,
                          NULL,
                          "org.freedesktop.login1",
                          "/org/freedesktop/login1",
                          "org.freedesktop.login1.Manager",
                          methodName,
                          NULL) < 0)
        return ret;

    if ((ret = virDBusMessageRead(message, "s", &response)) < 0)
        goto cleanup;

    *result = STREQ("yes", response) || STREQ("challenge", response);

    ret = 0;

 cleanup:
444
    virDBusMessageUnref(message);
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    VIR_FREE(response);

    return ret;
}

int virSystemdCanSuspend(bool *result)
{
    return virSystemdPMSupportTarget("CanSuspend", result);
}

int virSystemdCanHibernate(bool *result)
{
    return virSystemdPMSupportTarget("CanHibernate", result);
}

int virSystemdCanHybridSleep(bool *result)
{
    return virSystemdPMSupportTarget("CanHybridSleep", result);
}