uml_driver.c 51.2 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006, 2007, 2008, 2009 Red Hat, Inc.
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/inotify.h>
47
#include <sys/un.h>
48 49 50 51 52 53 54 55 56 57 58 59 60

#include "uml_driver.h"
#include "uml_conf.h"
#include "event.h"
#include "buf.h"
#include "util.h"
#include "nodeinfo.h"
#include "stats_linux.h"
#include "capabilities.h"
#include "memory.h"
#include "uuid.h"
#include "domain_conf.h"
#include "datatypes.h"
61
#include "logging.h"
62

63 64
#define VIR_FROM_THIS VIR_FROM_UML

65 66 67 68 69
/* For storing short-lived temporary files. */
#define TEMPDIR LOCAL_STATE_DIR "/cache/libvirt"

static int umlShutdown(void);

70 71
static void umlDriverLock(struct uml_driver *driver)
{
72
    virMutexLock(&driver->lock);
73 74 75
}
static void umlDriverUnlock(struct uml_driver *driver)
{
76
    virMutexUnlock(&driver->lock);
77 78
}

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

static int umlOpenMonitor(virConnectPtr conn,
                          struct uml_driver *driver,
                          virDomainObjPtr vm);
static int umlReadPidFile(virConnectPtr conn,
                          struct uml_driver *driver,
                          virDomainObjPtr vm);

static int umlSetCloseExec(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFD)) < 0)
        goto error;
    flags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, flags)) < 0)
        goto error;
    return 0;
 error:
D
Daniel Veillard 已提交
96
    VIR_ERROR0(_("Failed to set close-on-exec file descriptor flag"));
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    return -1;
}

static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm);

static void umlShutdownVMDaemon(virConnectPtr conn,
                                struct uml_driver *driver,
                                virDomainObjPtr vm);


static int umlMonitorCommand (virConnectPtr conn,
                              const struct uml_driver *driver,
                              const virDomainObjPtr vm,
                              const char *cmd,
                              char **reply);

static struct uml_driver *uml_driver = NULL;


static void
umlAutostartConfigs(struct uml_driver *driver) {
    unsigned int i;
121 122 123 124 125
    /* 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
     */
126 127 128
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
129
    /* Ignoring NULL conn which is mostly harmless here */
130 131 132 133

    for (i = 0 ; i < driver->domains.count ; i++) {
        if (driver->domains.objs[i]->autostart &&
            !virDomainIsActive(driver->domains.objs[i]) &&
134
            umlStartVMDaemon(conn, driver, driver->domains.objs[i]) < 0) {
135
            virErrorPtr err = virGetLastError();
D
Daniel Veillard 已提交
136
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
137 138 139
                     driver->domains.objs[i]->def->name, err->message);
        }
    }
140

141 142
    if (conn)
        virConnectClose(conn);
143 144 145 146 147 148 149 150 151 152 153 154 155
}


static int
umlIdentifyOneChrPTY(virConnectPtr conn,
                     struct uml_driver *driver,
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
156
    if (virAsprintf(&cmd, "config %s%d", dev, def->dstPort) < 0) {
157
        virReportOOMError(conn);
158 159 160
        return -1;
    }
requery:
161 162
    if (umlMonitorCommand(NULL, driver, dom, cmd, &res) < 0)
        return -1;
163

164
    if (res && STRPREFIX(res, "pts:")) {
165 166
        VIR_FREE(def->data.file.path);
        if ((def->data.file.path = strdup(res + 4)) == NULL) {
167
            virReportOOMError(conn);
168 169 170 171
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
172
    } else if (!res || STRPREFIX(res, "pts")) {
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        /* It can take a while to startup, so retry for
           upto 5 seconds */
        /* XXX should do this in a better non-blocking
           way somehow ...perhaps register a timer */
        if (retries++ < 50) {
            usleep(1000*10);
            goto requery;
        }
    }

    VIR_FREE(cmd);
    VIR_FREE(res);
    return 0;
}

static int
umlIdentifyChrPTY(virConnectPtr conn,
                  struct uml_driver *driver,
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
        dom->def->console->type == VIR_DOMAIN_CHR_TYPE_PTY)
        if (umlIdentifyOneChrPTY(conn, driver, dom,
                                 dom->def->console, "con") < 0)
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
        if (dom->def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_PTY &&
            umlIdentifyOneChrPTY(conn, driver, dom,
                                 dom->def->serials[i], "ssl") < 0)
            return -1;

    return 0;
}

