uml_driver.c 52.3 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
/* For storing short-lived temporary files. */
#define TEMPDIR LOCAL_STATE_DIR "/cache/libvirt"

68 69 70 71 72 73 74 75
typedef struct _umlDomainObjPrivate umlDomainObjPrivate;
typedef umlDomainObjPrivate *umlDomainObjPrivatePtr;
struct _umlDomainObjPrivate {
    int monitor;
    int monitorWatch;
};


76 77
static int umlShutdown(void);

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
static void *umlDomainObjPrivateAlloc(void)
{
    umlDomainObjPrivatePtr priv;

    if (VIR_ALLOC(priv) < 0)
        return NULL;

    priv->monitor = -1;
    priv->monitorWatch = -1;

    return priv;
}

static void umlDomainObjPrivateFree(void *data)
{
    umlDomainObjPrivatePtr priv = data;

    VIR_FREE(priv);
}


99 100
static void umlDriverLock(struct uml_driver *driver)
{
101
    virMutexLock(&driver->lock);
102 103 104
}
static void umlDriverUnlock(struct uml_driver *driver)
{
105
    virMutexUnlock(&driver->lock);
106 107
}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

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 已提交
125
    VIR_ERROR0(_("Failed to set close-on-exec file descriptor flag"));
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    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;

146 147 148 149 150 151 152 153 154 155 156 157 158
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 已提交
159
        !virDomainObjIsActive(vm)) {
160 161 162 163 164 165 166 167 168
        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);
}
169 170 171

static void
umlAutostartConfigs(struct uml_driver *driver) {
172 173 174 175 176
    /* 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
     */
177 178 179
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
180
    /* Ignoring NULL conn which is mostly harmless here */
181

182 183 184
    struct umlAutostartData data = { driver, conn };

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

186 187
    if (conn)
        virConnectClose(conn);
188 189 190 191
}


static int
192
umlIdentifyOneChrPTY(struct uml_driver *driver,
193 194 195 196 197 198 199
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
200
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
201
        virReportOOMError();
202 203 204
        return -1;
    }
requery:
205 206
    if (umlMonitorCommand(NULL, driver, dom, cmd, &res) < 0)
        return -1;
207

208
    if (res && STRPREFIX(res, "pts:")) {
209 210
        VIR_FREE(def->data.file.path);
        if ((def->data.file.path = strdup(res + 4)) == NULL) {
211
            virReportOOMError();
212 213 214 215
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
216
    } else if (!res || STRPREFIX(res, "pts")) {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        /* 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
233
umlIdentifyChrPTY(struct uml_driver *driver,
234 235 236 237 238 239
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
        dom->def->console->type == VIR_DOMAIN_CHR_TYPE_PTY)
240
        if (umlIdentifyOneChrPTY(driver, dom,
241 242 243 244 245
                                 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 &&
246
            umlIdentifyOneChrPTY(driver, dom,
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                                 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;

266
    umlDriverLock(driver);
267
    if (watch != driver->inotifyWatch)
268
        goto cleanup;
269 270 271 272 273 274

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
275
        goto cleanup;
276 277 278 279 280
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
281
            goto cleanup; /* bad */
282 283 284 285 286 287

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

        if (got < e->len)
288
            goto cleanup;
289 290 291 292 293 294 295 296 297 298 299 300 301

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

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

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

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
302
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
303
            if (!virDomainObjIsActive(dom)) {
304
                virDomainObjUnlock(dom);
305 306 307
                continue;
            }

308
            umlShutdownVMDaemon(NULL, driver, dom);
309
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
310
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
311
            if (virDomainObjIsActive(dom)) {
312
                virDomainObjUnlock(dom);
313 314 315 316
                continue;
            }

            if (umlReadPidFile(NULL, driver, dom) < 0) {
317
                virDomainObjUnlock(dom);
318 319 320 321 322 323
                continue;
            }

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

324 325
            if (umlOpenMonitor(NULL, driver, dom) < 0) {
                VIR_WARN0("Could not open monitor for new domain");
326
                umlShutdownVMDaemon(NULL, driver, dom);
327
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
328
                VIR_WARN0("Could not identify charater devices for new domain");
329
                umlShutdownVMDaemon(NULL, driver, dom);
330
            }
331
        }
332
        virDomainObjUnlock(dom);
333
    }
