uml_driver.c 61.8 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);
660 661
    sprintf(addr.sun_path + 1, "libvirt-uml-%u", vm->pid);
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
662
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
663
        virReportSystemError(errno,
664
                             "%s", _("cannot bind socket"));
665
        VIR_FORCE_CLOSE(priv->monitor);
666 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
        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];
};


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

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

707 708
    *reply = NULL;

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

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

    do {
E
Eric Blake 已提交
737
        ssize_t nbytes;
738
        addrlen = sizeof(addr);
E
Eric Blake 已提交
739
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
740
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
741 742 743
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
744
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
745 746
            goto error;
        }
747 748 749
        /* 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) {
750 751 752
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
753 754

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

        if (res.error)
            ret = -1;

    } while (res.extra);

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

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

    return ret;

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


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

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

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

    FD_ZERO(&keepfd);

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

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

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

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

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

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

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

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

911
    priv->monitor = -1;
912

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

919 920 921 922 923
    /*
     * 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++)
924 925 926 927
        if (FD_ISSET(i, &keepfd)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
928

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

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

942 943 944

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

    return ret;
}

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

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

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

964
    VIR_FORCE_CLOSE(priv->monitor);
965 966

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

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

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

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

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


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    conn->privateData = NULL;

    return 0;
}

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


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


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

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

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

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

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201

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

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


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

1241
    umlDriverLock(driver);
1242 1243 1244 1245 1246

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

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

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

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

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

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

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

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

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

1288 1289
    virCheckFlags(0, NULL);

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

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

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

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

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

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


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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    info->state = vm->state;

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

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

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


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

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

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

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

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


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

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

1581
    return n;
1582 1583 1584
}

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

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

    return n;
}


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

1601 1602
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1698
cleanup:
1699 1700 1701
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1702
    return ret;
1703 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
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);
}

1934 1935 1936

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

1990 1991
        if (autostart) {
            int err;
1992

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

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

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

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


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

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

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

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

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

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

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

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

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


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

2164 2165 2166 2167 2168 2169 2170 2171 2172

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

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

    return 0;
}
2280 2281

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

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

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

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

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