static void
umlInotifyEvent(int watch,
                int fd,
                int events ATTRIBUTE_UNUSED,
                void *data)
{
    char buf[1024];
    struct inotify_event *e;
    int got;
    char *tmp, *name;
    struct uml_driver *driver = data;
    virDomainObjPtr dom;

223
    umlDriverLock(driver);
224
    if (watch != driver->inotifyWatch)
225
        goto cleanup;
226 227 228 229 230 231

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
232
        goto cleanup;
233 234 235 236 237
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
238
            goto cleanup; /* bad */
239 240 241 242 243 244

        e = (struct inotify_event *)tmp;
        tmp += sizeof(struct inotify_event);
        got -= sizeof(struct inotify_event);

        if (got < e->len)
245
            goto cleanup;
246 247 248 249 250 251 252 253 254 255 256 257 258

        tmp += e->len;
        got -= e->len;

        name = (char *)&(e->name);

        dom = virDomainFindByName(&driver->domains, name);

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
259
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
260
            if (!virDomainIsActive(dom)) {
261
                virDomainObjUnlock(dom);
262 263 264
                continue;
            }

265
            umlShutdownVMDaemon(NULL, driver, dom);
266
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
267
            VIR_DEBUG("Got inotify domain startup '%s'", name);
268
            if (virDomainIsActive(dom)) {
269
                virDomainObjUnlock(dom);
270 271 272 273
                continue;
            }

            if (umlReadPidFile(NULL, driver, dom) < 0) {
274
                virDomainObjUnlock(dom);
275 276 277 278 279 280
                continue;
            }

            dom->def->id = driver->nextvmid++;
            dom->state = VIR_DOMAIN_RUNNING;

281 282
            if (umlOpenMonitor(NULL, driver, dom) < 0) {
                VIR_WARN0("Could not open monitor for new domain");
283
                umlShutdownVMDaemon(NULL, driver, dom);
284 285
            } else if (umlIdentifyChrPTY(NULL, driver, dom) < 0) {
                VIR_WARN0("Could not identify charater devices for new domain");
286
                umlShutdownVMDaemon(NULL, driver, dom);
287
            }
288
        }
289
        virDomainObjUnlock(dom);
290
    }
291 292 293

cleanup:
    umlDriverUnlock(driver);
294 295 296 297 298 299 300 301
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
302
umlStartup(int privileged) {
303 304 305
    uid_t uid = geteuid();
    char *base = NULL;
    char driverConf[PATH_MAX];
306
    char *userdir = NULL;
307 308 309 310

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

311 312
    uml_driver->privileged = privileged;

313 314 315 316
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
317 318
    umlDriverLock(uml_driver);

319 320
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
321
    uml_driver->inotifyWatch = -1;
322

323 324
    userdir = virGetUserDirectory(NULL, uid);
    if (!userdir)
325
        goto error;
326

327
    if (privileged) {
328 329
        if (virAsprintf(&uml_driver->logDir,
                        "%s/log/libvirt/uml", LOCAL_STATE_DIR) == -1)
330 331 332 333 334
            goto out_of_memory;

        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
            goto out_of_memory;
    } else {
335

336
        if (virAsprintf(&uml_driver->logDir,
337
                        "%s/.libvirt/uml/log", userdir) == -1)
338 339
            goto out_of_memory;

340
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
341 342 343
            goto out_of_memory;
    }

344
    if (virAsprintf(&uml_driver->monitorDir,
345
                    "%s/.uml", userdir) == -1)
346 347 348 349 350 351 352 353 354
        goto out_of_memory;

    /* Configuration paths are either ~/.libvirt/uml/... (session) or
     * /etc/libvirt/uml/... (system).
     */
    if (snprintf (driverConf, sizeof(driverConf), "%s/uml.conf", base) == -1)
        goto out_of_memory;
    driverConf[sizeof(driverConf)-1] = '\0';

355
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
356 357
        goto out_of_memory;

358
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
359 360 361 362 363 364 365 366 367
        goto out_of_memory;

    VIR_FREE(base);

    if ((uml_driver->caps = umlCapsInit()) == NULL)
        goto out_of_memory;


    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
D
Daniel Veillard 已提交
368
        VIR_ERROR0(_("cannot initialize inotify"));
369
        goto error;
370 371 372
    }

    if (virFileMakePath(uml_driver->monitorDir) < 0) {
373
        char ebuf[1024];
D
Daniel Veillard 已提交
374
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
375
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
376
        goto error;
377 378
    }

379
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
380 381 382
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
383
        goto error;
384 385
    }

386 387
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
388 389
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
390 391 392 393 394 395

    if (virDomainLoadAllConfigs(NULL,
                                uml_driver->caps,
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
396
                                0, NULL, NULL) < 0)
397 398
        goto error;

399 400
    umlAutostartConfigs(uml_driver);

401
    umlDriverUnlock(uml_driver);
402 403
    VIR_FREE(userdir);

404 405
    return 0;

406
out_of_memory:
D
Daniel Veillard 已提交
407
    VIR_ERROR0(_("umlStartup: out of memory"));
408 409

error:
410
    VIR_FREE(userdir);
411
    VIR_FREE(base);
412 413
    umlDriverUnlock(uml_driver);
    umlShutdown();
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    return -1;
}

