lxc_native.c 31.6 KB
Newer Older
1 2 3
/*
 * lxc_native.c: LXC native configuration import
 *
4
 * Copyright (c) 2014-2016 Red Hat, Inc.
5
 * Copyright (c) 2013-2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Cedric Bosdonnat <cbosdonnat@suse.com>
 */

#include <config.h>

#include "internal.h"
27
#include "lxc_container.h"
28 29
#include "lxc_native.h"
#include "util/viralloc.h"
30
#include "util/virfile.h"
31 32 33
#include "util/virlog.h"
#include "util/virstring.h"
#include "util/virconf.h"
34
#include "conf/domain_conf.h"
35 36 37

#define VIR_FROM_THIS VIR_FROM_LXC

38
VIR_LOG_INIT("lxc.lxc_native");
39 40 41 42

static virDomainFSDefPtr
lxcCreateFSDef(int type,
               const char *src,
43 44 45
               const char* dst,
               bool readonly,
               unsigned long long usage)
46 47 48
{
    virDomainFSDefPtr def;

49
    if (!(def = virDomainFSDefNew()))
50 51 52 53
        return NULL;

    def->type = type;
    def->accessmode = VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH;
54
    if (src && VIR_STRDUP(def->src->path, src) < 0)
55 56 57
        goto error;
    if (VIR_STRDUP(def->dst, dst) < 0)
        goto error;
58 59
    def->readonly = readonly;
    def->usage = usage;
60 61 62 63 64 65 66 67

    return def;

 error:
    virDomainFSDefFree(def);
    return NULL;
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
typedef struct _lxcFstab lxcFstab;
typedef lxcFstab *lxcFstabPtr;
struct _lxcFstab {
    lxcFstabPtr next;
    char *src;
    char *dst;
    char *type;
    char *options;
};

static void
lxcFstabFree(lxcFstabPtr fstab)
{
    while (fstab) {
        lxcFstabPtr next = NULL;
        next = fstab->next;

        VIR_FREE(fstab->src);
        VIR_FREE(fstab->dst);
        VIR_FREE(fstab->type);
        VIR_FREE(fstab->options);
        VIR_FREE(fstab);

        fstab = next;
    }
}

static char ** lxcStringSplit(const char *string)
{
    char *tmp;
    size_t i;
    size_t ntokens = 0;
    char **parts;
    char **result = NULL;

    if (VIR_STRDUP(tmp, string) < 0)
        return NULL;

    /* Replace potential \t by a space */
    for (i = 0; tmp[i]; i++) {
        if (tmp[i] == '\t')
            tmp[i] = ' ';
    }

    if (!(parts = virStringSplit(tmp, " ", 0)))
        goto error;

    /* Append NULL element */
    if (VIR_EXPAND_N(result, ntokens, 1) < 0)
        goto error;

    for (i = 0; parts[i]; i++) {
        if (STREQ(parts[i], ""))
            continue;

        if (VIR_EXPAND_N(result, ntokens, 1) < 0)
            goto error;

        if (VIR_STRDUP(result[ntokens-2], parts[i]) < 0)
            goto error;
    }

    VIR_FREE(tmp);
131
    virStringListFree(parts);
132 133
    return result;

134
 error:
135
    VIR_FREE(tmp);
136 137
    virStringListFree(parts);
    virStringListFree(result);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    return NULL;
}

static lxcFstabPtr
lxcParseFstabLine(char *fstabLine)
{
    lxcFstabPtr fstab = NULL;
    char **parts;

    if (!fstabLine || VIR_ALLOC(fstab) < 0)
        return NULL;

    if (!(parts = lxcStringSplit(fstabLine)))
        goto error;

    if (!parts[0] || !parts[1] || !parts[2] || !parts[3])
        goto error;

    if (VIR_STRDUP(fstab->src, parts[0]) < 0 ||
            VIR_STRDUP(fstab->dst, parts[1]) < 0 ||
            VIR_STRDUP(fstab->type, parts[2]) < 0 ||
            VIR_STRDUP(fstab->options, parts[3]) < 0)
        goto error;

162
    virStringListFree(parts);
163 164 165

    return fstab;

166
 error:
167
    lxcFstabFree(fstab);
168
    virStringListFree(parts);
169 170 171
    return NULL;
}

172 173 174 175
static int
lxcAddFSDef(virDomainDefPtr def,
            int type,
            const char *src,
176 177 178
            const char *dst,
            bool readonly,
            unsigned long long usage)
179 180 181
{
    virDomainFSDefPtr fsDef = NULL;

182
    if (!(fsDef = lxcCreateFSDef(type, src, dst, readonly, usage)))
183 184 185 186 187 188 189 190
        goto error;

    if (VIR_EXPAND_N(def->fss, def->nfss, 1) < 0)
        goto error;
    def->fss[def->nfss - 1] = fsDef;

    return 0;

191
 error:
192 193 194 195 196 197 198 199 200
    virDomainFSDefFree(fsDef);
    return -1;
}

static int
lxcSetRootfs(virDomainDefPtr def,
             virConfPtr properties)
{
    int type = VIR_DOMAIN_FS_TYPE_MOUNT;
J
John Ferlan 已提交
201
    VIR_AUTOFREE(char *) value = NULL;
202

203 204 205 206 207 208 209
    if (virConfGetValueString(properties, "lxc.rootfs.path", &value) <= 0) {
        virResetLastError();

        /* Check for pre LXC 3.0 legacy key */
        if (virConfGetValueString(properties, "lxc.rootfs", &value) <= 0)
            return -1;
    }
210

211
    if (STRPREFIX(value, "/dev/"))
212 213
        type = VIR_DOMAIN_FS_TYPE_BLOCK;

214
    if (lxcAddFSDef(def, type, value, "/", false, 0) < 0)
215 216 217 218 219
        return -1;

    return 0;
}

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
static int
lxcConvertSize(const char *size, unsigned long long *value)
{
    char *unit = NULL;

    /* Split the string into value and unit */
    if (virStrToLong_ull(size, &unit, 10, value) < 0)
        goto error;

    if (STREQ(unit, "%")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("can't convert relative size: '%s'"),
                       size);
        return -1;
    } else {
        if (virScaleInteger(value, unit, 1, ULLONG_MAX) < 0)
            goto error;
    }

    return 0;

241
 error:
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("failed to convert size: '%s'"),
                   size);
    return -1;
}

