virsystemd.c 16.3 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
#include <sys/socket.h>
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
27 28
#endif

29 30 31
#define __VIR_SYSTEMD_PRIV_H_ALLOW__ 1
#include "virsystemdpriv.h"

32
#include "virsystemd.h"
33
#include "viratomic.h"
34
#include "virbuffer.h"
35 36 37 38
#include "virdbus.h"
#include "virstring.h"
#include "viralloc.h"
#include "virutil.h"
39
#include "virlog.h"
40
#include "virerror.h"
41
#include "virfile.h"
42 43 44

#define VIR_FROM_THIS VIR_FROM_SYSTEMD

45
VIR_LOG_INIT("util.systemd");
46

47 48 49 50
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif

51
static void virSystemdEscapeName(virBufferPtr buf,
52
                                 const char *name)
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
{
    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"            \
        ":-_.\\"

70
    if (*name == '.') {
71 72 73 74 75 76 77
        ESCAPE(*name);
        name++;
    }

    while (*name) {
        if (*name == '/')
            virBufferAddChar(buf, '-');
78
        else if (*name == '-' ||
79 80 81 82 83 84 85 86 87 88 89 90 91
                 *name == '\\' ||
                 !strchr(VALID_CHARS, *name))
            ESCAPE(*name);
        else
            virBufferAddChar(buf, *name);
        name++;
    }

#undef ESCAPE
#undef VALID_CHARS
}

char *virSystemdMakeScopeName(const char *name,
92 93
                              const char *drivername,
                              bool legacy_behaviour)
94 95 96
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

97
    virBufferAddLit(&buf, "machine-");
98 99 100 101
    if (legacy_behaviour) {
        virSystemdEscapeName(&buf, drivername);
        virBufferAddLit(&buf, "\\x2d");
    }
102
    virSystemdEscapeName(&buf, name);
103 104
    virBufferAddLit(&buf, ".scope");

105
    if (virBufferCheckError(&buf) < 0)
106 107 108 109 110 111 112 113 114 115 116 117 118
        return NULL;

    return virBufferContentAndReset(&buf);
}


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

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

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

122
    if (virBufferCheckError(&buf) < 0)
123 124 125 126 127
        return NULL;

    return virBufferContentAndReset(&buf);
}

128 129 130 131 132 133 134 135 136
static int virSystemdHasMachinedCachedValue = -1;

/* Reset the cache from tests for testing the underlying dbus calls
 * as well */
void virSystemdHasMachinedResetCachedValue(void)
{
    virSystemdHasMachinedCachedValue = -1;
}

137 138 139 140 141 142 143 144
/* -2 = machine1 is not supported on this machine
 * -1 = error
 *  0 = machine1 is available
 */
static int
virSystemdHasMachined(void)
{
    int ret;
145 146 147 148 149 150 151 152 153
    int val;

    val = virAtomicIntGet(&virSystemdHasMachinedCachedValue);
    if (val != -1)
        return val;

    if ((ret = virDBusIsServiceEnabled("org.freedesktop.machine1")) < 0) {
        if (ret == -2)
            virAtomicIntSet(&virSystemdHasMachinedCachedValue, -2);
154
        return ret;
155
    }
156

157 158 159 160
    if ((ret = virDBusIsServiceRegistered("org.freedesktop.systemd1")) == -1)
        return ret;
    virAtomicIntSet(&virSystemdHasMachinedCachedValue, ret);
    return ret;
161 162
}

163 164 165 166 167

