uml_driver.c 61.1 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2011 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:
126
    VIR_ERROR(_("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
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
152
umlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
153 154 155 156 157 158
{
    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->source.data.file.path);
        if ((def->source.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
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
239
        dom->def->console->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
240
        if (umlIdentifyOneChrPTY(driver, dom,
241 242 243 244
                                 dom->def->console, "con") < 0)
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
245
        if (dom->def->serials[i]->source.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_WARN("Could not open monitor for new domain");
326
                umlShutdownVMDaemon(NULL, driver, dom);
327
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
328
                VIR_WARN("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 346
umlStartup(int privileged)
{
347 348
    uid_t uid = geteuid();
    char *base = NULL;
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

    /* Configuration paths are either ~/.libvirt/uml/... (session) or
     * /etc/libvirt/uml/... (system).
     */
401
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
402 403
        goto out_of_memory;

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

    VIR_FREE(base);

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

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

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
416
        VIR_ERROR(_("cannot initialize inotify"));
417
        goto error;
418 419
    }

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

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

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

439
    if (virDomainLoadAllConfigs(uml_driver->caps,
440 441 442
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
443
                                0, NULL, NULL) < 0)
444 445
        goto error;

446 447
    umlAutostartConfigs(uml_driver);

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

451 452
    return 0;

453
out_of_memory:
454
    VIR_ERROR(_("umlStartup: out of memory"));
455 456

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

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

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

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

    if (!uml_driver)
        return 0;

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

507
    return active;
508 509
}

510
static void
511
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
512 513 514 515 516
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
D
Daniel P. Berrange 已提交
517
    if (virDomainObjIsActive(dom))
518 519 520 521
        umlShutdownVMDaemon(NULL, driver, dom);
    virDomainObjUnlock(dom);
}

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

532
    umlDriverLock(uml_driver);
533 534
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
535
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
536 537
    virCapabilitiesFree(uml_driver->caps);

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

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

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

552
    umlDriverUnlock(uml_driver);
553
    virMutexDestroy(&uml_driver->lock);
554 555 556 557 558 559
    VIR_FREE(uml_driver);

    return 0;
}


560
static int umlReadPidFile(struct uml_driver *driver,
561 562 563 564 565 566 567 568
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

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

591
    if (VIR_FCLOSE(file) < 0)
592 593 594 595 596 597
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
598
        virReportSystemError(errno,
599 600
                             _("failed to read pid: %s"),
                             pidfile);
601 602 603 604
    VIR_FREE(pidfile);
    return rc;
}

605
static int umlMonitorAddress(const struct uml_driver *driver,
606 607 608
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
609
    int retval = 0;
610

611 612
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
613
        virReportOOMError();
614 615 616 617 618
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
619
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
620
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
621 622 623
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
624
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
625
    return retval;
626 627
}

628
static int umlOpenMonitor(struct uml_driver *driver,
629 630 631 632
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
633
    umlDomainObjPrivatePtr priv = vm->privateData;
634

635
    if (umlMonitorAddress(driver, vm, &addr) < 0)
636 637
        return -1;

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

649
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
650
        virReportSystemError(errno,
651
                             "%s", _("cannot open socket"));
652 653 654 655
        return -1;
    }

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


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

702 703
    VIR_DEBUG("Run command '%s'", cmd);

704 705
    *reply = NULL;

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

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

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

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

        if (res.error)
            ret = -1;

    } while (res.extra);

764 765
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

766 767 768 769
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
770 771 772 773 774 775 776 777 778

    return ret;

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


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

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

808 809 810
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
D
Daniel P. Berrange 已提交
811
    int ret;
812 813
    char *logfile;
    int logfd = -1;
814
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
815
    virCommandPtr cmd = NULL;
816

D
Daniel P. Berrange 已提交
817
    if (virDomainObjIsActive(vm)) {
818
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
819
                       _("VM is already active"));
820 821 822 823
        return -1;
    }

    if (!vm->def->os.kernel) {
824 825
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
826 827 828 829 830 831
        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
     */
E
Eric Blake 已提交
832
    if (!virFileIsExecutable(vm->def->os.kernel)) {
833
        virReportSystemError(errno,
834 835
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
836 837 838
        return -1;
    }

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

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

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

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

D
Daniel P. Berrange 已提交
869
    if (!(cmd = umlBuildCommandLine(conn, driver, vm))) {
870
        VIR_FORCE_CLOSE(logfd);
871
        virDomainConfVMNWFilterTeardown(vm);
872
        umlCleanupTapDevices(conn, vm);
873 874 875
        return -1;
    }

D
Daniel P. Berrange 已提交
876
    virCommandWriteArgLog(cmd, logfd);
877

878
    priv->monitor = -1;
879

D
Daniel P. Berrange 已提交
880 881 882 883 884 885
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
886
    VIR_FORCE_CLOSE(logfd);
887 888
    if (ret < 0)
        goto cleanup;
889

890
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
891
cleanup:
D
Daniel P. Berrange 已提交
892
    virCommandFree(cmd);
893

894 895
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
896
        umlCleanupTapDevices(conn, vm);
897 898
    }

899 900
    /* NB we don't mark it running here - we do that async
       with inotify */
901 902 903
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
904 905 906 907 908 909 910 911 912

    return ret;
}

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

D
Daniel P. Berrange 已提交
915
    if (!virDomainObjIsActive(vm))
916 917
        return;

918
    virKillProcess(vm->pid, SIGTERM);
919

920
    VIR_FORCE_CLOSE(priv->monitor);
921 922

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
923
        VIR_WARN("Got unexpected pid %d != %d",
924 925 926 927 928 929 930
               ret, vm->pid);
    }

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

