lxc_process.c 47.4 KB
Newer Older
1
/*
2
 * Copyright (C) 2010-2014 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright IBM Corp. 2008
 *
 * lxc_process.c: LXC process lifecycle management
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23
 */

#include <config.h>

G
Guido Günther 已提交
24
#include <sys/stat.h>
25 26 27 28 29 30 31
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#include "lxc_process.h"
#include "lxc_domain.h"
#include "lxc_container.h"
32
#include "lxc_cgroup.h"
G
Gao feng 已提交
33
#include "lxc_fuse.h"
34 35 36 37 38 39 40 41 42
#include "datatypes.h"
#include "virfile.h"
#include "virpidfile.h"
#include "virnetdev.h"
#include "virnetdevveth.h"
#include "virnetdevbridge.h"
#include "virtime.h"
#include "domain_nwfilter.h"
#include "network/bridge_driver.h"
43
#include "viralloc.h"
44
#include "domain_audit.h"
45
#include "virerror.h"
46
#include "virlog.h"
47
#include "vircommand.h"
48
#include "lxc_hostdev.h"
49
#include "virhook.h"
50
#include "virstring.h"
51
#include "viratomic.h"
52
#include "virprocess.h"
53
#include "virsystemd.h"
54 55 56

#define VIR_FROM_THIS VIR_FROM_LXC

57 58
VIR_LOG_INIT("lxc.lxc_process");

59 60
#define START_POSTFIX ": starting up\n"

61 62 63 64
static virDomainObjPtr
lxcProcessAutoDestroy(virDomainObjPtr dom,
                      virConnectPtr conn,
                      void *opaque)
65
{
66
    virLXCDriverPtr driver = opaque;
67
    virObjectEventPtr event = NULL;
68
    virLXCDomainObjPrivatePtr priv;
69

70
    VIR_DEBUG("driver=%p dom=%s conn=%p", driver, dom->def->name, conn);
71

72
    priv = dom->privateData;
73
    VIR_DEBUG("Killing domain");
74
    virLXCProcessStop(driver, dom, VIR_DOMAIN_SHUTOFF_DESTROYED);
75
    virDomainAuditStop(dom, "destroyed");
76
    event = virDomainEventLifecycleNewFromObj(dom,
77 78
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
79
    priv->doneStopEvent = true;
80

J
John Ferlan 已提交
81
    if (!dom->persistent) {
82 83 84
        virDomainObjListRemove(driver->domains, dom);
        dom = NULL;
    }
85 86

    if (event)
87
        virObjectEventStateQueue(driver->domainEventState, event);
88 89

    return dom;
90 91 92 93 94
}

/*
 * Precondition: driver is locked
 */
95 96 97 98
static int
virLXCProcessReboot(virLXCDriverPtr driver,
                    virDomainObjPtr vm)
{
99
    virConnectPtr conn = virCloseCallbacksGetConn(driver->closeCallbacks, vm);
100 101 102 103 104
    int reason = vm->state.reason;
    bool autodestroy = false;
    int ret = -1;
    virDomainDefPtr savedDef;

105 106
    VIR_DEBUG("Faking reboot");

107
    if (conn) {
108
        virObjectRef(conn);
109 110 111 112 113 114 115 116 117 118 119 120 121 122
        autodestroy = true;
    } else {
        conn = virConnectOpen("lxc:///");
        /* Ignoring NULL conn which is mostly harmless here */
    }

    /* In a reboot scenario, we need to make sure we continue
     * to use the current 'def', and not switch to 'newDef'.
     * So temporarily hide the newDef and then reinstate it
     */
    savedDef = vm->newDef;
    vm->newDef = NULL;
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
    vm->newDef = savedDef;
123 124
    if (virLXCProcessStart(conn, driver, vm,
                           0, NULL, autodestroy, reason) < 0) {
125 126 127 128 129 130 131
        VIR_WARN("Unable to handle reboot of vm %s",
                 vm->def->name);
        goto cleanup;
    }

    ret = 0;

132
 cleanup:
133
    virObjectUnref(conn);
134 135 136
    return ret;
}

137 138

/**
139
 * virLXCProcessCleanup:
140 141 142 143 144 145 146
 * @driver: pointer to driver structure
 * @vm: pointer to VM to clean up
 * @reason: reason for switching the VM to shutoff state
 *
 * Cleanout resources associated with the now dead VM
 *
 */
147
static void virLXCProcessCleanup(virLXCDriverPtr driver,
148 149
                                 virDomainObjPtr vm,
                                 virDomainShutoffReason reason)
150
{
151
    size_t i;
152
    virLXCDomainObjPrivatePtr priv = vm->privateData;
153
    virNetDevVPortProfilePtr vport = NULL;
154
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
155

156 157 158
    VIR_DEBUG("Stopping VM name=%s pid=%d reason=%d",
              vm->def->name, (int)vm->pid, (int)reason);

159 160 161 162 163 164 165 166 167 168 169 170
    /* now that we know it's stopped call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);

        /* we can't stop the operation even if the script raised an error */
        virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                    VIR_HOOK_LXC_OP_STOPPED, VIR_HOOK_SUBOP_END,
                    NULL, xml, NULL);
        VIR_FREE(xml);
    }

    /* Stop autodestroy in case guest is restarted */
171 172
    virCloseCallbacksUnset(driver->closeCallbacks, vm,
                           lxcProcessAutoDestroy);
173

174 175
    if (priv->monitor) {
        virLXCMonitorClose(priv->monitor);
176
        virObjectUnref(priv->monitor);
177 178
        priv->monitor = NULL;
    }
179

180 181
    virPidFileDelete(cfg->stateDir, vm->def->name);
    virDomainDeleteConfig(cfg->stateDir, NULL, vm);
182 183 184 185 186

    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
    vm->pid = -1;
    vm->def->id = -1;

187
    if (virAtomicIntDecAndTest(&driver->nactive) && driver->inhibitCallback)
188 189
        driver->inhibitCallback(false, driver->inhibitOpaque);

190 191
    virLXCDomainReAttachHostDevices(driver, vm->def);