334 335 336

cleanup:
    umlDriverUnlock(driver);
337 338 339 340 341 342 343 344
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
345
umlStartup(int privileged) {
346 347 348
    uid_t uid = geteuid();
    char *base = NULL;
    char driverConf[PATH_MAX];
349
    char *userdir = NULL;
350 351 352 353

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

354 355
    uml_driver->privileged = privileged;

356 357 358 359
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
360 361
    umlDriverLock(uml_driver);

362 363
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
364
    uml_driver->inotifyWatch = -1;
365

366 367 368
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

369 370
    userdir = virGetUserDirectory(NULL, uid);
    if (!userdir)
371
        goto error;
372

373
    if (privileged) {
374 375
        if (virAsprintf(&uml_driver->logDir,
                        "%s/log/libvirt/uml", LOCAL_STATE_DIR) == -1)
376 377 378 379 380
            goto out_of_memory;

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

382
        if (virAsprintf(&uml_driver->logDir,
383
                        "%s/.libvirt/uml/log", userdir) == -1)
384 385
            goto out_of_memory;

386
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
387 388 389
            goto out_of_memory;
    }

390
    if (virAsprintf(&uml_driver->monitorDir,
391
                    "%s/.uml", userdir) == -1)
392 393 394 395 396 397 398 399 400
        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';

401
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
402 403
        goto out_of_memory;

404
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
405 406 407 408 409 410 411
        goto out_of_memory;

    VIR_FREE(base);

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

412 413
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
414 415

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
D
Daniel Veillard 已提交
416
        VIR_ERROR0(_("cannot initialize inotify"));
417
        goto error;
418 419
    }

L
Laine Stump 已提交
420
    if (virFileMakePath(uml_driver->monitorDir) != 0) {
421
        char ebuf[1024];
D
Daniel Veillard 已提交
422
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
423
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
424
        goto error;
425 426
    }

427
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
428 429 430
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
431
        goto error;
432 433
    }

434 435
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
436 437
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
438 439 440 441 442 443

    if (virDomainLoadAllConfigs(NULL,
                                uml_driver->caps,
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
444
                                0, NULL, NULL) < 0)
445 446
        goto error;

447 448
    umlAutostartConfigs(uml_driver);

449
    umlDriverUnlock(uml_driver);
450 451
    VIR_FREE(userdir);

452 453
    return 0;

454
out_of_memory:
D
Daniel Veillard 已提交
455
    VIR_ERROR0(_("umlStartup: out of memory"));
456 457

error:
458
    VIR_FREE(userdir);
459
    VIR_FREE(base);
460 461
    umlDriverUnlock(uml_driver);
    umlShutdown();
462 463 464 465 466 467 468 469 470 471 472 473 474 475
    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;

476
    umlDriverLock(uml_driver);
477 478 479 480 481
    virDomainLoadAllConfigs(NULL,
                            uml_driver->caps,
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
482
                            0, NULL, NULL);
483 484

    umlAutostartConfigs(uml_driver);
485
    umlDriverUnlock(uml_driver);
486 487 488 489 490 491 492 493 494 495 496 497 498 499

    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) {
500
    int active = 0;
501 502 503 504

    if (!uml_driver)
        return 0;

505
    umlDriverLock(uml_driver);
506
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
507
    umlDriverUnlock(uml_driver);
508

509
    return active;
510 511
}

512 513 514 515 516 517 518
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 已提交
519
    if (virDomainObjIsActive(dom))
520 521 522 523
        umlShutdownVMDaemon(NULL, driver, dom);
    virDomainObjUnlock(dom);
}

524 525 526 527 528 529 530 531 532 533
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

534
    umlDriverLock(uml_driver);
535 536
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
537 538 539
    close(uml_driver->inotifyFD);
    virCapabilitiesFree(uml_driver->caps);

540 541 542
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
543

544
    virDomainObjListDeinit(&uml_driver->domains);
545 546 547 548 549 550 551 552 553

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

554
    umlDriverUnlock(uml_driver);
555
    virMutexDestroy(&uml_driver->lock);
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    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;
572 573
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
574
        virReportOOMError();
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        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;
590
        fclose(file);