static int
lxcAddFstabLine(virDomainDefPtr def, lxcFstabPtr fstab)
{
    const char *src = NULL;
    char *dst = NULL;
    char **options = virStringSplit(fstab->options, ",", 0);
    bool readonly;
    int type = VIR_DOMAIN_FS_TYPE_MOUNT;
    unsigned long long usage = 0;
    int ret = -1;

    if (!options)
        return -1;

    if (fstab->dst[0] != '/') {
        if (virAsprintf(&dst, "/%s", fstab->dst) < 0)
            goto cleanup;
    } else {
        if (VIR_STRDUP(dst, fstab->dst) < 0)
            goto cleanup;
    }

    /* Check that we don't add basic mounts */
    if (lxcIsBasicMountLocation(dst)) {
        ret = 0;
        goto cleanup;
    }

    if (STREQ(fstab->type, "tmpfs")) {
        char *sizeStr = NULL;
        size_t i;
        type = VIR_DOMAIN_FS_TYPE_RAM;

        for (i = 0; options[i]; i++) {
            if ((sizeStr = STRSKIP(options[i], "size="))) {
                if (lxcConvertSize(sizeStr, &usage) < 0)
                    goto cleanup;
                break;
            }
        }
        if (!sizeStr) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing tmpfs size, set the size option"));
            goto cleanup;
        }
    } else {
        src = fstab->src;
    }

297 298 299 300
    /* Is it a block device that needs special favor? */
    if (STRPREFIX(fstab->src, "/dev/"))
        type = VIR_DOMAIN_FS_TYPE_BLOCK;

301
    /* Do we have ro in options? */
302
    readonly = virStringListHasString((const char **)options, "ro");
303 304 305 306 307 308 309 310

    if (lxcAddFSDef(def, type, src, dst, readonly, usage) < 0)
        goto cleanup;

    ret = 1;

 cleanup:
    VIR_FREE(dst);
311
    virStringListFree(options);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    return ret;
}

static int
lxcFstabWalkCallback(const char* name, virConfValuePtr value, void * data)
{
    int ret = 0;
    lxcFstabPtr fstabLine;
    virDomainDefPtr def = data;

    /* We only care about lxc.mount.entry lines */
    if (STRNEQ(name, "lxc.mount.entry"))
        return 0;

    fstabLine = lxcParseFstabLine(value->str);

    if (!fstabLine)
        return -1;

    if (lxcAddFstabLine(def, fstabLine) < 0)
        ret = -1;

    lxcFstabFree(fstabLine);
    return ret;
}

338 339
static virDomainNetDefPtr
lxcCreateNetDef(const char *type,
340
                const char *linkdev,
341
                const char *mac,
342
                const char *flag,
343 344
                const char *macvlanmode,
                const char *name)