931
    virDomainConfVMNWFilterTeardown(vm);
932 933
    umlCleanupTapDevices(conn, vm);

934 935 936 937 938 939 940 941 942 943 944 945
    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) {
946 947 948
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
949

950
        conn->uri = xmlParseURI(uml_driver->privileged ?
951 952 953
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
954
            virReportOOMError();
955 956 957 958 959 960 961 962 963 964
            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;
965 966


967
        /* Check path and tell them correct path if they made a mistake */
968
        if (uml_driver->privileged) {
969
            if (STRNEQ (conn->uri->path, "/system") &&
970
                STRNEQ (conn->uri->path, "/session")) {
971
                umlReportError(VIR_ERR_INTERNAL_ERROR,
972 973 974 975 976 977
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
978
                umlReportError(VIR_ERR_INTERNAL_ERROR,
979 980 981 982
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
983
        }
984 985 986

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
987
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
988
                           _("uml state driver is not active"));
989 990 991 992 993 994 995 996 997 998
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
999
    /*struct uml_driver *driver = conn->privateData;*/
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

    conn->privateData = NULL;

    return 0;
}

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


1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
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;
}


1025 1026 1027 1028
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1029
    umlDriverLock(driver);
1030
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1031
        virReportOOMError();
1032
    umlDriverUnlock(driver);
1033 1034 1035 1036 1037 1038

    return xml;
}



1039 1040 1041
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1042 1043 1044
    FILE *pidinfo;
    unsigned long long usertime, systime;

1045
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1046 1047 1048 1049 1050 1051
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
1052
        VIR_FREE(proc);
1053 1054 1055
        return 0;
    }

1056 1057
    VIR_FREE(proc);

1058 1059
    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");
1060
        VIR_FORCE_FCLOSE(pidinfo);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        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);

1073
    VIR_FORCE_FCLOSE(pidinfo);
1074 1075 1076 1077 1078 1079 1080 1081

    return 0;
}


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

1085
    umlDriverLock(driver);
1086
    vm = virDomainFindByID(&driver->domains, id);
1087 1088
    umlDriverUnlock(driver);

1089
    if (!vm) {
1090
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1091
        goto cleanup;
1092 1093 1094 1095
    }

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

cleanup:
1098 1099
    if (vm)
        virDomainObjUnlock(vm);
1100 1101
    return dom;
}
1102

1103 1104 1105
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1106 1107
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1108

1109
    umlDriverLock(driver);
1110
    vm = virDomainFindByUUID(&driver->domains, uuid);
1111 1112
    umlDriverUnlock(driver);

1113
    if (!vm) {
1114
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1115
        goto cleanup;
1116 1117 1118 1119
    }

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

cleanup:
1122 1123
    if (vm)
        virDomainObjUnlock(vm);
1124 1125
    return dom;
}
1126

1127 1128 1129
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1130 1131
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1132

1133
    umlDriverLock(driver);
1134
    vm = virDomainFindByName(&driver->domains, name);
1135 1136
    umlDriverUnlock(driver);

1137
    if (!vm) {
1138
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1139
        goto cleanup;
1140 1141 1142 1143
    }

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

