uml_driver.c 51.5 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
    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;

117 118 119 120 121 122 123 124 125 126 127 128 129
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

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

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
130
        !virDomainObjIsActive(vm)) {
131 132 133 134 135 136 137 138 139
        virResetLastError();
        if (umlStartVMDaemon(data->conn, data->driver, vm) < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                      vm->def->name, err->message);
        }
    }
    virDomainObjUnlock(vm);
}
140 141 142

static void
umlAutostartConfigs(struct uml_driver *driver) {
143 144 145 146 147
    /* 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
     */
148 149 150
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
151
    /* Ignoring NULL conn which is mostly harmless here */
152

153 154 155
    struct umlAutostartData data = { driver, conn };

    virHashForEach(driver->domains.objs, umlAutostartDomain, &data);
156

157 158
    if (conn)
        virConnectClose(conn);
159 160 161 162 163 164 165 166 167 168 169 170 171
}


static int
umlIdentifyOneChrPTY(virConnectPtr conn,
                     struct uml_driver *driver,
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
172
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
173
        virReportOOMError(conn);
174 175 176
        return -1;
    }
requery:
177 178
    if (umlMonitorCommand(NULL, driver, dom, cmd, &res) < 0)
        return -1;
179

180
    if (res && STRPREFIX(res, "pts:")) {
181 182
        VIR_FREE(def->data.file.path);
        if ((def->data.file.path = strdup(res + 4)) == NULL) {
183
            virReportOOMError(conn);
184 185 186 187
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
188
    } else if (!res || STRPREFIX(res, "pts")) {
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        /* 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;

239
    umlDriverLock(driver);
240
    if (watch != driver->inotifyWatch)
241
        goto cleanup;
242 243 244 245 246 247

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
248
        goto cleanup;
249 250 251 252 253
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
254
            goto cleanup; /* bad */
255 256 257 258 259 260

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

        if (got < e->len)
261
            goto cleanup;
262 263 264 265 266 267 268 269 270 271 272 273 274

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

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

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

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
275
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
276
            if (!virDomainObjIsActive(dom)) {
277
                virDomainObjUnlock(dom);
278 279 280
                continue;
            }

281
            umlShutdownVMDaemon(NULL, driver, dom);
282
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
283
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
284
            if (virDomainObjIsActive(dom)) {
285
                virDomainObjUnlock(dom);
286 287 288 289
                continue;
            }

            if (umlReadPidFile(NULL, driver, dom) < 0) {
290
                virDomainObjUnlock(dom);
291 292 293 294 295 296
                continue;
            }

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

297 298
            if (umlOpenMonitor(NULL, driver, dom) < 0) {
                VIR_WARN0("Could not open monitor for new domain");
299
                umlShutdownVMDaemon(NULL, driver, dom);
300 301
            } else if (umlIdentifyChrPTY(NULL, driver, dom) < 0) {
                VIR_WARN0("Could not identify charater devices for new domain");
302
                umlShutdownVMDaemon(NULL, driver, dom);
303
            }
304
        }
305
        virDomainObjUnlock(dom);
306
    }
307 308 309

cleanup:
    umlDriverUnlock(driver);
310 311 312 313 314 315 316 317
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
318
umlStartup(int privileged) {
319 320 321
    uid_t uid = geteuid();
    char *base = NULL;
    char driverConf[PATH_MAX];
322
    char *userdir = NULL;
323 324 325 326

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

327 328
    uml_driver->privileged = privileged;

329 330 331 332
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
333 334
    umlDriverLock(uml_driver);

335 336
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
337
    uml_driver->inotifyWatch = -1;
338

339 340 341
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

342 343
    userdir = virGetUserDirectory(NULL, uid);
    if (!userdir)
344
        goto error;
345

346
    if (privileged) {
347 348
        if (virAsprintf(&uml_driver->logDir,
                        "%s/log/libvirt/uml", LOCAL_STATE_DIR) == -1)
349 350 351 352 353
            goto out_of_memory;

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

355
        if (virAsprintf(&uml_driver->logDir,
356
                        "%s/.libvirt/uml/log", userdir) == -1)
357 358
            goto out_of_memory;

359
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
360 361 362
            goto out_of_memory;
    }

363
    if (virAsprintf(&uml_driver->monitorDir,
364
                    "%s/.uml", userdir) == -1)
365 366 367 368 369 370 371 372 373
        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';

374
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
375 376
        goto out_of_memory;

377
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
378 379 380 381 382 383 384 385 386
        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 已提交
387
        VIR_ERROR0(_("cannot initialize inotify"));
388
        goto error;
389 390 391
    }

    if (virFileMakePath(uml_driver->monitorDir) < 0) {
392
        char ebuf[1024];
D
Daniel Veillard 已提交
393
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
394
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
395
        goto error;
396 397
    }