/**
 * umlReload:
 *
 * Function to restart the Uml daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
umlReload(void) {
    if (!uml_driver)
        return 0;

428
    umlDriverLock(uml_driver);
429 430 431 432 433
    virDomainLoadAllConfigs(NULL,
                            uml_driver->caps,
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
434
                            0, NULL, NULL);
435 436

    umlAutostartConfigs(uml_driver);
437
    umlDriverUnlock(uml_driver);
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

    return 0;
}

/**
 * umlActive:
 *
 * Checks if the Uml daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
umlActive(void) {
    unsigned int i;
453
    int active = 0;
454 455 456 457

    if (!uml_driver)
        return 0;

458 459 460
    umlDriverLock(uml_driver);
    for (i = 0 ; i < uml_driver->domains.count ; i++) {
        virDomainObjLock(uml_driver->domains.objs[i]);
461
        if (virDomainIsActive(uml_driver->domains.objs[i]))
462 463 464 465
            active = 1;
        virDomainObjUnlock(uml_driver->domains.objs[i]);
    }
    umlDriverUnlock(uml_driver);
466

467
    return active;
468 469 470 471 472 473 474 475 476 477 478 479 480 481
}

/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    unsigned int i;

    if (!uml_driver)
        return -1;

482
    umlDriverLock(uml_driver);
483 484
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
485 486 487 488 489 490
    close(uml_driver->inotifyFD);
    virCapabilitiesFree(uml_driver->caps);

    /* shutdown active VMs */
    for (i = 0 ; i < uml_driver->domains.count ; i++) {
        virDomainObjPtr dom = uml_driver->domains.objs[i];
491
        virDomainObjLock(dom);
492 493
        if (virDomainIsActive(dom))
            umlShutdownVMDaemon(NULL, uml_driver, dom);
494
        virDomainObjUnlock(dom);
495 496 497 498 499 500 501 502 503 504 505 506
    }

    virDomainObjListFree(&uml_driver->domains);

    VIR_FREE(uml_driver->logDir);
    VIR_FREE(uml_driver->configDir);
    VIR_FREE(uml_driver->autostartDir);
    VIR_FREE(uml_driver->monitorDir);

    if (uml_driver->brctl)
        brShutdown(uml_driver->brctl);

507
    umlDriverUnlock(uml_driver);
508
    virMutexDestroy(&uml_driver->lock);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    VIR_FREE(uml_driver);

    return 0;
}


static int umlReadPidFile(virConnectPtr conn,
                          struct uml_driver *driver,
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
525 526
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
527
        virReportOOMError(conn);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        return -1;
    }

reopen:
    if (!(file = fopen(pidfile, "r"))) {
        if (errno == ENOENT &&
            retries++ < 50) {
            usleep(1000 * 100);
            goto reopen;
        }
        goto cleanup;
    }

    if (fscanf(file, "%d", &vm->pid) != 1) {
        errno = EINVAL;
543
        fclose(file);
544 545 546 547 548 549 550 551 552 553
        goto cleanup;
    }

    if (fclose(file) < 0)
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
554 555 556
        virReportSystemError(conn, errno,
                             _("failed to read pid: %s"),
                             pidfile);
557 558 559 560 561 562 563 564 565 566
    VIR_FREE(pidfile);
    return rc;
}

static int umlMonitorAddress(virConnectPtr conn,
                             const struct uml_driver *driver,
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;

567 568
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
569
        virReportOOMError(conn);
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
    strncpy(addr->sun_path, sockname, sizeof(addr->sun_path)-1);
    NUL_TERMINATE(addr->sun_path);
    VIR_FREE(sockname);
    return 0;
}

