uml_driver.c 62.4 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
    if (ret < 0)
        goto cleanup;
921

922 923
    ret = virDomainObjSetDefTransient(driver->caps, vm);
cleanup:
924 925 926 927 928
    /*
     * 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++)
929 930 931 932
        if (FD_ISSET(i, &keepfd)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
933

934 935 936 937 938 939 940 941
    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);

942 943
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
944
        umlCleanupTapDevices(conn, vm);
945 946
    }

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

    return ret;
}

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

D
Daniel P. Berrange 已提交
963
    if (!virDomainObjIsActive(vm))
964 965
        return;

966
    virKillProcess(vm->pid, SIGTERM);
967

968
    VIR_FORCE_CLOSE(priv->monitor);
969 970

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

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

979
    virDomainConfVMNWFilterTeardown(vm);
980 981
    umlCleanupTapDevices(conn, vm);

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

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


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    conn->privateData = NULL;

    return 0;
}

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


1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
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;
}


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

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

    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");
1104
        VIR_FORCE_FCLOSE(pidinfo);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        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);

1117
    VIR_FORCE_FCLOSE(pidinfo);
1118 1119 1120 1121 1122 1123 1124 1125

    return 0;
}


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

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

1133
    if (!vm) {
1134
        umlReportError(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 umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1150 1151
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1152

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

1157
    if (!vm) {
1158
        umlReportError(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
    return dom;
}
1170

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

1177
    umlDriverLock(driver);
1178
    vm = virDomainFindByName(&driver->domains, name);
1179 1180
    umlDriverUnlock(driver);

1181
    if (!vm) {
1182
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1183
        goto cleanup;
1184 1185 1186 1187
    }

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

cleanup:
1190 1191
    if (vm)
        virDomainObjUnlock(vm);
1192 1193 1194
    return dom;
}

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

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

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

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
static int umlDomainIsUpdated(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(VIR_ERR_NO_DOMAIN, NULL);
        goto cleanup;
    }
    ret = obj->updated;

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

1260
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1261
    struct uml_driver *driver = conn->privateData;
1262
    struct utsname ut;
1263
    int ret = -1;
1264

1265
    umlDriverLock(driver);
1266 1267 1268 1269 1270

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

        if (virParseVersionString(ut.release, &driver->umlVersion) < 0) {
1271
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1272 1273 1274
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1275 1276
    }

1277 1278 1279 1280 1281 1282
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1283 1284 1285
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1286
    struct uml_driver *driver = conn->privateData;
1287
    int n;
1288

1289
    umlDriverLock(driver);
1290
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1291
    umlDriverUnlock(driver);
1292

1293
    return n;
1294 1295
}
static int umlNumDomains(virConnectPtr conn) {
1296
    struct uml_driver *driver = conn->privateData;
1297
    int n;
1298

1299
    umlDriverLock(driver);
1300
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1301
    umlDriverUnlock(driver);
1302 1303 1304 1305

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1306
                                      unsigned int flags) {
1307
    struct uml_driver *driver = conn->privateData;
1308
    virDomainDefPtr def;
1309
    virDomainObjPtr vm = NULL;
1310
    virDomainPtr dom = NULL;
1311

1312 1313
    virCheckFlags(0, NULL);

1314
    umlDriverLock(driver);
1315
    if (!(def = virDomainDefParseString(driver->caps, xml,
1316
                                        VIR_DOMAIN_XML_INACTIVE)))
1317
        goto cleanup;
1318

1319
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1320
        goto cleanup;
1321

1322
    if (!(vm = virDomainAssignDef(driver->caps,
1323
                                  &driver->domains,
1324
                                  def, false)))
1325 1326
        goto cleanup;
    def = NULL;
1327 1328 1329 1330

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1331 1332
        vm = NULL;
        goto cleanup;
1333 1334 1335 1336
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1337 1338 1339

cleanup:
    virDomainDefFree(def);
1340 1341 1342
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1343 1344 1345 1346 1347
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1348 1349
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1350
    char *info = NULL;
1351
    int ret = -1;
1352

1353
    umlDriverLock(driver);
1354
    vm = virDomainFindByID(&driver->domains, dom->id);
1355
    umlDriverUnlock(driver);
1356
    if (!vm) {
1357 1358
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1359
        goto cleanup;
1360 1361 1362 1363
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1364 1365
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1366
        goto cleanup;
1367
    }
1368
    ret = 0;
1369 1370
#endif

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


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

1384
    umlDriverLock(driver);
1385
    vm = virDomainFindByID(&driver->domains, dom->id);
1386
    if (!vm) {
1387 1388
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1389
        goto cleanup;
1390 1391 1392
    }

    umlShutdownVMDaemon(dom->conn, driver, vm);
1393
    if (!vm->persistent) {
1394 1395
        virDomainRemoveInactive(&driver->domains,
                                vm);
1396 1397 1398
        vm = NULL;
    }
    ret = 0;
1399

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


static char *umlDomainGetOSType(virDomainPtr dom) {
1409 1410 1411
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1412

1413
    umlDriverLock(driver);
1414
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1415
    umlDriverUnlock(driver);
1416
    if (!vm) {
1417 1418
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1419
        goto cleanup;
1420 1421
    }

1422
    if (!(type = strdup(vm->def->os.type)))
1423
        virReportOOMError();
1424 1425

cleanup:
1426 1427
    if (vm)
        virDomainObjUnlock(vm);
1428 1429 1430 1431 1432
    return type;
}

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

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

1441 1442 1443 1444
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1445
        umlReportError(VIR_ERR_INVALID_DOMAIN,
1446 1447
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1448
    }
1449
    ret = vm->def->mem.max_balloon;
1450

1451
cleanup:
1452 1453
    if (vm)
        virDomainObjUnlock(vm);
1454
    return ret;
1455 1456 1457
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1458 1459 1460
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1461

1462
    umlDriverLock(driver);
1463
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1464 1465
    umlDriverUnlock(driver);

1466 1467 1468 1469
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1470 1471
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1472
        goto cleanup;
1473 1474
    }

1475
    if (newmax < vm->def->mem.cur_balloon) {
1476 1477
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1478
        goto cleanup;
1479 1480
    }

1481
    vm->def->mem.max_balloon = newmax;
1482 1483 1484
    ret = 0;

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

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1491 1492 1493
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1494

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

1499 1500 1501 1502
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1503 1504
        umlReportError(VIR_ERR_INVALID_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1505
        goto cleanup;
1506 1507
    }

D
Daniel P. Berrange 已提交
1508
    if (virDomainObjIsActive(vm)) {
1509 1510
        umlReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot set memory of an active domain"));
1511
        goto cleanup;
1512 1513
    }

1514
    if (newmem > vm->def->mem.max_balloon) {
1515 1516
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1517
        goto cleanup;
1518 1519
    }

1520
    vm->def->mem.cur_balloon = newmem;
1521 1522 1523
    ret = 0;

cleanup:
1524 1525
    if (vm)
        virDomainObjUnlock(vm);
1526
    return ret;
1527 1528 1529 1530
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1531 1532 1533 1534
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1535
    umlDriverLock(driver);
1536
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1537 1538
    umlDriverUnlock(driver);

1539
    if (!vm) {
1540 1541
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1542
        goto cleanup;
1543 1544 1545 1546
    }

    info->state = vm->state;

D
Daniel P. Berrange 已提交
1547
    if (!virDomainObjIsActive(vm)) {
1548 1549 1550
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1551 1552
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1553
            goto cleanup;
1554 1555 1556
        }
    }

1557 1558
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1559
    info->nrVirtCpu = vm->def->vcpus;
1560 1561 1562
    ret = 0;

cleanup:
1563 1564
    if (vm)
        virDomainObjUnlock(vm);
1565
    return ret;
1566 1567 1568 1569 1570
}


static char *umlDomainDumpXML(virDomainPtr dom,
                                int flags ATTRIBUTE_UNUSED) {
1571 1572 1573 1574
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1575
    umlDriverLock(driver);
1576
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1577 1578
    umlDriverUnlock(driver);

1579
    if (!vm) {
1580 1581
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1582
        goto cleanup;
1583 1584
    }

1585
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1586 1587 1588 1589
                             vm->newDef : vm->def,
                             flags);

cleanup:
1590 1591
    if (vm)
        virDomainObjUnlock(vm);
1592
    return ret;
1593 1594 1595 1596 1597
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1598
    struct uml_driver *driver = conn->privateData;
1599
    int n;
1600

1601
    umlDriverLock(driver);
1602
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1603
    umlDriverUnlock(driver);
1604

1605
    return n;
1606 1607 1608
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1609
    struct uml_driver *driver = conn->privateData;
1610
    int n;
1611

1612
    umlDriverLock(driver);
1613
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1614
    umlDriverUnlock(driver);
1615 1616 1617 1618 1619

    return n;
}


1620
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1621 1622 1623
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1624

1625 1626
    virCheckFlags(0, -1);

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

1630
    if (!vm) {
1631 1632
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1633
        goto cleanup;
1634 1635
    }

1636 1637 1638
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1639 1640 1641
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1642
    return ret;
1643 1644
}

1645 1646 1647
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1648 1649

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1650
    struct uml_driver *driver = conn->privateData;
1651
    virDomainDefPtr def;
1652
    virDomainObjPtr vm = NULL;
1653
    virDomainPtr dom = NULL;
1654

1655
    umlDriverLock(driver);
1656
    if (!(def = virDomainDefParseString(driver->caps, xml,
1657
                                        VIR_DOMAIN_XML_INACTIVE)))
1658
        goto cleanup;
1659

1660 1661 1662
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1663
    if (!(vm = virDomainAssignDef(driver->caps,
1664
                                  &driver->domains,
1665
                                  def, false)))
1666 1667
        goto cleanup;
    def = NULL;
1668 1669
    vm->persistent = 1;

1670
    if (virDomainSaveConfig(driver->configDir,
1671 1672 1673
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1674
        vm = NULL;
1675
        goto cleanup;
1676 1677 1678 1679
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1680 1681 1682

cleanup:
    virDomainDefFree(def);
1683 1684 1685
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1686 1687 1688 1689
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1690 1691 1692
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1693

1694
    umlDriverLock(driver);
1695
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1696
    if (!vm) {
1697 1698
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1699
        goto cleanup;
1700 1701
    }

D
Daniel P. Berrange 已提交
1702
    if (virDomainObjIsActive(vm)) {
1703 1704
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot delete active domain"));
1705
        goto cleanup;
1706 1707 1708
    }

    if (!vm->persistent) {
1709 1710
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot undefine transient domain"));
1711
        goto cleanup;
1712 1713
    }

1714
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1715
        goto cleanup;
1716 1717 1718

    virDomainRemoveInactive(&driver->domains,
                            vm);
1719
    vm = NULL;
1720
    ret = 0;
1721

1722
cleanup:
1723 1724 1725
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1726
    return ret;
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 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
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);
}

1958 1959 1960

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1961 1962 1963
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1964

1965
    umlDriverLock(driver);
1966
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1967

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

    *autostart = vm->autostart;
1975
    ret = 0;
1976

1977
cleanup:
1978 1979
    if (vm)
        virDomainObjUnlock(vm);
1980
    umlDriverUnlock(driver);
1981
    return ret;
1982 1983 1984 1985
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1986
    struct uml_driver *driver = dom->conn->privateData;
1987
    virDomainObjPtr vm;
1988 1989 1990
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1991 1992 1993
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1994
    if (!vm) {
1995 1996
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1997
        goto cleanup;
1998 1999 2000
    }

    if (!vm->persistent) {
2001 2002
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot set autostart for transient domain"));
2003
        goto cleanup;
2004 2005 2006 2007
    }

    autostart = (autostart != 0);

2008
    if (vm->autostart != autostart) {
2009
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2010
            goto cleanup;
2011
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2012
            goto cleanup;
2013

2014 2015
        if (autostart) {
            int err;
2016

2017
            if ((err = virFileMakePath(driver->autostartDir))) {
2018
                virReportSystemError(err,
2019 2020
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2021 2022
                goto cleanup;
            }
2023

2024
            if (symlink(configFile, autostartLink) < 0) {
2025
                virReportSystemError(errno,
2026 2027
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2028 2029 2030 2031
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2032
                virReportSystemError(errno,
2033 2034
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2035 2036
                goto cleanup;
            }
2037 2038
        }

2039
        vm->autostart = autostart;
2040 2041 2042 2043 2044 2045
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2046 2047
    if (vm)
        virDomainObjUnlock(vm);
2048
    umlDriverUnlock(driver);
2049 2050 2051 2052 2053
    return ret;
}


static int
2054 2055 2056 2057 2058
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
                   unsigned int flags ATTRIBUTE_UNUSED)
2059
{
2060 2061 2062
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2063

2064
    umlDriverLock(driver);
2065
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2066 2067
    umlDriverUnlock(driver);

2068
    if (!vm) {
2069 2070
        umlReportError(VIR_ERR_INVALID_DOMAIN, "%s",
                       _("no domain with matching uuid"));
2071
        goto cleanup;
2072 2073 2074
    }

    if (!path || path[0] == '\0') {
2075 2076
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2077
        goto cleanup;
2078 2079 2080 2081 2082
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2083 2084 2085 2086
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2087 2088
    }

2089 2090 2091 2092 2093
    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) {
2094
            virReportSystemError(errno,
2095
                                 _("cannot open %s"), path);
2096 2097
            goto cleanup;
        }
2098

2099 2100 2101 2102 2103 2104
        /* 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) {
2105
            virReportSystemError(errno,
2106
                                 _("cannot read %s"), path);
2107 2108 2109 2110 2111
            goto cleanup;
        }

        ret = 0;
    } else {
2112 2113
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2114 2115
    }

2116
cleanup:
2117
    VIR_FORCE_CLOSE(fd);
2118 2119
    if (vm)
        virDomainObjUnlock(vm);
2120 2121 2122 2123
    return ret;
}


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 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
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;
}

2188 2189 2190 2191 2192 2193 2194 2195 2196

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

2297 2298 2299 2300 2301 2302 2303 2304
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2305 2306

static virStateDriver umlStateDriver = {
2307
    .name = "UML",
2308 2309 2310 2311 2312 2313
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2326 2327 2328
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2329 2330
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2331 2332
};

2333 2334 2335
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2336
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2337 2338
    return 0;
}