398
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
399 400 401
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
402
        goto error;
403 404
    }

405 406
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
407 408
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
409 410 411 412 413 414

    if (virDomainLoadAllConfigs(NULL,
                                uml_driver->caps,
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
415
                                0, NULL, NULL) < 0)
416 417
        goto error;

418 419
    umlAutostartConfigs(uml_driver);

420
    umlDriverUnlock(uml_driver);
421 422
    VIR_FREE(userdir);

423 424
    return 0;

425
out_of_memory:
D
Daniel Veillard 已提交
426
    VIR_ERROR0(_("umlStartup: out of memory"));
427 428

error:
429
    VIR_FREE(userdir);
430
    VIR_FREE(base);
431 432
    umlDriverUnlock(uml_driver);
    umlShutdown();
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    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;

447
    umlDriverLock(uml_driver);
448 449 450 451 452
    virDomainLoadAllConfigs(NULL,
                            uml_driver->caps,
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
453
                            0, NULL, NULL);
454 455

    umlAutostartConfigs(uml_driver);
456
    umlDriverUnlock(uml_driver);
457 458 459 460 461 462 463 464 465 466 467 468 469 470

    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) {
471
    int active = 0;
472 473 474 475

    if (!uml_driver)
        return 0;

476
    umlDriverLock(uml_driver);
477
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
478
    umlDriverUnlock(uml_driver);
479

480
    return active;
481 482
}

483 484 485 486 487 488 489
static void
umlShutdownOneVM(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
D
Daniel P. Berrange 已提交
490
    if (virDomainObjIsActive(dom))
491 492 493 494
        umlShutdownVMDaemon(NULL, driver, dom);
    virDomainObjUnlock(dom);
}

495 496 497 498 499 500 501 502 503 504
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

505
    umlDriverLock(uml_driver);
506 507
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
508 509 510
    close(uml_driver->inotifyFD);
    virCapabilitiesFree(uml_driver->caps);

511 512 513
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
514

515
    virDomainObjListDeinit(&uml_driver->domains);
516 517 518 519 520 521 522 523 524

    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);

525
    umlDriverUnlock(uml_driver);
526
    virMutexDestroy(&uml_driver->lock);
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    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;
543 544
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
545
        virReportOOMError(conn);
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        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;
561
        fclose(file);
562 563 564 565 566 567 568 569 570 571
        goto cleanup;
    }

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

    rc = 0;

 cleanup:
    if (rc != 0)
572 573 574
        virReportSystemError(conn, errno,
                             _("failed to read pid: %s"),
                             pidfile);
575 576 577 578 579 580 581 582 583
    VIR_FREE(pidfile);
    return rc;
}

static int umlMonitorAddress(virConnectPtr conn,
                             const struct uml_driver *driver,
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
584
    int retval = 0;
585

586 587
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
588
        virReportOOMError(conn);
589 590 591 592 593
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
594 595 596 597 598
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
599
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
600
    return retval;
601 602 603 604 605 606 607 608 609 610 611 612
}

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;