345 346
{
    virDomainNetDefPtr net = NULL;
347
    virMacAddr macAddr;
348 349 350 351

    if (VIR_ALLOC(net) < 0)
        goto error;

352 353 354 355
    if (STREQ_NULLABLE(flag, "up"))
        net->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_UP;
    else
        net->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN;
356

357 358
    if (VIR_STRDUP(net->ifname_guest, name) < 0)
        goto error;
359

360 361 362 363
    if (mac && virMacAddrParse(mac, &macAddr) == 0)
        net->mac = macAddr;

    if (STREQ(type, "veth")) {
364 365 366 367 368 369 370
        if (linkdev) {
            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;
            if (VIR_STRDUP(net->data.bridge.brname, linkdev) < 0)
                goto error;
        } else {
            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
        }
371 372
    } else if (STREQ(type, "macvlan")) {
        net->type = VIR_DOMAIN_NET_TYPE_DIRECT;
373

374
        if (!linkdev || VIR_STRDUP(net->data.direct.linkdev, linkdev) < 0)
375 376 377 378 379 380 381 382 383 384
            goto error;

        if (!macvlanmode || STREQ(macvlanmode, "private"))
            net->data.direct.mode = VIR_NETDEV_MACVLAN_MODE_PRIVATE;
        else if (STREQ(macvlanmode, "vepa"))
            net->data.direct.mode = VIR_NETDEV_MACVLAN_MODE_VEPA;
        else if (STREQ(macvlanmode, "bridge"))
            net->data.direct.mode = VIR_NETDEV_MACVLAN_MODE_BRIDGE;
        else
            VIR_WARN("Unknown macvlan type: %s", macvlanmode);
385 386 387 388
    }

    return net;

389
 error:
390 391 392 393
    virDomainNetDefFree(net);
    return NULL;
}

394 395 396
static virDomainHostdevDefPtr
lxcCreateHostdevDef(int mode, int type, const char *data)
{
J
John Ferlan 已提交
397
    virDomainHostdevDefPtr hostdev = virDomainHostdevDefNew();
398 399 400 401 402 403 404 405

    if (!hostdev)
        return NULL;

    hostdev->mode = mode;
    hostdev->source.caps.type = type;

    if (type == VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET &&
406
        VIR_STRDUP(hostdev->source.caps.u.net.ifname, data) < 0) {
407 408 409 410 411 412 413
        virDomainHostdevDefFree(hostdev);
        hostdev = NULL;
    }

    return hostdev;
}

414 415 416 417 418 419 420 421 422
typedef struct {
    virDomainDefPtr def;
    char *type;
    char *link;
    char *mac;
    char *flag;
    char *macvlanmode;
    char *vlanid;
    char *name;
423
    virNetDevIPAddrPtr *ips;
424
    size_t nips;
425 426
    char *gateway_ipv4;
    char *gateway_ipv6;
427 428 429 430
    bool privnet;
    size_t networks;
} lxcNetworkParseData;

431 432 433
static int
lxcAddNetworkRouteDefinition(const char *address,
                             int family,
434
                             virNetDevIPRoutePtr **routes,
435 436
                             size_t *nroutes)
{
437
    virNetDevIPRoutePtr route = NULL;
438 439
    char *familyStr = NULL;
    char *zero = NULL;
440

441 442
    if (VIR_STRDUP(zero, family == AF_INET ? VIR_SOCKET_ADDR_IPV4_ALL
                   : VIR_SOCKET_ADDR_IPV6_ALL) < 0)
443 444
        goto error;

445 446 447
    if (VIR_STRDUP(familyStr, family == AF_INET ? "ipv4" : "ipv6") < 0)
        goto error;

448 449 450
    if (!(route = virNetDevIPRouteCreate(_("Domain interface"), familyStr,
                                         zero, NULL, address, 0, false,
                                         0, false)))
451 452 453 454 455
        goto error;

    if (VIR_APPEND_ELEMENT(*routes, *nroutes, route) < 0)
        goto error;

456 457 458
    VIR_FREE(familyStr);
    VIR_FREE(zero);

459 460 461
    return 0;

 error:
462 463
    VIR_FREE(familyStr);
    VIR_FREE(zero);
464
    virNetDevIPRouteFree(route);
465 466 467
    return -1;
}

