lxc_driver.c 66.5 KB
Newer Older
D
Daniel Veillard 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright IBM Corp. 2008
 *
 * lxc_driver.c: linux container driver functions
 *
 * Authors:
 *  David L. Leskovec <dlesko at linux.vnet.ibm.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <config.h>

26
#include <fcntl.h>
D
Daniel Veillard 已提交
27 28
#include <sched.h>
#include <sys/utsname.h>
D
David L. Leskovec 已提交
29
#include <stdbool.h>
D
Daniel Veillard 已提交
30 31
#include <string.h>
#include <sys/types.h>
32 33 34
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/poll.h>
D
Daniel Veillard 已提交
35 36 37
#include <unistd.h>
#include <wait.h>

38
#include "virterror_internal.h"
39
#include "logging.h"
40
#include "datatypes.h"
D
Daniel Veillard 已提交
41
#include "lxc_conf.h"
42
#include "lxc_container.h"
D
Daniel Veillard 已提交
43
#include "lxc_driver.h"
44
#include "memory.h"
45
#include "util.h"
46 47
#include "bridge.h"
#include "veth.h"
48
#include "event.h"
49
#include "nodeinfo.h"
50
#include "uuid.h"
51

D
Daniel Veillard 已提交
52

53 54
#define VIR_FROM_THIS VIR_FROM_LXC

55
static int lxcStartup(int privileged);
56
static int lxcShutdown(void);
57
static lxc_driver_t *lxc_driver = NULL;
D
Daniel Veillard 已提交
58 59 60

/* Functions */

61 62
static void lxcDriverLock(lxc_driver_t *driver)
{
63
    virMutexLock(&driver->lock);
64 65 66
}
static void lxcDriverUnlock(lxc_driver_t *driver)
{
67
    virMutexUnlock(&driver->lock);
68 69
}

70 71 72 73
static void lxcDomainEventFlush(int timer, void *opaque);
static void lxcDomainEventQueue(lxc_driver_t *driver,
                                virDomainEventPtr event);

74

D
Daniel Veillard 已提交
75 76 77 78 79
static virDrvOpenStatus lxcOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                int flags ATTRIBUTE_UNUSED)
{
    /* Verify uri was specified */
80
    if (conn->uri == NULL) {
81 82
        if (lxc_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
83

84 85
        conn->uri = xmlParseURI("lxc:///");
        if (!conn->uri) {
86
            virReportOOMError(conn);
87 88
            return VIR_DRV_OPEN_ERROR;
        }
89 90 91 92 93 94 95 96 97 98 99 100
    } else {
        if (conn->uri->scheme == NULL ||
            STRNEQ(conn->uri->scheme, "lxc"))
            return VIR_DRV_OPEN_DECLINED;

        /* Leave for remote driver */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

        /* If path isn't '/' then they typoed, tell them correct path */
        if (STRNEQ(conn->uri->path, "/")) {
            lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
101
                     _("Unexpected LXC URI path '%s', try lxc:///"),
102 103 104
                     conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
D
Daniel Veillard 已提交
105

106 107 108
        /* URI was good, but driver isn't active */
        if (lxc_driver == NULL) {
            lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
109
                     "%s", _("lxc state driver is not active"));
110 111 112
            return VIR_DRV_OPEN_ERROR;
        }
    }
113

114
    conn->privateData = lxc_driver;
D
Daniel Veillard 已提交
115 116 117 118 119 120

    return VIR_DRV_OPEN_SUCCESS;
}

static int lxcClose(virConnectPtr conn)
{
121 122 123 124 125 126
    lxc_driver_t *driver = conn->privateData;

    lxcDriverLock(driver);
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
    lxcDriverUnlock(driver);

127 128
    conn->privateData = NULL;
    return 0;
D
Daniel Veillard 已提交
129 130
}

131 132 133 134 135 136 137 138 139 140 141 142 143
static char *lxcGetCapabilities(virConnectPtr conn) {
    lxc_driver_t *driver = conn->privateData;
    char *xml;

    lxcDriverLock(driver);
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
        virReportOOMError(conn);
    lxcDriverUnlock(driver);

    return xml;
}


D
Daniel Veillard 已提交
144 145 146
static virDomainPtr lxcDomainLookupByID(virConnectPtr conn,
                                        int id)
{
147 148 149
    lxc_driver_t *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
150

151
    lxcDriverLock(driver);
152
    vm = virDomainFindByID(&driver->domains, id);
153 154
    lxcDriverUnlock(driver);

D
Daniel Veillard 已提交
155 156
    if (!vm) {
        lxcError(conn, NULL, VIR_ERR_NO_DOMAIN, NULL);
157
        goto cleanup;
D
Daniel Veillard 已提交
158 159 160
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
161
    if (dom)
D
Daniel Veillard 已提交
162 163
        dom->id = vm->def->id;

164
cleanup:
165 166
    if (vm)
        virDomainObjUnlock(vm);
D
Daniel Veillard 已提交
167 168 169 170 171 172
    return dom;
}

static virDomainPtr lxcDomainLookupByUUID(virConnectPtr conn,
                                          const unsigned char *uuid)
{
173 174 175
    lxc_driver_t *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
176

177
    lxcDriverLock(driver);
178
    vm = virDomainFindByUUID(&driver->domains, uuid);
179 180
    lxcDriverUnlock(driver);

D
Daniel Veillard 已提交
181 182
    if (!vm) {
        lxcError(conn, NULL, VIR_ERR_NO_DOMAIN, NULL);
183
        goto cleanup;
D
Daniel Veillard 已提交
184 185 186
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
187
    if (dom)
D
Daniel Veillard 已提交
188 189
        dom->id = vm->def->id;

190
cleanup:
191 192
    if (vm)
        virDomainObjUnlock(vm);
D
Daniel Veillard 已提交
193 194 195 196 197 198
    return dom;
}

static virDomainPtr lxcDomainLookupByName(virConnectPtr conn,
                                          const char *name)
{
199 200 201
    lxc_driver_t *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
202

203
    lxcDriverLock(driver);
204
    vm = virDomainFindByName(&driver->domains, name);
205
    lxcDriverUnlock(driver);
D
Daniel Veillard 已提交
206 207
    if (!vm) {
        lxcError(conn, NULL, VIR_ERR_NO_DOMAIN, NULL);
208
        goto cleanup;
D
Daniel Veillard 已提交
209 210 211
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
212
    if (dom)
D
Daniel Veillard 已提交
213 214
        dom->id = vm->def->id;

215
cleanup:
216 217
    if (vm)
        virDomainObjUnlock(vm);
D
Daniel Veillard 已提交
218 219 220
    return dom;
}

221
static int lxcListDomains(virConnectPtr conn, int *ids, int nids) {
222
    lxc_driver_t *driver = conn->privateData;
223
    int n;
224

225
    lxcDriverLock(driver);
226
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
227
    lxcDriverUnlock(driver);
228

229
    return n;
D
Daniel Veillard 已提交
230
}
231

232
static int lxcNumDomains(virConnectPtr conn) {
233
    lxc_driver_t *driver = conn->privateData;
234
    int n;
235

236
    lxcDriverLock(driver);
237
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
238
    lxcDriverUnlock(driver);
239

240
    return n;
D
Daniel Veillard 已提交
241 242 243
}

static int lxcListDefinedDomains(virConnectPtr conn,
244
                                 char **const names, int nnames) {
245
    lxc_driver_t *driver = conn->privateData;
246
    int n;
247

248
    lxcDriverLock(driver);
249
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
250
    lxcDriverUnlock(driver);
251

252
    return n;
D
Daniel Veillard 已提交
253 254 255
}


256
static int lxcNumDefinedDomains(virConnectPtr conn) {
257
    lxc_driver_t *driver = conn->privateData;
258
    int n;
259

260
    lxcDriverLock(driver);
261
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
262
    lxcDriverUnlock(driver);
263

264
    return n;
D
Daniel Veillard 已提交
265 266
}

267 268


D
Daniel Veillard 已提交
269 270
static virDomainPtr lxcDomainDefine(virConnectPtr conn, const char *xml)
{
271 272
    lxc_driver_t *driver = conn->privateData;
    virDomainDefPtr def = NULL;
273
    virDomainObjPtr vm = NULL;
274
    virDomainPtr dom = NULL;
275 276
    virDomainEventPtr event = NULL;
    int newVM = 1;
D
Daniel Veillard 已提交
277

278
    lxcDriverLock(driver);
279 280
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
281
        goto cleanup;
D
Daniel Veillard 已提交
282

283 284 285 286 287 288 289 290
    /* See if a VM with matching UUID already exists */
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
    if (vm) {
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            lxcError(conn, NULL, VIR_ERR_OPERATION_FAILED,
291
                     _("Domain '%s' is already defined with uuid %s"),
292 293 294 295 296 297 298 299 300 301 302 303 304 305
                     vm->def->name, uuidstr);
            goto cleanup;
        }

        /* UUID & name match */
        virDomainObjUnlock(vm);
        newVM = 0;
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virDomainFindByName(&driver->domains, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            lxcError(conn, NULL, VIR_ERR_OPERATION_FAILED,
306
                     _("Domain '%s' is already defined with uuid %s"),
307 308 309 310 311
                     def->name, uuidstr);
            goto cleanup;
        }
    }

312 313
    if ((def->nets != NULL) && !(driver->have_netns)) {
        lxcError(conn, NULL, VIR_ERR_NO_SUPPORT,
J
Jim Meyering 已提交
314
                 "%s", _("System lacks NETNS support"));
315
        goto cleanup;
316 317
    }

318 319
    if (!(vm = virDomainAssignDef(conn, driver->caps,
                                  &driver->domains, def)))
320 321
        goto cleanup;
    def = NULL;
322
    vm->persistent = 1;
D
Daniel Veillard 已提交
323

324 325
    if (virDomainSaveConfig(conn,
                            driver->configDir,
326
                            vm->newDef ? vm->newDef : vm->def) < 0) {
327
        virDomainRemoveInactive(&driver->domains, vm);
328
        vm = NULL;
329
        goto cleanup;
D
Daniel Veillard 已提交
330 331
    }

332 333 334 335 336 337
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

D
Daniel Veillard 已提交
338
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
339
    if (dom)
D
Daniel Veillard 已提交
340 341
        dom->id = vm->def->id;

342 343
cleanup:
    virDomainDefFree(def);
344 345
    if (vm)
        virDomainObjUnlock(vm);
346 347
    if (event)
        lxcDomainEventQueue(driver, event);
348
    lxcDriverUnlock(driver);
D
Daniel Veillard 已提交
349 350 351 352 353
    return dom;
}

static int lxcDomainUndefine(virDomainPtr dom)
{
354 355
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
356
    virDomainEventPtr event = NULL;
357
    int ret = -1;
D
Daniel Veillard 已提交
358

359
    lxcDriverLock(driver);
360
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
361 362
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
363
                 "%s", _("No domain with matching uuid"));
364
        goto cleanup;
D
Daniel Veillard 已提交
365 366
    }

D
Daniel P. Berrange 已提交
367
    if (virDomainObjIsActive(vm)) {
368
        lxcError(dom->conn, dom, VIR_ERR_OPERATION_INVALID,
369
                 "%s", _("Cannot delete active domain"));
370
        goto cleanup;
D
Daniel Veillard 已提交
371 372
    }

373
    if (!vm->persistent) {
374
        lxcError(dom->conn, dom, VIR_ERR_OPERATION_INVALID,
375
                 "%s", _("Cannot undefine transient domain"));
376
        goto cleanup;
377
    }
D
Daniel Veillard 已提交
378

379 380 381
    if (virDomainDeleteConfig(dom->conn,
                              driver->configDir,
                              driver->autostartDir,
382 383
                              vm) < 0)
        goto cleanup;
D
Daniel Veillard 已提交
384

385 386 387 388
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

389
    virDomainRemoveInactive(&driver->domains, vm);
390
    vm = NULL;
391
    ret = 0;
D
Daniel Veillard 已提交
392

393
cleanup:
394 395
    if (vm)
        virDomainObjUnlock(vm);
396 397
    if (event)
        lxcDomainEventQueue(driver, event);
398
    lxcDriverUnlock(driver);
399
    return ret;
D
Daniel Veillard 已提交
400 401 402 403 404
}

static int lxcDomainGetInfo(virDomainPtr dom,
                            virDomainInfoPtr info)
{
405 406
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
407
    virCgroupPtr cgroup = NULL;
408
    int ret = -1;
D
Daniel Veillard 已提交
409

410
    lxcDriverLock(driver);
411
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
412

D
Daniel Veillard 已提交
413 414
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
415
                 "%s", _("No domain with matching uuid"));
416
        goto cleanup;
D
Daniel Veillard 已提交
417 418 419 420
    }

    info->state = vm->state;