192
    for (i = 0; i < vm->def->nnets; i++) {
193 194
        virDomainNetDefPtr iface = vm->def->nets[i];
        vport = virDomainNetGetActualVirtPortProfile(iface);
195 196 197 198 199 200 201 202
        if (iface->ifname) {
            if (vport &&
                vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
                ignore_value(virNetDevOpenvswitchRemovePort(
                                virDomainNetGetActualBridgeName(iface),
                                iface->ifname));
            ignore_value(virNetDevVethDelete(iface->ifname));
        }
203
        networkReleaseActualDevice(vm->def, iface);
204 205 206 207
    }

    virDomainConfVMNWFilterTeardown(vm);

208 209 210
    if (priv->cgroup) {
        virCgroupRemove(priv->cgroup);
        virCgroupFree(&priv->cgroup);
211 212
    }

213 214 215 216 217 218 219
    /* Get machined to terminate the machine as it may not have cleaned it
     * properly. See https://bugs.freedesktop.org/show_bug.cgi?id=68370 for
     * the bug we are working around here.
     */
    virSystemdTerminateMachine(vm->def->name, "lxc", true);


220
    /* The "release" hook cleans up additional resources */
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);

        /* we can't stop the operation even if the script raised an error */
        virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                    VIR_HOOK_LXC_OP_RELEASE, VIR_HOOK_SUBOP_END,
                    NULL, xml, NULL);
        VIR_FREE(xml);
    }

    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
237
    virObjectUnref(cfg);
238 239 240
}


241 242 243 244
char *virLXCProcessSetupInterfaceBridged(virConnectPtr conn,
                                         virDomainDefPtr vm,
                                         virDomainNetDefPtr net,
                                         const char *brname)
245
{
246
    char *ret = NULL;
247 248
    char *parentVeth;
    char *containerVeth = NULL;
249
    virNetDevVPortProfilePtr vport = virDomainNetGetActualVirtPortProfile(net);
250 251 252 253 254 255 256 257 258 259 260 261 262

    VIR_DEBUG("calling vethCreate()");
    parentVeth = net->ifname;
    if (virNetDevVethCreate(&parentVeth, &containerVeth) < 0)
        goto cleanup;
    VIR_DEBUG("parentVeth: %s, containerVeth: %s", parentVeth, containerVeth);

    if (net->ifname == NULL)
        net->ifname = parentVeth;

    if (virNetDevSetMAC(containerVeth, &net->mac) < 0)
        goto cleanup;

263 264 265 266 267 268 269 270
    if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH) {
        if (virNetDevOpenvswitchAddPort(brname, parentVeth, &net->mac,
                                        vm->uuid, vport, virDomainNetGetActualVlan(net)) < 0)
            goto cleanup;
    } else {
        if (virNetDevBridgeAddPort(brname, parentVeth) < 0)
            goto cleanup;
    }
271 272 273 274 275

    if (virNetDevSetOnline(parentVeth, true) < 0)
        goto cleanup;

    if (virNetDevBandwidthSet(net->ifname,
276 277
                              virDomainNetGetActualBandwidth(net),
                              false) < 0) {
278 279 280
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot set bandwidth limits on %s"),
                       net->ifname);
281 282 283 284 285 286 287
        goto cleanup;
    }

    if (net->filter &&
        virDomainConfNWFilterInstantiate(conn, vm->uuid, net) < 0)
        goto cleanup;

288
    ret = containerVeth;
289

290
 cleanup:
291 292 293 294
    return ret;
}


295 296 297
char *virLXCProcessSetupInterfaceDirect(virConnectPtr conn,
                                        virDomainDefPtr def,
                                        virDomainNetDefPtr net)
298
{
299
    char *ret = NULL;
300
    char *res_ifname = NULL;
301
    virLXCDriverPtr driver = conn->privateData;
302 303
    virNetDevBandwidthPtr bw;
    virNetDevVPortProfilePtr prof;
304
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
305 306 307 308 309 310 311 312

    /* XXX how todo bandwidth controls ?
     * Since the 'net-ifname' is about to be moved to a different
     * namespace & renamed, there will be no host side visible
     * interface for the container to attach rules to
     */
    bw = virDomainNetGetActualBandwidth(net);
    if (bw) {
313 314
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Unable to set network bandwidth on direct interfaces"));
315
        return NULL;
316 317 318 319 320 321 322 323 324 325 326
    }

    /* XXX how todo port profiles ?
     * Although we can do the association during container
     * startup, at shutdown we are unable to disassociate
     * because the macvlan device was moved to the container
     * and automagically dies when the container dies. So
     * we have no dev to perform disassociation with.
     */
    prof = virDomainNetGetActualVirtPortProfile(net);
    if (prof) {
327 328
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Unable to set port profile on direct interfaces"));
329
        return NULL;
330 331 332 333 334 335 336 337 338 339
    }

    if (virNetDevMacVLanCreateWithVPortProfile(
            net->ifname, &net->mac,
            virDomainNetGetActualDirectDev(net),
            virDomainNetGetActualDirectMode(net),
            false, false, def->uuid,
            virDomainNetGetActualVirtPortProfile(net),
            &res_ifname,
            VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
340
            cfg->stateDir,
341 342 343
            virDomainNetGetActualBandwidth(net)) < 0)
        goto cleanup;

344
    ret = res_ifname;
345

346
 cleanup:
347
    virObjectUnref(cfg);
348 349 350 351 352
    return ret;
}


/**
353
 * virLXCProcessSetupInterfaces:
354 355 356 357 358 359 360 361 362 363 364
 * @conn: pointer to connection
 * @def: pointer to virtual machine structure
 * @nveths: number of interfaces
 * @veths: interface names
 *
 * Sets up the container interfaces by creating the veth device pairs and
 * attaching the parent end to the appropriate bridge.  The container end
 * will moved into the container namespace later after clone has been called.
 *
 * Returns 0 on success or -1 in case of error
 */
365 366
static int virLXCProcessSetupInterfaces(virConnectPtr conn,
                                        virDomainDefPtr def,
367
                                        size_t *nveths,
368
                                        char ***veths)