591 592 593 594 595 596 597 598 599 600
        goto cleanup;
    }

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

    rc = 0;

 cleanup:
    if (rc != 0)
601 602 603
        virReportSystemError(conn, errno,
                             _("failed to read pid: %s"),
                             pidfile);
604 605 606 607 608 609 610 611 612
    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 已提交
613
    int retval = 0;
614

615 616
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
617
        virReportOOMError();
618 619 620 621 622
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
623 624 625 626 627
    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;
    }
628
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
629
    return retval;
630 631 632 633 634 635 636 637
}

static int umlOpenMonitor(virConnectPtr conn,
                          struct uml_driver *driver,
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
638
    umlDomainObjPrivatePtr priv = vm->privateData;
639 640 641 642

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

643
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
644 645 646
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
647
            retries++ < 50) {
648 649 650 651 652 653
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

654
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
655 656
        virReportSystemError(conn, errno,
                             "%s", _("cannot open socket"));
657 658 659 660
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
661 662
    sprintf(addr.sun_path + 1, "libvirt-uml-%u", vm->pid);
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
663
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
664 665
        virReportSystemError(conn, errno,
                             "%s", _("cannot bind socket"));
666 667
        close(priv->monitor);
        priv->monitor = -1;
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        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;
706
    umlDomainObjPrivatePtr priv = vm->privateData;
707

708 709
    VIR_DEBUG("Run command '%s'", cmd);

710 711 712 713 714 715 716 717 718 719
    *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)) {
720 721 722
        virReportSystemError(conn, EINVAL,
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
723 724
        return -1;
    }
C
Chris Lalancette 已提交
725 726 727 728 729
    if (virStrcpyStatic(req.data, cmd) == NULL) {
        umlReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
730

731
    if (sendto(priv->monitor, &req, sizeof req, 0,
732
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
733 734 735
        virReportSystemError(conn, errno,
                             _("cannot send command %s"),
                             cmd);
736 737 738 739 740
        return -1;
    }

    do {
        addrlen = sizeof(addr);
741
        if (recvfrom(priv->monitor, &res, sizeof res, 0,
742
                     (struct sockaddr *)&addr, &addrlen) < 0) {
743 744 745
            virReportSystemError(conn, errno,
                                 _("cannot read reply %s"),
                                 cmd);
746 747 748 749
            goto error;
        }

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
750
            virReportOOMError();
751 752 753 754 755 756 757 758 759 760 761
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

762 763
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

764 765 766 767 768 769 770 771 772 773
    *reply = retdata;

    return ret;

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


774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
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;
}

803 804 805 806 807
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
    const char **argv = NULL, **tmp;
    const char **progenv = NULL;
808 809
    int i, ret;
    pid_t pid;
810 811 812 813
    char *logfile;
    int logfd = -1;
    struct stat sb;
    fd_set keepfd;
814
    char ebuf[1024];
815
    umlDomainObjPrivatePtr priv = vm->privateData;
816 817 818

    FD_ZERO(&keepfd);

D
Daniel P. Berrange 已提交
819
    if (virDomainObjIsActive(vm)) {
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
        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) {
835 836 837
        virReportSystemError(conn, errno,
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
838 839 840
        return -1;
    }

L
Laine Stump 已提交
841
    if (virFileMakePath(driver->logDir) != 0) {
842 843 844
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
845 846 847
        return -1;
    }

848 849
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
850
        virReportOOMError();
851 852 853 854 855
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
856 857 858
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
859 860 861 862 863 864
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

    if (umlSetCloseExec(logfd) < 0) {
865 866
        virReportSystemError(conn, errno,
                             "%s", _("Unable to set VM logfile close-on-exec flag"));
867 868 869 870 871
        close(logfd);
        return -1;
    }

    if (umlBuildCommandLine(conn, driver, vm,
872
                            &argv, &progenv) < 0) {
873
        close(logfd);
874
        umlCleanupTapDevices(conn, vm);
875 876 877 878 879 880
        return -1;
    }

    tmp = progenv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
881
            VIR_WARN(_("Unable to write envv to logfile: %s"),
882
                   virStrerror(errno, ebuf, sizeof ebuf));
883
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
884
            VIR_WARN(_("Unable to write envv to logfile: %s"),
885
                   virStrerror(errno, ebuf, sizeof ebuf));
886 887 888 889 890
        tmp++;
    }
    tmp = argv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
D
Daniel Veillard 已提交
891
            VIR_WARN(_("Unable to write argv to logfile: %s"),
892
                   virStrerror(errno, ebuf, sizeof ebuf));
893
        if (safewrite(logfd, " ", 1) < 0)
D
Daniel Veillard 已提交
894
            VIR_WARN(_("Unable to write argv to logfile: %s"),
895
                   virStrerror(errno, ebuf, sizeof ebuf));
896 897 898
        tmp++;
    }
    if (safewrite(logfd, "\n", 1) < 0)
D
Daniel Veillard 已提交
899
        VIR_WARN(_("Unable to write argv to logfile: %s"),
900
                 virStrerror(errno, ebuf, sizeof ebuf));
901

902
    priv->monitor = -1;
903

904 905
    ret = virExecDaemonize(conn, argv, progenv, &keepfd, &pid,
                           -1, &logfd, &logfd,
906 907
                           VIR_EXEC_CLEAR_CAPS,
                           NULL, NULL, NULL);
908 909 910 911 912 913 914 915 916 917
    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);

918 919
    if (ret < 0)
        umlCleanupTapDevices(conn, vm);
920 921 922

    /* NB we don't mark it running here - we do that async
       with inotify */
923 924 925
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
926 927 928 929 930 931 932 933 934

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm)
{
    int ret;
935 936
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
937
    if (!virDomainObjIsActive(vm))
938 939
        return;

940
    virKillProcess(vm->pid, SIGTERM);
941

942 943 944
    if (priv->monitor != -1)
        close(priv->monitor);
    priv->monitor = -1;
945 946

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
D
Daniel Veillard 已提交
947
        VIR_WARN(_("Got unexpected pid %d != %d"),
948 949 950 951 952 953 954
               ret, vm->pid);
    }

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