D
Daniel P. Berrange 已提交
421
    if (!virDomainObjIsActive(vm) || driver->cgroup == NULL) {
D
Daniel Veillard 已提交
422
        info->cpuTime = 0;
R
Ryota Ozaki 已提交
423
        info->memory = vm->def->memory;
D
Daniel Veillard 已提交
424
    } else {
425
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
426
            lxcError(dom->conn, dom, VIR_ERR_INTERNAL_ERROR,
427
                     _("Unable to get cgroup for %s"), vm->def->name);
428 429 430 431
            goto cleanup;
        }

        if (virCgroupGetCpuacctUsage(cgroup, &(info->cpuTime)) < 0) {
R
Ryota Ozaki 已提交
432
            lxcError(dom->conn, dom, VIR_ERR_OPERATION_FAILED,
433
                     "%s", _("Cannot read cputime for domain"));
R
Ryota Ozaki 已提交
434 435 436 437
            goto cleanup;
        }
        if (virCgroupGetMemoryUsage(cgroup, &(info->memory)) < 0) {
            lxcError(dom->conn, dom, VIR_ERR_OPERATION_FAILED,
438
                     "%s", _("Cannot read memory usage for domain"));
439 440
            goto cleanup;
        }
D
Daniel Veillard 已提交
441 442
    }

443
    info->maxMem = vm->def->maxmem;
D
Daniel Veillard 已提交
444
    info->nrVirtCpu = 1;
445
    ret = 0;
D
Daniel Veillard 已提交
446

447
cleanup:
448
    lxcDriverUnlock(driver);
449 450
    if (cgroup)
        virCgroupFree(&cgroup);
451 452
    if (vm)
        virDomainObjUnlock(vm);
453
    return ret;
D
Daniel Veillard 已提交
454 455
}

456
static char *lxcGetOSType(virDomainPtr dom)
D
Daniel Veillard 已提交
457
{
458 459 460
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
461

462
    lxcDriverLock(driver);
463
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
464 465
    lxcDriverUnlock(driver);

466 467
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
468
                 "%s", _("No domain with matching uuid"));
469
        goto cleanup;
470 471
    }

472 473 474
    ret = strdup(vm->def->os.type);

cleanup:
475 476
    if (vm)
        virDomainObjUnlock(vm);
477
    return ret;
D
Daniel Veillard 已提交
478 479
}

R
Ryota Ozaki 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493
/* Returns max memory in kb, 0 if error */
static unsigned long lxcDomainGetMaxMemory(virDomainPtr dom) {
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    lxcDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
494
                         _("No domain with matching uuid '%s'"), uuidstr);
R
Ryota Ozaki 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        goto cleanup;
    }

    ret = vm->def->maxmem;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

static int lxcDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    lxcDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
519
                         _("No domain with matching uuid '%s'"), uuidstr);
R
Ryota Ozaki 已提交
520 521 522 523 524
        goto cleanup;
    }

    if (newmax < vm->def->memory) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_ARG,
525
                         "%s", _("Cannot set max memory lower than current memory"));
R
Ryota Ozaki 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        goto cleanup;
    }

    vm->def->maxmem = newmax;
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

static int lxcDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virCgroupPtr cgroup = NULL;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    lxcDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
551
                 _("No domain with matching uuid '%s'"), uuidstr);
R
Ryota Ozaki 已提交
552 553 554 555 556
        goto cleanup;
    }

    if (newmem > vm->def->maxmem) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_ARG,
557
                 "%s", _("Cannot set memory higher than max memory"));
R
Ryota Ozaki 已提交
558 559 560
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
561
    if (virDomainObjIsActive(vm)) {
R
Ryota Ozaki 已提交
562 563 564 565 566 567 568 569
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
            lxcError(dom->conn, dom, VIR_ERR_INTERNAL_ERROR,
                     _("Unable to get cgroup for %s\n"), vm->def->name);
            goto cleanup;
        }

        if (virCgroupSetMemory(cgroup, newmem) < 0) {
            lxcError(dom->conn, dom, VIR_ERR_OPERATION_FAILED,
570
                     "%s", _("Failed to set memory for domain"));
R
Ryota Ozaki 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
            goto cleanup;
        }
    } else {
        vm->def->memory = newmem;
    }
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    if (cgroup)
        virCgroupFree(&cgroup);
    return ret;
}

D
Daniel Veillard 已提交
586
static char *lxcDomainDumpXML(virDomainPtr dom,
587
                              int flags)
D
Daniel Veillard 已提交
588
{
589 590 591
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
D
Daniel Veillard 已提交
592

593
    lxcDriverLock(driver);
594
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
595 596
    lxcDriverUnlock(driver);

D
Daniel Veillard 已提交
597 598
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
599
                 "%s", _("No domain with matching uuid"));
600
        goto cleanup;
D
Daniel Veillard 已提交
601 602
    }

603 604 605 606 607 608
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) &&
                             vm->newDef ? vm->newDef : vm->def,
                             flags);

