uml_driver.c 61.9 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2010 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
 * 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 <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>
46
#include <sys/un.h>
47 48 49 50 51 52 53 54 55 56 57 58 59

#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"
60
#include "logging.h"
61
#include "domain_nwfilter.h"
62
#include "files.h"
63
#include "fdstream.h"
64
#include "configmake.h"
65

66 67
#define VIR_FROM_THIS VIR_FROM_UML

68
/* For storing short-lived temporary files. */
69
#define TEMPDIR LOCALSTATEDIR "/cache/libvirt"
70

71 72 73 74 75 76 77 78
typedef struct _umlDomainObjPrivate umlDomainObjPrivate;
typedef umlDomainObjPrivate *umlDomainObjPrivatePtr;
struct _umlDomainObjPrivate {
    int monitor;
    int monitorWatch;
};


79 80
static int umlShutdown(void);

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
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);
}


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

111

112
static int umlOpenMonitor(struct uml_driver *driver,
113
                          virDomainObjPtr vm);
114
static int umlReadPidFile(struct uml_driver *driver,
115 116 117 118 119 120 121 122 123 124 125
                          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 已提交
126
    VIR_ERROR0(_("Failed to set close-on-exec file descriptor flag"));
127 128 129 130 131 132 133 134 135 136 137 138
    return -1;
}

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

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


139 140 141 142
static int umlMonitorCommand(const struct uml_driver *driver,
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply);
143 144 145

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
        virResetLastError();
        if (umlStartVMDaemon(data->conn, data->driver, vm) < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
164
                      vm->def->name, err ? err->message : _("unknown error"));
165 166 167 168
        }
    }
    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
    if (umlMonitorCommand(driver, dom, cmd, &res) < 0)
206
        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
                continue;
            }

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

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