369 370 371 372
{
    int ret = -1;
    size_t i;

373
    for (i = 0; i < def->nnets; i++) {
374
        char *veth = NULL;
375 376 377 378
        /* If appropriate, grab a physical device from the configured
         * network's pool of devices, or resolve bridge device name
         * to the one defined in the network definition.
         */
379
        if (networkAllocateActualDevice(def, def->nets[i]) < 0)
380 381
            goto cleanup;

382
        if (VIR_EXPAND_N(*veths, *nveths, 1) < 0)
383 384
            goto cleanup;

385 386 387 388
        switch (virDomainNetGetActualType(def->nets[i])) {
        case VIR_DOMAIN_NET_TYPE_NETWORK: {
            virNetworkPtr network;
            char *brname = NULL;
389 390
            bool fail = false;
            virErrorPtr errobj;
391 392 393 394

            if (!(network = virNetworkLookupByName(conn,
                                                   def->nets[i]->data.network.name)))
                goto cleanup;
395 396
            if (!(brname = virNetworkGetBridgeName(network)))
               fail = true;
397 398 399

            /* Make sure any above failure is preserved */
            errobj = virSaveLastError();
400
            virNetworkFree(network);
401 402 403 404
            virSetError(errobj);
            virFreeError(errobj);

            if (fail)
405 406
                goto cleanup;

407 408 409 410
            if (!(veth = virLXCProcessSetupInterfaceBridged(conn,
                                                            def,
                                                            def->nets[i],
                                                            brname))) {
411 412 413 414 415 416 417 418 419
                VIR_FREE(brname);
                goto cleanup;
            }
            VIR_FREE(brname);
            break;
        }
        case VIR_DOMAIN_NET_TYPE_BRIDGE: {
            const char *brname = virDomainNetGetActualBridgeName(def->nets[i]);
            if (!brname) {
420 421
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("No bridge name specified"));
422 423
                goto cleanup;
            }
424 425 426 427
            if (!(veth = virLXCProcessSetupInterfaceBridged(conn,
                                                            def,
                                                            def->nets[i],
                                                            brname)))
428 429 430 431
                goto cleanup;
        }   break;

        case VIR_DOMAIN_NET_TYPE_DIRECT:
432 433 434
            if (!(veth = virLXCProcessSetupInterfaceDirect(conn,
                                                           def,
                                                           def->nets[i])))
435 436 437 438 439
                goto cleanup;
            break;

        case VIR_DOMAIN_NET_TYPE_USER:
        case VIR_DOMAIN_NET_TYPE_ETHERNET:
M
Michele Paolino 已提交
440
        case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
441 442 443 444 445
        case VIR_DOMAIN_NET_TYPE_SERVER:
        case VIR_DOMAIN_NET_TYPE_CLIENT:
        case VIR_DOMAIN_NET_TYPE_MCAST:
        case VIR_DOMAIN_NET_TYPE_INTERNAL:
        case VIR_DOMAIN_NET_TYPE_LAST:
446 447 448 449 450
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unsupported network type %s"),
                           virDomainNetTypeToString(
                               virDomainNetGetActualType(def->nets[i])
                               ));
451 452
            goto cleanup;
        }
453 454

        (*veths)[(*nveths)-1] = veth;
455 456
    }

457
    ret = 0;
458

459
 cleanup:
460
    if (ret < 0) {
461
        for (i = 0; i < def->nnets; i++) {
462 463 464 465 466 467
            virDomainNetDefPtr iface = def->nets[i];
            virNetDevVPortProfilePtr vport = virDomainNetGetActualVirtPortProfile(iface);
            if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
                ignore_value(virNetDevOpenvswitchRemovePort(
                                virDomainNetGetActualBridgeName(iface),
                                iface->ifname));
468
            networkReleaseActualDevice(def, iface);
469 470 471 472 473 474
        }
    }
    return ret;
}


475
extern virLXCDriverPtr lxc_driver;
476
static void virLXCProcessMonitorEOFNotify(virLXCMonitorPtr mon,
477
                                          virDomainObjPtr vm)
478 479
{
    virLXCDriverPtr driver = lxc_driver;
480
    virObjectEventPtr event = NULL;
481 482
    virLXCDomainObjPrivatePtr priv;

483 484
    VIR_DEBUG("mon=%p vm=%p", mon, vm);

485
    virObjectLock(vm);
486 487 488

    priv = vm->privateData;
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
489 490 491
    if (!priv->wantReboot) {
        virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
        if (!priv->doneStopEvent) {
492
            event = virDomainEventLifecycleNewFromObj(vm,
493 494 495 496 497 498 499
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             priv->stopReason);
            virDomainAuditStop(vm, "shutdown");
        } else {
            VIR_DEBUG("Stop event has already been sent");
        }
        if (!vm->persistent) {
500
            virDomainObjListRemove(driver->domains, vm);
501 502
            vm = NULL;
        }
503
    } else {
504 505 506 507 508 509
        int ret = virLXCProcessReboot(driver, vm);
        virDomainAuditStop(vm, "reboot");
        virDomainAuditStart(vm, "reboot", ret == 0);
        if (ret == 0) {
            event = virDomainEventRebootNewFromObj(vm);
        } else {
510
            event = virDomainEventLifecycleNewFromObj(vm,
511 512 513
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             priv->stopReason);
            if (!vm->persistent) {
514
                virDomainObjListRemove(driver->domains, vm);
515 516 517
                vm = NULL;
            }
        }
518 519 520
    }

    if (vm)
521
        virObjectUnlock(vm);
522
    if (event) {
523
        virObjectEventStateQueue(driver->domainEventState, event);
524 525 526
    }
}

527
static void virLXCProcessMonitorExitNotify(virLXCMonitorPtr mon ATTRIBUTE_UNUSED,
528
                                           virLXCMonitorExitStatus status,
529 530 531 532
                                           virDomainObjPtr vm)
{
    virLXCDomainObjPrivatePtr priv = vm->privateData;

533 534
    virObjectLock(vm);

535
    switch (status) {
536
    case VIR_LXC_MONITOR_EXIT_STATUS_SHUTDOWN:
537 538
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
        break;
539
    case VIR_LXC_MONITOR_EXIT_STATUS_ERROR:
540 541
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
        break;
542
    case VIR_LXC_MONITOR_EXIT_STATUS_REBOOT:
543 544 545
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
        priv->wantReboot = true;
        break;
546 547 548 549 550 551
    default:
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
        break;
    }
    VIR_DEBUG("Domain shutoff reason %d (from status %d)",
              priv->stopReason, status);
552 553

    virObjectUnlock(vm);
554
}
555