468
static int
469
lxcAddNetworkDefinition(lxcNetworkParseData *data)
470 471
{
    virDomainNetDefPtr net = NULL;
472
    virDomainHostdevDefPtr hostdev = NULL;
473
    bool isPhys, isVlan = false;
474
    size_t i;
475

476 477
    if ((data->type == NULL) || STREQ(data->type, "empty") ||
         STREQ(data->type, "") ||  STREQ(data->type, "none"))
478 479
        return 0;

480 481 482 483
    isPhys = STREQ(data->type, "phys");
    isVlan = STREQ(data->type, "vlan");
    if (data->type != NULL && (isPhys || isVlan)) {
        if (!data->link) {
484 485 486 487 488
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Missing 'link' attribute for NIC"));
            goto error;
        }
        if (!(hostdev = lxcCreateHostdevDef(VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES,
489
                                            VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET,
490
                                            data->link)))
491
            goto error;
492

493 494
        /* This still requires the user to manually setup the vlan interface
         * on the host */
495
        if (isVlan && data->vlanid) {
496 497
            VIR_FREE(hostdev->source.caps.u.net.ifname);
            if (virAsprintf(&hostdev->source.caps.u.net.ifname,
498
                            "%s.%s", data->link, data->vlanid) < 0)
499 500 501
                goto error;
        }

502 503
        hostdev->source.caps.u.net.ip.ips = data->ips;
        hostdev->source.caps.u.net.ip.nips = data->nips;
504

505 506
        if (data->gateway_ipv4 &&
            lxcAddNetworkRouteDefinition(data->gateway_ipv4, AF_INET,
507 508
                                         &hostdev->source.caps.u.net.ip.routes,
                                         &hostdev->source.caps.u.net.ip.nroutes) < 0)
509 510 511 512
                goto error;

        if (data->gateway_ipv6 &&
            lxcAddNetworkRouteDefinition(data->gateway_ipv6, AF_INET6,
513 514
                                         &hostdev->source.caps.u.net.ip.routes,
                                         &hostdev->source.caps.u.net.ip.nroutes) < 0)
515 516
                goto error;

517
        if (VIR_EXPAND_N(data->def->hostdevs, data->def->nhostdevs, 1) < 0)
518
            goto error;
519
        data->def->hostdevs[data->def->nhostdevs - 1] = hostdev;
520
    } else {
521 522 523
        if (!(net = lxcCreateNetDef(data->type, data->link, data->mac,
                                    data->flag, data->macvlanmode,
                                    data->name)))
524 525
            goto error;

526 527
        net->guestIP.ips = data->ips;
        net->guestIP.nips = data->nips;
528

529 530
        if (data->gateway_ipv4 &&
            lxcAddNetworkRouteDefinition(data->gateway_ipv4, AF_INET,
531 532
                                         &net->guestIP.routes,
                                         &net->guestIP.nroutes) < 0)
533 534 535 536
                goto error;

        if (data->gateway_ipv6 &&
            lxcAddNetworkRouteDefinition(data->gateway_ipv6, AF_INET6,
537 538
                                         &net->guestIP.routes,
                                         &net->guestIP.nroutes) < 0)
539 540
                goto error;

541
        if (VIR_EXPAND_N(data->def->nets, data->def->nnets, 1) < 0)
542
            goto error;
543
        data->def->nets[data->def->nnets - 1] = net;
544
    }
545 546 547

    return 1;

548
 error:
549 550 551
    for (i = 0; i < data->nips; i++)
        VIR_FREE(data->ips[i]);
    VIR_FREE(data->ips);
552
    virDomainNetDefFree(net);
553
    virDomainHostdevDefFree(hostdev);
554 555 556
    return -1;
}

557 558 559 560
static int
lxcNetworkWalkCallback(const char *name, virConfValuePtr value, void *data)
{
    lxcNetworkParseData *parseData = data;
561
    int status;
562 563

    if (STREQ(name, "lxc.network.type")) {
564 565 566 567
        virDomainDefPtr def = parseData->def;
        size_t networks = parseData->networks;
        bool privnet = parseData->privnet;

568
        /* Store the previous NIC */
569
        status = lxcAddNetworkDefinition(parseData);
570

571 572 573
        if (status < 0)
            return -1;
        else if (status > 0)
574
            networks++;
575
        else if (parseData->type != NULL && STREQ(parseData->type, "none"))
576 577 578 579 580 581 582 583
            privnet = false;

        /* clean NIC to store a new one */
        memset(parseData, 0, sizeof(*parseData));

        parseData->def = def;
        parseData->networks = networks;
        parseData->privnet = privnet;
584

585 586 587
        /* Keep the new value */
        parseData->type = value->str;
    }
588 589 590 591 592 593
    else if (STREQ(name, "lxc.network.link"))
        parseData->link = value->str;
    else if (STREQ(name, "lxc.network.hwaddr"))
        parseData->mac = value->str;
    else if (STREQ(name, "lxc.network.flags"))
        parseData->flag = value->str;
594 595
    else if (STREQ(name, "lxc.network.macvlan.mode"))
        parseData->macvlanmode = value->str;
596 597
    else if (STREQ(name, "lxc.network.vlan.id"))
        parseData->vlanid = value->str;
598 599
    else if (STREQ(name, "lxc.network.name"))
        parseData->name = value->str;
600 601 602 603
    else if (STREQ(name, "lxc.network.ipv4") ||
             STREQ(name, "lxc.network.ipv6")) {
        int family = AF_INET;
        char **ipparts = NULL;
604
        virNetDevIPAddrPtr ip = NULL;
605 606 607 608 609 610 611 612

        if (VIR_ALLOC(ip) < 0)
            return -1;

        if (STREQ(name, "lxc.network.ipv6"))
            family = AF_INET6;

        ipparts = virStringSplit(value->str, "/", 2);
613
        if (virStringListLength((const char * const *)ipparts) != 2 ||
614 615 616 617 618 619
            virSocketAddrParse(&ip->address, ipparts[0], family) < 0 ||
            virStrToLong_ui(ipparts[1], NULL, 10, &ip->prefix) < 0) {

            virReportError(VIR_ERR_INVALID_ARG,
                           _("Invalid CIDR address: '%s'"), value->str);

620
            virStringListFree(ipparts);
621 622 623 624
            VIR_FREE(ip);
            return -1;
        }

625
        virStringListFree(ipparts);
626 627 628 629 630

        if (VIR_APPEND_ELEMENT(parseData->ips, parseData->nips, ip) < 0) {
            VIR_FREE(ip);
            return -1;
        }
631 632 633 634
    } else if (STREQ(name, "lxc.network.ipv4.gateway")) {
        parseData->gateway_ipv4 = value->str;
    } else if (STREQ(name, "lxc.network.ipv6.gateway")) {
        parseData->gateway_ipv6 = value->str;
635
    } else if (STRPREFIX(name, "lxc.network")) {
636 637 638
        VIR_WARN("Unhandled network property: %s = %s",
                 name,
                 value->str);
639
    }
640

641 642 643 644 645 646
    return 0;
}