static int umlOpenMonitor(virConnectPtr conn,
                          struct uml_driver *driver,
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;

    if (umlMonitorAddress(conn, driver, vm, &addr) < 0)
        return -1;

591
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
592 593 594
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
595
            retries++ < 50) {
596 597 598 599 600 601 602
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

    if ((vm->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
603 604
        virReportSystemError(conn, errno,
                             "%s", _("cannot open socket"));
605 606 607 608
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
609 610
    sprintf(addr.sun_path + 1, "libvirt-uml-%u", vm->pid);
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
611
    if (bind(vm->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
612 613
        virReportSystemError(conn, errno,
                             "%s", _("cannot bind socket"));
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
        close(vm->monitor);
        vm->monitor = -1;
        return -1;
    }

    return 0;
}


#define MONITOR_MAGIC 0xcafebabe
#define MONITOR_BUFLEN 512
#define MONITOR_VERSION 2

struct monitor_request {
    uint32_t magic;
    uint32_t version;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};

struct monitor_response {
    uint32_t error;
    uint32_t extra;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};


static int umlMonitorCommand(virConnectPtr conn,
                             const struct uml_driver *driver,
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply)
{
    struct monitor_request req;
    struct monitor_response res;
    char *retdata = NULL;
    int retlen = 0, ret = 0;
    struct sockaddr_un addr;
    unsigned int addrlen;

655 656
    VIR_DEBUG("Run command '%s'", cmd);

657 658 659 660 661 662 663 664 665 666
    *reply = NULL;

    if (umlMonitorAddress(conn, driver, vm, &addr) < 0)
        return -1;

    memset(&req, 0, sizeof(req));
    req.magic = MONITOR_MAGIC;
    req.version = MONITOR_VERSION;
    req.length = strlen(cmd);
    if (req.length > (MONITOR_BUFLEN-1)) {
667 668 669
        virReportSystemError(conn, EINVAL,
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
670 671 672 673 674 675 676
        return -1;
    }
    strncpy(req.data, cmd, req.length);
    req.data[req.length] = '\0';

    if (sendto(vm->monitor, &req, sizeof req, 0,
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
677 678 679
        virReportSystemError(conn, errno,
                             _("cannot send command %s"),
                             cmd);
680 681 682 683 684 685 686
        return -1;
    }

    do {
        addrlen = sizeof(addr);
        if (recvfrom(vm->monitor, &res, sizeof res, 0,
                     (struct sockaddr *)&addr, &addrlen) < 0) {
687 688 689
            virReportSystemError(conn, errno,
                                 _("cannot read reply %s"),
                                 cmd);
690 691 692 693
            goto error;
        }

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
694
            virReportOOMError(conn);
695 696 697 698 699 700 701 702 703 704 705
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

706 707
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

708 709 710 711 712 713 714 715 716 717
    *reply = retdata;

    return ret;

error:
    VIR_FREE(retdata);
    return -1;
}


718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
static int umlCleanupTapDevices(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm) {
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
    VIR_ERROR0("Cleanup tap");
    if (brInit(&brctl) < 0)
        return -1;

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr def = vm->def->nets[i];

        if (def->type != VIR_DOMAIN_NET_TYPE_BRIDGE &&
            def->type != VIR_DOMAIN_NET_TYPE_NETWORK)
            continue;

        VIR_ERROR("Cleanup '%s'", def->ifname);
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
            VIR_ERROR("Cleanup failed %d", err);
            ret = -1;
        }
    }
    VIR_ERROR0("Cleanup tap done");
    brShutdown(brctl);
    return ret;
}

747 748 749 750 751
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
    const char **argv = NULL, **tmp;
    const char **progenv = NULL;
752 753
    int i, ret;
    pid_t pid;
754 755 756 757
    char *logfile;
    int logfd = -1;
    struct stat sb;
    fd_set keepfd;
758
    char ebuf[1024];
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

    FD_ZERO(&keepfd);

    if (virDomainIsActive(vm)) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("VM is already active"));
        return -1;
    }

    if (!vm->def->os.kernel) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no kernel specified"));
        return -1;
    }
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(vm->def->os.kernel, &sb) < 0) {
778 779 780
        virReportSystemError(conn, errno,
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
781 782 783 784
        return -1;
    }

    if (virFileMakePath(driver->logDir) < 0) {
785 786 787
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
788 789 790
        return -1;
    }

791 792
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
793
        virReportOOMError(conn);
794 795 796 797 798
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
799 800 801
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
802 803 804 805 806 807
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

    if (umlSetCloseExec(logfd) < 0) {
808 809
        virReportSystemError(conn, errno,
                             "%s", _("Unable to set VM logfile close-on-exec flag"));
810 811 812 813 814
        close(logfd);
        return -1;
    }

    if (umlBuildCommandLine(conn, driver, vm,
815
                            &argv, &progenv) < 0) {
816
        close(logfd);
817
        umlCleanupTapDevices(conn, vm);
818 819 820 821 822 823
        return -1;
    }

    tmp = progenv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
824
            VIR_WARN(_("Unable to write envv to logfile: %s"),
825
                   virStrerror(errno, ebuf, sizeof ebuf));
826
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
827
            VIR_WARN(_("Unable to write envv to logfile: %s"),
828
                   virStrerror(errno, ebuf, sizeof ebuf));
829 830 831 832 833
        tmp++;
    }
    tmp = argv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
834
            VIR_WARN(_("Unable to write argv to logfile: %s"),
835
                   virStrerror(errno, ebuf, sizeof ebuf));
836
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
837
            VIR_WARN(_("Unable to write argv to logfile: %s"),
838
                   virStrerror(errno, ebuf, sizeof ebuf));
839 840 841
        tmp++;
    }
    if (safewrite(logfd, "\n", 1) < 0)
D
Daniel Veillard 已提交
842
        VIR_WARN(_("Unable to write argv to logfile: %s"),
843
                 virStrerror(errno, ebuf, sizeof ebuf));
844 845 846

    vm->monitor = -1;

847 848
    ret = virExecDaemonize(conn, argv, progenv, &keepfd, &pid,
                           -1, &logfd, &logfd,
849 850
                           VIR_EXEC_CLEAR_CAPS,
                           NULL, NULL, NULL);
