lxc_process.c 54.4 KB
Newer Older
1
/*
2
 * Copyright (C) 2010-2016 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
#include "datatypes.h"
#include "virfile.h"
#include "virpidfile.h"
#include "virnetdev.h"
#include "virnetdevveth.h"
#include "virnetdevbridge.h"
40
#include "virnetdevopenvswitch.h"
41 42
#include "virtime.h"
#include "domain_nwfilter.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
#include "netdev_bandwidth_conf.h"
55 56 57

#define VIR_FROM_THIS VIR_FROM_LXC

58 59
VIR_LOG_INIT("lxc.lxc_process");

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

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

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

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

82
    if (!dom->persistent)
83
        virDomainObjListRemove(driver->domains, dom);
84

85
    virObjectEventStateQueue(driver->domainEventState, event);
86 87 88 89 90
}

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

101 102
    VIR_DEBUG("Faking reboot");

103
    if (conn) {
104
        virObjectRef(conn);
105 106
        autodestroy = true;
    } else {
107
        conn = virConnectOpen("lxc:///system");
108 109 110 111 112 113 114 115 116 117 118
        /* 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;
119 120
    if (virLXCProcessStart(conn, driver, vm,
                           0, NULL, autodestroy, reason) < 0) {
121 122 123 124 125 126 127
        VIR_WARN("Unable to handle reboot of vm %s",
                 vm->def->name);
        goto cleanup;
    }

    ret = 0;

128
 cleanup:
129
    virObjectUnref(conn);
130 131 132
    return ret;
}

133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
static void
lxcProcessRemoveDomainStatus(virLXCDriverConfigPtr cfg,
                              virDomainObjPtr vm)
{
    char ebuf[1024];
    char *file = NULL;

    if (virAsprintf(&file, "%s/%s.xml", cfg->stateDir, vm->def->name) < 0)
        return;

    if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
        VIR_WARN("Failed to remove domain XML for %s: %s",
                 vm->def->name, virStrerror(errno, ebuf, sizeof(ebuf)));
    VIR_FREE(file);
}


151
/**
152
 * virLXCProcessCleanup:
153 154 155 156 157 158 159
 * @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
 *
 */
160
static void virLXCProcessCleanup(virLXCDriverPtr driver,
161 162
                                 virDomainObjPtr vm,
                                 virDomainShutoffReason reason)
163
{
164
    size_t i;
165
    virLXCDomainObjPrivatePtr priv = vm->privateData;
166
    virNetDevVPortProfilePtr vport = NULL;
167
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
168
    virConnectPtr conn = NULL;
169

170
    VIR_DEBUG("Cleanup VM name=%s pid=%d reason=%d",
171 172
              vm->def->name, (int)vm->pid, (int)reason);

173 174
    /* now that we know it's stopped call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
175
        char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
176 177 178 179 180 181 182 183

        /* 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);
    }

184 185 186 187 188 189 190 191 192 193 194
    virSecurityManagerRestoreAllLabel(driver->securityManager,
                                      vm->def, false, false);
    virSecurityManagerReleaseLabel(driver->securityManager, vm->def);
    /* Clear out dynamically assigned labels */
    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);
    }

195
    /* Stop autodestroy in case guest is restarted */
196 197
    virCloseCallbacksUnset(driver->closeCallbacks, vm,
                           lxcProcessAutoDestroy);
198

199 200
    if (priv->monitor) {
        virLXCMonitorClose(priv->monitor);
201
        virObjectUnref(priv->monitor);
202 203
        priv->monitor = NULL;
    }
204

205
    virPidFileDelete(cfg->stateDir, vm->def->name);
206
    lxcProcessRemoveDomainStatus(cfg, vm);
207 208 209 210 211

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

212
    if (virAtomicIntDecAndTest(&driver->nactive) && driver->inhibitCallback)
213 214
        driver->inhibitCallback(false, driver->inhibitOpaque);

215 216
    virLXCDomainReAttachHostDevices(driver, vm->def);

217
    for (i = 0; i < vm->def->nnets; i++) {
218 219
        virDomainNetDefPtr iface = vm->def->nets[i];
        vport = virDomainNetGetActualVirtPortProfile(iface);
220 221 222 223 224 225 226 227
        if (iface->ifname) {
            if (vport &&
                vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
                ignore_value(virNetDevOpenvswitchRemovePort(
                                virDomainNetGetActualBridgeName(iface),
                                iface->ifname));
            ignore_value(virNetDevVethDelete(iface->ifname));
        }
228 229 230 231 232 233
        if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            if (conn || (conn = virGetConnectNetwork()))
                virDomainNetReleaseActualDevice(conn, vm->def, iface);
            else
                VIR_WARN("Unable to release network device '%s'", NULLSTR(iface->ifname));
        }
234 235 236 237
    }

    virDomainConfVMNWFilterTeardown(vm);

238 239
    if (priv->cgroup) {
        virCgroupRemove(priv->cgroup);
240
        virCgroupFree(&priv->cgroup);
241 242
    }

243 244 245 246
    /* 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.
     */
247
    virCgroupTerminateMachine(priv->machineName);
248
    VIR_FREE(priv->machineName);
249

250
    /* The "release" hook cleans up additional resources */
251
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
252
        char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
253 254 255 256 257 258 259 260

        /* 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);
    }

261
    virDomainObjRemoveTransientDef(vm);
262
    virObjectUnref(cfg);
263
    virObjectUnref(conn);
264 265 266
}


267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
int
virLXCProcessValidateInterface(virDomainNetDefPtr net)
{
    if (net->script) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("scripts are not supported on LXC network interfaces"));
        return -1;
    }
    return 0;
}


char *
virLXCProcessSetupInterfaceTap(virDomainDefPtr vm,
                               virDomainNetDefPtr net,
                               const char *brname)
283
{
284
    char *ret = NULL;
285 286
    char *parentVeth;
    char *containerVeth = NULL;
287
    virNetDevVPortProfilePtr vport = virDomainNetGetActualVirtPortProfile(net);
288 289 290 291 292 293 294 295 296 297 298 299 300

    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;

301 302 303 304 305 306 307 308 309
    if (brname) {
        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;
        }
310
    }
311 312 313 314

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

315 316 317 318 319 320 321 322
    if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_ETHERNET) {
        /* Set IP info for the host side, but only if the type is
         * 'ethernet'.
         */
        if (virNetDevIPInfoAddToDev(parentVeth, &net->hostIP) < 0)
            goto cleanup;
    }