324
            if (umlOpenMonitor(driver, dom) < 0) {
325
                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
    userdir = virGetUserDirectory(uid);
370
    if (!userdir)
371
        goto error;
372

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

378
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
379
            goto out_of_memory;
380 381

        if (virAsprintf(&uml_driver->monitorDir,
382
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
383
            goto out_of_memory;
384
    } else {
385

386
        if (virAsprintf(&uml_driver->logDir,
387
                        "%s/.libvirt/uml/log", userdir) == -1)
388 389
            goto out_of_memory;

390
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
391 392
            goto out_of_memory;

393 394 395 396
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
397 398 399 400 401 402 403 404

    /* 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';

405
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
406 407
        goto out_of_memory;

408
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
409 410 411 412 413 414 415
        goto out_of_memory;

    VIR_FREE(base);

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

416 417
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
418 419

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
D
Daniel Veillard 已提交
420
        VIR_ERROR0(_("cannot initialize inotify"));
421
        goto error;
422 423
    }

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

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

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

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

450 451
    umlAutostartConfigs(uml_driver);

452
    umlDriverUnlock(uml_driver);
453 454
    VIR_FREE(userdir);

455 456
    return 0;

457
out_of_memory:
D
Daniel Veillard 已提交
458
    VIR_ERROR0(_("umlStartup: out of memory"));
459 460

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

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

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

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

    if (!uml_driver)
        return 0;

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

511
    return active;
512 513
}

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

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

536
    umlDriverLock(uml_driver);
537 538
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
539
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
540 541
    virCapabilitiesFree(uml_driver->caps);

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

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

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

556
    umlDriverUnlock(uml_driver);
557
    virMutexDestroy(&uml_driver->lock);
558 559 560 561 562 563
    VIR_FREE(uml_driver);

    return 0;
}


564
static int umlReadPidFile(struct uml_driver *driver,
565 566 567 568 569 570 571 572
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
573 574
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
575
        virReportOOMError();
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        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;
591
        VIR_FORCE_FCLOSE(file);
592 593 594
        goto cleanup;
    }

595
    if (VIR_FCLOSE(file) < 0)
596 597 598 599 600 601
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
602
        virReportSystemError(errno,
603 604
                             _("failed to read pid: %s"),
                             pidfile);
605 606 607 608
    VIR_FREE(pidfile);
    return rc;
}

609
static int umlMonitorAddress(const struct uml_driver *driver,
610 611 612
                             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
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
624
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
625 626 627
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
628
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
629
    return retval;
630 631
}

632
static int umlOpenMonitor(struct uml_driver *driver,
633 634 635 636
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
637
    umlDomainObjPrivatePtr priv = vm->privateData;
638

639
    if (umlMonitorAddress(driver, vm, &addr) < 0)
640 641
        return -1;

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

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

    memset(addr.sun_path, 0, sizeof addr.sun_path);
E
Eric Blake 已提交
660 661
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
662
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
663
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
664
        virReportSystemError(errno,
665
                             "%s", _("cannot bind socket"));
666
        VIR_FORCE_CLOSE(priv->monitor);
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        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];
};


693
static int umlMonitorCommand(const struct uml_driver *driver,
694 695 696 697 698 699 700 701 702 703
                             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;
704
    umlDomainObjPrivatePtr priv = vm->privateData;
705

706 707
    VIR_DEBUG("Run command '%s'", cmd);

708 709
    *reply = NULL;

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

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

    do {
E
Eric Blake 已提交
738
        ssize_t nbytes;
739
        addrlen = sizeof(addr);
E
Eric Blake 已提交
740
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
741
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
742 743 744
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
745
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
746 747
            goto error;
        }
748 749 750
        /* Ensure res.length is safe to read before validating its value.  */
        if (nbytes < offsetof(struct monitor_request, data) ||
            nbytes < offsetof(struct monitor_request, data) + res.length) {
751 752 753
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
754 755

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
756
            virReportOOMError();
757 758 759 760 761 762 763 764 765 766 767
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

768 769
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

770 771 772 773
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
774 775 776 777 778 779 780 781 782

    return ret;

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


783 784 785 786 787 788
static int umlCleanupTapDevices(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm) {
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
789
    VIR_ERROR0(_("Cleanup tap"));
790 791 792 793 794 795 796 797 798 799
    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;

800
        VIR_ERROR(_("Cleanup '%s'"), def->ifname);
801 802
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
803
            VIR_ERROR(_("Cleanup failed %d"), err);
804 805 806
            ret = -1;
        }
    }
807
    VIR_ERROR0(_("Cleanup tap done"));
808 809 810 811
    brShutdown(brctl);
    return ret;
}

812 813 814 815 816
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
    const char **argv = NULL, **tmp;
    const char **progenv = NULL;
817 818
    int i, ret;
    pid_t pid;
819 820 821 822
    char *logfile;
    int logfd = -1;
    struct stat sb;
    fd_set keepfd;
823
    char ebuf[1024];
824
    umlDomainObjPrivatePtr priv = vm->privateData;
825 826 827

    FD_ZERO(&keepfd);

D
Daniel P. Berrange 已提交
828
    if (virDomainObjIsActive(vm)) {
829 830
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("VM is already active"));
831 832 833 834
        return -1;
    }

    if (!vm->def->os.kernel) {
835 836
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
837 838 839 840 841 842 843
        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) {
844
        virReportSystemError(errno,
845 846
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
847 848 849
        return -1;
    }

L
Laine Stump 已提交
850
    if (virFileMakePath(driver->logDir) != 0) {
851
        virReportSystemError(errno,
852 853
                             _("cannot create log directory %s"),
                             driver->logDir);
854 855 856
        return -1;
    }

857 858
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
859
        virReportOOMError();
860 861 862 863 864
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
865
        virReportSystemError(errno,
866 867
                             _("failed to create logfile %s"),
                             logfile);
868 869 870 871 872 873
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

    if (umlSetCloseExec(logfd) < 0) {
874
        virReportSystemError(errno,
875
                             "%s", _("Unable to set VM logfile close-on-exec flag"));
876
        VIR_FORCE_CLOSE(logfd);
877 878 879
        return -1;
    }

880
    if (umlBuildCommandLine(conn, driver, vm, &keepfd,
881
                            &argv, &progenv) < 0) {
882
        VIR_FORCE_CLOSE(logfd);
883
        virDomainConfVMNWFilterTeardown(vm);
884
        umlCleanupTapDevices(conn, vm);
885 886 887 888 889 890
        return -1;
    }

    tmp = progenv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
891
            VIR_WARN("Unable to write envv to logfile: %s",
892
                   virStrerror(errno, ebuf, sizeof ebuf));
893
        if (safewrite(logfd, " ", 1) < 0)
894
            VIR_WARN("Unable to write envv to logfile: %s",
895
                   virStrerror(errno, ebuf, sizeof ebuf));
896 897 898 899 900
        tmp++;
    }
    tmp = argv;
    while (*tmp) {
        if (safewrite(logfd, *tmp, strlen(*tmp)) < 0)
901
            VIR_WARN("Unable to write argv to logfile: %s",
902
                   virStrerror(errno, ebuf, sizeof ebuf));
903
        if (safewrite(logfd, " ", 1) < 0)
904
            VIR_WARN("Unable to write argv to logfile: %s",
905
                   virStrerror(errno, ebuf, sizeof ebuf));
906 907 908
        tmp++;
    }
    if (safewrite(logfd, "\n", 1) < 0)
909
        VIR_WARN("Unable to write argv to logfile: %s",
910
                 virStrerror(errno, ebuf, sizeof ebuf));
911

912
    priv->monitor = -1;
913

914
    ret = virExecDaemonize(argv, progenv, &keepfd, &pid,
915
                           -1, &logfd, &logfd,
916 917
                           VIR_EXEC_CLEAR_CAPS,
                           NULL, NULL, NULL);
918
    VIR_FORCE_CLOSE(logfd);
919

920 921 922 923 924
    /*
     * At the moment, the only thing that populates keepfd is
     * umlBuildCommandLineChr. We want to close every fd it opens.
     */
    for (i = 0; i < FD_SETSIZE; i++)
925 926 927 928
        if (FD_ISSET(i, &keepfd)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
929

930 931 932 933 934 935 936 937
    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);

938 939
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
940
        umlCleanupTapDevices(conn, vm);
941 942
    }