851 852 853 854 855 856 857 858 859 860
    close(logfd);

    for (i = 0 ; argv[i] ; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

861 862
    if (ret < 0)
        umlCleanupTapDevices(conn, vm);
863 864 865

    /* NB we don't mark it running here - we do that async
       with inotify */
866 867 868
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
869 870 871 872 873 874 875 876 877

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm)
{
    int ret;
878
    if (!virDomainIsActive(vm))
879 880
        return;

881
    virKillProcess(vm->pid, SIGTERM);
882 883 884 885 886 887

    if (vm->monitor != -1)
        close(vm->monitor);
    vm->monitor = -1;

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
D
Daniel Veillard 已提交
888
        VIR_WARN(_("Got unexpected pid %d != %d"),
889 890 891 892 893 894 895 896 897
               ret, vm->pid);
    }

    vm->pid = -1;
    vm->def->id = -1;
    vm->state = VIR_DOMAIN_SHUTOFF;
    VIR_FREE(vm->vcpupids);
    vm->nvcpupids = 0;

898 899
    umlCleanupTapDevices(conn, vm);

900 901 902 903 904 905 906 907 908 909 910 911
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
}


static virDrvOpenStatus umlOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                int flags ATTRIBUTE_UNUSED) {
912 913 914
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
915

916
        conn->uri = xmlParseURI(uml_driver->privileged ?
917 918 919 920 921 922 923 924 925 926 927 928 929 930
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
            virReportOOMError(conn);
            return VIR_DRV_OPEN_ERROR;
        }
    } else {
        if (conn->uri->scheme == NULL ||
            STRNEQ (conn->uri->scheme, "uml"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;
931 932


933
        /* Check path and tell them correct path if they made a mistake */
934
        if (uml_driver->privileged) {
935
            if (STRNEQ (conn->uri->path, "/system") &&
936 937 938 939 940 941 942 943 944 945 946 947 948
                STRNEQ (conn->uri->path, "/session")) {
                umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
                umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
949
        }
950 951 952 953 954

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
            umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                           _("uml state driver is not active"));
955 956 957 958 959 960 961 962 963 964
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
965
    /*struct uml_driver *driver = conn->privateData;*/
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

    conn->privateData = NULL;

    return 0;
}

static const char *umlGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
    return "UML";
}


static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

981
    umlDriverLock(driver);
982
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
983
        virReportOOMError(conn);
984
    umlDriverUnlock(driver);
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

    return xml;
}



static int umlGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
    unsigned long long usertime, systime;

    if (snprintf(proc, sizeof(proc), "/proc/%d/stat", pid) >= (int)sizeof(proc)) {
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
        /*printf("cannot read pid info");*/
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
        umlDebug("not enough arg");
1009
        fclose(pidinfo);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);

    umlDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);

    fclose(pidinfo);

    return 0;
}


static virDomainPtr umlDomainLookupByID(virConnectPtr conn,
                                          int id) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1031 1032
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1033

1034
    umlDriverLock(driver);
1035
    vm = virDomainFindByID(&driver->domains, id);
1036 1037
    umlDriverUnlock(driver);

1038 1039
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1040
        goto cleanup;
1041 1042 1043 1044
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1045 1046

cleanup:
1047 1048
    if (vm)
        virDomainObjUnlock(vm);
1049 1050
    return dom;
}
1051

1052 1053 1054
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1055 1056
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1057

1058
    umlDriverLock(driver);
1059
    vm = virDomainFindByUUID(&driver->domains, uuid);
1060 1061
    umlDriverUnlock(driver);

1062 1063
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1064
        goto cleanup;
1065 1066 1067 1068
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1069 1070

cleanup:
1071 1072
    if (vm)
        virDomainObjUnlock(vm);
1073 1074
    return dom;
}
1075

1076 1077 1078
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1079 1080
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1081

1082
    umlDriverLock(driver);
1083
    vm = virDomainFindByName(&driver->domains, name);
1084 1085
    umlDriverUnlock(driver);

1086 1087
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1088
        goto cleanup;
1089 1090 1091 1092
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1093 1094

cleanup:
1095 1096
    if (vm)
        virDomainObjUnlock(vm);
1097 1098 1099 1100
    return dom;
}

static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1101
    struct uml_driver *driver = conn->privateData;
1102 1103
    struct utsname ut;
    int major, minor, micro;
1104
    int ret = -1;
1105 1106 1107

    uname(&ut);

1108
    umlDriverLock(driver);
1109 1110 1111 1112
    if (sscanf(ut.release, "%u.%u.%u",
               &major, &minor, &micro) != 3) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse version %s"), ut.release);
1113
        goto cleanup;
1114 1115
    }

1116 1117 1118 1119 1120 1121
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1122 1123 1124 1125 1126
}