static int
lxcConvertNetworkSettings(virDomainDefPtr def, virConfPtr properties)
{
647
    int status;
648 649
    int result = -1;
    size_t i;
650
    lxcNetworkParseData data = {def, NULL, NULL, NULL, NULL,
651 652
                                NULL, NULL, NULL, NULL, 0,
                                NULL, NULL, true, 0};
653 654 655

    if (virConfWalk(properties, lxcNetworkWalkCallback, &data) < 0)
        goto error;
656 657


658
    /* Add the last network definition found */
659 660
    status = lxcAddNetworkDefinition(&data);

661
    if (status < 0)
662
        goto error;
663
    else if (status > 0)
664
        data.networks++;
665 666
    else if (data.type != NULL && STREQ(data.type, "none"))
        data.privnet = false;
667 668 669

    if (data.networks == 0 && data.privnet) {
        /* When no network type is provided LXC only adds loopback */
J
Ján Tomko 已提交
670
        def->features[VIR_DOMAIN_FEATURE_PRIVNET] = VIR_TRISTATE_SWITCH_ON;
671
    }
672
    result = 0;
673

674 675 676 677 678 679 680
    return result;

 error:
    for (i = 0; i < data.nips; i++)
        VIR_FREE(data.ips[i]);
    VIR_FREE(data.ips);
    return -1;
681 682
}

683 684 685
static int
lxcCreateConsoles(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
686
    VIR_AUTOFREE(char *) value = NULL;
687 688 689 690
    int nbttys = 0;
    virDomainChrDefPtr console;
    size_t i;

691 692 693 694 695 696 697
    if (virConfGetValueString(properties, "lxc.tty.max", &value) <= 0) {
        virResetLastError();

        /* Check for pre LXC 3.0 legacy key */
        if (virConfGetValueString(properties, "lxc.tty", &value) <= 0)
            return 0;
    }
698

699
    if (virStrToLong_i(value, NULL, 10, &nbttys) < 0) {
700
        virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to parse int: '%s'"),
701
                       value);
702 703 704 705 706 707 708 709
        return -1;
    }

    if (VIR_ALLOC_N(def->consoles, nbttys) < 0)
        return -1;

    def->nconsoles = nbttys;
    for (i = 0; i < nbttys; i++) {
710
        if (!(console = virDomainChrDefNew(NULL)))
711 712 713 714 715
            goto error;

        console->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
        console->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LXC;
        console->target.port = i;
716
        console->source->type = VIR_DOMAIN_CHR_TYPE_PTY;
717 718 719 720 721 722

        def->consoles[i] = console;
    }

    return 0;

723
 error:
724 725 726 727
    virDomainChrDefFree(console);
    return -1;
}

728 729 730 731 732 733 734 735
static int
lxcIdmapWalkCallback(const char *name, virConfValuePtr value, void *data)
{
    virDomainDefPtr def = data;
    virDomainIdMapEntryPtr idmap = NULL;
    char type;
    unsigned long start, target, count;

736 737 738 739 740
    /* LXC 3.0 uses "lxc.idmap", while legacy used "lxc.id_map" */
    if (STRNEQ(name, "lxc.idmap") || !value->str) {
        if (!value->str || STRNEQ(name, "lxc.id_map"))
            return 0;
    }
741 742 743

    if (sscanf(value->str, "%c %lu %lu %lu", &type,
               &target, &start, &count) != 4) {
744 745
        virReportError(VIR_ERR_INTERNAL_ERROR, _("invalid %s: '%s'"),
                       name, value->str);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
        return -1;
    }

    if (type == 'u') {
        if (VIR_EXPAND_N(def->idmap.uidmap, def->idmap.nuidmap, 1) < 0)
            return -1;
        idmap = &def->idmap.uidmap[def->idmap.nuidmap - 1];
    } else if (type == 'g') {
        if (VIR_EXPAND_N(def->idmap.gidmap, def->idmap.ngidmap, 1) < 0)
            return -1;
        idmap = &def->idmap.gidmap[def->idmap.ngidmap - 1];
    } else {
        return -1;
    }

    idmap->start = start;
    idmap->target = target;
    idmap->count = count;

    return 0;
}