943 944 945

    /* NB we don't mark it running here - we do that async
       with inotify */
946 947 948
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
949 950 951 952 953 954 955 956 957

    return ret;
}

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

D
Daniel P. Berrange 已提交
960
    if (!virDomainObjIsActive(vm))
961 962
        return;

963
    virKillProcess(vm->pid, SIGTERM);
964

965
    VIR_FORCE_CLOSE(priv->monitor);
966 967

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
968
        VIR_WARN("Got unexpected pid %d != %d",
969 970 971 972 973 974 975
               ret, vm->pid);
    }

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

976
    virDomainConfVMNWFilterTeardown(vm);
977 978
    umlCleanupTapDevices(conn, vm);

979 980 981 982 983 984 985 986 987 988 989 990
    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) {
991 992 993
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
994

995
        conn->uri = xmlParseURI(uml_driver->privileged ?
996 997 998
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
999
            virReportOOMError();
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
            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;
1010 1011


1012
        /* Check path and tell them correct path if they made a mistake */
1013
        if (uml_driver->privileged) {
1014
            if (STRNEQ (conn->uri->path, "/system") &&
1015
                STRNEQ (conn->uri->path, "/session")) {
1016
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1017 1018 1019 1020 1021 1022
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1023
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1024 1025 1026 1027
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1028
        }
1029 1030 1031

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1032
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1033
                           _("uml state driver is not active"));
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1044
    /*struct uml_driver *driver = conn->privateData;*/
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

    conn->privateData = NULL;

    return 0;
}

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


1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
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;
}


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

1074
    umlDriverLock(driver);
1075
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1076
        virReportOOMError();