613
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
614 615 616
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
617
            retries++ < 50) {
618 619 620 621 622 623 624
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

    if ((vm->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
625 626
        virReportSystemError(conn, errno,
                             "%s", _("cannot open socket"));
627 628 629 630
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
631 632
    sprintf(addr.sun_path + 1, "libvirt-uml-%u", vm->pid);
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
633
    if (bind(vm->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
634 635
        virReportSystemError(conn, errno,
                             "%s", _("cannot bind socket"));
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
        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;

677 678
    VIR_DEBUG("Run command '%s'", cmd);

679 680 681 682 683 684 685 686 687 688
    *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)) {
689 690 691
        virReportSystemError(conn, EINVAL,
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
692 693
        return -1;
    }
C
Chris Lalancette 已提交
694 695 696 697 698
    if (virStrcpyStatic(req.data, cmd) == NULL) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
699 700 701

    if (sendto(vm->monitor, &req, sizeof req, 0,
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
702 703 704
        virReportSystemError(conn, errno,
                             _("cannot send command %s"),
                             cmd);
705 706 707 708 709 710 711
        return -1;
    }

    do {
        addrlen = sizeof(addr);
        if (recvfrom(vm->monitor, &res, sizeof res, 0,
                     (struct sockaddr *)&addr, &addrlen) < 0) {
712 713 714
            virReportSystemError(conn, errno,
                                 _("cannot read reply %s"),
                                 cmd);
715 716 717 718
            goto error;
        }

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
719
            virReportOOMError(conn);
720 721 722 723 724 725 726 727 728 729 730
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

731 732
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

733 734 735 736 737 738 739 740 741 742
    *reply = retdata;

    return ret;

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


743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
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;
}

772 773 774 775 776
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
    const char **argv = NULL, **tmp;
    const char **progenv = NULL;
777 778
    int i, ret;
    pid_t pid;
779 780 781 782
    char *logfile;
    int logfd = -1;
    struct stat sb;
    fd_set keepfd;
783
    char ebuf[1024];
784 785 786

    FD_ZERO(&keepfd);

D
Daniel P. Berrange 已提交
787
    if (virDomainObjIsActive(vm)) {
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
        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) {
803 804 805
        virReportSystemError(conn, errno,
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
806 807 808 809
        return -1;
    }

    if (virFileMakePath(driver->logDir) < 0) {
810 811 812
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
813 814 815
        return -1;
    }

816 817
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
818
        virReportOOMError(conn);
819 820 821 822 823
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
824 825 826
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
827 828 829 830 831 832
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

    if (umlSetCloseExec(logfd) < 0) {
833 834
        virReportSystemError(conn, errno,
                             "%s", _("Unable to set VM logfile close-on-exec flag"));
835 836 837 838 839
        close(logfd);
        return -1;
    }

    if (umlBuildCommandLine(conn, driver, vm,
840
                            &argv, &progenv) < 0) {
841
        close(logfd);
842
        umlCleanupTapDevices(conn, vm);
843 844 845 846 847 848
        return -1;
    }

    tmp = progenv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
849
            VIR_WARN(_("Unable to write envv to logfile: %s"),
850
                   virStrerror(errno, ebuf, sizeof ebuf));
851
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
852
            VIR_WARN(_("Unable to write envv to logfile: %s"),
853
                   virStrerror(errno, ebuf, sizeof ebuf));
854 855 856 857 858
        tmp++;
    }
    tmp = argv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
859
            VIR_WARN(_("Unable to write argv to logfile: %s"),
860
                   virStrerror(errno, ebuf, sizeof ebuf));
861
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
862
            VIR_WARN(_("Unable to write argv to logfile: %s"),
863
                   virStrerror(errno, ebuf, sizeof ebuf));
864 865 866
        tmp++;
    }
    if (safewrite(logfd, "\n", 1) < 0)
D
Daniel Veillard 已提交
867
        VIR_WARN(_("Unable to write argv to logfile: %s"),
868
                 virStrerror(errno, ebuf, sizeof ebuf));
869 870 871

    vm->monitor = -1;

872 873
    ret = virExecDaemonize(conn, argv, progenv, &keepfd, &pid,
                           -1, &logfd, &logfd,
874 875
                           VIR_EXEC_CLEAR_CAPS,
                           NULL, NULL, NULL);
876 877 878 879 880 881 882 883 884 885
    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);

886 887
    if (ret < 0)
        umlCleanupTapDevices(conn, vm);
888 889 890

    /* NB we don't mark it running here - we do that async
       with inotify */
891 892 893
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
894 895 896 897 898 899 900 901 902

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm)
{
    int ret;
D
Daniel P. Berrange 已提交
903
    if (!virDomainObjIsActive(vm))
904 905
        return;

906
    virKillProcess(vm->pid, SIGTERM);
907 908 909 910 911 912

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

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
D
Daniel Veillard 已提交
913
        VIR_WARN(_("Got unexpected pid %d != %d"),
914 915 916 917 918 919 920 921 922
               ret, vm->pid);
    }

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

923 924
    umlCleanupTapDevices(conn, vm);

925 926 927 928 929 930 931 932 933 934 935 936
    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) {
937 938 939
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
940

941
        conn->uri = xmlParseURI(uml_driver->privileged ?
942 943 944 945 946 947 948 949 950 951 952 953 954 955
                                "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;
956 957


958
        /* Check path and tell them correct path if they made a mistake */
959
        if (uml_driver->privileged) {
960
            if (STRNEQ (conn->uri->path, "/system") &&
961 962 963 964 965 966 967 968 969 970 971 972 973
                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;
            }
974
        }
975 976 977 978 979

        /* 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"));
980 981 982 983 984 985 986 987 988 989
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
990
    /*struct uml_driver *driver = conn->privateData;*/
991 992 993 994 995 996 997 998 999 1000 1001

    conn->privateData = NULL;

    return 0;
}

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


1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
static int umlIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}


static int umlIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}


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