768 769 770
static int
lxcSetMemTune(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
771
    VIR_AUTOFREE(char *) value = NULL;
772 773
    unsigned long long size = 0;

774 775 776 777
    if (virConfGetValueString(properties,
                              "lxc.cgroup.memory.limit_in_bytes",
                              &value) > 0) {
        if (lxcConvertSize(value, &size) < 0)
778
            return -1;
779
        size = size / 1024;
780
        virDomainDefSetMemoryTotal(def, size);
781
        def->mem.hard_limit = virMemoryLimitTruncate(size);
J
John Ferlan 已提交
782
        VIR_FREE(value);
783 784
    }

785 786 787 788
    if (virConfGetValueString(properties,
                              "lxc.cgroup.memory.soft_limit_in_bytes",
                              &value) > 0) {
        if (lxcConvertSize(value, &size) < 0)
789
            return -1;
790
        def->mem.soft_limit = virMemoryLimitTruncate(size / 1024);
J
John Ferlan 已提交
791
        VIR_FREE(value);
792 793
    }

794 795 796 797
    if (virConfGetValueString(properties,
                              "lxc.cgroup.memory.memsw.limit_in_bytes",
                              &value) > 0) {
        if (lxcConvertSize(value, &size) < 0)
798
            return -1;
799
        def->mem.swap_hard_limit = virMemoryLimitTruncate(size / 1024);
800 801 802 803
    }
    return 0;
}

804 805 806
static int
lxcSetCpuTune(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
807
    VIR_AUTOFREE(char *) value = NULL;
808

809 810 811
    if (virConfGetValueString(properties, "lxc.cgroup.cpu.shares",
                              &value) > 0) {
        if (virStrToLong_ull(value, NULL, 10, &def->cputune.shares) < 0)
812 813
            goto error;
        def->cputune.sharesSpecified = true;
J
John Ferlan 已提交
814
        VIR_FREE(value);
815
    }
816

817 818 819 820
    if (virConfGetValueString(properties, "lxc.cgroup.cpu.cfs_quota_us",
                              &value) > 0) {
        if (virStrToLong_ll(value, NULL, 10, &def->cputune.quota) < 0)
            goto error;
J
John Ferlan 已提交
821
        VIR_FREE(value);
822
    }
823

824
    if (virConfGetValueString(properties, "lxc.cgroup.cpu.cfs_period_us",
J
John Ferlan 已提交
825
                              &value) > 0) {
826 827 828
        if (virStrToLong_ull(value, NULL, 10, &def->cputune.period) < 0)
            goto error;
    }
829 830 831

    return 0;

832
 error:
833
    virReportError(VIR_ERR_INTERNAL_ERROR,
834
                   _("failed to parse integer: '%s'"), value);
835 836 837
    return -1;
}

838 839 840
static int
lxcSetCpusetTune(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
841
    VIR_AUTOFREE(char *) value = NULL;
842
    virBitmapPtr nodeset = NULL;
843

844 845 846
    if (virConfGetValueString(properties, "lxc.cgroup.cpuset.cpus",
                              &value) > 0) {
        if (virBitmapParse(value, &def->cpumask, VIR_DOMAIN_CPUMASK_LEN) < 0)
847 848
            return -1;
        def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC;
J
John Ferlan 已提交
849
        VIR_FREE(value);
850 851
    }

852
    if (virConfGetValueString(properties, "lxc.cgroup.cpuset.mems",
J
John Ferlan 已提交
853
                              &value) > 0) {
854
        if (virBitmapParse(value, &nodeset, VIR_DOMAIN_CPUMASK_LEN) < 0)
855
            return -1;
856
        if (virDomainNumatuneSet(def->numa,
857 858 859 860 861
                                 def->placement_mode ==
                                 VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC,
                                 VIR_DOMAIN_NUMATUNE_PLACEMENT_STATIC,
                                 VIR_DOMAIN_NUMATUNE_MEM_STRICT,
                                 nodeset) < 0) {
862 863 864 865
            virBitmapFree(nodeset);
            return -1;
        }
        virBitmapFree(nodeset);
866 867 868 869 870
    }

    return 0;
}

871 872 873 874 875 876
static int
lxcBlkioDeviceWalkCallback(const char *name, virConfValuePtr value, void *data)
{
    char **parts = NULL;
    virBlkioDevicePtr device = NULL;
    virDomainDefPtr def = data;
877 878 879
    size_t i = 0;
    char *path = NULL;
    int ret = -1;
880

881 882
    if (!STRPREFIX(name, "lxc.cgroup.blkio.") ||
            STREQ(name, "lxc.cgroup.blkio.weight")|| !value->str)
883 884 885 886 887 888 889
        return 0;

    if (!(parts = lxcStringSplit(value->str)))
        return -1;

    if (!parts[0] || !parts[1]) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
890 891 892
                       _("invalid %s value: '%s'"),
                       name, value->str);
        goto cleanup;