1077
    umlDriverUnlock(driver);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

    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"))) {
        /* 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");
1101
        VIR_FORCE_FCLOSE(pidinfo);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        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);

1114
    VIR_FORCE_FCLOSE(pidinfo);
1115 1116 1117 1118 1119 1120 1121 1122

    return 0;
}


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

1126
    umlDriverLock(driver);
1127
    vm = virDomainFindByID(&driver->domains, id);
1128 1129
    umlDriverUnlock(driver);

1130
    if (!vm) {
1131
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1132
        goto cleanup;
1133 1134 1135 1136
    }

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

cleanup:
1139 1140
    if (vm)
        virDomainObjUnlock(vm);
1141 1142
    return dom;
}
1143

1144 1145 1146
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1147 1148
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1149

1150
    umlDriverLock(driver);
1151
    vm = virDomainFindByUUID(&driver->domains, uuid);
1152 1153
    umlDriverUnlock(driver);

1154
    if (!vm) {
1155
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1156
        goto cleanup;
1157 1158 1159 1160
    }

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

cleanup:
1163 1164
    if (vm)
        virDomainObjUnlock(vm);
1165 1166
    return dom;
}
1167

1168 1169 1170
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1171 1172
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1173

1174
    umlDriverLock(driver);
1175
    vm = virDomainFindByName(&driver->domains, name);
1176 1177
    umlDriverUnlock(driver);

1178
    if (!vm) {
1179
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1180
        goto cleanup;
1181 1182 1183 1184
    }

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

cleanup:
1187 1188
    if (vm)
        virDomainObjUnlock(vm);
1189 1190 1191
    return dom;
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

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) {
1203
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        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) {
1225
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        goto cleanup;
    }
    ret = obj->persistent;

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


1237
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1238
    struct uml_driver *driver = conn->privateData;
1239
    struct utsname ut;
1240
    int ret = -1;
1241

1242
    umlDriverLock(driver);
1243 1244 1245 1246 1247

    if (driver->umlVersion == 0) {
        uname(&ut);

        if (virParseVersionString(ut.release, &driver->umlVersion) < 0) {
1248
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1249 1250 1251
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1252 1253
    }

1254 1255 1256 1257 1258 1259
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1260 1261 1262
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1263
    struct uml_driver *driver = conn->privateData;
1264
    int n;
1265

1266
    umlDriverLock(driver);
1267
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1268
    umlDriverUnlock(driver);
1269

1270
    return n;
1271 1272
}
static int umlNumDomains(virConnectPtr conn) {
1273
    struct uml_driver *driver = conn->privateData;
1274
    int n;
1275

1276
    umlDriverLock(driver);
1277
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1278
    umlDriverUnlock(driver);
1279 1280 1281 1282

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1283
                                      unsigned int flags) {
1284
    struct uml_driver *driver = conn->privateData;
1285
    virDomainDefPtr def;
1286
    virDomainObjPtr vm = NULL;
1287
    virDomainPtr dom = NULL;
1288

1289 1290
    virCheckFlags(0, NULL);

1291
    umlDriverLock(driver);
1292
    if (!(def = virDomainDefParseString(driver->caps, xml,
1293
                                        VIR_DOMAIN_XML_INACTIVE)))
1294
        goto cleanup;
1295

1296
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1297
        goto cleanup;
1298

1299
    if (!(vm = virDomainAssignDef(driver->caps,
1300
                                  &driver->domains,
1301
                                  def, false)))
1302 1303
        goto cleanup;
    def = NULL;
1304 1305 1306 1307

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1308 1309
        vm = NULL;
        goto cleanup;
1310 1311 1312 1313
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1314 1315 1316

cleanup:
    virDomainDefFree(def);
1317 1318 1319
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1320 1321 1322 1323 1324
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1325 1326
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1327
    char *info = NULL;
1328
    int ret = -1;
1329

1330
    umlDriverLock(driver);
1331
    vm = virDomainFindByID(&driver->domains, dom->id);
1332
    umlDriverUnlock(driver);
1333
    if (!vm) {
1334 1335
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1336
        goto cleanup;
1337 1338 1339 1340
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1341 1342
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1343
        goto cleanup;
1344
    }
1345
    ret = 0;
1346 1347
#endif

1348 1349
cleanup:
    VIR_FREE(info);
1350 1351
    if (vm)
        virDomainObjUnlock(vm);
1352
    return ret;
1353 1354 1355 1356
}


static int umlDomainDestroy(virDomainPtr dom) {
1357 1358 1359
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1360

1361
    umlDriverLock(driver);
1362
    vm = virDomainFindByID(&driver->domains, dom->id);
1363
    if (!vm) {
1364 1365
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1366
        goto cleanup;
1367 1368 1369
    }

    umlShutdownVMDaemon(dom->conn, driver, vm);
1370
    if (!vm->persistent) {
1371 1372
        virDomainRemoveInactive(&driver->domains,
                                vm);
1373 1374 1375
        vm = NULL;
    }
    ret = 0;
1376

1377
cleanup:
1378 1379 1380
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1381
    return ret;
1382 1383 1384 1385
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1386 1387 1388
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1389

1390
    umlDriverLock(driver);
1391
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1392
    umlDriverUnlock(driver);
1393
    if (!vm) {
1394 1395
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1396
        goto cleanup;
1397 1398
    }

1399
    if (!(type = strdup(vm->def->os.type)))
1400
        virReportOOMError();
1401 1402

cleanup:
1403 1404
    if (vm)
        virDomainObjUnlock(vm);
1405 1406 1407 1408 1409
    return type;
}

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

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

1418 1419 1420 1421
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1422
        umlReportError(VIR_ERR_INVALID_DOMAIN,
1423 1424
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1425
    }
1426
    ret = vm->def->mem.max_balloon;
1427

1428
cleanup:
1429 1430
    if (vm)
        virDomainObjUnlock(vm);
1431
    return ret;
1432 1433 1434
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1435 1436 1437
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1438

1439
    umlDriverLock(driver);
1440
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1441 1442
    umlDriverUnlock(driver);

1443 1444 1445 1446
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1447 1448
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1449
        goto cleanup;
1450 1451
    }

1452
    if (newmax < vm->def->mem.cur_balloon) {
1453 1454
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1455
        goto cleanup;
1456 1457
    }

1458
    vm->def->mem.max_balloon = newmax;
1459 1460 1461
    ret = 0;

cleanup:
1462 1463
    if (vm)
        virDomainObjUnlock(vm);
1464
    return ret;
1465 1466 1467
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1468 1469 1470
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1471

1472
    umlDriverLock(driver);
1473
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1474 1475
    umlDriverUnlock(driver);

1476 1477 1478 1479
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1480 1481
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1482
        goto cleanup;
1483 1484
    }

D
Daniel P. Berrange 已提交
1485
    if (virDomainObjIsActive(vm)) {
1486 1487
        umlReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot set memory of an active domain"));
1488
        goto cleanup;
1489 1490
    }

1491
    if (newmem > vm->def->mem.max_balloon) {
1492 1493
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1494
        goto cleanup;
1495 1496
    }

1497
    vm->def->mem.cur_balloon = newmem;
1498 1499 1500
    ret = 0;

cleanup:
1501 1502
    if (vm)
        virDomainObjUnlock(vm);
1503
    return ret;
1504 1505 1506 1507
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1508 1509 1510 1511
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1512
    umlDriverLock(driver);
1513
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1514 1515
    umlDriverUnlock(driver);

1516
    if (!vm) {
1517 1518
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1519
        goto cleanup;
1520 1521 1522 1523
    }

    info->state = vm->state;

D
Daniel P. Berrange 已提交
1524
    if (!virDomainObjIsActive(vm)) {
1525 1526 1527
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1528 1529
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1530
            goto cleanup;
1531 1532 1533
        }
    }

1534 1535
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1536
    info->nrVirtCpu = vm->def->vcpus;
1537 1538 1539
    ret = 0;

cleanup:
1540 1541
    if (vm)
        virDomainObjUnlock(vm);
1542
    return ret;
1543 1544 1545 1546 1547
}


static char *umlDomainDumpXML(virDomainPtr dom,
                                int flags ATTRIBUTE_UNUSED) {
1548 1549 1550 1551
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1552
    umlDriverLock(driver);
1553
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1554 1555
    umlDriverUnlock(driver);

1556
    if (!vm) {
1557 1558
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1559
        goto cleanup;
1560 1561
    }

1562
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1563 1564 1565 1566
                             vm->newDef : vm->def,
                             flags);

cleanup:
1567 1568
    if (vm)
        virDomainObjUnlock(vm);
1569
    return ret;
1570 1571 1572 1573 1574
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1575
    struct uml_driver *driver = conn->privateData;
1576
    int n;
1577

1578
    umlDriverLock(driver);
1579
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1580
    umlDriverUnlock(driver);
1581

1582
    return n;
1583 1584 1585
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1586
    struct uml_driver *driver = conn->privateData;
1587
    int n;
1588

1589
    umlDriverLock(driver);
1590
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1591
    umlDriverUnlock(driver);
1592 1593 1594 1595 1596

    return n;
}


1597
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1598 1599 1600
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1601

1602 1603
    virCheckFlags(0, -1);

1604
    umlDriverLock(driver);
1605
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1606

1607
    if (!vm) {
1608 1609
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1610
        goto cleanup;
1611 1612
    }

1613 1614 1615
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1616 1617 1618
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1619
    return ret;
1620 1621
}

1622 1623 1624
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1625 1626

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1627
    struct uml_driver *driver = conn->privateData;
1628
    virDomainDefPtr def;
1629
    virDomainObjPtr vm = NULL;
1630
    virDomainPtr dom = NULL;
1631

1632
    umlDriverLock(driver);
1633
    if (!(def = virDomainDefParseString(driver->caps, xml,
1634
                                        VIR_DOMAIN_XML_INACTIVE)))
1635
        goto cleanup;
1636

1637 1638 1639
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1640
    if (!(vm = virDomainAssignDef(driver->caps,
1641
                                  &driver->domains,
1642
                                  def, false)))
1643 1644
        goto cleanup;
    def = NULL;
1645 1646
    vm->persistent = 1;

1647
    if (virDomainSaveConfig(driver->configDir,
1648 1649 1650
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1651
        vm = NULL;
1652
        goto cleanup;
1653 1654 1655 1656
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1657 1658 1659

cleanup:
    virDomainDefFree(def);
1660 1661 1662
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1663 1664 1665 1666
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1667 1668 1669
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1670

1671
    umlDriverLock(driver);
1672
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1673
    if (!vm) {
1674 1675
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1676
        goto cleanup;
1677 1678
    }

D
Daniel P. Berrange 已提交
1679
    if (virDomainObjIsActive(vm)) {
1680 1681
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot delete active domain"));
1682
        goto cleanup;
1683 1684 1685
    }

    if (!vm->persistent) {
1686 1687
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot undefine transient domain"));
1688
        goto cleanup;
1689 1690
    }

1691
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1692
        goto cleanup;
1693 1694 1695

    virDomainRemoveInactive(&driver->domains,
                            vm);
1696
    vm = NULL;
1697
    ret = 0;
1698

1699
cleanup:
1700 1701 1702
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1703
    return ret;
1704 1705 1706
}


1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
static int umlDomainAttachUmlDisk(struct uml_driver *driver,
                                  virDomainObjPtr vm,
                                  virDomainDiskDefPtr disk)
{
    int i;
    char *cmd = NULL;
    char *reply = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
            umlReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
            return -1;
        }
    }

    if (!disk->src) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("disk source path is missing"));
        goto error;
    }

    if (virAsprintf(&cmd, "config %s=%s", disk->dst, disk->src) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto error;

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return 0;

error:

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return -1;
}


static int umlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot attach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);

    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML) {
            ret = umlDomainAttachUmlDisk(driver, vm, dev->data.disk);
            if (ret == 0)
                dev->data.disk = NULL;
        } else {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(dev->data.disk->bus));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
        goto cleanup;
    }

cleanup:

    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


static int umlDomainAttachDeviceFlags(virDomainPtr dom,
                                      const char *xml,
                                      unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainAttachDevice(dom, xml);
}


static int umlDomainDetachUmlDisk(struct uml_driver *driver,
                                  virDomainObjPtr vm,
                                  virDomainDeviceDefPtr dev)
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    char *cmd;
    char *reply;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            break;
        }
    }

    if (i == vm->def->ndisks) {
        umlReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
        return -1;
    }

    detach = vm->def->disks[i];

    if (virAsprintf(&cmd, "remove %s", detach->dst) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto cleanup;

    virDomainDiskRemove(vm->def, i);

    virDomainDiskDefFree(detach);

    ret = 0;

    VIR_FREE(reply);

cleanup:
    VIR_FREE(cmd);

    return ret;
}


static int umlDomainDetachDevice(virDomainPtr dom, const char *xml) {
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot detach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML)
            ret = umlDomainDetachUmlDisk(driver, vm, dev);
        else {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("This type of device cannot be hot unplugged"));
    }

cleanup:
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


static int umlDomainDetachDeviceFlags(virDomainPtr dom,
                                      const char *xml,
                                      unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1935 1936 1937

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1938 1939 1940
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1941

1942
    umlDriverLock(driver);
1943
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1944

1945
    if (!vm) {
1946 1947
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1948
        goto cleanup;
1949 1950 1951
    }

    *autostart = vm->autostart;
1952
    ret = 0;
1953

1954
cleanup:
1955 1956
    if (vm)
        virDomainObjUnlock(vm);
1957
    umlDriverUnlock(driver);
1958
    return ret;
1959 1960 1961 1962
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1963
    struct uml_driver *driver = dom->conn->privateData;
1964
    virDomainObjPtr vm;
1965 1966 1967
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1968 1969 1970
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1971
    if (!vm) {
1972 1973
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1974
        goto cleanup;
1975 1976 1977
    }

    if (!vm->persistent) {
1978 1979
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot set autostart for transient domain"));
1980
        goto cleanup;
1981 1982 1983 1984
    }

    autostart = (autostart != 0);

1985
    if (vm->autostart != autostart) {
1986
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
1987
            goto cleanup;
1988
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
1989
            goto cleanup;
1990

1991 1992
        if (autostart) {
            int err;
1993

1994
            if ((err = virFileMakePath(driver->autostartDir))) {
1995
                virReportSystemError(err,
1996 1997
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1998 1999
                goto cleanup;
            }
2000

2001
            if (symlink(configFile, autostartLink) < 0) {
2002
                virReportSystemError(errno,
2003 2004
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2005 2006 2007 2008
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2009
                virReportSystemError(errno,
2010 2011
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2012 2013
                goto cleanup;
            }
2014 2015
        }

2016
        vm->autostart = autostart;
2017 2018 2019 2020 2021 2022
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2023 2024
    if (vm)
        virDomainObjUnlock(vm);
2025
    umlDriverUnlock(driver);
2026 2027 2028 2029 2030
    return ret;
}


static int
2031 2032 2033 2034 2035
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
                   unsigned int flags ATTRIBUTE_UNUSED)
2036
{
2037 2038 2039
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2040

2041
    umlDriverLock(driver);
2042
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2043 2044
    umlDriverUnlock(driver);

2045
    if (!vm) {
2046 2047
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
2048
        goto cleanup;
2049 2050 2051
    }

    if (!path || path[0] == '\0') {
2052 2053
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2054
        goto cleanup;
2055 2056 2057 2058 2059
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2060 2061 2062 2063
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2064 2065
    }

2066 2067 2068 2069 2070
    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) {
2071
            virReportSystemError(errno,
2072
                                 _("cannot open %s"), path);
2073 2074
            goto cleanup;
        }
2075

2076 2077 2078 2079 2080 2081
        /* 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) {
2082
            virReportSystemError(errno,
2083
                                 _("cannot read %s"), path);
2084 2085 2086 2087 2088
            goto cleanup;
        }

        ret = 0;
    } else {
2089 2090
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2091 2092
    }

2093
cleanup:
2094
    VIR_FORCE_CLOSE(fd);
2095 2096
    if (vm)
        virDomainObjUnlock(vm);
2097 2098 2099 2100
    return ret;
}


2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
static int
umlDomainOpenConsole(virDomainPtr dom,
                     const char *devname,
                     virStreamPtr st,
                     unsigned int flags)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    virDomainChrDefPtr chr = NULL;

    virCheckFlags(0, -1);

    umlDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    if (devname) {
        /* XXX support device aliases in future */
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
        goto cleanup;
    } else {
        if (vm->def->console)
            chr = vm->def->console;
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"), devname);
        goto cleanup;
    }

    if (chr->type != VIR_DOMAIN_CHR_TYPE_PTY) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

    if (virFDStreamOpenFile(st, chr->data.file.path, O_RDWR) < 0)
        goto cleanup;

    ret = 0;
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}