556 557 558 559 560 561 562 563 564 565
static int
virLXCProcessGetNsInode(pid_t pid,
                        const char *nsname,
                        ino_t *inode)
{
    char *path = NULL;
    struct stat sb;
    int ret = -1;

    if (virAsprintf(&path, "/proc/%llu/ns/%s",
566
                    (unsigned long long)pid, nsname) < 0)
567 568 569 570 571 572 573 574 575 576 577
        goto cleanup;

    if (stat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("Unable to stat %s"), path);
        goto cleanup;
    }

    *inode = sb.st_ino;
    ret = 0;

578
 cleanup:
579 580 581 582 583
    VIR_FREE(path);
    return ret;
}


584 585
/* XXX a little evil */
extern virLXCDriverPtr lxc_driver;
586 587 588 589
static void virLXCProcessMonitorInitNotify(virLXCMonitorPtr mon ATTRIBUTE_UNUSED,
                                           pid_t initpid,
                                           virDomainObjPtr vm)
{
590 591
    virLXCDriverPtr driver = lxc_driver;
    virLXCDomainObjPrivatePtr priv;
592
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
593 594
    ino_t inode;

595 596 597
    virObjectLock(vm);

    priv = vm->privateData;
598
    priv->initpid = initpid;
599 600 601 602 603 604 605 606 607 608

    if (virLXCProcessGetNsInode(initpid, "pid", &inode) < 0) {
        virErrorPtr err = virGetLastError();
        VIR_WARN("Cannot obtain pid NS inode for %llu: %s",
                 (unsigned long long)initpid,
                 err && err->message ? err->message : "<unknown>");
        virResetLastError();
        inode = 0;
    }
    virDomainAuditInit(vm, initpid, inode);
609

610
    if (virDomainSaveStatus(lxc_driver->xmlopt, cfg->stateDir, vm) < 0)
611
        VIR_WARN("Cannot update XML with PID for LXC %s", vm->def->name);
612 613

    virObjectUnlock(vm);
614
    virObjectUnref(cfg);
615 616
}

617 618
static virLXCMonitorCallbacks monitorCallbacks = {
    .eofNotify = virLXCProcessMonitorEOFNotify,
619
    .exitNotify = virLXCProcessMonitorExitNotify,
620
    .initNotify = virLXCProcessMonitorInitNotify,
621
};
622

623 624 625 626 627

static virLXCMonitorPtr virLXCProcessConnectMonitor(virLXCDriverPtr driver,
                                                    virDomainObjPtr vm)
{
    virLXCMonitorPtr monitor = NULL;
628
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
629

630 631
    if (virSecurityManagerSetSocketLabel(driver->securityManager, vm->def) < 0)
        goto cleanup;
632

633 634
    /* Hold an extra reference because we can't allow 'vm' to be
     * deleted while the monitor is active */
635
    virObjectRef(vm);
636

637
    monitor = virLXCMonitorNew(vm, cfg->stateDir, &monitorCallbacks);
638 639

    if (monitor == NULL)
640
        virObjectUnref(vm);
641 642

    if (virSecurityManagerClearSocketLabel(driver->securityManager, vm->def) < 0) {
643
        if (monitor) {
644
            virObjectUnref(monitor);
645 646
            monitor = NULL;
        }
647
        goto cleanup;
648 649
    }

650
 cleanup:
651
    virObjectUnref(cfg);
652
    return monitor;
653 654 655
}


656
int virLXCProcessStop(virLXCDriverPtr driver,
657 658
                      virDomainObjPtr vm,
                      virDomainShutoffReason reason)
659 660
{
    int rc;
661
    virLXCDomainObjPrivatePtr priv;
662

663 664
    VIR_DEBUG("Stopping VM name=%s pid=%d reason=%d",
              vm->def->name, (int)vm->pid, (int)reason);
665 666 667 668 669
    if (!virDomainObjIsActive(vm)) {
        VIR_DEBUG("VM '%s' not active", vm->def->name);
        return 0;
    }

670 671
    priv = vm->privateData;

672
    if (vm->pid <= 0) {
673 674
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid PID %d for container"), vm->pid);
675 676 677 678 679 680 681
        return -1;
    }

    virSecurityManagerRestoreAllLabel(driver->securityManager,
                                      vm->def, false);
    virSecurityManagerReleaseLabel(driver->securityManager, vm->def);
    /* Clear out dynamically assigned labels */
682 683 684 685 686
    if (vm->def->nseclabels &&
        vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        VIR_FREE(vm->def->seclabels[0]->model);
        VIR_FREE(vm->def->seclabels[0]->label);
        VIR_FREE(vm->def->seclabels[0]->imagelabel);
687 688
    }

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    /* If the LXC domain is suspended we send all processes a SIGKILL
     * and thaw them. Upon wakeup the process sees the pending signal
     * and dies immediately. It is guaranteed that priv->cgroup != NULL
     * here because the domain has aleady been suspended using the
     * freezer cgroup.
     */
    if (reason == VIR_DOMAIN_SHUTOFF_DESTROYED &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
        if (virCgroupKillRecursive(priv->cgroup, SIGKILL) <= 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to kill all processes"));
            return -1;
        }

        if (virCgroupSetFreezerState(priv->cgroup, "THAWED") < 0) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Unable to thaw all processes"));

            return -1;
        }

        goto cleanup;
    }

713 714
    if (priv->cgroup) {
        rc = virCgroupKillPainfully(priv->cgroup);
715 716 717
        if (rc < 0)
            return -1;
        if (rc > 0) {
718
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
719 720
                           _("Some processes refused to die"));
            return -1;
721 722
        }
    } else {
723 724
        /* If cgroup doesn't exist, just try cleaning up the
         * libvirt_lxc process */
725 726 727 728 729
        if (virProcessKillPainfully(vm->pid, true) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Processes %d refused to die"), (int)vm->pid);
            return -1;
        }
730 731
    }

732
 cleanup:
733
    virLXCProcessCleanup(driver, vm, reason);
734

735
    return 0;
736 737 738 739
}


static virCommandPtr
740
virLXCProcessBuildControllerCmd(virLXCDriverPtr driver,
741 742 743 744 745
                                virDomainObjPtr vm,
                                int nveths,
                                char **veths,
                                int *ttyFDs,
                                size_t nttyFDs,
746 747
                                int *files,
                                size_t nfiles,
748
                                int handshakefd)