1020
    umlDriverLock(driver);
1021
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1022
        virReportOOMError(conn);
1023
    umlDriverUnlock(driver);
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

    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");
1048
        fclose(pidinfo);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
        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;
1070 1071
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1072

1073
    umlDriverLock(driver);
1074
    vm = virDomainFindByID(&driver->domains, id);
1075 1076
    umlDriverUnlock(driver);

1077 1078
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1079
        goto cleanup;
1080 1081 1082 1083
    }

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

cleanup:
1086 1087
    if (vm)
        virDomainObjUnlock(vm);
1088 1089
    return dom;
}
1090

1091 1092 1093
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1094 1095
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1096

1097
    umlDriverLock(driver);
1098
    vm = virDomainFindByUUID(&driver->domains, uuid);
1099 1100
    umlDriverUnlock(driver);

1101 1102
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1103
        goto cleanup;
1104 1105 1106 1107
    }

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

cleanup:
1110 1111
    if (vm)
        virDomainObjUnlock(vm);
1112 1113
    return dom;
}
1114

1115 1116 1117
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1118 1119
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1120

1121
    umlDriverLock(driver);
1122
    vm = virDomainFindByName(&driver->domains, name);
1123 1124
    umlDriverUnlock(driver);

1125 1126
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1127
        goto cleanup;
1128 1129 1130 1131
    }

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

cleanup:
1134 1135
    if (vm)
        virDomainObjUnlock(vm);
1136 1137 1138
    return dom;
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