323
    if (net->filter &&
324
        virDomainConfNWFilterInstantiate(vm->name, vm->uuid, net, false) < 0)
325 326
        goto cleanup;

327
    ret = containerVeth;
328

329
 cleanup:
330 331 332 333
    return ret;
}


334 335 336
char *virLXCProcessSetupInterfaceDirect(virConnectPtr conn,
                                        virDomainDefPtr def,
                                        virDomainNetDefPtr net)
337
{
338
    char *ret = NULL;
339
    char *res_ifname = NULL;
340
    virLXCDriverPtr driver = conn->privateData;
341 342
    virNetDevBandwidthPtr bw;
    virNetDevVPortProfilePtr prof;
343
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
344
    const char *linkdev = virDomainNetGetActualDirectDev(net);
345
    unsigned int macvlan_create_flags = VIR_NETDEV_MACVLAN_CREATE_IFUP;
346 347 348 349 350 351 352 353

    /* 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) {
354 355
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Unable to set network bandwidth on direct interfaces"));
356
        return NULL;
357 358 359 360 361 362 363 364 365 366 367
    }

    /* 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) {
368 369
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Unable to set port profile on direct interfaces"));
370
        return NULL;
371 372 373 374
    }

    if (virNetDevMacVLanCreateWithVPortProfile(
            net->ifname, &net->mac,
375
            linkdev,
376
            virDomainNetGetActualDirectMode(net),
377
            virDomainNetGetActualVlan(net),
378
            def->uuid,
379
            prof,
380 381
            &res_ifname,
            VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
382
            cfg->stateDir,
383
            NULL, 0,
384
            macvlan_create_flags) < 0)
385 386
        goto cleanup;

387
    ret = res_ifname;
388

389
 cleanup:
390
    virObjectUnref(cfg);
391 392 393
    return ret;
}

I
ik.nitk 已提交
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
static const char *nsInfoLocal[VIR_LXC_DOMAIN_NAMESPACE_LAST] = {
    [VIR_LXC_DOMAIN_NAMESPACE_SHARENET] = "net",
    [VIR_LXC_DOMAIN_NAMESPACE_SHAREIPC] = "ipc",
    [VIR_LXC_DOMAIN_NAMESPACE_SHAREUTS] = "uts",
};

static int virLXCProcessSetupNamespaceName(virConnectPtr conn, int ns_type, const char *name)
{
    virLXCDriverPtr driver = conn->privateData;
    int fd = -1;
    virDomainObjPtr vm;
    virLXCDomainObjPrivatePtr priv;
    char *path;

    vm = virDomainObjListFindByName(driver->domains, name);
    if (!vm) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching name '%s'"), name);
        return -1;
    }

    priv = vm->privateData;
    if (!priv->initpid) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Init pid is not yet available"));
        goto cleanup;
    }

    if (virAsprintf(&path, "/proc/%lld/ns/%s",
                    (long long int)priv->initpid,
                    nsInfoLocal[ns_type]) < 0)
        goto cleanup;

    if ((fd = open(path, O_RDONLY)) < 0) {
        virReportSystemError(errno,
                             _("failed to open ns %s"),
                             virLXCDomainNamespaceTypeToString(ns_type));
        goto cleanup;
    }

 cleanup:
    VIR_FREE(path);
436
    virDomainObjEndAPI(&vm);
I
ik.nitk 已提交
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
    return fd;
}


static int virLXCProcessSetupNamespacePID(int ns_type, const char *name)
{
    int fd;
    char *path;

    if (virAsprintf(&path, "/proc/%s/ns/%s",
                    name,
                    nsInfoLocal[ns_type]) < 0)
        return -1;
    fd = open(path, O_RDONLY);
    VIR_FREE(path);
    if (fd < 0) {
        virReportSystemError(errno,
                             _("failed to open ns %s"),
                             virLXCDomainNamespaceTypeToString(ns_type));
        return -1;
    }
    return fd;
}


static int virLXCProcessSetupNamespaceNet(int ns_type, const char *name)
{
    char *path;
    int fd;
    if (ns_type != VIR_LXC_DOMAIN_NAMESPACE_SHARENET) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("'netns' namespace source can only be "
                         "used with sharenet"));
        return -1;
    }

    if (virAsprintf(&path, "/var/run/netns/%s", name) < 0)
        return  -1;
    fd = open(path, O_RDONLY);
    VIR_FREE(path);
    if (fd < 0) {
        virReportSystemError(errno,
                             _("failed to open netns %s"), name);
        return -1;
    }
    return fd;
}


/**
 * virLXCProcessSetupNamespaces:
 * @conn: pointer to connection
 * @def: pointer to virtual machines namespaceData
 * @nsFDs: out parameter to store the namespace FD
 *
 * Opens the specified namespace that needs to be shared and
 * will moved into the container namespace later after clone has been called.
 *
 * Returns 0 on success or -1 in case of error
 */
static int virLXCProcessSetupNamespaces(virConnectPtr conn,
                                        lxcDomainDefPtr lxcDef,
                                        int *nsFDs)
{
    size_t i;

    for (i = 0; i < VIR_LXC_DOMAIN_NAMESPACE_LAST; i++)
        nsFDs[i] = -1;
    /*If there are no namespace to be opened just return success*/
    if (lxcDef == NULL)
        return 0;

    for (i = 0; i < VIR_LXC_DOMAIN_NAMESPACE_LAST; i++) {
        switch (lxcDef->ns_source[i]) {
        case VIR_LXC_DOMAIN_NAMESPACE_SOURCE_NONE:
            continue;
        case VIR_LXC_DOMAIN_NAMESPACE_SOURCE_NAME:
            if ((nsFDs[i] = virLXCProcessSetupNamespaceName(conn, i, lxcDef->ns_val[i])) < 0)
                return -1;
            break;
        case VIR_LXC_DOMAIN_NAMESPACE_SOURCE_PID:
            if ((nsFDs[i] = virLXCProcessSetupNamespacePID(i, lxcDef->ns_val[i])) < 0)
                return -1;
            break;
        case VIR_LXC_DOMAIN_NAMESPACE_SOURCE_NETNS:
            if ((nsFDs[i] = virLXCProcessSetupNamespaceNet(i, lxcDef->ns_val[i])) < 0)
                return -1;
            break;
        }
    }

    return 0;
}
530 531

/**
532
 * virLXCProcessSetupInterfaces:
533 534
 * @conn: pointer to connection
 * @def: pointer to virtual machine structure
535
 * @veths: string list of interface names
536 537 538 539 540 541 542
 *
 * 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
 */
543 544 545
static int virLXCProcessSetupInterfaces(virConnectPtr conn,
                                        virDomainDefPtr def,
                                        char ***veths)
546 547 548
{
    int ret = -1;
    size_t i;
549
    size_t niface = 0;
550 551
    virDomainNetDefPtr net;
    virDomainNetType type;
552
    virConnectPtr netconn = NULL;
553
    virErrorPtr save_err = NULL;
554

555 556 557
    if (VIR_ALLOC_N(*veths, def->nnets + 1) < 0)
        return -1;

558
    for (i = 0; i < def->nnets; i++) {
559
        char *veth = NULL;
560
        virNetDevBandwidthPtr actualBandwidth;
561 562 563 564
        /* 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.
         */
565
        net = def->nets[i];
566 567

        if (virLXCProcessValidateInterface(net) < 0)
568
            goto cleanup;
569

570 571 572 573 574 575
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            if (!netconn && !(netconn = virGetConnectNetwork()))
                goto cleanup;
            if (virDomainNetAllocateActualDevice(netconn, def, net) < 0)
                goto cleanup;
        }
576

577 578
        type = virDomainNetGetActualType(net);
        switch (type) {
579
        case VIR_DOMAIN_NET_TYPE_NETWORK:
580
        case VIR_DOMAIN_NET_TYPE_BRIDGE: {
581
            const char *brname = virDomainNetGetActualBridgeName(net);
582
            if (!brname) {
583 584
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("No bridge name specified"));
585 586
                goto cleanup;
            }
587
            if (!(veth = virLXCProcessSetupInterfaceTap(def, net, brname)))
588 589
                goto cleanup;
        }   break;
590 591 592 593
        case VIR_DOMAIN_NET_TYPE_ETHERNET:
            if (!(veth = virLXCProcessSetupInterfaceTap(def, net, NULL)))
                goto cleanup;
            break;
594
        case VIR_DOMAIN_NET_TYPE_DIRECT:
595
            if (!(veth = virLXCProcessSetupInterfaceDirect(conn, def, net)))
596 597 598
                goto cleanup;
            break;

599
        case VIR_DOMAIN_NET_TYPE_USER:
M
Michele Paolino 已提交
600
        case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
601 602 603
        case VIR_DOMAIN_NET_TYPE_SERVER:
        case VIR_DOMAIN_NET_TYPE_CLIENT:
        case VIR_DOMAIN_NET_TYPE_MCAST:
604
        case VIR_DOMAIN_NET_TYPE_UDP:
605 606
        case VIR_DOMAIN_NET_TYPE_INTERNAL:
        case VIR_DOMAIN_NET_TYPE_LAST:
607
        case VIR_DOMAIN_NET_TYPE_HOSTDEV:
608 609
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unsupported network type %s"),
610
                           virDomainNetTypeToString(type));
611
            goto cleanup;
612

613
        }