cleanup:
609 610
    if (vm)
        virDomainObjUnlock(vm);
611
    return ret;
D
Daniel Veillard 已提交
612 613
}

614 615 616

/**
 * lxcVmCleanup:
617 618 619
 * @conn: pointer to connection
 * @driver: pointer to driver structure
 * @vm: pointer to VM to clean up
620 621 622 623 624 625 626
 *
 * waitpid() on the container process.  kill and wait the tty process
 * This is called by both lxcDomainDestroy and lxcSigHandler when a
 * container exits.
 *
 * Returns 0 on success or -1 in case of error
 */
627
static int lxcVmCleanup(virConnectPtr conn,
628
                        lxc_driver_t *driver,
629
                        virDomainObjPtr  vm)
630 631 632 633
{
    int rc = -1;
    int waitRc;
    int childStatus = -1;
D
Dan Smith 已提交
634
    virCgroupPtr cgroup;
635
    int i;
636 637 638 639 640 641

    while (((waitRc = waitpid(vm->pid, &childStatus, 0)) == -1) &&
           errno == EINTR)
        ; /* empty */

    if ((waitRc != vm->pid) && (errno != ECHILD)) {
642 643 644
        virReportSystemError(conn, errno,
                             _("waitpid failed to wait for container %d: %d"),
                             vm->pid, waitRc);
645 646 647 648 649 650 651 652 653
    }

    rc = 0;

    if (WIFEXITED(childStatus)) {
        rc = WEXITSTATUS(childStatus);
        DEBUG("container exited with rc: %d", rc);
    }

654
    virEventRemoveHandle(vm->monitorWatch);
655 656 657
    close(vm->monitor);

    virFileDeletePid(driver->stateDir, vm->def->name);
658
    virDomainDeleteConfig(conn, driver->stateDir, NULL, vm);
659 660 661 662 663 664

    vm->state = VIR_DOMAIN_SHUTOFF;
    vm->pid = -1;
    vm->def->id = -1;
    vm->monitor = -1;

665 666 667
    for (i = 0 ; i < vm->def->nnets ; i++) {
        vethInterfaceUpOrDown(vm->def->nets[i]->ifname, 0);
        vethDelete(vm->def->nets[i]->ifname);
668 669
    }

670 671
    if (driver->cgroup &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) == 0) {
D
Dan Smith 已提交
672 673 674 675
        virCgroupRemove(cgroup);
        virCgroupFree(&cgroup);
    }

676 677 678 679 680 681 682
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }

683 684 685
    return rc;
}

686 687
/**
 * lxcSetupInterfaces:
688
 * @conn: pointer to connection
689
 * @def: pointer to virtual machine structure
690 691
 * @nveths: number of interfaces
 * @veths: interface names
692 693 694 695 696 697 698 699
 *
 * 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
 */
static int lxcSetupInterfaces(virConnectPtr conn,
700
                              virDomainDefPtr def,
701 702
                              unsigned int *nveths,
                              char ***veths)
703
{
704
    int rc = -1, i;
705
    char *bridge = NULL;
706 707
    char parentVeth[PATH_MAX] = "";
    char containerVeth[PATH_MAX] = "";
708
    brControl *brctl = NULL;
709

710
    if (brInit(&brctl) != 0)
711 712
        return -1;

713 714
    for (i = 0 ; i < def->nnets ; i++) {
        switch (def->nets[i]->type) {
715 716 717
        case VIR_DOMAIN_NET_TYPE_NETWORK:
        {
            virNetworkPtr network = virNetworkLookupByName(conn,
718
                                                           def->nets[i]->data.network.name);
719 720 721 722 723 724 725
            if (!network) {
                goto error_exit;
            }

            bridge = virNetworkGetBridgeName(network);

            virNetworkFree(network);
726 727 728
            break;
        }
        case VIR_DOMAIN_NET_TYPE_BRIDGE:
729
            bridge = def->nets[i]->data.bridge.brname;
730
            break;
731 732 733 734 735
        }

        DEBUG("bridge: %s", bridge);
        if (NULL == bridge) {
            lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
736
                     "%s", _("Failed to get bridge for interface"));
737 738 739 740
            goto error_exit;
        }

        DEBUG0("calling vethCreate()");
741 742
        if (NULL != def->nets[i]->ifname) {
            strcpy(parentVeth, def->nets[i]->ifname);
743 744 745 746
        }
        DEBUG("parentVeth: %s, containerVeth: %s", parentVeth, containerVeth);
        if (0 != (rc = vethCreate(parentVeth, PATH_MAX, containerVeth, PATH_MAX))) {
            lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
747
                     _("Failed to create veth device pair: %d"), rc);
748 749
            goto error_exit;
        }
750 751
        if (NULL == def->nets[i]->ifname) {
            def->nets[i]->ifname = strdup(parentVeth);
752
        }
753 754 755
        if (VIR_REALLOC_N(*veths, (*nveths)+1) < 0)
            goto error_exit;
        if (((*veths)[(*nveths)++] = strdup(containerVeth)) == NULL)
756 757
            goto error_exit;

758
        if (NULL == def->nets[i]->ifname) {
759
            lxcError(NULL, NULL, VIR_ERR_INTERNAL_ERROR,
760
                     "%s", _("Failed to allocate veth names"));
761 762 763
            goto error_exit;
        }

764 765 766 767 768
        if (def->nets[i]->mac) {
            char macaddr[VIR_MAC_STRING_BUFLEN];
            virFormatMacAddr(def->nets[i]->mac, macaddr);
            if (0 != (rc = setMacAddr(containerVeth, macaddr))) {
                virReportSystemError(conn, rc,
769
                                     _("Failed to set %s to %s"),
770 771 772 773 774
                                     macaddr, containerVeth);
                goto error_exit;
            }
        }

775
        if (0 != (rc = brAddInterface(brctl, bridge, parentVeth))) {
776
            virReportSystemError(conn, rc,
777
                                 _("Failed to add %s device to %s"),
778
                                 parentVeth, bridge);
779 780 781 782
            goto error_exit;
        }

        if (0 != (rc = vethInterfaceUpOrDown(parentVeth, 1))) {
783 784 785
            virReportSystemError(conn, rc,
                                 _("Failed to enable %s device"),
                                 parentVeth);
786 787 788 789 790 791 792 793
            goto error_exit;
        }

    }

    rc = 0;

error_exit:
794
    brShutdown(brctl);
795 796 797
    return rc;
}

798

799 800
static int lxcMonitorClient(virConnectPtr conn,
                            lxc_driver_t * driver,
801
                            virDomainObjPtr vm)
802
{
803 804 805
    char *sockpath = NULL;
    int fd;
    struct sockaddr_un addr;
806

807 808
    if (virAsprintf(&sockpath, "%s/%s.sock",
                    driver->stateDir, vm->def->name) < 0) {
809
        virReportOOMError(conn);
810 811 812 813
        return -1;
    }

    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
814
        virReportSystemError(conn, errno, "%s",
815
                             _("Failed to create client socket"));
816
        goto error;
817 818
    }

819 820
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
C
Chris Lalancette 已提交
821 822 823 824 825
    if (virStrcpyStatic(addr.sun_path, sockpath) == NULL) {
        lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
                 _("Socket path %s too big for destination"), sockpath);
        goto error;
    }
826 827

    if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
828
        virReportSystemError(conn, errno, "%s",
829
                             _("Failed to connect to client socket"));
830
        goto error;
831 832
    }

833 834
    VIR_FREE(sockpath);
    return fd;
835

836 837 838 839 840 841 842 843 844 845
error:
    VIR_FREE(sockpath);
    if (fd != -1)
        close(fd);
    return -1;
}


static int lxcVmTerminate(virConnectPtr conn,
                          lxc_driver_t *driver,
846
                          virDomainObjPtr vm,
847 848 849 850
                          int signum)
{
    if (signum == 0)
        signum = SIGINT;
851

852 853
    if (vm->pid <= 0) {
        lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
854
                 _("Invalid PID %d for container"), vm->pid);
855 856 857
        return -1;
    }

858 859
    if (kill(vm->pid, signum) < 0) {
        if (errno != ESRCH) {
860
            virReportSystemError(conn, errno,
861
                                 _("Failed to kill pid %d"),
862
                                 vm->pid);
863
            return -1;
864
        }
865 866
    }

867
    vm->state = VIR_DOMAIN_SHUTDOWN;
868

869
    return lxcVmCleanup(conn, driver, vm);
870
}
871