2165 2166 2167 2168 2169 2170 2171 2172 2173

static virDriver umlDriver = {
    VIR_DRV_UML,
    "UML",
    umlOpen, /* open */
    umlClose, /* close */
    NULL, /* supports_feature */
    umlGetType, /* type */
    umlGetVersion, /* version */
2174
    NULL, /* libvirtVersion (impl. in libvirt.c) */
2175
    virGetHostname, /* getHostname */
2176
    NULL, /* getMaxVcpus */
2177
    nodeGetInfo, /* nodeGetInfo */
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
    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 */
E
Eric Blake 已提交
2199 2200
    NULL, /* domainSetVcpusFlags */
    NULL, /* domainGetVcpusFlags */
2201 2202 2203
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
    NULL, /* domainGetMaxVcpus */
2204 2205
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
2206
    umlDomainDumpXML, /* domainDumpXML */
2207 2208
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
2209 2210
    umlListDefinedDomains, /* listDefinedDomains */
    umlNumDefinedDomains, /* numOfDefinedDomains */
2211
    umlDomainStart, /* domainCreate */
2212
    umlDomainStartWithFlags, /* domainCreateWithFlags */
2213 2214
    umlDomainDefine, /* domainDefineXML */
    umlDomainUndefine, /* domainUndefine */
2215 2216 2217 2218
    umlDomainAttachDevice, /* domainAttachDevice */
    umlDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
    umlDomainDetachDevice, /* domainDetachDevice */
    umlDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
2219
    NULL, /* domainUpdateDeviceFlags */
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
    umlDomainGetAutostart, /* domainGetAutostart */
    umlDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
2230
    NULL, /* domainMemoryStats */
2231 2232
    umlDomainBlockPeek, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
2233
    NULL, /* domainGetBlockInfo */
2234 2235
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
2236
    NULL, /* domainEventRegister */
2237
    NULL, /* domainEventDeregister */
2238 2239
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
2240
    NULL, /* nodeDeviceDettach */
2241 2242
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
2243
    NULL, /* domainMigratePrepareTunnel */
2244 2245 2246 2247
    umlIsEncrypted, /* isEncrypted */
    umlIsSecure, /* isSecure */
    umlDomainIsActive, /* domainIsActive */
    umlDomainIsPersistent, /* domainIsPersistent */
J
Jiri Denemark 已提交
2248
    NULL, /* cpuCompare */
2249
    NULL, /* cpuBaseline */
2250
    NULL, /* domainGetJobInfo */
2251
    NULL, /* domainAbortJob */
2252
    NULL, /* domainMigrateSetMaxDowntime */
2253 2254
    NULL, /* domainEventRegisterAny */
    NULL, /* domainEventDeregisterAny */
2255 2256 2257
    NULL, /* domainManagedSave */
    NULL, /* domainHasManagedSaveImage */
    NULL, /* domainManagedSaveRemove */
C
Chris Lalancette 已提交
2258 2259 2260 2261 2262 2263 2264 2265 2266
    NULL, /* domainSnapshotCreateXML */
    NULL, /* domainSnapshotDumpXML */
    NULL, /* domainSnapshotNum */
    NULL, /* domainSnapshotListNames */
    NULL, /* domainSnapshotLookupByName */
    NULL, /* domainHasCurrentSnapshot */
    NULL, /* domainSnapshotCurrent */
    NULL, /* domainRevertToSnapshot */
    NULL, /* domainSnapshotDelete */
C
Chris Lalancette 已提交
2267
    NULL, /* qemuDomainMonitorCommand */
2268 2269
    NULL, /* domainSetMemoryParamters */
    NULL, /* domainGetMemoryParamters */
2270
    umlDomainOpenConsole, /* domainOpenConsole */
2271 2272
};

2273 2274 2275 2276 2277 2278 2279 2280
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2281 2282

static virStateDriver umlStateDriver = {
2283
    .name = "UML",
2284 2285 2286 2287 2288 2289
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

static void
umlVMDriverUnlock(void)
{
    umlDriverUnlock(uml_driver);
}

2302 2303 2304
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2305 2306
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2307 2308
};

2309 2310 2311
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2312
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2313 2314
    return 0;
}