614

615 616 617 618
        /* Set bandwidth or warn if requested and not supported. */
        actualBandwidth = virDomainNetGetActualBandwidth(net);
        if (actualBandwidth) {
            if (virNetDevSupportBandwidth(type)) {
619 620
                if (virNetDevBandwidthSet(net->ifname, actualBandwidth, false,
                                          !virDomainNetTypeSharesHostView(net)) < 0)
621 622 623 624 625 626 627
                    goto cleanup;
            } else {
                VIR_WARN("setting bandwidth on interfaces of "
                         "type '%s' is not implemented yet",
                         virDomainNetTypeToString(type));
            }
        }
628

629
        (*veths)[i] = veth;
630

631 632 633
        if (VIR_STRDUP(def->nets[i]->ifname_guest_actual, veth) < 0)
            goto cleanup;

634
        /* Make sure all net definitions will have a name in the container */
635 636
        if (!net->ifname_guest) {
            if (virAsprintf(&net->ifname_guest, "eth%zu", niface) < 0)
637
                goto cleanup;
638 639
            niface++;
        }
640 641
    }

642
    ret = 0;
643

644
 cleanup:
645
    if (ret < 0) {
646
        virErrorPreserveLast(&save_err);
647
        for (i = 0; i < def->nnets; i++) {
648 649 650 651 652 653
            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));
654 655
            if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK && netconn)
                virDomainNetReleaseActualDevice(netconn, def, iface);
656
        }
657
        virErrorRestore(&save_err);
658
    }
659
    virObjectUnref(netconn);
660 661 662
    return ret;
}

663 664 665 666 667 668 669 670 671 672 673
static void
virLXCProcessCleanInterfaces(virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < def->nnets; i++) {
        VIR_FREE(def->nets[i]->ifname_guest_actual);
        VIR_DEBUG("Cleared net names: %s", def->nets[i]->ifname_guest);
    }
}