static int umlDomainIsActive(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
        umlReportError(dom->conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

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


static int umlDomainIsPersistent(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
        umlReportError(dom->conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
        goto cleanup;
    }
    ret = obj->persistent;

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


1184
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1185
    struct uml_driver *driver = conn->privateData;
1186 1187
    struct utsname ut;
    int major, minor, micro;
1188
    int ret = -1;
1189 1190 1191

    uname(&ut);

1192
    umlDriverLock(driver);
1193 1194 1195 1196
    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);
1197
        goto cleanup;
1198 1199
    }

1200 1201 1202 1203 1204 1205
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1206 1207 1208
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1209
    struct uml_driver *driver = conn->privateData;
1210
    int n;
1211

1212
    umlDriverLock(driver);
1213
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1214
    umlDriverUnlock(driver);
1215

1216
    return n;
1217 1218
}
static int umlNumDomains(virConnectPtr conn) {
1219
    struct uml_driver *driver = conn->privateData;
1220
    int n;
1221

1222
    umlDriverLock(driver);
1223
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1224
    umlDriverUnlock(driver);
1225 1226 1227 1228 1229

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1230
    struct uml_driver *driver = conn->privateData;
1231
    virDomainDefPtr def;
1232
    virDomainObjPtr vm = NULL;
1233
    virDomainPtr dom = NULL;
1234

1235
    umlDriverLock(driver);
1236 1237
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1238
        goto cleanup;
1239

1240
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1241
        goto cleanup;
1242 1243

    if (!(vm = virDomainAssignDef(conn,
1244
                                  driver->caps,
1245
                                  &driver->domains,
1246 1247 1248
                                  def)))
        goto cleanup;
    def = NULL;
1249 1250 1251 1252

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1253 1254
        vm = NULL;
        goto cleanup;
1255 1256 1257 1258
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1259 1260 1261

cleanup:
    virDomainDefFree(def);
1262 1263 1264
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1265 1266 1267 1268 1269
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1270 1271
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1272
    char *info = NULL;
1273
    int ret = -1;
1274

1275
    umlDriverLock(driver);
1276
    vm = virDomainFindByID(&driver->domains, dom->id);
1277
    umlDriverUnlock(driver);
1278 1279 1280
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1281
        goto cleanup;
1282 1283 1284 1285 1286 1287
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("shutdown operation failed"));
1288
        goto cleanup;
1289
    }
1290
    ret = 0;
1291 1292
#endif

1293 1294
cleanup:
    VIR_FREE(info);
1295 1296
    if (vm)
        virDomainObjUnlock(vm);
1297
    return ret;
1298 1299 1300 1301
}


static int umlDomainDestroy(virDomainPtr dom) {
1302 1303 1304
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1305

1306
    umlDriverLock(driver);
1307
    vm = virDomainFindByID(&driver->domains, dom->id);
1308 1309 1310
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1311
        goto cleanup;
1312 1313 1314
    }

    umlShutdownVMDaemon(dom->conn, driver, vm);
1315
    if (!vm->persistent) {
1316 1317
        virDomainRemoveInactive(&driver->domains,
                                vm);
1318 1319 1320
        vm = NULL;
    }
    ret = 0;
1321

1322
cleanup:
1323 1324 1325
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1326
    return ret;
1327 1328 1329 1330
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1331 1332 1333
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1334

1335
    umlDriverLock(driver);
1336
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1337
    umlDriverUnlock(driver);
1338 1339 1340
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1341
        goto cleanup;
1342 1343
    }

1344
    if (!(type = strdup(vm->def->os.type)))
1345
        virReportOOMError(dom->conn);
1346 1347

cleanup:
1348 1349
    if (vm)
        virDomainObjUnlock(vm);
1350 1351 1352 1353 1354
    return type;
}

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

1359
    umlDriverLock(driver);
1360
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1361 1362
    umlDriverUnlock(driver);

1363 1364 1365 1366 1367
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1368 1369
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1370
    }
1371
    ret = vm->def->maxmem;
1372

1373
cleanup:
1374 1375
    if (vm)
        virDomainObjUnlock(vm);
1376
    return ret;
1377 1378 1379
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1380 1381 1382
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1383

1384
    umlDriverLock(driver);
1385
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1386 1387
    umlDriverUnlock(driver);

1388 1389 1390 1391 1392 1393
    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);
1394
        goto cleanup;
1395 1396 1397 1398 1399
    }

    if (newmax < vm->def->memory) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set max memory lower than current memory"));
1400
        goto cleanup;
1401 1402 1403
    }

    vm->def->maxmem = newmax;
1404 1405 1406
    ret = 0;

cleanup:
1407 1408
    if (vm)
        virDomainObjUnlock(vm);
1409
    return ret;
1410 1411 1412
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1413 1414 1415
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1416

1417
    umlDriverLock(driver);
1418
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1419 1420
    umlDriverUnlock(driver);