872 873
static void lxcMonitorEvent(int watch,
                            int fd,
874 875 876
                            int events ATTRIBUTE_UNUSED,
                            void *data)
{
877 878
    lxc_driver_t *driver = lxc_driver;
    virDomainObjPtr vm = data;
879
    virDomainEventPtr event = NULL;
880

881
    lxcDriverLock(driver);
882 883
    virDomainObjLock(vm);
    lxcDriverUnlock(driver);
884

885
    if (vm->monitor != fd || vm->monitorWatch != watch) {
886
        virEventRemoveHandle(watch);
887
        goto cleanup;
888 889
    }

890
    if (lxcVmTerminate(NULL, driver, vm, SIGINT) < 0) {
891
        virEventRemoveHandle(watch);
892 893 894 895 896
    } else {
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
    }
897 898 899 900
    if (!vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
901 902

cleanup:
903 904 905
    virDomainObjUnlock(vm);
    if (event) {
        lxcDriverLock(driver);
906
        lxcDomainEventQueue(driver, event);
907 908
        lxcDriverUnlock(driver);
    }
909 910 911
}


912 913 914 915 916 917 918 919 920 921 922
static int lxcControllerStart(virConnectPtr conn,
                              virDomainObjPtr vm,
                              int nveths,
                              char **veths,
                              int appPty,
                              int logfd)
{
    int i;
    int rc;
    int largc = 0, larga = 0;
    const char **largv = NULL;
A
Amy Griffis 已提交
923 924 925 926 927
    int lenvc = 0, lenva = 0;
    const char **lenv = NULL;
    char *filterstr;
    char *outputstr;
    char *tmp;
A
Amy Griffis 已提交
928
    int log_level;
929 930
    pid_t child;
    int status;
931 932
    fd_set keepfd;
    char appPtyStr[30];
933
    const char *emulator;
A
Amy Griffis 已提交
934
    lxc_driver_t *driver = conn->privateData;
935 936

    FD_ZERO(&keepfd);
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

#define ADD_ARG_SPACE                                                   \
    do { \
        if (largc == larga) {                                           \
            larga += 10;                                                \
            if (VIR_REALLOC_N(largv, larga) < 0)                        \
                goto no_memory;                                         \
        }                                                               \
    } while (0)

#define ADD_ARG(thisarg)                                                \
    do {                                                                \
        ADD_ARG_SPACE;                                                  \
        largv[largc++] = thisarg;                                       \
    } while (0)

#define ADD_ARG_LIT(thisarg)                                            \
    do {                                                                \
        ADD_ARG_SPACE;                                                  \
        if ((largv[largc++] = strdup(thisarg)) == NULL)                 \
            goto no_memory;                                             \
    } while (0)

A
Amy Griffis 已提交
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
#define ADD_ENV_SPACE                                                   \
    do {                                                                \
        if (lenvc == lenva) {                                           \
            lenva += 10;                                                \
            if (VIR_REALLOC_N(lenv, lenva) < 0)                         \
                goto no_memory;                                         \
        }                                                               \
    } while (0)

#define ADD_ENV(thisarg)                                                \
    do {                                                                \
        ADD_ENV_SPACE;                                                  \
        lenv[lenvc++] = thisarg;                                        \
    } while (0)

#define ADD_ENV_PAIR(envname, val)                                      \
    do {                                                                \
        char *envval;                                                   \
        ADD_ENV_SPACE;                                                  \
        if (virAsprintf(&envval, "%s=%s", envname, val) < 0)            \
            goto no_memory;                                             \
        lenv[lenvc++] = envval;                                         \
    } while (0)

984 985 986 987 988 989 990 991 992 993 994 995 996
#define ADD_ENV_COPY(envname)                                           \
    do {                                                                \
        char *val = getenv(envname);                                    \
        if (val != NULL) {                                              \
            ADD_ENV_PAIR(envname, val);                                 \
        }                                                               \
    } while (0)

    /*
     * The controller may call ip command, so we have to remain PATH.
     */
    ADD_ENV_COPY("PATH");

A
Amy Griffis 已提交
997 998
    log_level = virLogGetDefaultPriority();
    if (virAsprintf(&tmp, "LIBVIRT_DEBUG=%d", log_level) < 0)
A
Amy Griffis 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        goto no_memory;
    ADD_ENV(tmp);

    if (virLogGetNbFilters() > 0) {
        filterstr = virLogGetFilters();
        if (!filterstr)
            goto no_memory;
        ADD_ENV_PAIR("LIBVIRT_LOG_FILTERS", filterstr);
        VIR_FREE(filterstr);
    }

A
Amy Griffis 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    if (driver->log_libvirtd) {
        if (virLogGetNbOutputs() > 0) {
            outputstr = virLogGetOutputs();
            if (!outputstr)
                goto no_memory;
            ADD_ENV_PAIR("LIBVIRT_LOG_OUTPUTS", outputstr);
            VIR_FREE(outputstr);
        }
    } else {
        if (virAsprintf(&tmp, "LIBVIRT_LOG_OUTPUTS=%d:stderr", log_level) < 0)
A
Amy Griffis 已提交
1020
            goto no_memory;
A
Amy Griffis 已提交
1021
        ADD_ENV(tmp);
A
Amy Griffis 已提交
1022 1023 1024 1025
    }

    ADD_ENV(NULL);

1026 1027
    snprintf(appPtyStr, sizeof(appPtyStr), "%d", appPty);

1028 1029 1030
    emulator = vm->def->emulator;

    ADD_ARG_LIT(emulator);
1031 1032 1033
    ADD_ARG_LIT("--name");
    ADD_ARG_LIT(vm->def->name);
    ADD_ARG_LIT("--console");
1034
    ADD_ARG_LIT(appPtyStr);
1035 1036 1037 1038 1039 1040 1041 1042 1043
    ADD_ARG_LIT("--background");

    for (i = 0 ; i < nveths ; i++) {
        ADD_ARG_LIT("--veth");
        ADD_ARG_LIT(veths[i]);
    }

    ADD_ARG(NULL);

1044 1045
    FD_SET(appPty, &keepfd);

A
Amy Griffis 已提交
1046
    if (virExec(conn, largv, lenv, &keepfd, &child,
1047
                -1, &logfd, &logfd,
1048 1049 1050 1051 1052 1053 1054 1055 1056
                VIR_EXEC_NONE) < 0)
        goto cleanup;

    /* We now wait for the process to exit - the controller
     * will fork() itself into the background - waiting for
     * it to exit thus guarentees it has written its pidfile
     */
    while ((rc = waitpid(child, &status, 0) == -1) && errno == EINTR);
    if (rc == -1) {
1057
        virReportSystemError(conn, errno,
1058
                             _("Cannot wait for '%s'"),
1059
                             largv[0]);
1060 1061 1062 1063 1064
        goto cleanup;
    }

    if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0)) {
        lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
1065
                 _("Container '%s' unexpectedly shutdown during startup"),
1066 1067 1068 1069 1070 1071 1072
                 largv[0]);
        goto cleanup;
    }

#undef ADD_ARG
#undef ADD_ARG_LIT
#undef ADD_ARG_SPACE
A
Amy Griffis 已提交
1073 1074
#undef ADD_ENV_SPACE
#undef ADD_ENV_PAIR
1075

A
Amy Griffis 已提交
1076
    return 0;
1077 1078

no_memory:
1079
    virReportOOMError(conn);
A
Amy Griffis 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
cleanup:
    if (largv) {
        for (i = 0 ; i < largc ; i++)
            VIR_FREE(largv[i]);
        VIR_FREE(largv);
    }
    if (lenv) {
        for (i=0 ; i < lenvc ; i++)
            VIR_FREE(lenv[i]);
        VIR_FREE(lenv);
    }
    return -1;
1092 1093 1094
}


1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
/**
 * lxcVmStart:
 * @conn: pointer to connection
 * @driver: pointer to driver structure
 * @vm: pointer to virtual machine structure
 *
 * Starts a vm
 *
 * Returns 0 on success or -1 in case of error
 */
static int lxcVmStart(virConnectPtr conn,
                      lxc_driver_t * driver,
1107
                      virDomainObjPtr  vm)
1108
{
1109
    int rc = -1, r;
1110 1111
    unsigned int i;
    int parentTty;
1112
    char *parentTtyPath = NULL;
1113 1114 1115 1116 1117
    char *logfile = NULL;
    int logfd = -1;
    unsigned int nveths = 0;
    char **veths = NULL;

1118 1119
    if ((r = virFileMakePath(driver->logDir)) < 0) {
        virReportSystemError(conn, r,
1120
                             _("Cannot create log directory '%s'"),
1121
                             driver->logDir);
1122 1123
        return -1;
    }
1124

1125 1126
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
1127
        virReportOOMError(conn);
1128
        return -1;
1129 1130
    }

1131
    /* open parent tty */
1132
    if (virFileOpenTty(&parentTty, &parentTtyPath, 1) < 0) {
1133
        virReportSystemError(conn, errno, "%s",
1134
                             _("Failed to allocate tty"));
1135 1136
        goto cleanup;
    }
1137 1138 1139 1140 1141 1142 1143
    if (vm->def->console &&
        vm->def->console->type == VIR_DOMAIN_CHR_TYPE_PTY) {
        VIR_FREE(vm->def->console->data.file.path);
        vm->def->console->data.file.path = parentTtyPath;
    } else {
        VIR_FREE(parentTtyPath);
    }