char *
virSystemdGetMachineNameByPID(pid_t pid)
{
    DBusConnection *conn;
168
    DBusMessage *reply = NULL;
169 170
    char *name = NULL, *object = NULL;

171
    if (virSystemdHasMachined() < 0)
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        goto cleanup;

    if (!(conn = virDBusGetSystemBus()))
        goto cleanup;

    if (virDBusCallMethod(conn, &reply, NULL,
                          "org.freedesktop.machine1",
                          "/org/freedesktop/machine1",
                          "org.freedesktop.machine1.Manager",
                          "GetMachineByPID",
                          "u", pid) < 0)
        goto cleanup;

    if (virDBusMessageRead(reply, "o", &object) < 0)
        goto cleanup;

188 189 190
    virDBusMessageUnref(reply);
    reply = NULL;

M
Michal Privoznik 已提交
191 192
    VIR_DEBUG("Domain with pid %lld has object path '%s'",
              (long long) pid, object);
193 194 195 196 197 198 199 200 201 202 203 204 205 206

    if (virDBusCallMethod(conn, &reply, NULL,
                          "org.freedesktop.machine1",
                          object,
                          "org.freedesktop.DBus.Properties",
                          "Get",
                          "ss",
                          "org.freedesktop.machine1.Machine",
                          "Name") < 0)
        goto cleanup;

    if (virDBusMessageRead(reply, "v", "s", &name) < 0)
        goto cleanup;

M
Michal Privoznik 已提交
207 208
    VIR_DEBUG("Domain with pid %lld has machine name '%s'",
              (long long) pid, name);
209 210 211

 cleanup:
    VIR_FREE(object);
212
    virDBusMessageUnref(reply);
213 214 215 216 217

    return name;
}


218 219 220 221 222 223 224 225
/**
 * 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
226 227 228 229
 * @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
230 231
 *
 * Returns 0 on success, -1 on fatal error, or -2 if systemd-machine is not available
232 233 234 235 236 237 238
 */
int virSystemdCreateMachine(const char *name,
                            const char *drivername,
                            const unsigned char *uuid,
                            const char *rootdir,
                            pid_t pidleader,
                            bool iscontainer,
239 240
                            size_t nnicindexes,
                            int *nicindexes,
241 242
                            const char *partition)
{
243
    int ret;
244 245 246
    DBusConnection *conn;
    char *creatorname = NULL;
    char *slicename = NULL;
247
    static int hasCreateWithNetwork = 1;
248

249
    if ((ret = virSystemdHasMachined()) < 0)
250 251
        return ret;

252 253
    if (!(conn = virDBusGetSystemBus()))
        return -1;
254

255
    ret = -1;
256 257 258 259 260

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

    if (partition) {
261 262
        if (!(slicename = virSystemdMakeSliceName(partition)))
             goto cleanup;
263 264 265 266 267 268
    } else {
        if (VIR_STRDUP(slicename, "") < 0)
            goto cleanup;
    }

    /*
269 270 271 272 273 274 275 276 277 278 279 280
     * 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);
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
     *
     * 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
     *
308 309 310
     * @nicindexes: list of network interface indexes for the
     * host end of the VETH device pairs.
     *
311 312 313 314 315 316
     * @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.
317
     *
318 319
     */

320
    VIR_DEBUG("Attempting to create machine via systemd");
321
    if (virAtomicIntGet(&hasCreateWithNetwork)) {
322 323
        virError error;
        memset(&error, 0, sizeof(error));
324 325 326 327 328 329 330 331 332

        if (virDBusCallMethod(conn,
                              NULL,
                              &error,
                              "org.freedesktop.machine1",
                              "/org/freedesktop/machine1",
                              "org.freedesktop.machine1.Manager",
                              "CreateMachineWithNetwork",
                              "sayssusa&ia(sv)",
333
                              name,
334 335 336 337 338 339 340 341 342 343 344 345 346
                              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",
347
                              "Before", "as", 1, "virt-guest-shutdown.target") < 0)
348 349
            goto cleanup;

350
        if (error.level == VIR_ERR_ERROR) {
351
            if (virDBusErrorIsUnknownMethod(&error)) {
352 353
                VIR_INFO("CreateMachineWithNetwork isn't supported, switching "
                         "to legacy CreateMachine method for systemd-machined");
354
                virResetError(&error);
355 356 357 358 359 360
                virAtomicIntSet(&hasCreateWithNetwork, 0);
                /* Could re-structure without Using goto, but this
                 * avoids another atomic read which would trigger
                 * another memory barrier */
                goto fallback;
            }
361 362
            virReportErrorObject(&error);
            virResetError(&error);
363 364 365 366 367 368 369 370 371 372 373 374
            goto cleanup;
        }
    } else {
    fallback:
        if (virDBusCallMethod(conn,
                              NULL,
                              NULL,
                              "org.freedesktop.machine1",
                              "/org/freedesktop/machine1",
                              "org.freedesktop.machine1.Manager",
                              "CreateMachine",
                              "sayssusa(sv)",
375
                              name,
376 377 378 379 380 381 382 383 384 385 386 387
                              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",
388
                              "Before", "as", 1, "virt-guest-shutdown.target") < 0)
389 390
            goto cleanup;
    }
391 392 393

    ret = 0;

394
 cleanup:
395
    VIR_FREE(creatorname);
396
    VIR_FREE(slicename);
397 398
    return ret;
}
399