1421 1422 1423 1424 1425 1426
    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);
1427
        goto cleanup;
1428 1429
    }

D
Daniel P. Berrange 已提交
1430
    if (virDomainObjIsActive(vm)) {
1431 1432
        umlReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cannot set memory of an active domain"));
1433
        goto cleanup;
1434 1435 1436 1437 1438
    }

    if (newmem > vm->def->maxmem) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set memory higher than max memory"));
1439
        goto cleanup;
1440 1441 1442
    }

    vm->def->memory = newmem;
1443 1444 1445
    ret = 0;

cleanup:
1446 1447
    if (vm)
        virDomainObjUnlock(vm);
1448
    return ret;
1449 1450 1451 1452
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1453 1454 1455 1456
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1457
    umlDriverLock(driver);
1458
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1459 1460
    umlDriverUnlock(driver);

1461 1462
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1463 1464
                       "%s", _("no domain with matching uuid"));
        goto cleanup;
1465 1466 1467 1468
    }

    info->state = vm->state;

D
Daniel P. Berrange 已提交
1469
    if (!virDomainObjIsActive(vm)) {
1470 1471 1472
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1473 1474 1475
            umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot read cputime for domain"));
            goto cleanup;
1476 1477 1478 1479 1480 1481
        }
    }

    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
1482 1483 1484
    ret = 0;

cleanup:
1485 1486
    if (vm)
        virDomainObjUnlock(vm);
1487
    return ret;
1488 1489 1490 1491 1492
}


static char *umlDomainDumpXML(virDomainPtr dom,
                                int flags ATTRIBUTE_UNUSED) {
1493 1494 1495 1496
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1497
    umlDriverLock(driver);
1498
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1499 1500
    umlDriverUnlock(driver);

1501 1502 1503
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1504
        goto cleanup;
1505 1506
    }

1507 1508 1509 1510 1511 1512
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
1513 1514
    if (vm)
        virDomainObjUnlock(vm);
1515
    return ret;
1516 1517 1518 1519 1520
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1521
    struct uml_driver *driver = conn->privateData;
1522
    int n;
1523

1524
    umlDriverLock(driver);
1525
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1526
    umlDriverUnlock(driver);
1527

1528
    return n;
1529 1530 1531
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1532
    struct uml_driver *driver = conn->privateData;
1533
    int n;
1534

1535
    umlDriverLock(driver);
1536
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1537
    umlDriverUnlock(driver);
1538 1539 1540 1541 1542 1543

    return n;
}


static int umlDomainStart(virDomainPtr dom) {
1544 1545 1546
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1547

1548
    umlDriverLock(driver);
1549
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1550

1551 1552 1553
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1554
        goto cleanup;
1555 1556
    }

1557 1558 1559
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1560 1561 1562
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1563
    return ret;
1564 1565 1566 1567
}


static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1568
    struct uml_driver *driver = conn->privateData;
1569
    virDomainDefPtr def;
1570
    virDomainObjPtr vm = NULL;
1571
    virDomainPtr dom = NULL;
1572

1573
    umlDriverLock(driver);
1574 1575
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1576
        goto cleanup;
1577

1578 1579 1580
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1581
    if (!(vm = virDomainAssignDef(conn,
1582
                                  driver->caps,
1583
                                  &driver->domains,
1584 1585 1586
                                  def)))
        goto cleanup;
    def = NULL;