674

675
extern virLXCDriverPtr lxc_driver;
676
static void virLXCProcessMonitorEOFNotify(virLXCMonitorPtr mon,
677
                                          virDomainObjPtr vm)
678 679
{
    virLXCDriverPtr driver = lxc_driver;
680
    virObjectEventPtr event = NULL;
681 682
    virLXCDomainObjPrivatePtr priv;

683 684
    VIR_DEBUG("mon=%p vm=%p", mon, vm);

685
    virObjectLock(vm);
686 687 688

    priv = vm->privateData;
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
689 690 691
    if (!priv->wantReboot) {
        virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
        if (!priv->doneStopEvent) {
692
            event = virDomainEventLifecycleNewFromObj(vm,
693 694 695 696 697 698
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             priv->stopReason);
            virDomainAuditStop(vm, "shutdown");
        } else {
            VIR_DEBUG("Stop event has already been sent");
        }
699
        if (!vm->persistent)
700
            virDomainObjListRemove(driver->domains, vm);
701
    } else {
702 703 704 705 706 707
        int ret = virLXCProcessReboot(driver, vm);
        virDomainAuditStop(vm, "reboot");
        virDomainAuditStart(vm, "reboot", ret == 0);
        if (ret == 0) {
            event = virDomainEventRebootNewFromObj(vm);
        } else {
708
            event = virDomainEventLifecycleNewFromObj(vm,
709 710
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             priv->stopReason);
711
            if (!vm->persistent)
712
                virDomainObjListRemove(driver->domains, vm);
713
        }
714 715
    }

716 717 718 719
    /* NB: virLXCProcessConnectMonitor will perform the virObjectRef(vm)
     * before adding monitorCallbacks. Since we are now done with the @vm
     * we can Unref/Unlock */
    virDomainObjEndAPI(&vm);
720
    virObjectEventStateQueue(driver->domainEventState, event);
721 722
}

723
static void virLXCProcessMonitorExitNotify(virLXCMonitorPtr mon ATTRIBUTE_UNUSED,
724
                                           virLXCMonitorExitStatus status,
725 726 727 728
                                           virDomainObjPtr vm)
{
    virLXCDomainObjPrivatePtr priv = vm->privateData;

729 730
    virObjectLock(vm);

731
    switch (status) {
732
    case VIR_LXC_MONITOR_EXIT_STATUS_SHUTDOWN:
733 734
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
        break;
735
    case VIR_LXC_MONITOR_EXIT_STATUS_ERROR:
736 737
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
        break;
738
    case VIR_LXC_MONITOR_EXIT_STATUS_REBOOT:
739 740 741
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
        priv->wantReboot = true;
        break;
742 743 744 745 746 747
    default:
        priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
        break;
    }
    VIR_DEBUG("Domain shutoff reason %d (from status %d)",
              priv->stopReason, status);
748 749

    virObjectUnlock(vm);
750
}
751

752 753 754 755 756 757 758 759 760
static int
virLXCProcessGetNsInode(pid_t pid,
                        const char *nsname,
                        ino_t *inode)
{
    char *path = NULL;
    struct stat sb;
    int ret = -1;

M
Michal Privoznik 已提交
761
    if (virAsprintf(&path, "/proc/%lld/ns/%s",
762
                    (long long)pid, nsname) < 0)
763 764 765 766 767 768 769 770 771 772 773
        goto cleanup;

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

    *inode = sb.st_ino;
    ret = 0;

774
 cleanup:
775 776 777 778 779
    VIR_FREE(path);
    return ret;
}


780 781
/* XXX a little evil */
extern virLXCDriverPtr lxc_driver;
782 783 784 785
static void virLXCProcessMonitorInitNotify(virLXCMonitorPtr mon ATTRIBUTE_UNUSED,
                                           pid_t initpid,
                                           virDomainObjPtr vm)
{
786 787
    virLXCDriverPtr driver = lxc_driver;
    virLXCDomainObjPrivatePtr priv;
788
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
789
    ino_t inode = 0;
790

791 792 793
    virObjectLock(vm);

    priv = vm->privateData;
794
    priv->initpid = initpid;
795 796

    if (virLXCProcessGetNsInode(initpid, "pid", &inode) < 0) {
M
Michal Privoznik 已提交
797
        VIR_WARN("Cannot obtain pid NS inode for %lld: %s",
798
                 (long long)initpid,
799
                 virGetLastErrorMessage());
800 801 802
        virResetLastError();
    }
    virDomainAuditInit(vm, initpid, inode);
803

804
    if (virDomainSaveStatus(lxc_driver->xmlopt, cfg->stateDir, vm, lxc_driver->caps) < 0)
805
        VIR_WARN("Cannot update XML with PID for LXC %s", vm->def->name);
806 807

    virObjectUnlock(vm);
808
    virObjectUnref(cfg);
809 810
}

811 812
static virLXCMonitorCallbacks monitorCallbacks = {
    .eofNotify = virLXCProcessMonitorEOFNotify,
813
    .exitNotify = virLXCProcessMonitorExitNotify,
814
    .initNotify = virLXCProcessMonitorInitNotify,
815
};
816

817 818 819 820 821

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

824 825
    if (virSecurityManagerSetSocketLabel(driver->securityManager, vm->def) < 0)
        goto cleanup;
826

827
    /* Hold an extra reference because we can't allow 'vm' to be
828 829
     * deleted while the monitor is active. This will be unreffed
     * during EOFNotify processing. */
830
    virObjectRef(vm);
831

832
    monitor = virLXCMonitorNew(vm, cfg->stateDir, &monitorCallbacks);
833 834

    if (monitor == NULL)
835
        virObjectUnref(vm);
836 837

    if (virSecurityManagerClearSocketLabel(driver->securityManager, vm->def) < 0) {
838
        if (monitor) {
839
            virObjectUnref(monitor);
840 841
            monitor = NULL;
        }
842
        goto cleanup;
843 844
    }