749 750 751 752 753
{
    size_t i;
    char *filterstr;
    char *outputstr;
    virCommandPtr cmd;
754
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
755 756 757 758

    cmd = virCommandNew(vm->def->emulator);

    /* The controller may call ip command, so we have to retain PATH. */
759
    virCommandAddEnvPassBlockSUID(cmd, "PATH", "/bin:/usr/bin");
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

    virCommandAddEnvFormat(cmd, "LIBVIRT_DEBUG=%d",
                           virLogGetDefaultPriority());

    if (virLogGetNbFilters() > 0) {
        filterstr = virLogGetFilters();
        if (!filterstr) {
            virReportOOMError();
            goto cleanup;
        }

        virCommandAddEnvPair(cmd, "LIBVIRT_LOG_FILTERS", filterstr);
        VIR_FREE(filterstr);
    }

775
    if (cfg->log_libvirtd) {
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
        if (virLogGetNbOutputs() > 0) {
            outputstr = virLogGetOutputs();
            if (!outputstr) {
                virReportOOMError();
                goto cleanup;
            }

            virCommandAddEnvPair(cmd, "LIBVIRT_LOG_OUTPUTS", outputstr);
            VIR_FREE(outputstr);
        }
    } else {
        virCommandAddEnvFormat(cmd,
                               "LIBVIRT_LOG_OUTPUTS=%d:stderr",
                               virLogGetDefaultPriority());
    }

    virCommandAddArgList(cmd, "--name", vm->def->name, NULL);
793
    for (i = 0; i < nttyFDs; i++) {
794 795
        virCommandAddArg(cmd, "--console");
        virCommandAddArgFormat(cmd, "%d", ttyFDs[i]);
796
        virCommandPassFD(cmd, ttyFDs[i], 0);
797 798
    }

799 800 801
    for (i = 0; i < nfiles; i++) {
        virCommandAddArg(cmd, "--passfd");
        virCommandAddArgFormat(cmd, "%d", files[i]);
802
        virCommandPassFD(cmd, files[i], 0);
803 804
    }

805 806 807 808 809 810 811
    virCommandAddArgPair(cmd, "--security",
                         virSecurityManagerGetModel(driver->securityManager));

    virCommandAddArg(cmd, "--handshake");
    virCommandAddArgFormat(cmd, "%d", handshakefd);
    virCommandAddArg(cmd, "--background");

812
    for (i = 0; i < nveths; i++) {
813 814 815
        virCommandAddArgList(cmd, "--veth", veths[i], NULL);
    }

816
    virCommandPassFD(cmd, handshakefd, 0);
817 818

    return cmd;
819
 cleanup:
820
    virCommandFree(cmd);
821
    virObjectUnref(cfg);
822 823 824
    return NULL;
}

825

826 827 828 829 830 831 832 833 834 835 836 837 838 839
static bool
virLXCProcessIgnorableLogLine(const char *str)
{
    if (virLogProbablyLogMessage(str))
        return true;
    if (strstr(str, "PATH="))
        return true;
    if (strstr(str, "error receiving signal from container"))
        return true;
    if (STREQ(str, ""))
        return true;
    return false;
}

840
static int
841 842 843 844
virLXCProcessReadLogOutputData(virDomainObjPtr vm,
                               int fd,
                               char *buf,
                               size_t buflen)
845 846
{
    int retries = 10;
847 848 849
    int got = 0;
    int ret = -1;
    char *filter_next = buf;
850

851
    buf[0] = '\0';
852 853 854

    while (retries) {
        ssize_t bytes;
855
        bool isdead = false;
856
        char *eol;
857

858 859
        if (vm->pid <= 0 ||
            (kill(vm->pid, 0) == -1 && errno == ESRCH))
860
            isdead = true;
861 862 863 864 865 866

        /* Any failures should be detected before we read the log, so we
         * always have something useful to report on failure. */
        bytes = saferead(fd, buf+got, buflen-got-1);
        if (bytes < 0) {
            virReportSystemError(errno, "%s",
867
                                 _("Failure while reading log output"));
868 869 870 871 872 873
            goto cleanup;
        }

        got += bytes;
        buf[got] = '\0';

874 875 876
        /* Filter out debug messages from intermediate libvirt process */
        while ((eol = strchr(filter_next, '\n'))) {
            *eol = '\0';
877
            if (virLXCProcessIgnorableLogLine(filter_next)) {
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
                memmove(filter_next, eol + 1, got - (eol - buf));
                got -= eol + 1 - filter_next;
            } else {
                filter_next = eol + 1;
                *eol = '\n';
            }
        }

        if (got == buflen-1) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Out of space while reading log output: %s"),
                           buf);
            goto cleanup;
        }

        if (isdead) {
            ret = got;
            goto cleanup;
896 897 898 899 900 901
        }

        usleep(100*1000);
        retries--;
    }

902 903 904
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Timed out while reading log output: %s"),
                   buf);
905

906
 cleanup:
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    return ret;
}


static int
virLXCProcessReadLogOutput(virDomainObjPtr vm,
                           char *logfile,
                           off_t pos,
                           char *buf,
                           size_t buflen)
{
    int fd = -1;
    int ret;

    if ((fd = open(logfile, O_RDONLY)) < 0) {
        virReportSystemError(errno,
                             _("Unable to open log file %s"),
                             logfile);
        return -1;
    }

    if (lseek(fd, pos, SEEK_SET) < 0) {
        virReportSystemError(errno,
                             _("Unable to seek log file %s to %llu"),
                             logfile, (unsigned long long)pos);
        VIR_FORCE_CLOSE(fd);
        return -1;
    }

    ret = virLXCProcessReadLogOutputData(vm,
                                         fd,
                                         buf,
                                         buflen);

941 942 943 944
    VIR_FORCE_CLOSE(fd);
    return ret;
}

945 946 947 948