955 956
    umlCleanupTapDevices(conn, vm);

957 958 959 960 961 962 963 964 965 966 967 968
    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) {
969 970 971
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
972

973
        conn->uri = xmlParseURI(uml_driver->privileged ?
974 975 976
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
977
            virReportOOMError();
978 979 980 981 982 983 984 985 986 987
            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;
988 989


990
        /* Check path and tell them correct path if they made a mistake */
991
        if (uml_driver->privileged) {
992
            if (STRNEQ (conn->uri->path, "/system") &&
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
                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;
            }
1006
        }
1007 1008 1009 1010 1011

        /* 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"));
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1022
    /*struct uml_driver *driver = conn->privateData;*/
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

    conn->privateData = NULL;

    return 0;
}

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


1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
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;
}


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

1052
    umlDriverLock(driver);
1053
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1054
        virReportOOMError();
1055
    umlDriverUnlock(driver);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

    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");
1080
        fclose(pidinfo);
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        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;
1102 1103
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1104

1105
    umlDriverLock(driver);
1106
    vm = virDomainFindByID(&driver->domains, id);
1107 1108
    umlDriverUnlock(driver);

1109 1110
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1111
        goto cleanup;
1112 1113 1114 1115
    }

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

cleanup:
1118 1119
    if (vm)
        virDomainObjUnlock(vm);
1120 1121
    return dom;
}
1122

1123 1124 1125
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1126 1127
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1128

1129
    umlDriverLock(driver);
1130
    vm = virDomainFindByUUID(&driver->domains, uuid);
1131 1132
    umlDriverUnlock(driver);

1133 1134
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1135
        goto cleanup;
1136 1137 1138 1139
    }

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

cleanup:
1142 1143
    if (vm)
        virDomainObjUnlock(vm);
1144 1145
    return dom;
}
1146

1147 1148 1149
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1150 1151
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1152

1153
    umlDriverLock(driver);
1154
    vm = virDomainFindByName(&driver->domains, name);
1155 1156
    umlDriverUnlock(driver);

1157 1158
    if (!vm) {
        umlReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1159
        goto cleanup;
1160 1161 1162 1163
    }

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

cleanup:
1166 1167
    if (vm)
        virDomainObjUnlock(vm);
1168 1169 1170
    return dom;
}

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

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


1216
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1217
    struct uml_driver *driver = conn->privateData;
1218 1219
    struct utsname ut;
    int major, minor, micro;