893 894
    }

895 896
    if (virAsprintf(&path, "/dev/block/%s", parts[0]) < 0)
        goto cleanup;
897

898 899 900 901 902 903 904 905 906 907 908 909 910
    /* Do we already have a device definition for this path?
     * Get that device or create a new one */
    for (i = 0; !device && i < def->blkio.ndevices; i++) {
        if (STREQ(def->blkio.devices[i].path, path))
            device = &def->blkio.devices[i];
    }
    if (!device) {
        if (VIR_EXPAND_N(def->blkio.devices, def->blkio.ndevices, 1) < 0)
            goto cleanup;
        device = &def->blkio.devices[def->blkio.ndevices - 1];
        device->path = path;
        path = NULL;
    }
911

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
    /* Set the value */
    if (STREQ(name, "lxc.cgroup.blkio.device_weight")) {
        if (virStrToLong_ui(parts[1], NULL, 10, &device->weight) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse device weight: '%s'"), parts[1]);
            goto cleanup;
        }
    } else if (STREQ(name, "lxc.cgroup.blkio.throttle.read_bps_device")) {
        if (virStrToLong_ull(parts[1], NULL, 10, &device->rbps) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse read_bps_device: '%s'"),
                           parts[1]);
            goto cleanup;
        }
    } else if (STREQ(name, "lxc.cgroup.blkio.throttle.write_bps_device")) {
        if (virStrToLong_ull(parts[1], NULL, 10, &device->wbps) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse write_bps_device: '%s'"),
                           parts[1]);
            goto cleanup;
        }
    } else if (STREQ(name, "lxc.cgroup.blkio.throttle.read_iops_device")) {
        if (virStrToLong_ui(parts[1], NULL, 10, &device->riops) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse read_iops_device: '%s'"),
                           parts[1]);
            goto cleanup;
        }
    } else if (STREQ(name, "lxc.cgroup.blkio.throttle.write_iops_device")) {
        if (virStrToLong_ui(parts[1], NULL, 10, &device->wiops) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse write_iops_device: '%s'"),
                           parts[1]);
            goto cleanup;
        }
    } else {
        VIR_WARN("Unhandled blkio tune config: %s", name);
949 950
    }

951
    ret = 0;
952

953
 cleanup:
954
    virStringListFree(parts);
955
    VIR_FREE(path);
956

957
    return ret;
958 959 960 961 962
}

static int
lxcSetBlkioTune(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
963
    VIR_AUTOFREE(char *) value = NULL;
964

965 966 967 968 969 970 971
    if (virConfGetValueString(properties, "lxc.cgroup.blkio.weight",
                              &value) > 0) {
        if (virStrToLong_ui(value, NULL, 10, &def->blkio.weight) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse integer: '%s'"), value);
            return -1;
        }
972 973 974 975 976 977 978 979
    }

    if (virConfWalk(properties, lxcBlkioDeviceWalkCallback, def) < 0)
        return -1;

    return 0;
}

980 981 982
static void
lxcSetCapDrop(virDomainDefPtr def, virConfPtr properties)
{
J
John Ferlan 已提交
983
    VIR_AUTOFREE(char *) value = NULL;
984 985 986 987
    char **toDrop = NULL;
    const char *capString;
    size_t i;

988 989
    if (virConfGetValueString(properties, "lxc.cap.drop", &value) > 0)
        toDrop = virStringSplit(value, " ", 0);
990 991 992

    for (i = 0; i < VIR_DOMAIN_CAPS_FEATURE_LAST; i++) {
        capString = virDomainCapsFeatureTypeToString(i);
993
        if (toDrop != NULL &&
994
            virStringListHasString((const char **)toDrop, capString))
J
Ján Tomko 已提交
995
            def->caps_features[i] = VIR_TRISTATE_SWITCH_OFF;
996 997 998 999
    }

    def->features[VIR_DOMAIN_FEATURE_CAPABILITIES] = VIR_DOMAIN_CAPABILITIES_POLICY_ALLOW;

1000
    virStringListFree(toDrop);
1001 1002
}

1003
virDomainDefPtr
1004 1005 1006
lxcParseConfigString(const char *config,
                     virCapsPtr caps,
                     virDomainXMLOptionPtr xmlopt)
