cgroup.c 18.8 KB
Newer Older
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 26 27 28 29
/*
 * cgroup.c: Tools for managing cgroups
 *
 * Copyright IBM Corp. 2008
 *
 * See COPYING.LIB for the License of this software
 *
 * Authors:
 *  Dan Smith <danms@us.ibm.com>
 */
#include <config.h>

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <mntent.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <libgen.h>

#include "internal.h"
#include "util.h"
#include "memory.h"
#include "cgroup.h"
30
#include "logging.h"
31 32 33

#define CGROUP_MAX_VAL 512

34
enum {
35
    VIR_CGROUP_CONTROLLER_CPU,
36
    VIR_CGROUP_CONTROLLER_CPUACCT,
37
    VIR_CGROUP_CONTROLLER_CPUSET,
38 39 40 41
    VIR_CGROUP_CONTROLLER_MEMORY,
    VIR_CGROUP_CONTROLLER_DEVICES,

    VIR_CGROUP_CONTROLLER_LAST
42 43
};

44 45
VIR_ENUM_DECL(virCgroupController);
VIR_ENUM_IMPL(virCgroupController, VIR_CGROUP_CONTROLLER_LAST,
46 47 48 49 50 51 52
              "cpu", "cpuacct", "cpuset", "memory", "devices");

struct virCgroupController {
    int type;
    char *mountPoint;
    char *placement;
};
53 54 55

struct virCgroup {
    char *path;
56 57

    struct virCgroupController controllers[VIR_CGROUP_CONTROLLER_LAST];
58 59 60 61 62 63 64 65 66
};

/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void virCgroupFree(virCgroupPtr *group)
{
67 68 69 70 71 72 73 74
    int i;

    if (*group == NULL)
        return;

    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        VIR_FREE((*group)->controllers[i].mountPoint);
        VIR_FREE((*group)->controllers[i].placement);
75
    }
76 77 78

    VIR_FREE((*group)->path);
    VIR_FREE(*group);
79 80
}

81 82 83 84 85 86

/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
static int virCgroupDetectMounts(virCgroupPtr group)
87
{
88
    int i;
89
    FILE *mounts = NULL;
90 91 92 93 94
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    mounts = fopen("/proc/mounts", "r");
    if (mounts == NULL) {
95 96
        VIR_ERROR0("Unable to open /proc/mounts");
        return -ENOENT;
97 98 99
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
100 101
        if (STRNEQ(entry.mnt_type, "cgroup"))
            continue;
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = entry.mnt_opts;
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
                    len = next-tmp;
                    next++;
                } else {
                    len = strlen(tmp);
                }
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
                    !(group->controllers[i].mountPoint = strdup(entry.mnt_dir)))
                    goto no_memory;
                tmp = next;
            }
        }
122 123 124 125
    }

    fclose(mounts);

126
    return 0;
127

128 129 130 131
no_memory:
    if (mounts)
        fclose(mounts);
    return -ENOMEM;
132 133
}

134 135 136 137 138

/*
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
 * neccessarily in the root
139
 */
140
static int virCgroupDetectPlacement(virCgroupPtr group)
141 142
{
    int i;
143 144
    FILE *mapping  = NULL;
    char line[1024];
145

146 147 148 149
    mapping = fopen("/proc/self/cgroup", "r");
    if (mapping == NULL) {
        VIR_ERROR0("Unable to open /proc/self/cgroup");
        return -ENOENT;
150 151
    }

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
        char *path = controllers ? strchr(controllers+1, ':') : NULL;
        char *nl = path ? strchr(path, '\n') : NULL;

        if (!controllers || !path)
            continue;

        if (nl)
            *nl = '\0';

        *path = '\0';
        controllers++;
        path++;

        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = controllers;
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
                    len = next-tmp;
                    next++;
                } else {
                    len = strlen(tmp);
                }
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
                    !(group->controllers[i].placement = strdup(STREQ(path, "/") ? "" : path)))
                    goto no_memory;

                tmp = next;
            }
        }
    }

    fclose(mapping);

191
    return 0;
192 193 194 195

no_memory:
    return -ENOMEM;

196 197
}

198
static int virCgroupDetect(virCgroupPtr group)
199
{
200 201 202
    int any = 0;
    int rc;
    int i;
203

204 205 206 207
    rc = virCgroupDetectMounts(group);
    if (rc < 0) {
        VIR_ERROR("Failed to detect mounts for %s", group->path);
        return rc;
208 209
    }

210 211 212 213 214 215 216
    /* Check that at least 1 controller is available */
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        if (group->controllers[i].mountPoint != NULL)
            any = 1;
    }
    if (!any)
        return -ENXIO;
217 218


219
    rc = virCgroupDetectPlacement(group);
220