1220
    int ret = -1;
1221 1222 1223

    uname(&ut);

1224
    umlDriverLock(driver);
1225 1226 1227 1228
    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);
1229
        goto cleanup;
1230 1231
    }

1232 1233 1234 1235 1236 1237
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1238 1239 1240
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1241
    struct uml_driver *driver = conn->privateData;
1242
    int n;
1243

1244
    umlDriverLock(driver);
1245
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1246
    umlDriverUnlock(driver);
1247

1248
    return n;
1249 1250
}
static int umlNumDomains(virConnectPtr conn) {
1251
    struct uml_driver *driver = conn->privateData;
1252
    int n;
1253

1254
    umlDriverLock(driver);
1255
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1256
    umlDriverUnlock(driver);
1257 1258 1259 1260 1261

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1262
    struct uml_driver *driver = conn->privateData;
1263
    virDomainDefPtr def;
1264
    virDomainObjPtr vm = NULL;
1265
    virDomainPtr dom = NULL;
1266

1267
    umlDriverLock(driver);
1268 1269
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1270
        goto cleanup;
1271

1272
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1273
        goto cleanup;
1274 1275

    if (!(vm = virDomainAssignDef(conn,
1276
                                  driver->caps,
1277
                                  &driver->domains,
1278 1279 1280
                                  def)))
        goto cleanup;
    def = NULL;
1281 1282 1283 1284

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1285 1286
        vm = NULL;
        goto cleanup;
1287 1288 1289 1290
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1291 1292 1293

cleanup:
    virDomainDefFree(def);
1294 1295 1296
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1297 1298 1299 1300 1301
    return dom;
}


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

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

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("shutdown operation failed"));
1320
        goto cleanup;
1321
    }
1322
    ret = 0;
1323 1324
#endif

1325 1326
cleanup:
    VIR_FREE(info);
1327 1328
    if (vm)
        virDomainObjUnlock(vm);
1329
    return ret;
1330 1331 1332 1333
}


static int umlDomainDestroy(virDomainPtr dom) {
1334 1335 1336
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1337

1338
    umlDriverLock(driver);
1339
    vm = virDomainFindByID(&driver->domains, dom->id);
1340 1341 1342
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1343
        goto cleanup;
1344 1345 1346
    }

    umlShutdownVMDaemon(dom->conn, driver, vm);
1347
    if (!vm->persistent) {
1348 1349
        virDomainRemoveInactive(&driver->domains,
                                vm);
1350 1351 1352
        vm = NULL;
    }
    ret = 0;
1353

1354
cleanup:
1355 1356 1357
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1358
    return ret;
1359 1360 1361 1362
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1363 1364 1365
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1366

1367
    umlDriverLock(driver);
1368
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1369
    umlDriverUnlock(driver);
1370 1371 1372
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1373
        goto cleanup;
1374 1375
    }

1376
    if (!(type = strdup(vm->def->os.type)))
1377
        virReportOOMError();
1378 1379

cleanup:
1380 1381
    if (vm)
        virDomainObjUnlock(vm);
1382 1383 1384 1385 1386
    return type;
}

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

1391
    umlDriverLock(driver);
1392
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1393 1394
    umlDriverUnlock(driver);

1395 1396 1397 1398 1399
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1400 1401
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1402
    }
1403
    ret = vm->def->maxmem;
1404

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

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

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

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

    if (newmax < vm->def->memory) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set max memory lower than current memory"));
1432
        goto cleanup;
1433 1434 1435
    }

    vm->def->maxmem = newmax;
1436 1437 1438
    ret = 0;

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

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1445 1446 1447
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1448

1449
    umlDriverLock(driver);
1450
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1451 1452
    umlDriverUnlock(driver);

1453 1454 1455 1456 1457 1458
    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);
1459
        goto cleanup;
1460 1461
    }

D
Daniel P. Berrange 已提交
1462
    if (virDomainObjIsActive(vm)) {
1463 1464
        umlReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cannot set memory of an active domain"));
1465
        goto cleanup;
1466 1467 1468 1469 1470
    }

    if (newmem > vm->def->maxmem) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s", _("cannot set memory higher than max memory"));
1471
        goto cleanup;
1472 1473 1474
    }

    vm->def->memory = newmem;
1475 1476 1477
    ret = 0;