400
int virSystemdTerminateMachine(const char *name)
401 402 403
{
    int ret;
    DBusConnection *conn;
404 405
    virError error;

406 407 408
    if (!name)
        return 0;

409
    memset(&error, 0, sizeof(error));
410

411
    if ((ret = virSystemdHasMachined()) < 0)
412 413 414
        goto cleanup;

    ret = -1;
415

416
    if (!(conn = virDBusGetSystemBus()))
417
        goto cleanup;
418 419 420 421 422 423 424 425 426 427 428 429 430

    /*
     * 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,
431
                          NULL,
432
                          &error,
433 434 435 436 437
                          "org.freedesktop.machine1",
                          "/org/freedesktop/machine1",
                          "org.freedesktop.machine1.Manager",
                          "TerminateMachine",
                          "s",
438
                          name) < 0)
439 440
        goto cleanup;

M
Marc Hartmayer 已提交
441
    if (error.level == VIR_ERR_ERROR &&
442
        STRNEQ_NULLABLE("org.freedesktop.machine1.NoSuchMachine",
443 444 445 446 447
                        error.str1)) {
        virReportErrorObject(&error);
        goto cleanup;
    }

448 449
    ret = 0;

450
 cleanup:
451 452
    virResetError(&error);

453 454
    return ret;
}
455 456 457 458

void
virSystemdNotifyStartup(void)
{
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
#ifdef HAVE_SYS_UN_H
    const char *path;
    const char *msg = "READY=1";
    int fd;
    struct sockaddr_un un = {
        .sun_family = AF_UNIX,
    };
    struct iovec iov = {
        .iov_base = (char *)msg,
        .iov_len = strlen(msg),
    };
    struct msghdr mh = {
        .msg_name = &un,
        .msg_iov = &iov,
        .msg_iovlen = 1,
    };

    if (!(path = virGetEnvBlockSUID("NOTIFY_SOCKET"))) {
        VIR_DEBUG("Skipping systemd notify, not requested");
        return;
    }

    /* NB sun_path field is *not* NUL-terminated, hence >, not >= */
    if (strlen(path) > sizeof(un.sun_path)) {
        VIR_WARN("Systemd notify socket path '%s' too long", path);
        return;
    }

    memcpy(un.sun_path, path, strlen(path));
    if (un.sun_path[0] == '@')
        un.sun_path[0] = '\0';

491 492
    mh.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(path);

493 494 495 496 497 498 499 500 501 502 503
    fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (fd < 0) {
        VIR_WARN("Unable to create socket FD");
        return;
    }

    if (sendmsg(fd, &mh, MSG_NOSIGNAL) < 0)
        VIR_WARN("Failed to notify systemd");

    VIR_FORCE_CLOSE(fd);
#endif /* HAVE_SYS_UN_H */
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 537 538 539 540 541 542 543

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:
544
    virDBusMessageUnref(message);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    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);
}