845
 cleanup:
846
    virObjectUnref(cfg);
847
    return monitor;
848 849 850
}


851
int virLXCProcessStop(virLXCDriverPtr driver,
852 853
                      virDomainObjPtr vm,
                      virDomainShutoffReason reason)
854 855
{
    int rc;
856
    virLXCDomainObjPrivatePtr priv;
857

858 859
    VIR_DEBUG("Stopping VM name=%s pid=%d reason=%d",
              vm->def->name, (int)vm->pid, (int)reason);
860 861 862 863 864
    if (!virDomainObjIsActive(vm)) {
        VIR_DEBUG("VM '%s' not active", vm->def->name);
        return 0;
    }

865 866
    priv = vm->privateData;

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    /* 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;
    }

891 892
    if (priv->cgroup) {
        rc = virCgroupKillPainfully(priv->cgroup);
893 894 895
        if (rc < 0)
            return -1;
        if (rc > 0) {
896
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
897 898
                           _("Some processes refused to die"));
            return -1;
899
        }
900
    } else if (vm->pid > 0) {
901 902
        /* If cgroup doesn't exist, just try cleaning up the
         * libvirt_lxc process */
903 904 905 906 907
        if (virProcessKillPainfully(vm->pid, true) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Processes %d refused to die"), (int)vm->pid);
            return -1;
        }
908 909
    }

910
 cleanup:
911
    virLXCProcessCleanup(driver, vm, reason);
912

913
    return 0;
914 915 916 917
}


static virCommandPtr
918
virLXCProcessBuildControllerCmd(virLXCDriverPtr driver,
919 920 921 922
                                virDomainObjPtr vm,
                                char **veths,
                                int *ttyFDs,
                                size_t nttyFDs,
I
ik.nitk 已提交
923
                                int *nsInheritFDs,
924 925
                                int *files,
                                size_t nfiles,
926
                                int handshakefd,
927
                                int * const logfd,
928
                                const char *pidfile)