cleanup:
1478 1479
    if (vm)
        virDomainObjUnlock(vm);
1480
    return ret;
1481 1482 1483 1484
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1485 1486 1487 1488
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1489
    umlDriverLock(driver);
1490
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1491 1492
    umlDriverUnlock(driver);

1493 1494
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1495 1496
                       "%s", _("no domain with matching uuid"));
        goto cleanup;
1497 1498 1499 1500
    }

    info->state = vm->state;

D
Daniel P. Berrange 已提交
1501
    if (!virDomainObjIsActive(vm)) {
1502 1503 1504
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1505 1506 1507
            umlReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot read cputime for domain"));
            goto cleanup;
1508 1509 1510 1511 1512 1513
        }
    }

    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
1514 1515 1516
    ret = 0;

cleanup:
1517 1518
    if (vm)
        virDomainObjUnlock(vm);
1519
    return ret;
1520 1521 1522 1523 1524
}


static char *umlDomainDumpXML(virDomainPtr dom,
                                int flags ATTRIBUTE_UNUSED) {
1525 1526 1527 1528
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1529
    umlDriverLock(driver);
1530
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1531 1532
    umlDriverUnlock(driver);

1533 1534 1535
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1536
        goto cleanup;
1537 1538
    }

1539 1540 1541 1542 1543 1544
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
1545 1546
    if (vm)
        virDomainObjUnlock(vm);
1547
    return ret;
1548 1549 1550 1551 1552
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1553
    struct uml_driver *driver = conn->privateData;
1554
    int n;
1555

1556
    umlDriverLock(driver);
1557
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1558
    umlDriverUnlock(driver);
1559

1560
    return n;
1561 1562 1563
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1564
    struct uml_driver *driver = conn->privateData;
1565
    int n;
1566

1567
    umlDriverLock(driver);
1568
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1569
    umlDriverUnlock(driver);
1570 1571 1572 1573 1574 1575

    return n;
}


static int umlDomainStart(virDomainPtr dom) {
1576 1577 1578
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1579

1580
    umlDriverLock(driver);
1581
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1582

1583 1584 1585
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1586
        goto cleanup;
1587 1588
    }

1589 1590 1591
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1592 1593 1594
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1595
    return ret;
1596 1597 1598 1599
}


static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1600
    struct uml_driver *driver = conn->privateData;
1601
    virDomainDefPtr def;
1602
    virDomainObjPtr vm = NULL;
1603
    virDomainPtr dom = NULL;
1604

1605
    umlDriverLock(driver);
1606 1607
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1608
        goto cleanup;
1609

1610 1611 1612
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1613
    if (!(vm = virDomainAssignDef(conn,
1614
                                  driver->caps,
1615
                                  &driver->domains,
1616 1617 1618
                                  def)))
        goto cleanup;
    def = NULL;
1619 1620 1621 1622 1623 1624 1625
    vm->persistent = 1;

    if (virDomainSaveConfig(conn,
                            driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1626
        vm = NULL;
1627
        goto cleanup;
1628 1629 1630 1631
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1632 1633 1634

cleanup:
    virDomainDefFree(def);
1635 1636 1637
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1638 1639 1640 1641
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1642 1643 1644
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1645

1646
    umlDriverLock(driver);
1647
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1648 1649 1650
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1651
        goto cleanup;
1652 1653
    }

D
Daniel P. Berrange 已提交
1654
    if (virDomainObjIsActive(vm)) {
1655 1656
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
1657
        goto cleanup;
1658 1659 1660 1661 1662
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
1663
        goto cleanup;
1664 1665 1666
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
1667
        goto cleanup;
1668 1669 1670

    virDomainRemoveInactive(&driver->domains,
                            vm);
1671
    vm = NULL;
1672
    ret = 0;
1673

1674
cleanup:
1675 1676 1677
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1678
    return ret;
1679 1680 1681 1682 1683 1684
}



static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1685 1686 1687
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1688

1689
    umlDriverLock(driver);
1690
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1691

1692 1693 1694
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1695
        goto cleanup;
1696 1697 1698
    }

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

1701
cleanup:
1702 1703
    if (vm)
        virDomainObjUnlock(vm);
1704
    umlDriverUnlock(driver);
1705
    return ret;