1144

1145
    if (lxcSetupInterfaces(conn, vm->def, &nveths, &veths) != 0)
1146
        goto cleanup;
1147

1148
    /* Persist the live configuration now we have veth & tty info */
1149
    if (virDomainSaveConfig(conn, driver->stateDir, vm->def) < 0)
1150 1151
        goto cleanup;

1152
    if ((logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT,
1153
             S_IRUSR|S_IWUSR)) < 0) {
1154
        virReportSystemError(conn, errno,
1155
                             _("Failed to open '%s'"),
1156
                             logfile);
1157
        goto cleanup;
1158 1159
    }

1160 1161 1162 1163
    if (lxcControllerStart(conn,
                           vm,
                           nveths, veths,
                           parentTty, logfd) < 0)
1164
        goto cleanup;
1165 1166 1167 1168 1169

    /* Connect to the controller as a client *first* because
     * this will block until the child has written their
     * pid file out to disk */
    if ((vm->monitor = lxcMonitorClient(conn, driver, vm)) < 0)
1170 1171
        goto cleanup;

1172
    /* And get its pid */
1173 1174
    if ((r = virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) != 0) {
        virReportSystemError(conn, r,
1175 1176
                             _("Failed to read pid file %s/%s.pid"),
                             driver->stateDir, vm->def->name);
1177
        goto cleanup;
1178
    }
1179

1180
    vm->def->id = vm->pid;
1181 1182
    vm->state = VIR_DOMAIN_RUNNING;

1183 1184 1185 1186
    if ((vm->monitorWatch = virEventAddHandle(
             vm->monitor,
             VIR_EVENT_HANDLE_ERROR | VIR_EVENT_HANDLE_HANGUP,
             lxcMonitorEvent,
1187
             driver, NULL)) < 0) {
1188 1189 1190
        lxcVmTerminate(conn, driver, vm, 0);
        goto cleanup;
    }
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    rc = 0;

cleanup:
    for (i = 0 ; i < nveths ; i++) {
        if (rc != 0)
            vethDelete(veths[i]);
        VIR_FREE(veths[i]);
    }
    if (rc != 0 && vm->monitor != -1) {
        close(vm->monitor);
        vm->monitor = -1;
    }
    if (parentTty != -1)
        close(parentTty);
    if (logfd != -1)
        close(logfd);
    VIR_FREE(logfile);
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    return rc;
}

/**
 * lxcDomainStart:
 * @dom: domain to start
 *
 * Looks up domain and starts it.
 *
 * Returns 0 on success or -1 in case of error
 */
static int lxcDomainStart(virDomainPtr dom)
{
1222 1223
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1224
    virDomainEventPtr event = NULL;
1225
    int ret = -1;
1226

1227
    lxcDriverLock(driver);
1228
    vm = virDomainFindByName(&driver->domains, dom->name);
1229
    if (!vm) {
1230
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
1231
                 _("No domain named %s"), dom->name);
1232 1233 1234
        goto cleanup;
    }

1235
    if ((vm->def->nets != NULL) && !(driver->have_netns)) {
1236
        lxcError(dom->conn, NULL, VIR_ERR_NO_SUPPORT,
J
Jim Meyering 已提交
1237
                 "%s", _("System lacks NETNS support"));
1238 1239 1240
        goto cleanup;
    }

1241
    ret = lxcVmStart(dom->conn, driver, vm);
1242

1243 1244 1245 1246 1247
    if (ret == 0)
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);

1248
cleanup:
1249 1250
    if (vm)
        virDomainObjUnlock(vm);
1251 1252
    if (event)
        lxcDomainEventQueue(driver, event);
1253
    lxcDriverUnlock(driver);
1254
    return ret;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
}

/**
 * lxcDomainCreateAndStart:
 * @conn: pointer to connection
 * @xml: XML definition of domain
 * @flags: Unused
 *
 * Creates a domain based on xml and starts it
 *
 * Returns 0 on success or -1 in case of error
 */
static virDomainPtr
lxcDomainCreateAndStart(virConnectPtr conn,
                        const char *xml,
                        unsigned int flags ATTRIBUTE_UNUSED) {
1271
    lxc_driver_t *driver = conn->privateData;
1272
    virDomainObjPtr vm = NULL;
1273
    virDomainDefPtr def;
1274
    virDomainPtr dom = NULL;
1275
    virDomainEventPtr event = NULL;
1276

1277
    lxcDriverLock(driver);
1278 1279
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1280
        goto cleanup;
1281

1282 1283 1284 1285 1286 1287 1288 1289
    /* See if a VM with matching UUID already exists */
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
    if (vm) {
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            lxcError(conn, NULL, VIR_ERR_OPERATION_FAILED,
1290
                     _("Domain '%s' is already defined with uuid %s"),
1291 1292 1293 1294 1295
                     vm->def->name, uuidstr);
            goto cleanup;
        }

        /* UUID & name match, but if VM is already active, refuse it */
D
Daniel P. Berrange 已提交
1296
        if (virDomainObjIsActive(vm)) {
1297
            lxcError(conn, NULL, VIR_ERR_OPERATION_FAILED,
1298
                     _("Domain is already active as '%s'"), vm->def->name);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
            goto cleanup;
        }
        virDomainObjUnlock(vm);
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virDomainFindByName(&driver->domains, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            lxcError(conn, NULL, VIR_ERR_OPERATION_FAILED,
1309
                     _("Domain '%s' is already defined with uuid %s"),
1310 1311 1312 1313 1314
                     def->name, uuidstr);
            goto cleanup;
        }
    }

1315 1316
    if ((def->nets != NULL) && !(driver->have_netns)) {
        lxcError(conn, NULL, VIR_ERR_NO_SUPPORT,
J
Jim Meyering 已提交
1317
                 "%s", _("System lacks NETNS support"));
1318
        goto cleanup;
1319 1320
    }

1321

1322 1323
    if (!(vm = virDomainAssignDef(conn, driver->caps,
                                  &driver->domains, def)))
1324 1325
        goto cleanup;
    def = NULL;
1326 1327

    if (lxcVmStart(conn, driver, vm) < 0) {
1328
        virDomainRemoveInactive(&driver->domains, vm);
1329
        vm = NULL;
1330
        goto cleanup;
1331 1332
    }

1333 1334 1335 1336
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);

1337
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1338
    if (dom)
1339 1340
        dom->id = vm->def->id;

1341 1342
cleanup:
    virDomainDefFree(def);
1343 1344
    if (vm)
        virDomainObjUnlock(vm);
1345 1346
    if (event)
        lxcDomainEventQueue(driver, event);
1347
    lxcDriverUnlock(driver);
1348 1349 1350 1351 1352
    return dom;
}

/**
 * lxcDomainShutdown:
1353
 * @dom: pointer to domain to shutdown
1354 1355 1356 1357 1358 1359 1360
 *
 * Sends SIGINT to container root process to request it to shutdown
 *
 * Returns 0 on success or -1 in case of error
 */
static int lxcDomainShutdown(virDomainPtr dom)
{
1361 1362
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1363
    virDomainEventPtr event = NULL;
1364
    int ret = -1;
1365

1366
    lxcDriverLock(driver);
1367
    vm = virDomainFindByID(&driver->domains, dom->id);
1368 1369
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
1370
                 _("No domain with id %d"), dom->id);
1371
        goto cleanup;
1372 1373
    }

1374
    ret = lxcVmTerminate(dom->conn, driver, vm, 0);
1375 1376 1377
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
1378 1379 1380 1381
    if (!vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
1382 1383

cleanup:
1384 1385
    if (vm)
        virDomainObjUnlock(vm);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    if (event)
        lxcDomainEventQueue(driver, event);
    lxcDriverUnlock(driver);
    return ret;
}


static int
lxcDomainEventRegister (virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
{
    lxc_driver_t *driver = conn->privateData;
    int ret;

    lxcDriverLock(driver);
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
1405
    lxcDriverUnlock(driver);
1406

1407
    return ret;
1408 1409
}

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
static int
lxcDomainEventDeregister (virConnectPtr conn,
                          virConnectDomainEventCallback callback)
{
    lxc_driver_t *driver = conn->privateData;
    int ret;

    lxcDriverLock(driver);
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
    lxcDriverUnlock(driver);

    return ret;
}

static void lxcDomainEventDispatchFunc(virConnectPtr conn,
                                       virDomainEventPtr event,
                                       virConnectDomainEventCallback cb,
                                       void *cbopaque,
                                       void *opaque)
{
    lxc_driver_t *driver = opaque;

    /* Drop the lock whle dispatching, for sake of re-entrancy */
    lxcDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    lxcDriverLock(driver);
}


static void lxcDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    lxc_driver_t *driver = opaque;
    virDomainEventQueue tempQueue;

    lxcDriverLock(driver);

    driver->domainEventDispatching = 1;

    /* Copy the queue, so we're reentrant safe */
    tempQueue.count = driver->domainEventQueue->count;
    tempQueue.events = driver->domainEventQueue->events;
    driver->domainEventQueue->count = 0;
    driver->domainEventQueue->events = NULL;

    virEventUpdateTimeout(driver->domainEventTimer, -1);
    virDomainEventQueueDispatch(&tempQueue,
                                driver->domainEventCallbacks,
                                lxcDomainEventDispatchFunc,
                                driver);

    /* Purge any deleted callbacks */
    virDomainEventCallbackListPurgeMarked(driver->domainEventCallbacks);

    driver->domainEventDispatching = 0;
    lxcDriverUnlock(driver);
}