cleanup:
1146 1147
    if (vm)
        virDomainObjUnlock(vm);
1148 1149 1150
    return dom;
}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

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) {
1162
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
        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) {
1184
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
        goto cleanup;
    }
    ret = obj->persistent;

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

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
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;
}
1215

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

1221
    umlDriverLock(driver);
1222 1223 1224 1225 1226

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

        if (virParseVersionString(ut.release, &driver->umlVersion) < 0) {
1227
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1228 1229 1230
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1231 1232
    }

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

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

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

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

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

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

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

1268 1269
    virCheckFlags(0, NULL);

1270
    umlDriverLock(driver);
1271
    if (!(def = virDomainDefParseString(driver->caps, xml,
1272
                                        VIR_DOMAIN_XML_INACTIVE)))
1273
        goto cleanup;
1274

1275
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1276
        goto cleanup;
1277

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

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

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

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


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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

        virUUIDFormat(dom->uuid, uuidstr);
1401
        umlReportError(VIR_ERR_NO_DOMAIN,
1402 1403
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1404
    }
1405
    ret = vm->def->mem.max_balloon;
1406

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

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

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

1422 1423 1424 1425
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1426
        umlReportError(VIR_ERR_NO_DOMAIN,
1427
                       _("no domain with matching uuid '%s'"), uuidstr);
1428
        goto cleanup;
1429 1430
    }

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

1437
    vm->def->mem.max_balloon = newmax;
1438 1439 1440
    ret = 0;

cleanup:
1441 1442
    if (vm)
        virDomainObjUnlock(vm);
1443
    return ret;
1444 1445 1446
}

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

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

1455 1456 1457 1458
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1459
        umlReportError(VIR_ERR_NO_DOMAIN,
1460
                       _("no domain with matching uuid '%s'"), uuidstr);
1461
        goto cleanup;
1462 1463
    }

D
Daniel P. Berrange 已提交
1464
    if (virDomainObjIsActive(vm)) {
1465
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1466
                       _("cannot set memory of an active domain"));
1467
        goto cleanup;
1468 1469
    }

1470
    if (newmem > vm->def->mem.max_balloon) {
1471 1472
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1473
        goto cleanup;
1474 1475
    }

1476
    vm->def->mem.cur_balloon = newmem;
1477 1478 1479
    ret = 0;

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

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

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

1495
    if (!vm) {
1496
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1497
                       _("no domain with matching uuid"));
1498
        goto cleanup;
1499 1500 1501 1502
    }

    info->state = vm->state;

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

1513 1514
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1515
    info->nrVirtCpu = vm->def->vcpus;
1516 1517 1518
    ret = 0;

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


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

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

1535
    if (!vm) {
1536
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1537
                       _("no domain with matching uuid"));
1538
        goto cleanup;
1539 1540
    }

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

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


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

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

1561
    return n;
1562 1563 1564
}

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

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

    return n;
}


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

1581 1582
    virCheckFlags(0, -1);

1583
    umlDriverLock(driver);
1584
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1585

1586
    if (!vm) {
1587
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1588
                       _("no domain with matching uuid"));
1589
        goto cleanup;
1590 1591
    }

1592 1593 1594
    ret = umlStartVMDaemon(dom->conn, driver, vm);

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

1601 1602 1603
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1604 1605

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1606
    struct uml_driver *driver = conn->privateData;
1607
    virDomainDefPtr def;
1608
    virDomainObjPtr vm = NULL;
1609
    virDomainPtr dom = NULL;
1610

1611
    umlDriverLock(driver);
1612
    if (!(def = virDomainDefParseString(driver->caps, xml,
1613
                                        VIR_DOMAIN_XML_INACTIVE)))
1614
        goto cleanup;
1615

1616 1617 1618
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1619
    if (!(vm = virDomainAssignDef(driver->caps,
1620
                                  &driver->domains,
1621
                                  def, false)))
1622 1623
        goto cleanup;
    def = NULL;
1624 1625
    vm->persistent = 1;

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

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1636 1637 1638

cleanup:
    virDomainDefFree(def);
1639 1640 1641
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1642 1643 1644 1645
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1646 1647 1648
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1649

1650
    umlDriverLock(driver);
1651
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1652
    if (!vm) {
1653
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1654
                       _("no domain with matching uuid"));
1655
        goto cleanup;
1656 1657
    }