929 930 931 932 933
{
    size_t i;
    char *filterstr;
    char *outputstr;
    virCommandPtr cmd;
934
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
935 936 937 938

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

    /* The controller may call ip command, so we have to retain PATH. */
939
    virCommandAddEnvPass(cmd, "PATH");
940 941 942 943 944 945 946 947

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

    if (virLogGetNbFilters() > 0) {
        filterstr = virLogGetFilters();
        if (!filterstr) {
            virReportOOMError();
948
            goto error;
949 950 951 952 953 954
        }

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

955
    if (cfg->log_libvirtd) {
956 957 958 959
        if (virLogGetNbOutputs() > 0) {
            outputstr = virLogGetOutputs();
            if (!outputstr) {
                virReportOOMError();
960
                goto error;
961 962 963 964 965 966 967 968 969 970 971 972
            }

            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);
973
    for (i = 0; i < nttyFDs; i++) {
974 975
        virCommandAddArg(cmd, "--console");
        virCommandAddArgFormat(cmd, "%d", ttyFDs[i]);
976
        virCommandPassFD(cmd, ttyFDs[i], 0);
977 978
    }

979 980 981
    for (i = 0; i < nfiles; i++) {
        virCommandAddArg(cmd, "--passfd");
        virCommandAddArgFormat(cmd, "%d", files[i]);
982
        virCommandPassFD(cmd, files[i], 0);
983 984
    }

I
ik.nitk 已提交
985 986 987 988 989
    for (i = 0; i < VIR_LXC_DOMAIN_NAMESPACE_LAST; i++) {
        if (nsInheritFDs[i] > 0) {
            char *tmp = NULL;
            if (virAsprintf(&tmp, "--share-%s",
                            nsInfoLocal[i]) < 0)
990
                goto error;
I
ik.nitk 已提交
991 992 993 994 995 996 997
            virCommandAddArg(cmd, tmp);
            virCommandAddArgFormat(cmd, "%d", nsInheritFDs[i]);
            virCommandPassFD(cmd, nsInheritFDs[i], 0);
            VIR_FREE(tmp);
        }
    }

998 999 1000 1001 1002 1003
    virCommandAddArgPair(cmd, "--security",
                         virSecurityManagerGetModel(driver->securityManager));

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

1004
    for (i = 0; veths && veths[i]; i++)
1005 1006
        virCommandAddArgList(cmd, "--veth", veths[i], NULL);

1007
    virCommandPassFD(cmd, handshakefd, 0);
1008 1009
    virCommandDaemonize(cmd);
    virCommandSetPidFile(cmd, pidfile);
1010 1011
    virCommandSetOutputFD(cmd, logfd);
    virCommandSetErrorFD(cmd, logfd);
1012 1013 1014
    /* So we can pause before exec'ing the controller to
     * write the live domain status XML with the PID */
    virCommandRequireHandshake(cmd);
1015

1016
 cleanup:
1017
    virObjectUnref(cfg);
1018 1019 1020 1021 1022
    return cmd;
 error:
    virCommandFree(cmd);
    cmd = NULL;
    goto cleanup;
1023 1024
}

1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
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;
}

1040
static int
1041 1042 1043 1044
virLXCProcessReadLogOutputData(virDomainObjPtr vm,
                               int fd,
                               char *buf,
                               size_t buflen)
1045 1046
{
    int retries = 10;
1047 1048 1049
    int got = 0;
    int ret = -1;
    char *filter_next = buf;
1050

1051
    buf[0] = '\0';
1052 1053 1054

    while (retries) {
        ssize_t bytes;
1055
        bool isdead = false;
1056
        char *eol;
1057

1058 1059
        if (vm->pid <= 0 ||
            (kill(vm->pid, 0) == -1 && errno == ESRCH))
1060
            isdead = true;
1061 1062 1063 1064 1065 1066

        /* 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",
1067
                                 _("Failure while reading log output"));
1068 1069 1070 1071 1072 1073
            goto cleanup;
        }

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

1074 1075 1076
        /* Filter out debug messages from intermediate libvirt process */
        while ((eol = strchr(filter_next, '\n'))) {
            *eol = '\0';
1077
            if (virLXCProcessIgnorableLogLine(filter_next)) {
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
                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;
1096 1097 1098 1099 1100 1101
        }

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

1102 1103 1104
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Timed out while reading log output: %s"),
                   buf);
1105

1106
 cleanup:
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    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);

1141 1142 1143 1144
    VIR_FORCE_CLOSE(fd);
    return ret;
}

1145 1146 1147 1148

static int
virLXCProcessEnsureRootFS(virDomainObjPtr vm)
{
1149
    virDomainFSDefPtr root = virDomainGetFilesystemForTarget(vm->def, "/");
1150 1151 1152 1153

    if (root)
        return 0;

1154
    if (!(root = virDomainFSDefNew()))
1155
        goto error;
1156 1157 1158

    root->type = VIR_DOMAIN_FS_TYPE_MOUNT;

1159
    if (VIR_STRDUP(root->src->path, "/") < 0 ||
1160 1161
        VIR_STRDUP(root->dst, "/") < 0)
        goto error;
1162

1163 1164 1165 1166 1167
    if (VIR_INSERT_ELEMENT(vm->def->fss,
                           0,
                           vm->def->nfss,
                           root) < 0)
        goto error;
1168 1169 1170

    return 0;

1171
 error:
1172 1173 1174 1175
    virDomainFSDefFree(root);
    return -1;
}

1176
/**
1177
 * virLXCProcessStart:
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
 * @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
 */
1188
int virLXCProcessStart(virConnectPtr conn,
1189
                       virLXCDriverPtr  driver,
1190
                       virDomainObjPtr vm,
1191
                       unsigned int nfiles, int *files,
1192 1193
                       bool autoDestroy,
                       virDomainRunningReason reason)
1194 1195 1196 1197 1198 1199 1200
{
    int rc = -1, r;
    size_t nttyFDs = 0;
    int *ttyFDs = NULL;
    size_t i;
    char *logfile = NULL;
    int logfd = -1;
1201
    VIR_AUTOSTRINGLIST veths = NULL;
1202 1203 1204 1205
    int handshakefds[2] = { -1, -1 };
    off_t pos = -1;
    char ebuf[1024];
    char *timestamp;
I
ik.nitk 已提交
1206
    int nsInheritFDs[VIR_LXC_DOMAIN_NAMESPACE_LAST];
1207
    virCommandPtr cmd = NULL;
1208
    virLXCDomainObjPrivatePtr priv = vm->privateData;
1209
    virCapsPtr caps = NULL;
1210
    virErrorPtr err = NULL;
1211
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
1212
    virCgroupPtr selfcgroup;
1213
    int status;
1214
    char *pidfile = NULL;
1215

1216
    if (virCgroupNewSelf(&selfcgroup) < 0)
1217 1218
        return -1;

1219
    if (!virCgroupHasController(selfcgroup,
1220
                                VIR_CGROUP_CONTROLLER_CPUACCT)) {
1221
        virCgroupFree(&selfcgroup);
1222 1223
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'cpuacct' cgroups controller mount"));
1224 1225
        return -1;
    }
1226
    if (!virCgroupHasController(selfcgroup,
1227
                                VIR_CGROUP_CONTROLLER_DEVICES)) {
1228
        virCgroupFree(&selfcgroup);
1229 1230
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'devices' cgroups controller mount"));
1231 1232
        return -1;
    }
1233
    if (!virCgroupHasController(selfcgroup,
1234
                                VIR_CGROUP_CONTROLLER_MEMORY)) {
1235
        virCgroupFree(&selfcgroup);
1236 1237
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'memory' cgroups controller mount"));
1238 1239
        return -1;
    }
1240
    virCgroupFree(&selfcgroup);
1241

1242 1243 1244 1245 1246 1247 1248
    if (vm->def->nconsoles == 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("At least one PTY console is required"));
        return -1;
    }

    for (i = 0; i < vm->def->nconsoles; i++) {
1249
        if (vm->def->consoles[i]->source->type != VIR_DOMAIN_CHR_TYPE_PTY) {
1250 1251 1252 1253 1254 1255
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Only PTY console types are supported"));
            return -1;
        }
    }

1256
    if (virFileMakePath(cfg->logDir) < 0) {
1257 1258
        virReportSystemError(errno,
                             _("Cannot create log directory '%s'"),
1259
                             cfg->logDir);
1260 1261 1262
        return -1;
    }

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    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;
    }

1277
    if (virAsprintf(&logfile, "%s/%s.log",
1278
                    cfg->logDir, vm->def->name) < 0)
1279 1280 1281 1282
        goto cleanup;

    if (!(pidfile = virPidFileBuildPath(cfg->stateDir, vm->def->name)))
        goto cleanup;
1283

1284 1285 1286
    if (!(caps = virLXCDriverGetCapabilities(driver, false)))
        goto cleanup;

1287 1288 1289 1290 1291
    /* 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");
1292
    if (virDomainObjSetDefTransient(caps, driver->xmlopt, vm, NULL) < 0)
1293 1294 1295 1296
        goto cleanup;

    /* Run an early hook to set-up missing devices */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
1297
        char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        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;
    }

1312 1313 1314
    if (virLXCProcessEnsureRootFS(vm) < 0)
        goto cleanup;

1315 1316 1317 1318 1319
    /* Must be run before security labelling */
    VIR_DEBUG("Preparing host devices");
    if (virLXCPrepareHostDevices(driver, vm->def) < 0)
        goto cleanup;

1320 1321 1322 1323 1324
    /* 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;
1325
    if (VIR_ALLOC_N(ttyFDs, nttyFDs) < 0)
1326
        goto cleanup;
1327
    for (i = 0; i < vm->def->nconsoles; i++)
1328
        ttyFDs[i] = -1;
1329 1330 1331 1332

    /* If you are using a SecurityDriver with dynamic labelling,
       then generate a security label for isolation */
    VIR_DEBUG("Generating domain security label (if required)");