/* driver must be locked before calling */
static void lxcDomainEventQueue(lxc_driver_t *driver,
                                 virDomainEventPtr event)
{
    if (virDomainEventQueuePush(driver->domainEventQueue,
                                event) < 0)
        virDomainEventFree(event);
    if (lxc_driver->domainEventQueue->count == 1)
        virEventUpdateTimeout(driver->domainEventTimer, 0);
}
1483 1484 1485

/**
 * lxcDomainDestroy:
1486
 * @dom: pointer to domain to destroy
1487 1488 1489 1490 1491 1492 1493
 *
 * Sends SIGKILL to container root process to terminate the container
 *
 * Returns 0 on success or -1 in case of error
 */
static int lxcDomainDestroy(virDomainPtr dom)
{
1494 1495
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1496
    virDomainEventPtr event = NULL;
1497
    int ret = -1;
1498

1499
    lxcDriverLock(driver);
1500
    vm = virDomainFindByID(&driver->domains, dom->id);
1501 1502
    if (!vm) {
        lxcError(dom->conn, dom, VIR_ERR_INVALID_DOMAIN,
1503
                 _("No domain with id %d"), dom->id);
1504
        goto cleanup;
1505 1506
    }

1507
    ret = lxcVmTerminate(dom->conn, driver, vm, SIGKILL);
1508 1509 1510
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1511 1512 1513 1514
    if (!vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
1515 1516

cleanup:
1517 1518
    if (vm)
        virDomainObjUnlock(vm);
1519 1520
    if (event)
        lxcDomainEventQueue(driver, event);
1521
    lxcDriverUnlock(driver);
1522
    return ret;
1523
}
1524

1525 1526 1527 1528 1529
static int lxcCheckNetNsSupport(void)
{
    const char *argv[] = {"ip", "link", "set", "lo", "netns", "-1", NULL};
    int ip_rc;

1530 1531 1532
    if (virRun(NULL, argv, &ip_rc) < 0 ||
        !(WIFEXITED(ip_rc) && (WEXITSTATUS(ip_rc) != 255)))
        return 0;
1533

1534 1535
    if (lxcContainerAvailable(LXC_CONTAINER_FEATURE_NET) < 0)
        return 0;
1536

1537
    return 1;
1538 1539
}

1540

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
struct lxcAutostartData {
    lxc_driver_t *driver;
    virConnectPtr conn;
};

static void
lxcAutostartDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr vm = payload;
    const struct lxcAutostartData *data = opaque;

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
1554
        !virDomainObjIsActive(vm)) {
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
        int ret = lxcVmStart(data->conn, data->driver, vm);
        if (ret < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s\n"),
                      vm->def->name,
                      err ? err->message : "");
        } else {
            virDomainEventPtr event =
                virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
                lxcDomainEventQueue(data->driver, event);
        }
    }
    virDomainObjUnlock(vm);
}

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
static void
lxcAutostartConfigs(lxc_driver_t *driver) {
    /* 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 */

1583 1584
    struct lxcAutostartData data = { driver, conn };

1585
    lxcDriverLock(driver);
1586
    virHashForEach(driver->domains.objs, lxcAutostartDomain, &data);
1587 1588 1589 1590 1591 1592
    lxcDriverUnlock(driver);

    if (conn)
        virConnectClose(conn);
}

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
static void
lxcReconnectVM(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr vm = payload;
    lxc_driver_t *driver = opaque;
    char *config = NULL;
    virDomainDefPtr tmp;

    virDomainObjLock(vm);
    if ((vm->monitor = lxcMonitorClient(NULL, driver, vm)) < 0) {
        goto cleanup;
    }

    /* Read pid from controller */
    if ((virFileReadPid(lxc_driver->stateDir, vm->def->name, &vm->pid)) != 0) {
        close(vm->monitor);
        vm->monitor = -1;
        goto cleanup;
    }

    if ((config = virDomainConfigFile(NULL,
                                      driver->stateDir,
                                      vm->def->name)) == NULL)
        goto cleanup;

    /* Try and load the live config */
    tmp = virDomainDefParseFile(NULL, driver->caps, config, 0);
    VIR_FREE(config);
    if (tmp) {
        vm->newDef = vm->def;
        vm->def = tmp;
    }

    if (vm->pid != 0) {
        vm->def->id = vm->pid;
        vm->state = VIR_DOMAIN_RUNNING;
    } else {
        vm->def->id = -1;
        close(vm->monitor);
        vm->monitor = -1;
    }

cleanup:
    virDomainObjUnlock(vm);
}

1639

1640
static int lxcStartup(int privileged)
D
Daniel Veillard 已提交
1641
{
1642
    char *ld;
1643
    int rc;
1644 1645 1646 1647 1648 1649

    /* Valgrind gets very annoyed when we clone containers, so
     * disable LXC when under valgrind
     * XXX remove this when valgrind is fixed
     */
    ld = getenv("LD_PRELOAD");
1650 1651 1652 1653
    if (ld && strstr(ld, "vgpreload")) {
        VIR_INFO0("Running under valgrind, disabling driver");
        return 0;
    }
1654

1655
    /* Check that the user is root, silently disable if not */
1656
    if (!privileged) {
1657 1658 1659 1660 1661 1662 1663 1664
        VIR_INFO0("Not running privileged, disabling driver");
        return 0;
    }

    /* Check that this is a container enabled kernel */
    if (lxcContainerAvailable(0) < 0) {
        VIR_INFO0("LXC support not available in this kernel, disabling driver");
        return 0;
1665 1666
    }

1667
    if (VIR_ALLOC(lxc_driver) < 0) {
1668 1669
        return -1;
    }
1670 1671 1672 1673
    if (virMutexInit(&lxc_driver->lock) < 0) {
        VIR_FREE(lxc_driver);
        return -1;
    }
1674
    lxcDriverLock(lxc_driver);
D
Daniel Veillard 已提交
1675

1676 1677 1678
    if (virDomainObjListInit(&lxc_driver->domains) < 0)
        goto cleanup;

1679
    if (VIR_ALLOC(lxc_driver->domainEventCallbacks) < 0)
1680 1681 1682 1683 1684 1685 1686 1687
        goto cleanup;
    if (!(lxc_driver->domainEventQueue = virDomainEventQueueNew()))
        goto cleanup;

    if ((lxc_driver->domainEventTimer =
         virEventAddTimeout(-1, lxcDomainEventFlush, lxc_driver, NULL)) < 0)
        goto cleanup;

A
Amy Griffis 已提交
1688
    lxc_driver->log_libvirtd = 0; /* by default log to container logfile */
1689
    lxc_driver->have_netns = lxcCheckNetNsSupport();
D
Daniel Veillard 已提交
1690

1691 1692 1693 1694 1695 1696 1697
    rc = virCgroupForDriver("lxc", &lxc_driver->cgroup, privileged, 1);
    if (rc < 0) {
        char buf[1024];
        VIR_WARN("Unable to create cgroup for driver: %s",
                 virStrerror(-rc, buf, sizeof(buf)));
    }

D
Daniel Veillard 已提交
1698
    /* Call function to load lxc driver configuration information */
1699 1700
    if (lxcLoadDriverConfig(lxc_driver) < 0)
        goto cleanup;
D
Daniel Veillard 已提交
1701

1702 1703
    if ((lxc_driver->caps = lxcCapsInit()) == NULL)
        goto cleanup;
D
Daniel Veillard 已提交
1704

1705 1706 1707 1708
    if (virDomainLoadAllConfigs(NULL,
                                lxc_driver->caps,
                                &lxc_driver->domains,
                                lxc_driver->configDir,
1709
                                lxc_driver->autostartDir,
1710
                                0, NULL, NULL) < 0)
1711
        goto cleanup;
1712

1713
    virHashForEach(lxc_driver->domains.objs, lxcReconnectVM, lxc_driver);
1714

1715
    lxcDriverUnlock(lxc_driver);
D
Daniel Veillard 已提交
1716 1717
    return 0;

1718 1719 1720 1721
cleanup:
    lxcDriverUnlock(lxc_driver);
    lxcShutdown();
    return -1;
D
Daniel Veillard 已提交
1722 1723
}