static int
virLXCProcessEnsureRootFS(virDomainObjPtr vm)
{
949
    virDomainFSDefPtr root = virDomainGetFilesystemForTarget(vm->def, "/");
950 951 952 953 954

    if (root)
        return 0;

    if (VIR_ALLOC(root) < 0)
955
        goto error;
956 957 958

    root->type = VIR_DOMAIN_FS_TYPE_MOUNT;

959 960 961
    if (VIR_STRDUP(root->src, "/") < 0 ||
        VIR_STRDUP(root->dst, "/") < 0)
        goto error;
962

963 964 965 966 967
    if (VIR_INSERT_ELEMENT(vm->def->fss,
                           0,
                           vm->def->nfss,
                           root) < 0)
        goto error;
968 969 970

    return 0;

971
 error:
972 973 974 975
    virDomainFSDefFree(root);
    return -1;
}

976
/**
977
 * virLXCProcessStart:
978 979 980 981 982 983 984 985 986 987
 * @conn: pointer to connection
 * @driver: pointer to driver structure
 * @vm: pointer to virtual machine structure
 * @autoDestroy: mark the domain for auto destruction
 * @reason: reason for switching vm to running state
 *
 * Starts a vm
 *
 * Returns 0 on success or -1 in case of error
 */
988
int virLXCProcessStart(virConnectPtr conn,
989
                       virLXCDriverPtr  driver,
990
                       virDomainObjPtr vm,
991
                       unsigned int nfiles, int *files,
992 993
                       bool autoDestroy,
                       virDomainRunningReason reason)
994 995 996 997 998 999 1000
{
    int rc = -1, r;
    size_t nttyFDs = 0;
    int *ttyFDs = NULL;
    size_t i;
    char *logfile = NULL;
    int logfd = -1;
1001
    size_t nveths = 0;
1002 1003 1004 1005 1006 1007
    char **veths = NULL;
    int handshakefds[2] = { -1, -1 };
    off_t pos = -1;
    char ebuf[1024];
    char *timestamp;
    virCommandPtr cmd = NULL;
1008
    virLXCDomainObjPrivatePtr priv = vm->privateData;
1009
    virCapsPtr caps = NULL;
1010
    virErrorPtr err = NULL;
1011
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
1012
    virCgroupPtr selfcgroup;
1013
    int status;
1014

1015
    if (virCgroupNewSelf(&selfcgroup) < 0)
1016 1017
        return -1;

1018
    if (!virCgroupHasController(selfcgroup,
1019
                                VIR_CGROUP_CONTROLLER_CPUACCT)) {
1020
        virCgroupFree(&selfcgroup);
1021 1022
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'cpuacct' cgroups controller mount"));
1023 1024
        return -1;
    }
1025
    if (!virCgroupHasController(selfcgroup,
1026
                                VIR_CGROUP_CONTROLLER_DEVICES)) {
1027
        virCgroupFree(&selfcgroup);
1028 1029
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'devices' cgroups controller mount"));
1030 1031
        return -1;
    }
1032
    if (!virCgroupHasController(selfcgroup,
1033
                                VIR_CGROUP_CONTROLLER_MEMORY)) {
1034
        virCgroupFree(&selfcgroup);
1035 1036
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'memory' cgroups controller mount"));
1037 1038
        return -1;
    }
1039
    virCgroupFree(&selfcgroup);
1040

1041
    if (virFileMakePath(cfg->logDir) < 0) {
1042 1043
        virReportSystemError(errno,
                             _("Cannot create log directory '%s'"),
1044
                             cfg->logDir);
1045 1046 1047
        return -1;
    }

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    if (!vm->def->resource) {
        virDomainResourceDefPtr res;

        if (VIR_ALLOC(res) < 0)
            goto cleanup;

        if (VIR_STRDUP(res->partition, "/machine") < 0) {
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
    }

1062
    if (virAsprintf(&logfile, "%s/%s.log",
1063
                    cfg->logDir, vm->def->name) < 0)
1064 1065
        return -1;

1066 1067 1068
    if (!(caps = virLXCDriverGetCapabilities(driver, false)))
        goto cleanup;

1069 1070 1071 1072 1073
    /* Do this up front, so any part of the startup process can add
     * runtime state to vm->def that won't be persisted. This let's us
     * report implicit runtime defaults in the XML, like vnc listen/socket
     */
    VIR_DEBUG("Setting current domain def as transient");
1074
    if (virDomainObjSetDefTransient(caps, driver->xmlopt, vm, true) < 0)
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        goto cleanup;

    /* Run an early hook to set-up missing devices */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_PREPARE, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

1094 1095 1096
    if (virLXCProcessEnsureRootFS(vm) < 0)
        goto cleanup;

1097 1098 1099 1100 1101
    /* Must be run before security labelling */
    VIR_DEBUG("Preparing host devices");
    if (virLXCPrepareHostDevices(driver, vm->def) < 0)
        goto cleanup;

1102 1103 1104 1105 1106
    /* Here we open all the PTYs we need on the host OS side.
     * The LXC controller will open the guest OS side PTYs
     * and forward I/O between them.
     */
    nttyFDs = vm->def->nconsoles;
1107
    if (VIR_ALLOC_N(ttyFDs, nttyFDs) < 0)
1108
        goto cleanup;
1109
    for (i = 0; i < vm->def->nconsoles; i++)
1110
        ttyFDs[i] = -1;
1111 1112 1113 1114

    /* If you are using a SecurityDriver with dynamic labelling,
       then generate a security label for isolation */
    VIR_DEBUG("Generating domain security label (if required)");
1115 1116 1117
    if (vm->def->nseclabels &&
        vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DEFAULT)
        vm->def->seclabels[0]->type = VIR_DOMAIN_SECLABEL_NONE;
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    if (virSecurityManagerGenLabel(driver->securityManager, vm->def) < 0) {
        virDomainAuditSecurityLabel(vm, false);
        goto cleanup;
    }
    virDomainAuditSecurityLabel(vm, true);

    VIR_DEBUG("Setting domain security labels");
    if (virSecurityManagerSetAllLabel(driver->securityManager,
                                      vm->def, NULL) < 0)
        goto cleanup;

1130
    for (i = 0; i < vm->def->nconsoles; i++) {
1131 1132
        char *ttyPath;
        if (vm->def->consoles[i]->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
1133 1134
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Only PTY console types are supported"));
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
            goto cleanup;
        }

        if (virFileOpenTty(&ttyFDs[i], &ttyPath, 1) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Failed to allocate tty"));
            goto cleanup;
        }

        VIR_FREE(vm->def->consoles[i]->source.data.file.path);
        vm->def->consoles[i]->source.data.file.path = ttyPath;

        VIR_FREE(vm->def->consoles[i]->info.alias);
1148
        if (virAsprintf(&vm->def->consoles[i]->info.alias, "console%zu", i) < 0)
1149 1150 1151
            goto cleanup;
    }

1152
    if (virLXCProcessSetupInterfaces(conn, vm->def, &nveths, &veths) < 0)
1153 1154 1155
        goto cleanup;

    /* Save the configuration for the controller */
1156
    if (virDomainSaveConfig(cfg->stateDir, vm->def) < 0)
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        goto cleanup;

    if ((logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT,
             S_IRUSR|S_IWUSR)) < 0) {
        virReportSystemError(errno,
                             _("Failed to open '%s'"),
                             logfile);
        goto cleanup;
    }

    if (pipe(handshakefds) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to create pipe"));
        goto cleanup;
    }

1173 1174 1175 1176
    if (!(cmd = virLXCProcessBuildControllerCmd(driver,
                                                vm,
                                                nveths, veths,
                                                ttyFDs, nttyFDs,
1177
                                                files, nfiles,
1178
                                                handshakefds[1])))
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        goto cleanup;
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);

    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_START, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

    /* Log timestamp */