static char *
umlGetHostname (virConnectPtr conn)
{
1127
    char *result;
1128

1129 1130
    result = virGetHostname();
    if (result == NULL) {
1131 1132
        virReportSystemError(conn, errno,
                             "%s", _("cannot lookup hostname"));
1133 1134 1135
        return NULL;
    }
    /* Caller frees this string. */
1136
    return result;
1137 1138 1139
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1140
    struct uml_driver *driver = conn->privateData;
1141 1142
    int got = 0, i;

1143 1144 1145
    umlDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1146 1147
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1148 1149 1150
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    umlDriverUnlock(driver);
1151 1152 1153 1154

    return got;
}
static int umlNumDomains(virConnectPtr conn) {
1155
    struct uml_driver *driver = conn->privateData;
1156 1157
    int n = 0, i;

1158 1159 1160
    umlDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1161 1162
        if (virDomainIsActive(driver->domains.objs[i]))
            n++;
1163 1164 1165
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    umlDriverUnlock(driver);
1166 1167 1168 1169 1170

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1171
    struct uml_driver *driver = conn->privateData;
1172
    virDomainDefPtr def;
1173
    virDomainObjPtr vm = NULL;
1174
    virDomainPtr dom = NULL;
1175

1176
    umlDriverLock(driver);
1177 1178
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1179
        goto cleanup;
1180 1181 1182 1183 1184 1185

    vm = virDomainFindByName(&driver->domains, def->name);
    if (vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                         _("domain '%s' is already defined"),
                         def->name);
1186
        goto cleanup;
1187 1188 1189 1190 1191 1192 1193 1194 1195
    }
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        umlReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                         _("domain with uuid '%s' is already defined"),
                         uuidstr);
1196
        goto cleanup;
1197 1198 1199 1200
    }

    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1201 1202 1203
                                  def)))
        goto cleanup;
    def = NULL;
1204 1205 1206 1207

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1208 1209
        vm = NULL;
        goto cleanup;
1210 1211 1212 1213
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1214 1215 1216

cleanup:
    virDomainDefFree(def);
1217 1218 1219
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1220 1221 1222 1223 1224
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1225 1226
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1227
    char *info = NULL;
1228
    int ret = -1;
1229

1230
    umlDriverLock(driver);
1231
    vm = virDomainFindByID(&driver->domains, dom->id);
1232
    umlDriverUnlock(driver);
1233 1234 1235
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1236
        goto cleanup;
1237 1238 1239 1240 1241 1242
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("shutdown operation failed"));
1243
        goto cleanup;
1244
    }
1245
    ret = 0;
1246 1247
#endif

1248 1249
cleanup:
    VIR_FREE(info);
1250 1251
    if (vm)
        virDomainObjUnlock(vm);
1252
    return ret;
1253 1254 1255 1256
}


static int umlDomainDestroy(virDomainPtr dom) {
1257 1258 1259
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1260

1261
    umlDriverLock(driver);
1262
    vm = virDomainFindByID(&driver->domains, dom->id);
1263 1264 1265
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1266
        goto cleanup;
1267 1268 1269
    }

    umlShutdownVMDaemon(dom->conn, driver, vm);
1270
    if (!vm->persistent) {
1271 1272
        virDomainRemoveInactive(&driver->domains,
                                vm);
1273 1274 1275
        vm = NULL;
    }
    ret = 0;
1276

1277
cleanup:
1278 1279 1280
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1281
    return ret;
1282 1283 1284 1285
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1286 1287 1288
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1289

1290
    umlDriverLock(driver);
1291
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1292
    umlDriverUnlock(driver);
1293 1294 1295
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1296
        goto cleanup;
1297 1298
    }

1299
    if (!(type = strdup(vm->def->os.type)))
1300
        virReportOOMError(dom->conn);
1301 1302

cleanup:
1303 1304
    if (vm)
        virDomainObjUnlock(vm);
1305 1306 1307 1308 1309
    return type;
}

/* Returns max memory in kb, 0 if error */
static unsigned long umlDomainGetMaxMemory(virDomainPtr dom) {
1310 1311 1312
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1313

1314
    umlDriverLock(driver);
1315
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1316 1317
    umlDriverUnlock(driver);

1318 1319 1320 1321 1322
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1323 1324
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1325
    }
1326
    ret = vm->def->maxmem;
1327

1328
cleanup:
1329 1330
    if (vm)
        virDomainObjUnlock(vm);
1331
    return ret;
1332 1333 1334
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1335 1336 1337
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1338

1339
    umlDriverLock(driver);
1340
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1341 1342
    umlDriverUnlock(driver);

1343 1344 1345 1346 1347 1348
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
1349
        goto cleanup;
1350 1351 1352 1353 1354
    }

    if (newmax < vm->def->memory) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set max memory lower than current memory"));
1355
        goto cleanup;
1356 1357 1358
    }

    vm->def->maxmem = newmax;
1359 1360 1361
    ret = 0;

cleanup:
1362 1363
    if (vm)
        virDomainObjUnlock(vm);
1364
    return ret;
1365 1366 1367
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1368 1369 1370
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1371

1372
    umlDriverLock(driver);
1373
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1374 1375
    umlDriverUnlock(driver);

1376 1377 1378 1379 1380 1381
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
1382
        goto cleanup;