1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
static void lxcNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    lxc_driver_t *driver = opaque;

    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            lxcDomainEventQueue(driver, event);
    }
}

/**
 * lxcReload:
 *
 * Function to restart the LXC driver, it will recheck the configuration
 * files and perform autostart
 */
static int
lxcReload(void) {
    if (!lxc_driver)
        return 0;

    lxcDriverLock(lxc_driver);
    virDomainLoadAllConfigs(NULL,
                            lxc_driver->caps,
                            &lxc_driver->domains,
                            lxc_driver->configDir,
                            lxc_driver->autostartDir,
                            0, lxcNotifyLoadDomain, lxc_driver);
    lxcDriverUnlock(lxc_driver);

    lxcAutostartConfigs(lxc_driver);

    return 0;
}

1763
static int lxcShutdown(void)
D
Daniel Veillard 已提交
1764
{
1765
    if (lxc_driver == NULL)
1766
        return(-1);
1767

1768
    lxcDriverLock(lxc_driver);
1769
    virDomainObjListDeinit(&lxc_driver->domains);
1770

1771 1772 1773 1774 1775 1776
    virDomainEventCallbackListFree(lxc_driver->domainEventCallbacks);
    virDomainEventQueueFree(lxc_driver->domainEventQueue);

    if (lxc_driver->domainEventTimer != -1)
        virEventRemoveTimeout(lxc_driver->domainEventTimer);

1777 1778 1779 1780 1781 1782
    virCapabilitiesFree(lxc_driver->caps);
    VIR_FREE(lxc_driver->configDir);
    VIR_FREE(lxc_driver->autostartDir);
    VIR_FREE(lxc_driver->stateDir);
    VIR_FREE(lxc_driver->logDir);
    lxcDriverUnlock(lxc_driver);
1783
    virMutexDestroy(&lxc_driver->lock);
1784
    VIR_FREE(lxc_driver);
1785 1786 1787

    return 0;
}
D
Daniel Veillard 已提交
1788

1789 1790 1791 1792 1793 1794 1795 1796 1797
/**
 * lxcActive:
 *
 * Checks if the LXC daemon is active, i.e. has an active domain
 *
 * Returns 1 if active, 0 otherwise
 */
static int
lxcActive(void) {
1798
    int active;
1799

1800 1801
    if (lxc_driver == NULL)
        return(0);
1802

1803
    lxcDriverLock(lxc_driver);
1804
    active = virDomainObjListNumOfDomains(&lxc_driver->domains, 1);
1805
    lxcDriverUnlock(lxc_driver);
1806

1807
    return active;
D
Daniel Veillard 已提交
1808 1809
}

D
Dan Smith 已提交
1810 1811 1812 1813 1814 1815 1816
static int lxcVersion(virConnectPtr conn, unsigned long *version)
{
    struct utsname ver;
    int maj;
    int min;
    int rev;

1817
    uname(&ver);
D
Dan Smith 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828

    if (sscanf(ver.release, "%i.%i.%i", &maj, &min, &rev) != 3) {
        lxcError(conn, NULL, VIR_ERR_INTERNAL_ERROR,
                 _("Unknown release: %s"), ver.release);
        return -1;
    }

    *version = (maj * 1000 * 1000) + (min * 1000) + rev;

    return 0;
}
1829

1830 1831
static char *lxcGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED,
                                 int *nparams)
1832 1833 1834 1835 1836 1837 1838
{
    if (nparams)
        *nparams = 1;

    return strdup("posix");
}

1839
static int lxcSetSchedulerParameters(virDomainPtr domain,
1840 1841 1842
                                     virSchedParameterPtr params,
                                     int nparams)
{
1843
    lxc_driver_t *driver = domain->conn->privateData;
1844
    int i;
1845 1846 1847
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
1848

1849
    if (driver->cgroup == NULL)
1850 1851 1852 1853
        return -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
1854

1855 1856 1857 1858
    if (vm == NULL) {
        lxcError(NULL, domain, VIR_ERR_INTERNAL_ERROR,
                 _("No such domain %s"), domain->uuid);
        goto cleanup;
1859 1860
    }

1861
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0)
1862
        goto cleanup;
1863 1864 1865

    for (i = 0; i < nparams; i++) {
        virSchedParameterPtr param = &params[i];
1866
        if (param->type != VIR_DOMAIN_SCHED_FIELD_ULLONG) {
C
Chris Lalancette 已提交
1867
            lxcError(NULL, domain, VIR_ERR_INVALID_ARG, "%s",
1868
                     _("Invalid type for cpu_shares tunable, expected a 'ullong'"));
1869 1870
            goto cleanup;
        }
1871 1872

        if (STREQ(param->field, "cpu_shares")) {
1873
            if (virCgroupSetCpuShares(group, params[i].value.ul) != 0)
1874
                goto cleanup;
1875
        } else {
1876
            lxcError(NULL, domain, VIR_ERR_INVALID_ARG,
1877
                     _("Invalid parameter `%s'"), param->field);
1878
            goto cleanup;
1879 1880
        }
    }
1881
    ret = 0;
1882

1883
cleanup:
1884
    lxcDriverUnlock(driver);
1885
    virCgroupFree(&group);
1886 1887
    if (vm)
        virDomainObjUnlock(vm);
1888
    return ret;
1889 1890
}

1891
static int lxcGetSchedulerParameters(virDomainPtr domain,
1892 1893 1894
                                     virSchedParameterPtr params,
                                     int *nparams)
{
1895
    lxc_driver_t *driver = domain->conn->privateData;
1896 1897
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
1898
    unsigned long long val;
1899
    int ret = -1;
1900

1901
    if (driver->cgroup == NULL)
1902
        return -1;
1903 1904

    if ((*nparams) != 1) {
1905
        lxcError(NULL, domain, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1906
                 "%s", _("Invalid parameter count"));
1907
        return -1;
1908 1909
    }

1910 1911 1912
    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);

1913 1914 1915 1916
    if (vm == NULL) {
        lxcError(NULL, domain, VIR_ERR_INTERNAL_ERROR,
                 _("No such domain %s"), domain->uuid);
        goto cleanup;
1917 1918
    }

1919
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0)
1920
        goto cleanup;
1921

1922 1923
    if (virCgroupGetCpuShares(group, &val) != 0)
        goto cleanup;
1924
    params[0].value.ul = val;
C
Chris Lalancette 已提交
1925 1926 1927 1928 1929
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
        lxcError(NULL, domain, VIR_ERR_INTERNAL_ERROR,
                 "%s", _("Field cpu_shares too big for destination"));
        goto cleanup;
    }
1930 1931
    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;

1932
    ret = 0;
1933

1934
cleanup:
1935
    lxcDriverUnlock(driver);
1936
    virCgroupFree(&group);
1937 1938
    if (vm)
        virDomainObjUnlock(vm);
1939
    return ret;
1940 1941
}

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
static int lxcDomainGetAutostart(virDomainPtr dom,
                                   int *autostart) {
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    lxcDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
1956
                 _("No domain with matching uuid '%s'"), uuidstr);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
        goto cleanup;
    }

    *autostart = vm->autostart;
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

static int lxcDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
1983
                 _("No domain with matching uuid '%s'"), uuidstr);