1333

1334 1335 1336
    if (vm->def->nseclabels &&
        vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DEFAULT)
        vm->def->seclabels[0]->type = VIR_DOMAIN_SECLABEL_NONE;
1337

1338 1339 1340
    if (virSecurityManagerCheckAllLabel(driver->securityManager, vm->def) < 0)
        goto cleanup;

1341 1342 1343 1344 1345 1346 1347 1348
    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,
1349
                                      vm->def, NULL, false) < 0)
1350 1351
        goto cleanup;

1352
    VIR_DEBUG("Setting up consoles");
1353
    for (i = 0; i < vm->def->nconsoles; i++) {
1354 1355 1356 1357 1358 1359 1360 1361
        char *ttyPath;

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

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

        VIR_FREE(vm->def->consoles[i]->info.alias);
1366
        if (virAsprintf(&vm->def->consoles[i]->info.alias, "console%zu", i) < 0)
1367 1368 1369
            goto cleanup;
    }

1370
    VIR_DEBUG("Setting up Interfaces");
1371
    if (virLXCProcessSetupInterfaces(conn, vm->def, &veths) < 0)
1372 1373
        goto cleanup;

I
ik.nitk 已提交
1374 1375 1376 1377
    VIR_DEBUG("Setting up namespaces if any");
    if (virLXCProcessSetupNamespaces(conn, vm->def->namespaceData, nsInheritFDs) < 0)
        goto cleanup;

1378
    VIR_DEBUG("Preparing to launch");
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    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;
    }

1393 1394
    if (!(cmd = virLXCProcessBuildControllerCmd(driver,
                                                vm,
1395
                                                veths,
1396
                                                ttyFDs, nttyFDs,
I
ik.nitk 已提交
1397
                                                nsInheritFDs,
1398
                                                files, nfiles,
1399
                                                handshakefds[1],
1400
                                                &logfd,
1401
                                                pidfile)))
1402 1403 1404 1405
        goto cleanup;

    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
1406
        char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        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 */
1422
    if ((timestamp = virTimeStringNow()) == NULL)
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        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)));

1437
    VIR_DEBUG("Launching container");
1438
    virCommandRawStatus(cmd);
1439
    if (virCommandRun(cmd, &status) < 0)
1440 1441
        goto cleanup;

1442
    if (status != 0) {
1443 1444 1445 1446 1447 1448 1449 1450
        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"));
        }
1451 1452 1453 1454 1455
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("guest failed to start: %s"), ebuf);
        goto cleanup;
    }

1456
    /* It has started running, so get its pid */
1457
    if ((r = virPidFileReadPath(pidfile, &vm->pid)) < 0) {
1458
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf, sizeof(ebuf)) > 0)
1459
            virReportError(VIR_ERR_INTERNAL_ERROR,
1460
                           _("guest failed to start: %s"), ebuf);
1461 1462
        else
            virReportSystemError(-r,
1463 1464
                                 _("Failed to read pid file %s"),
                                 pidfile);
1465 1466 1467
        goto cleanup;
    }

1468
    priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
1469
    priv->wantReboot = false;
1470 1471
    vm->def->id = vm->pid;
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, reason);
1472
    priv->doneStopEvent = false;
1473

1474 1475
    if (VIR_CLOSE(handshakefds[1]) < 0) {
        virReportSystemError(errno, "%s", _("could not close handshake fd"));
1476
        goto cleanup;
1477 1478 1479
    }

    if (virCommandHandshakeWait(cmd) < 0)
1480
        goto cleanup;
1481 1482 1483

    /* Write domain status to disk for the controller to
     * read when it starts */
1484
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
1485
        goto cleanup;
1486 1487 1488

    /* Allow the child to exec the controller */
    if (virCommandHandshakeNotify(cmd) < 0)
1489
        goto cleanup;
1490

1491
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
1492 1493
        driver->inhibitCallback(true, driver->inhibitOpaque);

1494 1495 1496
    if (lxcContainerWaitForContinue(handshakefds[0]) < 0) {
        char out[1024];

1497
        if (!(virLXCProcessReadLogOutput(vm, logfile, pos, out, 1024) < 0)) {
1498 1499
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), out);
1500 1501
        }

1502
        goto cleanup;
1503 1504
    }

1505 1506 1507 1508
    priv->machineName = virLXCDomainGetMachineName(vm->def, vm->pid);
    if (!priv->machineName)
        goto cleanup;

1509 1510 1511 1512
    /* We know the cgroup must exist by this synchronization
     * point so lets detect that first, since it gives us a
     * more reliable way to kill everything off if something
     * goes wrong from here onwards ... */
1513
    if (virCgroupNewDetectMachine(vm->def->name, "lxc",
1514 1515
                                  vm->pid, -1, priv->machineName,
                                  &priv->cgroup) < 0)
1516
        goto cleanup;
1517 1518 1519 1520 1521

    if (!priv->cgroup) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No valid cgroup for machine %s"),
                       vm->def->name);
1522
        goto cleanup;
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
    }

    /* And we can get the first monitor connection now too */
    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);
        }
1535
        goto cleanup;
1536 1537
    }

1538
    if (autoDestroy &&
1539 1540
        virCloseCallbacksSet(driver->closeCallbacks, vm,
                             conn, lxcProcessAutoDestroy) < 0)
1541
        goto cleanup;
1542

1543 1544 1545
    /* We don't need the temporary NIC names anymore, clear them */
    virLXCProcessCleanInterfaces(vm->def);

1546 1547
    /* finally we can call the 'started' hook script if any */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
1548
        char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
        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)
1560
            goto cleanup;
1561 1562 1563 1564
    }

    rc = 0;

1565
 cleanup:
1566 1567 1568 1569 1570
    if (VIR_CLOSE(logfd) < 0) {
        virReportSystemError(errno, "%s", _("could not close logfile"));
        rc = -1;
    }
    if (rc != 0) {
1571
        err = virSaveLastError();
1572
        virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
1573
    }
1574
    virCommandFree(cmd);
1575
    for (i = 0; i < nttyFDs; i++)
1576 1577 1578 1579
        VIR_FORCE_CLOSE(ttyFDs[i]);
    VIR_FREE(ttyFDs);
    VIR_FORCE_CLOSE(handshakefds[0]);
    VIR_FORCE_CLOSE(handshakefds[1]);
1580
    VIR_FREE(pidfile);
1581
    VIR_FREE(logfile);
1582
    virObjectUnref(cfg);
1583
    virObjectUnref(caps);
1584 1585 1586 1587 1588 1589 1590 1591 1592

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

    return rc;
}

1593
struct virLXCProcessAutostartData {
1594
    virLXCDriverPtr driver;
1595 1596 1597
    virConnectPtr conn;
};

1598 1599 1600
static int
virLXCProcessAutostartDomain(virDomainObjPtr vm,
                             void *opaque)
1601
{
1602
    const struct virLXCProcessAutostartData *data = opaque;
1603
    int ret = 0;
1604

1605
    virObjectLock(vm);
1606 1607
    if (vm->autostart &&
        !virDomainObjIsActive(vm)) {
1608 1609
        ret = virLXCProcessStart(data->conn, data->driver, vm,
                                 0, NULL, false,
1610
                                 VIR_DOMAIN_RUNNING_BOOTED);
1611 1612 1613 1614
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                      vm->def->name,
1615
                      virGetLastErrorMessage());
1616
        } else {
1617
            virObjectEventPtr event =
1618
                virDomainEventLifecycleNewFromObj(vm,
1619 1620
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
1621
            virObjectEventStateQueue(data->driver->domainEventState, event);
1622 1623
        }
    }
1624
    virObjectUnlock(vm);
1625
    return ret;
1626 1627 1628 1629
}


void
1630 1631
virLXCProcessAutostartAll(virLXCDriverPtr driver)
{
1632 1633 1634 1635 1636
    /* 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
     */
1637
    virConnectPtr conn = virConnectOpen("lxc:///system");
1638 1639
    /* Ignoring NULL conn which is mostly harmless here */

1640
    struct virLXCProcessAutostartData data = { driver, conn };
1641

1642 1643 1644
    virDomainObjListForEach(driver->domains,
                            virLXCProcessAutostartDomain,
                            &data);
1645

1646
    virObjectUnref(conn);
1647 1648
}

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676

static void
virLXCProcessReconnectNotifyNets(virDomainDefPtr def)
{
    size_t i;
    virConnectPtr conn = NULL;

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
        /* keep others from trying to use the macvtap device name, but
         * don't return error if this happens, since that causes the
         * domain to be unceremoniously killed, which would be *very*
         * impolite.
         */
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT)
           ignore_value(virNetDevMacVLanReserveName(net->ifname, false));

        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            if (!conn && !(conn = virGetConnectNetwork()))
                continue;
            virDomainNetNotifyActualDevice(conn, def, net);
        }
    }

    virObjectUnref(conn);
}


1677 1678 1679
static int
virLXCProcessReconnectDomain(virDomainObjPtr vm,
                             void *opaque)
1680
{
1681
    virLXCDriverPtr driver = opaque;
1682
    virLXCDomainObjPrivatePtr priv;
1683
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
1684
    int ret = -1;
1685

1686
    virObjectLock(vm);
1687
    VIR_DEBUG("Reconnect id=%d pid=%d state=%d", vm->def->id, vm->pid, vm->state.state);
1688 1689 1690 1691 1692 1693 1694 1695

    priv = vm->privateData;

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

1696
        if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
1697 1698
            driver->inhibitCallback(true, driver->inhibitOpaque);

1699
        if (!(priv->monitor = virLXCProcessConnectMonitor(driver, vm)))
1700 1701
            goto error;

1702 1703 1704 1705 1706 1707
        priv->machineName = virLXCDomainGetMachineName(vm->def, vm->pid);
        if (!priv->machineName)
            goto cleanup;

        if (virCgroupNewDetectMachine(vm->def->name, "lxc", vm->pid, -1,
                                      priv->machineName, &priv->cgroup) < 0)
1708 1709
            goto error;

1710
        if (!priv->cgroup) {
1711
            virReportError(VIR_ERR_INTERNAL_ERROR,
1712
                           _("No valid cgroup for machine %s"),
1713 1714 1715 1716
                           vm->def->name);
            goto error;
        }

1717
        if (virLXCUpdateActiveUSBHostdevs(driver, vm->def) < 0)
1718 1719
            goto error;

1720 1721 1722 1723
        if (virSecurityManagerReserveLabel(driver->securityManager,
                                           vm->def, vm->pid) < 0)
            goto error;

1724 1725
        virLXCProcessReconnectNotifyNets(vm->def);

1726 1727 1728
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
            VIR_WARN("Cannot update XML for running LXC guest %s", vm->def->name);

1729 1730
        /* now that we know it's reconnected call the hook if present */
        if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
1731
            char *xml = virDomainDefFormat(vm->def, driver->caps, 0);
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
            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;
    }

1747
    ret = 0;
1748
 cleanup:
1749
    virObjectUnref(cfg);
1750
    virObjectUnlock(vm);
1751
    return ret;
1752

1753
 error:
1754
    virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
1755 1756 1757 1758 1759
    virDomainAuditStop(vm, "failed");
    goto cleanup;
}


1760
int virLXCProcessReconnectAll(virLXCDriverPtr driver,
1761
                              virDomainObjListPtr doms)
1762
{
1763
    virDomainObjListForEach(doms, virLXCProcessReconnectDomain, driver);
1764 1765
    return 0;
}