1383 1384 1385 1386 1387
    }

    if (virDomainIsActive(vm)) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cannot set memory of an active domain"));
1388
        goto cleanup;
1389 1390 1391 1392 1393
    }

    if (newmem > vm->def->maxmem) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set memory higher than max memory"));
1394
        goto cleanup;
1395 1396 1397
    }

    vm->def->memory = newmem;
1398 1399 1400
    ret = 0;

cleanup:
1401 1402
    if (vm)
        virDomainObjUnlock(vm);
1403
    return ret;
1404 1405 1406 1407
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1408 1409 1410 1411
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1412
    umlDriverLock(driver);
1413
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1414 1415
    umlDriverUnlock(driver);

1416 1417
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1418 1419
                       "%s", _("no domain with matching uuid"));
        goto cleanup;
1420 1421 1422 1423 1424 1425 1426 1427
    }

    info->state = vm->state;

    if (!virDomainIsActive(vm)) {
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1428 1429 1430
            umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot read cputime for domain"));
            goto cleanup;
1431 1432 1433 1434 1435 1436
        }
    }

    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
1437 1438 1439
    ret = 0;

cleanup:
1440 1441
    if (vm)
        virDomainObjUnlock(vm);
1442
    return ret;
1443 1444 1445 1446 1447
}


static char *umlDomainDumpXML(virDomainPtr dom,
                                int flags ATTRIBUTE_UNUSED) {
1448 1449 1450 1451
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1452
    umlDriverLock(driver);
1453
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1454 1455
    umlDriverUnlock(driver);

1456 1457 1458
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1459
        goto cleanup;
1460 1461
    }

1462 1463 1464 1465 1466 1467
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
1468 1469
    if (vm)
        virDomainObjUnlock(vm);
1470
    return ret;
1471 1472 1473 1474 1475
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1476
    struct uml_driver *driver = conn->privateData;
1477 1478
    int got = 0, i;

1479
    umlDriverLock(driver);
1480
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
1481
        virDomainObjLock(driver->domains.objs[i]);
1482 1483
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
1484
                virReportOOMError(conn);
1485
                virDomainObjUnlock(driver->domains.objs[i]);
1486 1487 1488
                goto cleanup;
            }
        }
1489
        virDomainObjUnlock(driver->domains.objs[i]);
1490
    }
1491
    umlDriverUnlock(driver);
1492 1493 1494 1495 1496 1497

    return got;

 cleanup:
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
1498
    umlDriverUnlock(driver);
1499 1500 1501 1502
    return -1;
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1503
    struct uml_driver *driver = conn->privateData;
1504 1505
    int n = 0, i;

1506 1507 1508
    umlDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1509 1510
        if (!virDomainIsActive(driver->domains.objs[i]))
            n++;
1511 1512 1513
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    umlDriverUnlock(driver);
1514 1515 1516 1517 1518 1519

    return n;
}


static int umlDomainStart(virDomainPtr dom) {
1520 1521 1522
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1523

1524
    umlDriverLock(driver);
1525
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1526

1527 1528 1529
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1530
        goto cleanup;
1531 1532
    }

1533 1534 1535
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1536 1537 1538
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1539
    return ret;
1540 1541 1542 1543
}


static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1544
    struct uml_driver *driver = conn->privateData;
1545
    virDomainDefPtr def;
1546
    virDomainObjPtr vm = NULL;
1547
    virDomainPtr dom = NULL;
1548

1549
    umlDriverLock(driver);
1550 1551
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1552
        goto cleanup;
1553 1554 1555

    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1556 1557 1558
                                  def)))
        goto cleanup;
    def = NULL;
1559 1560 1561 1562 1563 1564 1565
    vm->persistent = 1;

    if (virDomainSaveConfig(conn,
                            driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1566
        vm = NULL;
1567
        goto cleanup;
1568 1569 1570 1571
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1572 1573 1574

cleanup:
    virDomainDefFree(def);
1575 1576 1577
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1578 1579 1580 1581
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1582 1583 1584
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1585

1586
    umlDriverLock(driver);
1587
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1588 1589 1590
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1591
        goto cleanup;
1592 1593 1594 1595 1596
    }

    if (virDomainIsActive(vm)) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
1597
        goto cleanup;
1598 1599 1600 1601 1602
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
1603
        goto cleanup;
1604 1605 1606
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
1607
        goto cleanup;
1608 1609 1610

    virDomainRemoveInactive(&driver->domains,
                            vm);
1611
    vm = NULL;
1612
    ret = 0;
1613

1614
cleanup:
1615 1616 1617
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1618
    return ret;
1619 1620 1621 1622 1623 1624
}



static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1625 1626 1627
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1628

1629
    umlDriverLock(driver);
1630
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1631

1632 1633 1634
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1635
        goto cleanup;
1636 1637 1638
    }

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

1641
cleanup:
1642 1643
    if (vm)
        virDomainObjUnlock(vm);
1644
    umlDriverUnlock(driver);
1645
    return ret;