221 222 223 224 225
    if (rc == 0) {
        /* Check that for every mounted controller, we found our placement */
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            if (!group->controllers[i].mountPoint)
                continue;
226

227 228 229 230 231 232 233
            if (!group->controllers[i].placement) {
                VIR_ERROR("Could not find placement for controller %s at %s",
                          virCgroupControllerTypeToString(i),
                          group->controllers[i].placement);
                rc = -ENOENT;
                break;
            }
234

235 236 237 238 239 240 241
            VIR_DEBUG("Detected mount/mapping %i:%s at %s in %s", i,
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint,
                      group->controllers[i].placement);
        }
    } else {
        VIR_ERROR("Failed to detect mapping for %s", group->path);
242 243 244 245 246
    }

    return rc;
}

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

static int virCgroupPathOfController(virCgroupPtr group,
                                     int controller,
                                     const char *key,
                                     char **path)
{
    if (group->controllers[controller].mountPoint == NULL)
        return -ENOENT;

    if (group->controllers[controller].placement == NULL)
        return -ENOENT;

    if (virAsprintf(path, "%s%s%s/%s",
                    group->controllers[controller].mountPoint,
                    group->controllers[controller].placement,
                    STREQ(group->path, "/") ? "" : group->path,
                    key ? key : "") == -1)
        return -ENOMEM;

    return 0;
}


270
static int virCgroupSetValueStr(virCgroupPtr group,
271
                                int controller,
272 273 274 275 276 277
                                const char *key,
                                const char *value)
{
    int rc = 0;
    char *keypath = NULL;

278
    rc = virCgroupPathOfController(group, controller, key, &keypath);
279 280 281
    if (rc != 0)
        return rc;

282 283
    VIR_DEBUG("Set value %s", keypath);
    rc = virFileWriteStr(keypath, value);
284 285 286
    if (rc < 0) {
        DEBUG("Failed to write value '%s': %m", value);
        rc = -errno;
287 288
    } else {
        rc = 0;
289 290 291 292 293 294 295 296
    }

    VIR_FREE(keypath);

    return rc;
}

static int virCgroupGetValueStr(virCgroupPtr group,
297
                                int controller,
298 299 300 301 302 303
                                const char *key,
                                char **value)
{
    int rc;
    char *keypath = NULL;

304
    *value = NULL;
305

306
    rc = virCgroupPathOfController(group, controller, key, &keypath);
307 308 309 310 311
    if (rc != 0) {
        DEBUG("No path of %s, %s", group->path, key);
        return rc;
    }

312
    VIR_DEBUG("Get value %s", keypath);
313

314
    rc = virFileReadAll(keypath, 1024, value);
315 316 317
    if (rc < 0) {
        DEBUG("Failed to read %s: %m\n", keypath);
        rc = -errno;
318 319
    } else {
        rc = 0;
320 321 322 323 324 325 326
    }

    VIR_FREE(keypath);

    return rc;
}

327
static int virCgroupSetValueU64(virCgroupPtr group,
328
                                int controller,
329 330 331 332 333 334 335 336 337
                                const char *key,
                                uint64_t value)
{
    char *strval = NULL;
    int rc;

    if (virAsprintf(&strval, "%" PRIu64, value) == -1)
        return -ENOMEM;

338
    rc = virCgroupSetValueStr(group, controller, key, strval);
339 340 341 342 343 344 345

    VIR_FREE(strval);

    return rc;
}


346 347 348 349
#if 0
/* This is included for completeness, but not yet used */

static int virCgroupSetValueI64(virCgroupPtr group,
350
                                int controller,
351
                                const char *key,
352 353 354 355 356
                                int64_t value)
{
    char *strval = NULL;
    int rc;

357
    if (virAsprintf(&strval, "%" PRIi64, value) == -1)
358 359
        return -ENOMEM;

360
    rc = virCgroupSetValueStr(group, controller, key, strval);
361 362 363 364 365 366 367

    VIR_FREE(strval);

    return rc;
}

static int virCgroupGetValueI64(virCgroupPtr group,
368
                                int controller,
369 370
                                const char *key,
                                int64_t *value)
371 372 373 374
{
    char *strval = NULL;
    int rc = 0;

375
    rc = virCgroupGetValueStr(group, controller, key, &strval);
376 377 378
    if (rc != 0)
        goto out;

379
    if (sscanf(strval, "%" SCNi64, value) != 1)
380 381 382 383 384 385
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}
386
#endif
387

388
static int virCgroupGetValueU64(virCgroupPtr group,
389
                                int controller,
390
                                const char *key,
391
                                uint64_t *value)
392 393 394 395
{
    char *strval = NULL;
    int rc = 0;

396
    rc = virCgroupGetValueStr(group, controller, key, &strval);
397 398 399
    if (rc != 0)
        goto out;

400
    if (sscanf(strval, "%" SCNu64, value) != 1)
401 402 403 404 405 406 407 408
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}