1587 1588 1589 1590 1591 1592 1593
    vm->persistent = 1;

    if (virDomainSaveConfig(conn,
                            driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1594
        vm = NULL;
1595
        goto cleanup;
1596 1597 1598 1599
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1600 1601 1602

cleanup:
    virDomainDefFree(def);
1603 1604 1605
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1606 1607 1608 1609
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1610 1611 1612
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1613

1614
    umlDriverLock(driver);
1615
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1616 1617 1618
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1619
        goto cleanup;
1620 1621
    }

D
Daniel P. Berrange 已提交
1622
    if (virDomainObjIsActive(vm)) {
1623 1624
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
1625
        goto cleanup;
1626 1627 1628 1629 1630
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
1631
        goto cleanup;
1632 1633 1634
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
1635
        goto cleanup;
1636 1637 1638

    virDomainRemoveInactive(&driver->domains,
                            vm);
1639
    vm = NULL;
1640
    ret = 0;
1641

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



static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1653 1654 1655
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1656

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

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

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

1669
cleanup:
1670 1671
    if (vm)
        virDomainObjUnlock(vm);
1672
    umlDriverUnlock(driver);
1673
    return ret;
1674 1675 1676 1677
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1678
    struct uml_driver *driver = dom->conn->privateData;
1679
    virDomainObjPtr vm;
1680 1681 1682
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1683 1684 1685
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1686 1687 1688
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1689
        goto cleanup;
1690 1691 1692 1693 1694
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
1695
        goto cleanup;
1696 1697 1698 1699
    }

    autostart = (autostart != 0);

1700 1701 1702 1703 1704
    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;
1705

1706 1707
        if (autostart) {
            int err;
1708

1709
            if ((err = virFileMakePath(driver->autostartDir))) {
1710 1711 1712
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1713 1714
                goto cleanup;
            }
1715

1716
            if (symlink(configFile, autostartLink) < 0) {
1717 1718 1719
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
1720 1721 1722 1723
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1724 1725 1726
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
1727 1728
                goto cleanup;
            }
1729 1730
        }

1731
        vm->autostart = autostart;
1732 1733 1734 1735 1736 1737
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1738 1739
    if (vm)
        virDomainObjUnlock(vm);
1740
    umlDriverUnlock(driver);
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
    return ret;
}


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

1756
    umlDriverLock(driver);
1757
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1758 1759
    umlDriverUnlock(driver);

1760 1761
    if (!vm) {
        umlReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
1762
                        "%s", _("no domain with matching uuid"));
1763
        goto cleanup;
1764 1765 1766 1767
    }

    if (!path || path[0] == '\0') {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1768
                       "%s", _("NULL or empty path"));
1769
        goto cleanup;
1770 1771 1772 1773 1774
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
1775 1776 1777 1778
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
1779 1780
    }

1781 1782 1783 1784 1785
    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) {
1786 1787
            virReportSystemError(dom->conn, errno,
                                 _("cannot open %s"), path);
1788 1789
            goto cleanup;
        }
1790

1791 1792 1793 1794 1795 1796
        /* 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) {
1797 1798
            virReportSystemError(dom->conn, errno,
                                 _("cannot read %s"), path);
1799 1800 1801 1802 1803 1804
            goto cleanup;
        }

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

1808
cleanup:
1809
    if (fd >= 0) close (fd);
1810 1811
    if (vm)
        virDomainObjUnlock(vm);
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    return ret;
}



static virDriver umlDriver = {
    VIR_DRV_UML,
    "UML",
    umlOpen, /* open */
    umlClose, /* close */
    NULL, /* supports_feature */
    umlGetType, /* type */
    umlGetVersion, /* version */
1825
    NULL, /* libvirtVersion (impl. in libvirt.c) */
1826
    virGetHostname, /* getHostname */
1827
    NULL, /* getMaxVcpus */
1828
    nodeGetInfo, /* nodeGetInfo */
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    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 */
1853 1854
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
1855
    umlDomainDumpXML, /* domainDumpXML */
1856 1857
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
1858 1859
    umlListDefinedDomains, /* listDefinedDomains */
    umlNumDefinedDomains, /* numOfDefinedDomains */
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
    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 */
1877 1878
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
1879
    NULL, /* domainEventRegister */
1880
    NULL, /* domainEventDeregister */
1881 1882
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
1883
    NULL, /* nodeDeviceDettach */
1884 1885
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
1886
    NULL, /* domainMigratePrepareTunnel */
1887 1888 1889 1890
    umlIsEncrypted,
    umlIsSecure,
    umlDomainIsActive,
    umlDomainIsPersistent,
1891 1892 1893 1894
};


static virStateDriver umlStateDriver = {
1895
    .name = "UML",
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

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