D
Daniel P. Berrange 已提交
1658
    if (virDomainObjIsActive(vm)) {
1659
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1660
                       _("cannot delete active domain"));
1661
        goto cleanup;
1662 1663 1664
    }

    if (!vm->persistent) {
1665
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1666
                       _("cannot undefine transient domain"));
1667
        goto cleanup;
1668 1669
    }

1670
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1671
        goto cleanup;
1672 1673 1674

    virDomainRemoveInactive(&driver->domains,
                            vm);
1675
    vm = NULL;
1676
    ret = 0;
1677

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


1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 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
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);
}

1914 1915 1916

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1917 1918 1919
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1920

1921
    umlDriverLock(driver);
1922
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1923

1924
    if (!vm) {
1925
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1926
                       _("no domain with matching uuid"));
1927
        goto cleanup;
1928 1929 1930
    }

    *autostart = vm->autostart;
1931
    ret = 0;
1932

1933
cleanup:
1934 1935
    if (vm)
        virDomainObjUnlock(vm);
1936
    umlDriverUnlock(driver);
1937
    return ret;
1938 1939 1940 1941
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1942
    struct uml_driver *driver = dom->conn->privateData;
1943
    virDomainObjPtr vm;
1944 1945 1946
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

1947 1948 1949
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

1950
    if (!vm) {
1951
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1952
                       _("no domain with matching uuid"));
1953
        goto cleanup;
1954 1955 1956
    }

    if (!vm->persistent) {
1957
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1958
                       _("cannot set autostart for transient domain"));
1959
        goto cleanup;
1960 1961 1962 1963
    }

    autostart = (autostart != 0);

1964
    if (vm->autostart != autostart) {
1965
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
1966
            goto cleanup;
1967
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
1968
            goto cleanup;
1969

1970 1971
        if (autostart) {
            int err;
1972

1973
            if ((err = virFileMakePath(driver->autostartDir))) {
1974
                virReportSystemError(err,
1975 1976
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1977 1978
                goto cleanup;
            }
1979

1980
            if (symlink(configFile, autostartLink) < 0) {
1981
                virReportSystemError(errno,
1982 1983
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
1984 1985 1986 1987
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1988
                virReportSystemError(errno,
1989 1990
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
1991 1992
                goto cleanup;
            }
1993 1994
        }

1995
        vm->autostart = autostart;
1996 1997 1998 1999 2000 2001
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2002 2003
    if (vm)
        virDomainObjUnlock(vm);
2004
    umlDriverUnlock(driver);
2005 2006 2007 2008 2009
    return ret;
}


static int
2010 2011 2012 2013 2014
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
                   unsigned int flags ATTRIBUTE_UNUSED)
2015
{
2016 2017 2018
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2019

2020
    umlDriverLock(driver);
2021
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2022 2023
    umlDriverUnlock(driver);

2024
    if (!vm) {
2025
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2026
                       _("no domain with matching uuid"));
2027
        goto cleanup;
2028 2029 2030
    }

    if (!path || path[0] == '\0') {
2031 2032
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2033
        goto cleanup;
2034 2035 2036 2037 2038
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2039 2040 2041 2042
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2043 2044
    }

2045 2046 2047 2048 2049
    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) {
2050
            virReportSystemError(errno,
2051
                                 _("cannot open %s"), path);
2052 2053
            goto cleanup;
        }
2054

2055 2056 2057 2058 2059 2060
        /* 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) {
2061
            virReportSystemError(errno,
2062
                                 _("cannot read %s"), path);
2063 2064 2065 2066 2067
            goto cleanup;
        }

        ret = 0;
    } else {
2068 2069
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2070 2071
    }

2072
cleanup:
2073
    VIR_FORCE_CLOSE(fd);
2074 2075
    if (vm)
        virDomainObjUnlock(vm);
2076 2077 2078 2079
    return ret;
}


2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 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
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;
    }

2127
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2128 2129 2130 2131 2132
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

2133 2134
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
        goto cleanup;

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

2145 2146 2147 2148 2149 2150 2151 2152 2153

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

2261 2262 2263 2264 2265 2266 2267 2268
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2269 2270

static virStateDriver umlStateDriver = {
2271
    .name = "UML",
2272 2273 2274 2275 2276 2277
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2290 2291 2292
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2293 2294
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2295 2296
};

2297 2298 2299
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2300
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2301 2302
    return 0;
}