409
static int virCgroupCpuSetInherit(virCgroupPtr parent, virCgroupPtr group)
410 411 412 413 414 415 416 417
{
    int i;
    int rc = 0;
    const char *inherit_values[] = {
        "cpuset.cpus",
        "cpuset.mems",
    };

418 419 420
    VIR_DEBUG("Setting up inheritance %s -> %s", parent->path, group->path);
    for (i = 0; i < ARRAY_CARDINALITY(inherit_values) ; i++) {
        char *value;
421

422 423 424 425
        rc = virCgroupGetValueStr(parent,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  &value);
426
        if (rc != 0) {
427 428 429 430 431 432 433 434 435 436 437 438 439
            VIR_ERROR("Failed to get %s %d", inherit_values[i], rc);
            break;
        }

        VIR_DEBUG("Inherit %s = %s", inherit_values[i], value);

        rc = virCgroupSetValueStr(group,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  value);

        if (rc != 0) {
            VIR_ERROR("Failed to set %s %d", inherit_values[i], rc);
440 441 442 443 444 445 446
            break;
        }
    }

    return rc;
}

447
static int virCgroupMakeGroup(virCgroupPtr parent, virCgroupPtr group)
448 449 450 451
{
    int i;
    int rc = 0;

452
    VIR_DEBUG("Make group %s", group->path);
453
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
454 455
        char *path = NULL;

456 457
        /* Skip over controllers that aren't mounted */
        if (!group->controllers[i].mountPoint)
458 459
            continue;

460 461 462
        rc = virCgroupPathOfController(group, i, "", &path);
        if (rc < 0)
            return rc;
463

464
        VIR_DEBUG("Make controller %s", path);
465
        if (access(path, F_OK) != 0) {
466
            if (mkdir(path, 0755) < 0) {
467 468 469 470
                rc = -errno;
                VIR_FREE(path);
                break;
            }
471 472 473 474 475 476 477
            if (group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint != NULL &&
                (i == VIR_CGROUP_CONTROLLER_CPUSET ||
                 STREQ(group->controllers[i].mountPoint, group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint))) {
                rc = virCgroupCpuSetInherit(parent, group);
                if (rc != 0)
                    break;
            }
478 479 480 481 482 483 484 485
        }

        VIR_FREE(path);
    }

    return rc;
}

486 487 488

static int virCgroupNew(const char *path,
                        virCgroupPtr *group)
489 490 491 492
{
    int rc = 0;
    char *typpath = NULL;

493 494
    VIR_DEBUG("New group %s", path);
    *group = NULL;
495

496
    if (VIR_ALLOC((*group)) != 0) {
497 498 499 500
        rc = -ENOMEM;
        goto err;
    }

501
    if (!((*group)->path = strdup(path))) {
502 503 504 505
        rc = -ENOMEM;
        goto err;
    }

506 507 508
    rc = virCgroupDetect(*group);
    if (rc < 0)
        goto err;
509 510 511

    return rc;
err:
512 513
    virCgroupFree(group);
    *group = NULL;
514 515 516 517 518 519

    VIR_FREE(typpath);

    return rc;
}

520 521
static int virCgroupAppRoot(int privileged,
                            virCgroupPtr *group)
522
{
523 524
    virCgroupPtr rootgrp = NULL;
    int rc;
525

526 527 528
    rc = virCgroupNew("/", &rootgrp);
    if (rc != 0)
        return rc;
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    if (privileged) {
        rc = virCgroupNew("/libvirt", group);
    } else {
        char *rootname;
        char *username;
        username = virGetUserName(NULL, getuid());
        if (!username) {
            rc = -ENOMEM;
            goto cleanup;
        }
        rc = virAsprintf(&rootname, "/libvirt-%s", username);
        VIR_FREE(username);
        if (rc < 0) {
            rc = -ENOMEM;
            goto cleanup;
        }
546

547 548
        rc = virCgroupNew(rootname, group);
        VIR_FREE(rootname);
549 550
    }
    if (rc != 0)
551
        goto cleanup;
552

553
    rc = virCgroupMakeGroup(rootgrp, *group);
554

555 556
cleanup:
    virCgroupFree(&rootgrp);
557 558 559
    return rc;
}

560

561 562 563 564 565 566 567 568 569 570 571 572 573
/**
 * virCgroupRemove:
 *
 * @group: The group to be removed
 *
 * Returns: 0 on success
 */
int virCgroupRemove(virCgroupPtr group)
{
    int rc = 0;
    int i;
    char *grppath = NULL;

574
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
575 576
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
577 578
            continue;

579 580 581 582 583
        if (virCgroupPathOfController(group,
                                      i,
                                      NULL,
                                      &grppath) != 0)
            continue;
584

585 586 587 588
        DEBUG("Removing cgroup %s", grppath);
        if (rmdir(grppath) != 0 && errno != ENOENT) {
            rc = -errno;
        }
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        VIR_FREE(grppath);
    }

    return rc;
}