1984 1985 1986 1987 1988
        goto cleanup;
    }

    if (!vm->persistent) {
        lxcError(dom->conn, dom, VIR_ERR_INTERNAL_ERROR,
1989
                 "%s", _("Cannot set autostart for transient domain"));
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
        goto cleanup;
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
        if ((configFile = virDomainConfigFile(dom->conn, driver->configDir, vm->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virDomainConfigFile(dom->conn, driver->autostartDir, vm->def->name)) == NULL)
            goto cleanup;

        if (autostart) {
            int err;

            if ((err = virFileMakePath(driver->autostartDir))) {
                virReportSystemError(dom->conn, err,
2006
                                     _("Cannot create autostart directory %s"),
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
                                     driver->autostartDir);
                goto cleanup;
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
                goto cleanup;
            }
        }

        vm->autostart = autostart;
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
        virDomainObjUnlock(vm);
    lxcDriverUnlock(driver);
    return ret;
}

R
Ryota Ozaki 已提交
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
static int lxcFreezeContainer(lxc_driver_t *driver, virDomainObjPtr vm)
{
    int timeout = 1000; /* In milliseconds */
    int check_interval = 1; /* In milliseconds */
    int exp = 10;
    int waited_time = 0;
    int ret = -1;
    char *state = NULL;
    virCgroupPtr cgroup = NULL;

    if (!(driver->cgroup &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) == 0))
        return -1;

    while (waited_time < timeout) {
        int r;
        /*
         * Writing "FROZEN" to the "freezer.state" freezes the group,
         * i.e., the container, temporarily transiting "FREEZING" state.
         * Once the freezing is completed, the state of the group transits
         * to "FROZEN".
         * (see linux-2.6/Documentation/cgroups/freezer-subsystem.txt)
         */
        r = virCgroupSetFreezerState(cgroup, "FROZEN");

        /*
         * Returning EBUSY explicitly indicates that the group is
         * being freezed but incomplete and other errors are true
         * errors.
         */
        if (r < 0 && r != -EBUSY) {
            VIR_DEBUG("Writing freezer.state failed with errno: %d", r);
            goto error;
        }
        if (r == -EBUSY)
            VIR_DEBUG0("Writing freezer.state gets EBUSY");

        /*
         * Unfortunately, returning 0 (success) is likely to happen
         * even when the freezing has not been completed. Sometimes
         * the state of the group remains "FREEZING" like when
         * returning -EBUSY and even worse may never transit to
         * "FROZEN" even if writing "FROZEN" again.
         *
         * So we don't trust the return value anyway and always
         * decide that the freezing has been complete only with
         * the state actually transit to "FROZEN".
         */
        usleep(check_interval * 1000);

        r = virCgroupGetFreezerState(cgroup, &state);

        if (r < 0) {
            VIR_DEBUG("Reading freezer.state failed with errno: %d", r);
            goto error;
        }
        VIR_DEBUG("Read freezer.state: %s", state);

        if (STREQ(state, "FROZEN")) {
            ret = 0;
            goto cleanup;
        }

        waited_time += check_interval;
        /*
         * Increasing check_interval exponentially starting with
         * small initial value treats nicely two cases; One is
         * a container is under no load and waiting for long period
         * makes no sense. The other is under heavy load. The container
         * may stay longer time in FREEZING or never transit to FROZEN.
         * In that case, eager polling will just waste CPU time.
         */
        check_interval *= exp;
        VIR_FREE(state);
    }
    VIR_DEBUG0("lxcFreezeContainer timeout");
error:
    /*
     * If timeout or an error on reading the state occurs,
     * activate the group again and return an error.
     * This is likely to fall the group back again gracefully.
     */
    virCgroupSetFreezerState(cgroup, "THAWED");
    ret = -1;

cleanup:
    if (cgroup)
        virCgroupFree(&cgroup);
    VIR_FREE(state);
    return ret;
}

static int lxcDomainSuspend(virDomainPtr dom)
{
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainEventPtr event = NULL;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
2145
                 _("No domain with matching uuid '%s'"), uuidstr);
R
Ryota Ozaki 已提交
2146 2147 2148
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
2149
    if (!virDomainObjIsActive(vm)) {
R
Ryota Ozaki 已提交
2150
        lxcError(dom->conn, dom, VIR_ERR_OPERATION_INVALID,
2151
                 "%s", _("Domain is not running"));
R
Ryota Ozaki 已提交
2152 2153 2154 2155 2156 2157
        goto cleanup;
    }

    if (vm->state != VIR_DOMAIN_PAUSED) {
        if (lxcFreezeContainer(driver, vm) < 0) {
            lxcError(dom->conn, dom, VIR_ERR_OPERATION_FAILED,
2158
                     "%s", _("Suspend operation failed"));
R
Ryota Ozaki 已提交
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

    if (virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
        goto cleanup;
    ret = 0;

cleanup:
    if (event)
        lxcDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    lxcDriverUnlock(driver);
    return ret;
}

static int lxcUnfreezeContainer(lxc_driver_t *driver, virDomainObjPtr vm)
{
    int ret;
    virCgroupPtr cgroup = NULL;

    if (!(driver->cgroup &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) == 0))
        return -1;

    ret = virCgroupSetFreezerState(cgroup, "THAWED");

    virCgroupFree(&cgroup);
    return ret;
}

static int lxcDomainResume(virDomainPtr dom)
{
    lxc_driver_t *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainEventPtr event = NULL;
    int ret = -1;

    lxcDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        lxcError(dom->conn, dom, VIR_ERR_NO_DOMAIN,
2210
                 _("No domain with matching uuid '%s'"), uuidstr);
R
Ryota Ozaki 已提交
2211 2212 2213
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
2214
    if (!virDomainObjIsActive(vm)) {
R
Ryota Ozaki 已提交
2215
        lxcError(dom->conn, dom, VIR_ERR_OPERATION_INVALID,
2216
                 "%s", _("Domain is not running"));
R
Ryota Ozaki 已提交
2217 2218 2219 2220 2221 2222
        goto cleanup;
    }

    if (vm->state == VIR_DOMAIN_PAUSED) {
        if (lxcUnfreezeContainer(driver, vm) < 0) {
            lxcError(dom->conn, dom, VIR_ERR_OPERATION_FAILED,
2223
                     "%s", _("Resume operation failed"));
R
Ryota Ozaki 已提交
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

    if (virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
        goto cleanup;
    ret = 0;

cleanup:
    if (event)
        lxcDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    lxcDriverUnlock(driver);
    return ret;
}


D
Daniel Veillard 已提交
2247 2248 2249 2250 2251 2252 2253 2254
/* Function Tables */
static virDriver lxcDriver = {
    VIR_DRV_LXC, /* the number virDrvNo */
    "LXC", /* the name of the driver */
    lxcOpen, /* open */
    lxcClose, /* close */
    NULL, /* supports_feature */
    NULL, /* type */
D
Dan Smith 已提交
2255
    lxcVersion, /* version */
2256
    virGetHostname, /* getHostname */
D
Daniel Veillard 已提交
2257
    NULL, /* getMaxVcpus */
2258 2259
    nodeGetInfo, /* nodeGetInfo */
    lxcGetCapabilities, /* getCapabilities */
D
Daniel Veillard 已提交
2260 2261
    lxcListDomains, /* listDomains */
    lxcNumDomains, /* numOfDomains */
2262
    lxcDomainCreateAndStart, /* domainCreateXML */
D
Daniel Veillard 已提交
2263 2264 2265
    lxcDomainLookupByID, /* domainLookupByID */
    lxcDomainLookupByUUID, /* domainLookupByUUID */
    lxcDomainLookupByName, /* domainLookupByName */
R
Ryota Ozaki 已提交
2266 2267
    lxcDomainSuspend, /* domainSuspend */
    lxcDomainResume, /* domainResume */
2268
    lxcDomainShutdown, /* domainShutdown */
D
Daniel Veillard 已提交
2269
    NULL, /* domainReboot */
2270
    lxcDomainDestroy, /* domainDestroy */
D
Daniel Veillard 已提交
2271
    lxcGetOSType, /* domainGetOSType */
R
Ryota Ozaki 已提交
2272 2273 2274
    lxcDomainGetMaxMemory, /* domainGetMaxMemory */
    lxcDomainSetMaxMemory, /* domainSetMaxMemory */
    lxcDomainSetMemory, /* domainSetMemory */
D
Daniel Veillard 已提交
2275 2276 2277 2278 2279 2280 2281 2282
    lxcDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
    NULL, /* domainCoreDump */
    NULL, /* domainSetVcpus */
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
    NULL, /* domainGetMaxVcpus */
2283 2284
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
D
Daniel Veillard 已提交
2285
    lxcDomainDumpXML, /* domainDumpXML */
2286 2287
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
D
Daniel Veillard 已提交
2288 2289
    lxcListDefinedDomains, /* listDefinedDomains */
    lxcNumDefinedDomains, /* numOfDefinedDomains */
2290
    lxcDomainStart, /* domainCreate */
D
Daniel Veillard 已提交
2291 2292 2293 2294
    lxcDomainDefine, /* domainDefineXML */
    lxcDomainUndefine, /* domainUndefine */
    NULL, /* domainAttachDevice */
    NULL, /* domainDetachDevice */
2295 2296
    lxcDomainGetAutostart, /* domainGetAutostart */
    lxcDomainSetAutostart, /* domainSetAutostart */
2297 2298 2299
    lxcGetSchedulerType, /* domainGetSchedulerType */
    lxcGetSchedulerParameters, /* domainGetSchedulerParameters */
    lxcSetSchedulerParameters, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
2300 2301 2302 2303 2304
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
D
Daniel P. Berrange 已提交
2305 2306
    NULL, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
2307 2308
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
2309 2310
    lxcDomainEventRegister, /* domainEventRegister */
    lxcDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
2311 2312
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
2313
    NULL, /* nodeDeviceDettach */
2314 2315
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
2316
    NULL, /* domainMigratePrepareTunnel */
D
Daniel Veillard 已提交
2317 2318
};

2319
static virStateDriver lxcStateDriver = {
2320
    .name = "LXC",
2321 2322 2323
    .initialize = lxcStartup,
    .cleanup = lxcShutdown,
    .active = lxcActive,
2324
    .reload = lxcReload,
2325 2326
};

D
Daniel Veillard 已提交
2327 2328 2329
int lxcRegister(void)
{
    virRegisterDriver(&lxcDriver);
2330
    virRegisterStateDriver(&lxcStateDriver);
D
Daniel Veillard 已提交
2331 2332
    return 0;
}