1646 1647 1648 1649
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1650
    struct uml_driver *driver = dom->conn->privateData;
1651
    virDomainObjPtr vm;
1652 1653 1654
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1655 1656 1657
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1658 1659 1660
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1661
        goto cleanup;
1662 1663 1664 1665 1666
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
1667
        goto cleanup;
1668 1669 1670 1671
    }

    autostart = (autostart != 0);

1672 1673 1674 1675 1676
    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;
1677

1678 1679
        if (autostart) {
            int err;
1680

1681
            if ((err = virFileMakePath(driver->autostartDir))) {
1682 1683 1684
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1685 1686
                goto cleanup;
            }
1687

1688
            if (symlink(configFile, autostartLink) < 0) {
1689 1690 1691
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
1692 1693 1694 1695
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1696 1697 1698
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
1699 1700
                goto cleanup;
            }
1701 1702
        }

1703
        vm->autostart = autostart;
1704 1705 1706 1707 1708 1709
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1710 1711
    if (vm)
        virDomainObjUnlock(vm);
1712
    umlDriverUnlock(driver);
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    return ret;
}


static int
umlDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
1724 1725 1726
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
1727

1728
    umlDriverLock(driver);
1729
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1730 1731
    umlDriverUnlock(driver);

1732 1733
    if (!vm) {
        umlReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
1734
                        "%s", _("no domain with matching uuid"));
1735
        goto cleanup;
1736 1737 1738 1739
    }

    if (!path || path[0] == '\0') {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1740
                       "%s", _("NULL or empty path"));
1741
        goto cleanup;
1742 1743 1744 1745 1746
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
1747 1748 1749 1750
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
1751 1752
    }

1753 1754 1755 1756 1757
    if (ret == 0) {
        ret = -1;
        /* The path is correct, now try to open it and get its size. */
        fd = open (path, O_RDONLY);
        if (fd == -1) {
1758 1759
            virReportSystemError(dom->conn, errno,
                                 _("cannot open %s"), path);
1760 1761
            goto cleanup;
        }
1762

1763 1764 1765 1766 1767 1768
        /* Seek and read. */
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
        if (lseek (fd, offset, SEEK_SET) == (off_t) -1 ||
            saferead (fd, buffer, size) == (ssize_t) -1) {
1769 1770
            virReportSystemError(dom->conn, errno,
                                 _("cannot read %s"), path);
1771 1772 1773 1774 1775 1776
            goto cleanup;
        }

        ret = 0;
    } else {
        umlReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1777
                        "%s", _("invalid path"));
1778 1779
    }

1780
cleanup:
1781
    if (fd >= 0) close (fd);
1782 1783
    if (vm)
        virDomainObjUnlock(vm);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
    return ret;
}



static virDriver umlDriver = {
    VIR_DRV_UML,
    "UML",
    umlOpen, /* open */
    umlClose, /* close */
    NULL, /* supports_feature */
    umlGetType, /* type */
    umlGetVersion, /* version */
1797
    umlGetHostname, /* getHostname */
1798
    NULL, /* getMaxVcpus */
1799
    nodeGetInfo, /* nodeGetInfo */
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    umlGetCapabilities, /* getCapabilities */
    umlListDomains, /* listDomains */
    umlNumDomains, /* numOfDomains */
    umlDomainCreate, /* domainCreateXML */
    umlDomainLookupByID, /* domainLookupByID */
    umlDomainLookupByUUID, /* domainLookupByUUID */
    umlDomainLookupByName, /* domainLookupByName */
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    umlDomainShutdown, /* domainShutdown */
    NULL, /* domainReboot */
    umlDomainDestroy, /* domainDestroy */
    umlDomainGetOSType, /* domainGetOSType */
    umlDomainGetMaxMemory, /* domainGetMaxMemory */
    umlDomainSetMaxMemory, /* domainSetMaxMemory */
    umlDomainSetMemory, /* domainSetMemory */
    umlDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
    NULL, /* domainCoreDump */
    NULL, /* domainSetVcpus */
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
    NULL, /* domainGetMaxVcpus */
1824 1825
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
1826
    umlDomainDumpXML, /* domainDumpXML */
1827 1828
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
1829 1830
    umlListDefinedDomains, /* listDefinedDomains */
    umlNumDefinedDomains, /* numOfDefinedDomains */
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
    umlDomainStart, /* domainCreate */
    umlDomainDefine, /* domainDefineXML */
    umlDomainUndefine, /* domainUndefine */
    NULL, /* domainAttachDevice */
    NULL, /* domainDetachDevice */
    umlDomainGetAutostart, /* domainGetAutostart */
    umlDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
    umlDomainBlockPeek, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
1848 1849
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
1850
    NULL, /* domainEventRegister */
1851
    NULL, /* domainEventDeregister */
1852 1853
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
1854
    NULL, /* nodeDeviceDettach */
1855 1856
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
};


static virStateDriver umlStateDriver = {
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
    return 0;
}