1706 1707 1708 1709
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1710
    struct uml_driver *driver = dom->conn->privateData;
1711
    virDomainObjPtr vm;
1712 1713 1714
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1715 1716 1717
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1718 1719 1720
    if (!vm) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1721
        goto cleanup;
1722 1723 1724 1725 1726
    }

    if (!vm->persistent) {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
1727
        goto cleanup;
1728 1729 1730 1731
    }

    autostart = (autostart != 0);

1732 1733 1734 1735 1736
    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;
1737

1738 1739
        if (autostart) {
            int err;
1740

1741
            if ((err = virFileMakePath(driver->autostartDir))) {
1742 1743 1744
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1745 1746
                goto cleanup;
            }
1747

1748
            if (symlink(configFile, autostartLink) < 0) {
1749 1750 1751
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
1752 1753 1754 1755
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1756 1757 1758
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
1759 1760
                goto cleanup;
            }
1761 1762
        }

1763
        vm->autostart = autostart;
1764 1765 1766 1767 1768 1769
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1770 1771
    if (vm)
        virDomainObjUnlock(vm);
1772
    umlDriverUnlock(driver);
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
    return ret;
}


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

1788
    umlDriverLock(driver);
1789
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1790 1791
    umlDriverUnlock(driver);

1792 1793
    if (!vm) {
        umlReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
1794
                        "%s", _("no domain with matching uuid"));
1795
        goto cleanup;
1796 1797 1798 1799
    }

    if (!path || path[0] == '\0') {
        umlReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1800
                       "%s", _("NULL or empty path"));
1801
        goto cleanup;
1802 1803 1804 1805 1806
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
1807 1808 1809 1810
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
1811 1812
    }

1813 1814 1815 1816 1817
    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) {
1818 1819
            virReportSystemError(dom->conn, errno,
                                 _("cannot open %s"), path);
1820 1821
            goto cleanup;
        }
1822

1823 1824 1825 1826 1827 1828
        /* 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) {
1829 1830
            virReportSystemError(dom->conn, errno,
                                 _("cannot read %s"), path);
1831 1832 1833 1834 1835 1836
            goto cleanup;
        }

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

1840
cleanup:
1841
    if (fd >= 0) close (fd);
1842 1843
    if (vm)
        virDomainObjUnlock(vm);
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    return ret;
}



static virDriver umlDriver = {
    VIR_DRV_UML,
    "UML",
    umlOpen, /* open */
    umlClose, /* close */
    NULL, /* supports_feature */
    umlGetType, /* type */
    umlGetVersion, /* version */
1857
    NULL, /* libvirtVersion (impl. in libvirt.c) */
1858
    virGetHostname, /* getHostname */
1859
    NULL, /* getMaxVcpus */
1860
    nodeGetInfo, /* nodeGetInfo */
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
    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 */
1885 1886
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
1887
    umlDomainDumpXML, /* domainDumpXML */
1888 1889
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
1890 1891
    umlListDefinedDomains, /* listDefinedDomains */
    umlNumDefinedDomains, /* numOfDefinedDomains */
1892 1893 1894 1895
    umlDomainStart, /* domainCreate */
    umlDomainDefine, /* domainDefineXML */
    umlDomainUndefine, /* domainUndefine */
    NULL, /* domainAttachDevice */
1896
    NULL, /* domainAttachDeviceFlags */
1897
    NULL, /* domainDetachDevice */
1898
    NULL, /* domainDetachDeviceFlags */
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
    umlDomainGetAutostart, /* domainGetAutostart */
    umlDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
1909
    NULL, /* domainMemoryStats */
1910 1911
    umlDomainBlockPeek, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
1912 1913
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
1914
    NULL, /* domainEventRegister */
1915
    NULL, /* domainEventDeregister */
1916 1917
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
1918
    NULL, /* nodeDeviceDettach */
1919 1920
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
1921
    NULL, /* domainMigratePrepareTunnel */
1922 1923 1924 1925
    umlIsEncrypted,
    umlIsSecure,
    umlDomainIsActive,
    umlDomainIsPersistent,
J
Jiri Denemark 已提交
1926
    NULL, /* cpuCompare */
1927 1928 1929 1930
};


static virStateDriver umlStateDriver = {
1931
    .name = "UML",
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

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