/**
 * virCgroupAddTask:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 *
 * Returns: 0 on success
 */
int virCgroupAddTask(virCgroupPtr group, pid_t pid)
{
    int rc = 0;
    int i;

608
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
609 610 611
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;
612

613
        rc = virCgroupSetValueU64(group, i, "tasks", (unsigned long long)pid);
614 615 616 617 618 619 620
        if (rc != 0)
            break;
    }

    return rc;
}

621

622
/**
623
 * virCgroupForDriver:
624
 *
625
 * @name: name of this driver (e.g., xen, qemu, lxc)
626 627 628 629
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
630 631 632 633
int virCgroupForDriver(const char *name,
                       virCgroupPtr *group,
                       int privileged,
                       int create)
634 635
{
    int rc;
636
    char *path = NULL;
637
    virCgroupPtr rootgrp = NULL;
638

639
    rc = virCgroupAppRoot(privileged, &rootgrp);
640
    if (rc != 0)
641 642
        goto out;

643 644
    if (virAsprintf(&path, "%s/%s", rootgrp->path, name) < 0) {
        rc = -ENOMEM;
645
        goto out;
646
    }
647

648 649 650 651 652 653 654 655 656
    rc = virCgroupNew(path, group);
    VIR_FREE(path);

    if (rc == 0 &&
        create) {
        rc = virCgroupMakeGroup(rootgrp, *group);
        if (rc != 0)
            virCgroupFree(group);
    }
657

658
out:
659
    virCgroupFree(&rootgrp);
660 661 662 663

    return rc;
}

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

/**
 * virCgroupForDomain:
 *
 * @driver: group for driver owning the domain
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
int virCgroupForDomain(virCgroupPtr driver,
                       const char *name,
                       virCgroupPtr *group,
                       int create)
{
    int rc;
    char *path;

    if (virAsprintf(&path, "%s/%s", driver->path, name) < 0)
        return -ENOMEM;

    rc = virCgroupNew(path, group);
    VIR_FREE(path);

    if (rc == 0 &&
        create) {
        rc = virCgroupMakeGroup(driver, *group);
        if (rc != 0)
            virCgroupFree(group);
    }

    return rc;
}

698 699 700 701 702 703 704 705 706 707 708
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
int virCgroupSetMemory(virCgroupPtr group, unsigned long kb)
{
    return virCgroupSetValueU64(group,
709
                                VIR_CGROUP_CONTROLLER_MEMORY,
710 711 712 713 714 715 716 717 718 719 720 721 722 723
                                "memory.limit_in_bytes",
                                kb << 10);
}

/**
 * virCgroupDenyAllDevices:
 *
 * @group: The cgroup to deny devices for
 *
 * Returns: 0 on success
 */
int virCgroupDenyAllDevices(virCgroupPtr group)
{
    return virCgroupSetValueStr(group,
724 725 726
                                VIR_CGROUP_CONTROLLER_DEVICES,
                                "devices.deny",
                                "a");
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
}

/**
 * virCgroupAllowDevice:
 *
 * @group: The cgroup to allow a device for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device
 * @minor: The minor number of the device
 *
 * Returns: 0 on success
 */
int virCgroupAllowDevice(virCgroupPtr group,
                         char type,
                         int major,
                         int minor)
{
    int rc;
    char *devstr = NULL;

747
    if (virAsprintf(&devstr, "%c %i:%i rwm", type, major, minor) == -1) {
748 749 750 751 752
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
753
                              VIR_CGROUP_CONTROLLER_DEVICES,
754 755 756 757 758 759 760
                              "devices.allow",
                              devstr);
out:
    VIR_FREE(devstr);

    return rc;
}
761

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
/**
 * virCgroupAllowDeviceMajor:
 *
 * @group: The cgroup to allow an entire device major type for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device type
 *
 * Returns: 0 on success
 */
int virCgroupAllowDeviceMajor(virCgroupPtr group,
                              char type,
                              int major)
{
    int rc;
    char *devstr = NULL;

778
    if (virAsprintf(&devstr, "%c %i:* rwm", type, major) == -1) {
779 780 781 782 783
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
784
                              VIR_CGROUP_CONTROLLER_DEVICES,
785 786 787 788 789 790 791 792
                              "devices.allow",
                              devstr);
 out:
    VIR_FREE(devstr);

    return rc;
}

793
int virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
794
{
795 796
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
797
                                "cpu.shares", shares);
798 799
}

800
int virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
801
{
802 803
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
804
                                "cpu.shares", shares);
805
}
806 807 808

int virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage)
{
809 810
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPUACCT,
811
                                "cpuacct.usage", usage);
812
}