1201
    if ((timestamp = virTimeStringNow()) == NULL)
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
        goto cleanup;
    if (safewrite(logfd, timestamp, strlen(timestamp)) < 0 ||
        safewrite(logfd, START_POSTFIX, strlen(START_POSTFIX)) < 0) {
        VIR_WARN("Unable to write timestamp to logfile: %s",
                 virStrerror(errno, ebuf, sizeof(ebuf)));
    }
    VIR_FREE(timestamp);

    /* Log generated command line */
    virCommandWriteArgLog(cmd, logfd);
    if ((pos = lseek(logfd, 0, SEEK_END)) < 0)
        VIR_WARN("Unable to seek to end of logfile: %s",
                 virStrerror(errno, ebuf, sizeof(ebuf)));

1216
    virCommandRawStatus(cmd);
1217
    if (virCommandRun(cmd, &status) < 0)
1218 1219
        goto cleanup;

1220
    if (status != 0) {
1221 1222 1223 1224 1225 1226 1227 1228
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf,
                                       sizeof(ebuf)) <= 0) {
            if (WIFEXITED(status))
                snprintf(ebuf, sizeof(ebuf), _("unexpected exit status %d"),
                         WEXITSTATUS(status));
            else
                snprintf(ebuf, sizeof(ebuf), "%s", _("terminated abnormally"));
        }
1229 1230 1231 1232 1233 1234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("guest failed to start: %s"), ebuf);
        goto cleanup;
    }


1235 1236 1237 1238 1239 1240 1241
    if (VIR_CLOSE(handshakefds[1]) < 0) {
        virReportSystemError(errno, "%s", _("could not close handshake fd"));
        goto cleanup;
    }

    /* Connect to the controller as a client *first* because
     * this will block until the child has written their
1242
     * pid file out to disk & created their cgroup */
1243 1244 1245 1246 1247 1248 1249 1250 1251
    if (!(priv->monitor = virLXCProcessConnectMonitor(driver, vm))) {
        /* Intentionally overwrite the real monitor error message,
         * since a better one is almost always found in the logs
         */
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf, sizeof(ebuf)) > 0) {
            virResetLastError();
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), ebuf);
        }
1252
        goto cleanup;
1253
    }
1254 1255

    /* And get its pid */
1256
    if ((r = virPidFileRead(cfg->stateDir, vm->def->name, &vm->pid)) < 0) {
1257
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf, sizeof(ebuf)) > 0)
1258
            virReportError(VIR_ERR_INTERNAL_ERROR,
1259
                           _("guest failed to start: %s"), ebuf);
1260 1261 1262
        else
            virReportSystemError(-r,
                                 _("Failed to read pid file %s/%s.pid"),
1263
                                 cfg->stateDir, vm->def->name);
1264 1265 1266
        goto cleanup;
    }

1267
    if (virCgroupNewDetectMachine(vm->def->name, "lxc", vm->pid,
1268 1269 1270
                                  vm->def->resource ?
                                  vm->def->resource->partition :
                                  NULL,
1271
                                  -1, &priv->cgroup) < 0)
1272 1273
        goto error;

1274
    if (!priv->cgroup) {
1275
        virReportError(VIR_ERR_INTERNAL_ERROR,
1276
                       _("No valid cgroup for machine %s"),
1277 1278 1279 1280
                       vm->def->name);
        goto error;
    }

1281
    priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
1282
    priv->wantReboot = false;
1283 1284
    vm->def->id = vm->pid;
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, reason);
1285
    priv->doneStopEvent = false;
1286

1287
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
1288 1289
        driver->inhibitCallback(true, driver->inhibitOpaque);

1290 1291 1292
    if (lxcContainerWaitForContinue(handshakefds[0]) < 0) {
        char out[1024];

1293
        if (!(virLXCProcessReadLogOutput(vm, logfile, pos, out, 1024) < 0)) {
1294 1295
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), out);
1296 1297 1298 1299 1300 1301
        }

        goto error;
    }

    if (autoDestroy &&
1302 1303
        virCloseCallbacksSet(driver->closeCallbacks, vm,
                             conn, lxcProcessAutoDestroy) < 0)
1304 1305
        goto error;

1306
    if (virDomainObjSetDefTransient(caps, driver->xmlopt,
1307
                                    vm, false) < 0)
1308 1309 1310 1311 1312 1313 1314 1315
        goto error;

    /* Write domain status to disk.
     *
     * XXX: Earlier we wrote the plain "live" domain XML to this
     * location for the benefit of libvirt_lxc. We're now overwriting
     * it with the live status XML instead. This is a (currently
     * harmless) inconsistency we should fix one day */
1316
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
        goto error;

    /* finally we can call the 'started' hook script if any */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_STARTED, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto error;
    }

    rc = 0;

1338
 cleanup:
1339 1340 1341 1342 1343 1344 1345
    if (rc != 0 && !err)
        err = virSaveLastError();
    virCommandFree(cmd);
    if (VIR_CLOSE(logfd) < 0) {
        virReportSystemError(errno, "%s", _("could not close logfile"));
        rc = -1;
    }