1007 1008 1009
{
    virDomainDefPtr vmdef = NULL;
    virConfPtr properties = NULL;
J
John Ferlan 已提交
1010
    VIR_AUTOFREE(char *) value = NULL;
1011

J
Ján Tomko 已提交
1012
    if (!(properties = virConfReadString(config, VIR_CONF_FLAG_LXC_FORMAT)))
1013 1014
        return NULL;

1015
    if (!(vmdef = virDomainDefNew()))
1016 1017 1018 1019 1020 1021 1022
        goto error;

    if (virUUIDGenerate(vmdef->uuid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate uuid"));
        goto error;
    }
1023

1024
    vmdef->id = -1;
1025
    virDomainDefSetMemoryTotal(vmdef, 64 * 1024);
1026

1027
    vmdef->onReboot = VIR_DOMAIN_LIFECYCLE_ACTION_RESTART;
1028
    vmdef->onCrash = VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY;
1029
    vmdef->onPoweroff = VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY;
1030 1031 1032 1033
    vmdef->virtType = VIR_DOMAIN_VIRT_LXC;

    /* Value not handled by the LXC driver, setting to
     * minimum required to make XML parsing pass */
1034
    if (virDomainDefSetVcpusMax(vmdef, 1, xmlopt) < 0)
1035 1036
        goto error;

1037 1038
    if (virDomainDefSetVcpus(vmdef, 1) < 0)
        goto error;
1039

1040
    vmdef->nfss = 0;
1041
    vmdef->os.type = VIR_DOMAIN_OSTYPE_EXE;
1042

1043 1044 1045
    if (virConfGetValueString(properties, "lxc.arch", &value) > 0) {
        virArch arch = virArchFromString(value);
        if (arch == VIR_ARCH_NONE && STREQ(value, "x86"))
1046
            arch = VIR_ARCH_I686;
1047
        else if (arch == VIR_ARCH_NONE && STREQ(value, "amd64"))
1048 1049
            arch = VIR_ARCH_X86_64;
        vmdef->os.arch = arch;
J
John Ferlan 已提交
1050
        VIR_FREE(value);
1051 1052
    }

1053 1054 1055
    if (VIR_STRDUP(vmdef->os.init, "/sbin/init") < 0)
        goto error;

1056 1057 1058 1059 1060 1061 1062 1063 1064
    if (virConfGetValueString(properties, "lxc.uts.name", &value) <= 0) {
        virResetLastError();

        /* Check for pre LXC 3.0 legacy key */
        if (virConfGetValueString(properties, "lxc.utsname", &value) <= 0)
            goto error;
    }

    if (VIR_STRDUP(vmdef->name, value) < 0)
1065
        goto error;
1066

1067 1068 1069
    if (!vmdef->name && (VIR_STRDUP(vmdef->name, "unnamed") < 0))
        goto error;

1070 1071 1072
    if (lxcSetRootfs(vmdef, properties) < 0)
        goto error;

1073 1074 1075 1076
    /* LXC 3.0 uses "lxc.mount.fstab", while legacy used just "lxc.mount".
     * In either case, generate the error to use "lxc.mount.entry" instead */
    if (virConfGetValue(properties, "lxc.mount.fstab") ||
        virConfGetValue(properties, "lxc.mount")) {
1077
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
1078 1079
                       _("lxc.mount.fstab or lxc.mount found, use "
                         "lxc.mount.entry lines instead"));
1080 1081 1082 1083 1084 1085 1086
        goto error;
    }

    /* Loop over lxc.mount.entry to add filesystem devices for them */
    if (virConfWalk(properties, lxcFstabWalkCallback, vmdef) < 0)
        goto error;

1087 1088 1089 1090
    /* Network configuration */
    if (lxcConvertNetworkSettings(vmdef, properties) < 0)
        goto error;

1091 1092 1093 1094
    /* Consoles */
    if (lxcCreateConsoles(vmdef, properties) < 0)
        goto error;

1095
    /* lxc.idmap or legacy lxc.id_map */
1096 1097 1098
    if (virConfWalk(properties, lxcIdmapWalkCallback, vmdef) < 0)
        goto error;

1099 1100 1101 1102
    /* lxc.cgroup.memory.* */
    if (lxcSetMemTune(vmdef, properties) < 0)
        goto error;

1103 1104 1105 1106
    /* lxc.cgroup.cpu.* */
    if (lxcSetCpuTune(vmdef, properties) < 0)
        goto error;

1107 1108 1109 1110
    /* lxc.cgroup.cpuset.* */
    if (lxcSetCpusetTune(vmdef, properties) < 0)
        goto error;

1111 1112 1113 1114
    /* lxc.cgroup.blkio.* */
    if (lxcSetBlkioTune(vmdef, properties) < 0)
        goto error;

1115 1116 1117
    /* lxc.cap.drop */
    lxcSetCapDrop(vmdef, properties);

1118
    if (virDomainDefPostParse(vmdef, caps, VIR_DOMAIN_DEF_PARSE_ABI_UPDATE,
1119
                              xmlopt, NULL) < 0)
1120 1121
        goto cleanup;

1122 1123
    goto cleanup;

1124
 error:
1125 1126 1127
    virDomainDefFree(vmdef);
    vmdef = NULL;

1128
 cleanup:
1129 1130 1131 1132
    virConfFree(properties);

    return vmdef;
}