1346
    for (i = 0; i < nveths; i++) {
1347
        if (rc != 0 && veths[i])
1348 1349 1350 1351
            ignore_value(virNetDevVethDelete(veths[i]));
        VIR_FREE(veths[i]);
    }
    if (rc != 0) {
1352 1353 1354 1355
        if (vm->newDef) {
            virDomainDefFree(vm->newDef);
            vm->newDef = NULL;
        }
1356
        if (priv->monitor) {
1357
            virObjectUnref(priv->monitor);
1358 1359
            priv->monitor = NULL;
        }
1360 1361 1362 1363 1364 1365
        virDomainConfVMNWFilterTeardown(vm);

        virSecurityManagerRestoreAllLabel(driver->securityManager,
                                          vm->def, false);
        virSecurityManagerReleaseLabel(driver->securityManager, vm->def);
        /* Clear out dynamically assigned labels */
1366 1367 1368 1369 1370
        if (vm->def->nseclabels &&
            vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
            VIR_FREE(vm->def->seclabels[0]->model);
            VIR_FREE(vm->def->seclabels[0]->label);
            VIR_FREE(vm->def->seclabels[0]->imagelabel);
1371 1372
        }
    }
1373
    for (i = 0; i < nttyFDs; i++)
1374 1375 1376 1377 1378
        VIR_FORCE_CLOSE(ttyFDs[i]);
    VIR_FREE(ttyFDs);
    VIR_FORCE_CLOSE(handshakefds[0]);
    VIR_FORCE_CLOSE(handshakefds[1]);
    VIR_FREE(logfile);
1379
    virObjectUnref(cfg);
1380
    virObjectUnref(caps);
1381 1382 1383 1384 1385 1386 1387 1388

    if (err) {
        virSetError(err);
        virFreeError(err);
    }

    return rc;

1389
 error:
1390
    err = virSaveLastError();
1391
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
1392 1393 1394
    goto cleanup;
}

1395
struct virLXCProcessAutostartData {
1396
    virLXCDriverPtr driver;
1397 1398 1399
    virConnectPtr conn;
};

1400 1401 1402
static int
virLXCProcessAutostartDomain(virDomainObjPtr vm,
                             void *opaque)
1403
{
1404
    const struct virLXCProcessAutostartData *data = opaque;
1405
    int ret = 0;
1406

1407
    virObjectLock(vm);
1408 1409
    if (vm->autostart &&
        !virDomainObjIsActive(vm)) {
1410 1411
        ret = virLXCProcessStart(data->conn, data->driver, vm,
                                 0, NULL, false,
1412
                                 VIR_DOMAIN_RUNNING_BOOTED);
1413 1414 1415 1416 1417 1418 1419
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                      vm->def->name,
                      err ? err->message : "");
        } else {
1420
            virObjectEventPtr event =
1421
                virDomainEventLifecycleNewFromObj(vm,
1422 1423 1424
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
1425
                virObjectEventStateQueue(data->driver->domainEventState, event);
1426 1427
        }
    }
1428
    virObjectUnlock(vm);
1429
    return ret;
1430 1431 1432 1433
}


void
1434 1435
virLXCProcessAutostartAll(virLXCDriverPtr driver)
{
1436 1437 1438 1439 1440 1441 1442 1443
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
    virConnectPtr conn = virConnectOpen("lxc:///");
    /* Ignoring NULL conn which is mostly harmless here */

1444
    struct virLXCProcessAutostartData data = { driver, conn };
1445

1446 1447 1448
    virDomainObjListForEach(driver->domains,
                            virLXCProcessAutostartDomain,
                            &data);
1449

1450
    virObjectUnref(conn);
1451 1452
}

1453 1454 1455
static int
virLXCProcessReconnectDomain(virDomainObjPtr vm,
                             void *opaque)
1456
{
1457
    virLXCDriverPtr driver = opaque;
1458
    virLXCDomainObjPrivatePtr priv;
1459
    int ret = -1;
1460

1461
    virObjectLock(vm);
1462
    VIR_DEBUG("Reconnect id=%d pid=%d state=%d", vm->def->id, vm->pid, vm->state.state);
1463 1464 1465 1466 1467 1468 1469 1470

    priv = vm->privateData;

    if (vm->pid != 0) {
        vm->def->id = vm->pid;
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNKNOWN);

1471
        if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
1472 1473
            driver->inhibitCallback(true, driver->inhibitOpaque);

1474
        if (!(priv->monitor = virLXCProcessConnectMonitor(driver, vm)))
1475 1476
            goto error;

1477
        if (virCgroupNewDetectMachine(vm->def->name, "lxc", vm->pid,
1478 1479 1480
                                      vm->def->resource ?
                                      vm->def->resource->partition :
                                      NULL,
1481
                                      -1, &priv->cgroup) < 0)
1482 1483
            goto error;

1484
        if (!priv->cgroup) {
1485
            virReportError(VIR_ERR_INTERNAL_ERROR,
1486
                           _("No valid cgroup for machine %s"),
1487 1488 1489 1490
                           vm->def->name);
            goto error;
        }

1491
        if (virLXCUpdateActiveUSBHostdevs(driver, vm->def) < 0)
1492 1493
            goto error;

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        if (virSecurityManagerReserveLabel(driver->securityManager,
                                           vm->def, vm->pid) < 0)
            goto error;

        /* now that we know it's reconnected call the hook if present */
        if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
            char *xml = virDomainDefFormat(vm->def, 0);
            int hookret;

            /* we can't stop the operation even if the script raised an error */
            hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                                  VIR_HOOK_LXC_OP_RECONNECT, VIR_HOOK_SUBOP_BEGIN,
                                  NULL, xml, NULL);
            VIR_FREE(xml);
            if (hookret < 0)
                goto error;
        }

    } else {
        vm->def->id = -1;
    }

1516
    ret = 0;
1517
 cleanup:
1518
    virObjectUnlock(vm);
1519
    return ret;
1520

1521
 error:
1522
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
1523 1524 1525 1526 1527
    virDomainAuditStop(vm, "failed");
    goto cleanup;
}


1528
int virLXCProcessReconnectAll(virLXCDriverPtr driver,
1529
                              virDomainObjListPtr doms)
1530
{
1531
    virDomainObjListForEach(doms, virLXCProcessReconnectDomain, driver);
1532 1533
    return 0;
}