uml_driver.c 62.0 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2010 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/inotify.h>
46
#include <sys/un.h>
47 48 49 50 51 52 53 54 55 56 57 58 59

#include "uml_driver.h"
#include "uml_conf.h"
#include "event.h"
#include "buf.h"
#include "util.h"
#include "nodeinfo.h"
#include "stats_linux.h"
#include "capabilities.h"
#include "memory.h"
#include "uuid.h"
#include "domain_conf.h"
#include "datatypes.h"
60
#include "logging.h"
61
#include "domain_nwfilter.h"
62
#include "files.h"
63
#include "fdstream.h"
64
#include "configmake.h"
65

66 67
#define VIR_FROM_THIS VIR_FROM_UML

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

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


79 80
static int umlShutdown(void);

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

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

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

    return priv;
}

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

    VIR_FREE(priv);
}


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

111

112
static int umlOpenMonitor(struct uml_driver *driver,
113
                          virDomainObjPtr vm);
114
static int umlReadPidFile(struct uml_driver *driver,
115 116 117 118 119 120 121 122 123 124 125
                          virDomainObjPtr vm);

static int umlSetCloseExec(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFD)) < 0)
        goto error;
    flags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, flags)) < 0)
        goto error;
    return 0;
 error:
D
Daniel Veillard 已提交
126
    VIR_ERROR0(_("Failed to set close-on-exec file descriptor flag"));
127 128 129 130 131 132 133 134 135 136 137 138
    return -1;
}

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

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


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

static struct uml_driver *uml_driver = NULL;

146 147 148 149 150 151 152 153 154 155 156 157 158
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
umlAutostartDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr vm = payload;
    const struct umlAutostartData *data = opaque;

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
159
        !virDomainObjIsActive(vm)) {
160 161 162 163
        virResetLastError();
        if (umlStartVMDaemon(data->conn, data->driver, vm) < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
164
                      vm->def->name, err ? err->message : _("unknown error"));
165 166 167 168
        }
    }
    virDomainObjUnlock(vm);
}
169 170 171

static void
umlAutostartConfigs(struct uml_driver *driver) {
172 173 174 175 176
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
177 178 179
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
180
    /* Ignoring NULL conn which is mostly harmless here */
181

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

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

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


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

208
    if (res && STRPREFIX(res, "pts:")) {
209 210
        VIR_FREE(def->data.file.path);
        if ((def->data.file.path = strdup(res + 4)) == NULL) {
211
            virReportOOMError();
212 213 214 215
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
216
    } else if (!res || STRPREFIX(res, "pts")) {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        /* It can take a while to startup, so retry for
           upto 5 seconds */
        /* XXX should do this in a better non-blocking
           way somehow ...perhaps register a timer */
        if (retries++ < 50) {
            usleep(1000*10);
            goto requery;
        }
    }

    VIR_FREE(cmd);
    VIR_FREE(res);
    return 0;
}

static int
233
umlIdentifyChrPTY(struct uml_driver *driver,
234 235 236 237 238 239
                  virDomainObjPtr dom)
{
    int i;

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

    for (i = 0 ; i < dom->def->nserials; i++)
        if (dom->def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_PTY &&
246
            umlIdentifyOneChrPTY(driver, dom,
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                                 dom->def->serials[i], "ssl") < 0)
            return -1;

    return 0;
}

static void
umlInotifyEvent(int watch,
                int fd,
                int events ATTRIBUTE_UNUSED,
                void *data)
{
    char buf[1024];
    struct inotify_event *e;
    int got;
    char *tmp, *name;
    struct uml_driver *driver = data;
    virDomainObjPtr dom;

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

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

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

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

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

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

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

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

        if (!dom) {
            continue;
        }

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

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

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

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

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

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

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

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

354 355
    uml_driver->privileged = privileged;

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

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

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

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

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

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

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

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

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

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

    /* Configuration paths are either ~/.libvirt/uml/... (session) or
     * /etc/libvirt/uml/... (system).
     */
    if (snprintf (driverConf, sizeof(driverConf), "%s/uml.conf", base) == -1)
        goto out_of_memory;
    driverConf[sizeof(driverConf)-1] = '\0';

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

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

    VIR_FREE(base);

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

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

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

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

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

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

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

450 451
    umlAutostartConfigs(uml_driver);

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

455 456
    return 0;

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

error:
461
    VIR_FREE(userdir);
462
    VIR_FREE(base);
463 464
    umlDriverUnlock(uml_driver);
    umlShutdown();
465 466 467 468 469 470 471 472 473 474 475 476 477 478
    return -1;
}

/**
 * umlReload:
 *
 * Function to restart the Uml daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
umlReload(void) {
    if (!uml_driver)
        return 0;

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

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

    return 0;
}

/**
 * umlActive:
 *
 * Checks if the Uml daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
umlActive(void) {
502
    int active = 0;
503 504 505 506

    if (!uml_driver)
        return 0;

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

511
    return active;
512 513
}

514 515 516 517 518 519 520
static void
umlShutdownOneVM(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
D
Daniel P. Berrange 已提交
521
    if (virDomainObjIsActive(dom))
522 523 524 525
        umlShutdownVMDaemon(NULL, driver, dom);
    virDomainObjUnlock(dom);
}

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

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

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

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

    VIR_FREE(uml_driver->logDir);
    VIR_FREE(uml_driver->configDir);
    VIR_FREE(uml_driver->autostartDir);
    VIR_FREE(uml_driver->monitorDir);

    if (uml_driver->brctl)
        brShutdown(uml_driver->brctl);

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

    return 0;
}


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

    vm->pid = -1;
573 574
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
575
        virReportOOMError();
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        return -1;
    }

reopen:
    if (!(file = fopen(pidfile, "r"))) {
        if (errno == ENOENT &&
            retries++ < 50) {
            usleep(1000 * 100);
            goto reopen;
        }
        goto cleanup;
    }

    if (fscanf(file, "%d", &vm->pid) != 1) {
        errno = EINVAL;
591
        VIR_FORCE_FCLOSE(file);
592 593 594
        goto cleanup;
    }

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

    rc = 0;

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

609
static int umlMonitorAddress(const struct uml_driver *driver,
610 611 612
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
613
    int retval = 0;
614

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

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

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

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

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

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

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

    return 0;
}


#define MONITOR_MAGIC 0xcafebabe
#define MONITOR_BUFLEN 512
#define MONITOR_VERSION 2

struct monitor_request {
    uint32_t magic;
    uint32_t version;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};

struct monitor_response {
    uint32_t error;
    uint32_t extra;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};


693
static int umlMonitorCommand(const struct uml_driver *driver,
694 695 696 697 698 699 700 701 702 703
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply)
{
    struct monitor_request req;
    struct monitor_response res;
    char *retdata = NULL;
    int retlen = 0, ret = 0;
    struct sockaddr_un addr;
    unsigned int addrlen;
704
    umlDomainObjPrivatePtr priv = vm->privateData;
705

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

708 709
    *reply = NULL;

710
    if (umlMonitorAddress(driver, vm, &addr) < 0)
711 712 713 714 715 716 717
        return -1;

    memset(&req, 0, sizeof(req));
    req.magic = MONITOR_MAGIC;
    req.version = MONITOR_VERSION;
    req.length = strlen(cmd);
    if (req.length > (MONITOR_BUFLEN-1)) {
718
        virReportSystemError(EINVAL,
719 720
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
721 722
        return -1;
    }
C
Chris Lalancette 已提交
723
    if (virStrcpyStatic(req.data, cmd) == NULL) {
724
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
725 726 727
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
728

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

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

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

        if (res.error)
            ret = -1;

    } while (res.extra);

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

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

    return ret;

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


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

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr def = vm->def->nets[i];

        if (def->type != VIR_DOMAIN_NET_TYPE_BRIDGE &&
            def->type != VIR_DOMAIN_NET_TYPE_NETWORK)
            continue;

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

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

    FD_ZERO(&keepfd);

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

    if (!vm->def->os.kernel) {
835 836
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
837 838 839 840 841 842 843
        return -1;
    }
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(vm->def->os.kernel, &sb) < 0) {
844
        virReportSystemError(errno,
845 846
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
847 848 849
        return -1;
    }

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

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

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

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

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

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

912
    priv->monitor = -1;
913

914
    ret = virExecDaemonize(argv, progenv, &keepfd, &pid,
915
                           -1, &logfd, &logfd,
916 917
                           VIR_EXEC_CLEAR_CAPS,
                           NULL, NULL, NULL);
918
    VIR_FORCE_CLOSE(logfd);
919 920
    if (ret < 0)
        goto cleanup;
921

922 923
    ret = virDomainObjSetDefTransient(driver->caps, vm);
cleanup:
924 925 926 927 928
    /*
     * At the moment, the only thing that populates keepfd is
     * umlBuildCommandLineChr. We want to close every fd it opens.
     */
    for (i = 0; i < FD_SETSIZE; i++)
929 930 931 932
        if (FD_ISSET(i, &keepfd)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
933

934 935 936 937 938 939 940 941
    for (i = 0 ; argv[i] ; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

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

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

    return ret;
}

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

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

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

968
    VIR_FORCE_CLOSE(priv->monitor);
969 970

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

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

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

982 983 984 985 986 987 988 989 990 991 992 993
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
}


static virDrvOpenStatus umlOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                int flags ATTRIBUTE_UNUSED) {
994 995 996
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
997

998
        conn->uri = xmlParseURI(uml_driver->privileged ?
999 1000 1001
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
1002
            virReportOOMError();
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
            return VIR_DRV_OPEN_ERROR;
        }
    } else {
        if (conn->uri->scheme == NULL ||
            STRNEQ (conn->uri->scheme, "uml"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;
1013 1014


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    conn->privateData = NULL;

    return 0;
}

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


1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
static int umlIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}


static int umlIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}


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

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

    return xml;
}



static int umlGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
    unsigned long long usertime, systime;

    if (snprintf(proc, sizeof(proc), "/proc/%d/stat", pid) >= (int)sizeof(proc)) {
        return -1;
    }

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

    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
        umlDebug("not enough arg");
1104
        VIR_FORCE_FCLOSE(pidinfo);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);

    umlDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);

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

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

static int umlDomainIsActive(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
1206
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

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


static int umlDomainIsPersistent(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
1228
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        goto cleanup;
    }
    ret = obj->persistent;

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


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

1245
    umlDriverLock(driver);
1246 1247 1248 1249 1250

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

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

1257 1258 1259 1260 1261 1262
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1263 1264 1265
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1266
    struct uml_driver *driver = conn->privateData;
1267
    int n;
1268

1269
    umlDriverLock(driver);
1270
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1271
    umlDriverUnlock(driver);
1272

1273
    return n;
1274 1275
}
static int umlNumDomains(virConnectPtr conn) {
1276
    struct uml_driver *driver = conn->privateData;
1277
    int n;
1278

1279
    umlDriverLock(driver);
1280
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1281
    umlDriverUnlock(driver);
1282 1283 1284 1285

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

1292 1293
    virCheckFlags(0, NULL);

1294
    umlDriverLock(driver);
1295
    if (!(def = virDomainDefParseString(driver->caps, xml,
1296
                                        VIR_DOMAIN_XML_INACTIVE)))
1297
        goto cleanup;
1298

1299
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1300
        goto cleanup;
1301

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

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

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1317 1318 1319

cleanup:
    virDomainDefFree(def);
1320 1321 1322
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1323 1324 1325 1326 1327
    return dom;
}


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

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

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

1351 1352
cleanup:
    VIR_FREE(info);
1353 1354
    if (vm)
        virDomainObjUnlock(vm);
1355
    return ret;
1356 1357 1358 1359
}


static int umlDomainDestroy(virDomainPtr dom) {
1360 1361 1362
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1363

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

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

1380
cleanup:
1381 1382 1383
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1384
    return ret;
1385 1386 1387 1388
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1389 1390 1391
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1392

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

1402
    if (!(type = strdup(vm->def->os.type)))
1403
        virReportOOMError();
1404 1405

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

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

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

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

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

1431
cleanup:
1432 1433
    if (vm)
        virDomainObjUnlock(vm);
1434
    return ret;
1435 1436 1437
}

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

1442
    umlDriverLock(driver);
1443
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1444 1445
    umlDriverUnlock(driver);

1446 1447 1448 1449
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

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

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

1461
    vm->def->mem.max_balloon = newmax;
1462 1463 1464
    ret = 0;

cleanup:
1465 1466
    if (vm)
        virDomainObjUnlock(vm);
1467
    return ret;
1468 1469 1470
}

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

1475
    umlDriverLock(driver);
1476
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1477 1478
    umlDriverUnlock(driver);

1479 1480 1481 1482
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

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

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

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

1500
    vm->def->mem.cur_balloon = newmem;
1501 1502 1503
    ret = 0;

cleanup:
1504 1505
    if (vm)
        virDomainObjUnlock(vm);
1506
    return ret;
1507 1508 1509 1510
}

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

1515
    umlDriverLock(driver);
1516
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1517 1518
    umlDriverUnlock(driver);

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

    info->state = vm->state;

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

1537 1538
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1539
    info->nrVirtCpu = vm->def->vcpus;
1540 1541 1542
    ret = 0;

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


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

1555
    umlDriverLock(driver);
1556
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1557 1558
    umlDriverUnlock(driver);

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

1565
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1566 1567 1568 1569
                             vm->newDef : vm->def,
                             flags);

cleanup:
1570 1571
    if (vm)
        virDomainObjUnlock(vm);
1572
    return ret;
1573 1574 1575 1576 1577
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1578
    struct uml_driver *driver = conn->privateData;
1579
    int n;
1580

1581
    umlDriverLock(driver);
1582
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1583
    umlDriverUnlock(driver);
1584

1585
    return n;
1586 1587 1588
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1589
    struct uml_driver *driver = conn->privateData;
1590
    int n;
1591

1592
    umlDriverLock(driver);
1593
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1594
    umlDriverUnlock(driver);
1595 1596 1597 1598 1599

    return n;
}


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

1605 1606
    virCheckFlags(0, -1);

1607
    umlDriverLock(driver);
1608
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1609

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

1616 1617 1618
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1619 1620 1621
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1622
    return ret;
1623 1624
}

1625 1626 1627
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1628 1629

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

1635
    umlDriverLock(driver);
1636
    if (!(def = virDomainDefParseString(driver->caps, xml,
1637
                                        VIR_DOMAIN_XML_INACTIVE)))
1638
        goto cleanup;
1639

1640 1641 1642
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

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

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

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1660 1661 1662

cleanup:
    virDomainDefFree(def);
1663 1664 1665
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1666 1667 1668 1669
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1670 1671 1672
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1673

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

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

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

1694
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1695
        goto cleanup;
1696 1697 1698

    virDomainRemoveInactive(&driver->domains,
                            vm);
1699
    vm = NULL;
1700
    ret = 0;
1701

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


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

1938 1939 1940

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

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

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

    *autostart = vm->autostart;
1955
    ret = 0;
1956

1957
cleanup:
1958 1959
    if (vm)
        virDomainObjUnlock(vm);
1960
    umlDriverUnlock(driver);
1961
    return ret;
1962 1963 1964 1965
}

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

1971 1972 1973
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

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

    autostart = (autostart != 0);

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

1994 1995
        if (autostart) {
            int err;
1996

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

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

2019
        vm->autostart = autostart;
2020 2021 2022 2023 2024 2025
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2026 2027
    if (vm)
        virDomainObjUnlock(vm);
2028
    umlDriverUnlock(driver);
2029 2030 2031 2032 2033
    return ret;
}


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

2044
    umlDriverLock(driver);
2045
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2046 2047
    umlDriverUnlock(driver);

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

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

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

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

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

        ret = 0;
    } else {
2092 2093
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2094 2095
    }

2096
cleanup:
2097
    VIR_FORCE_CLOSE(fd);
2098 2099
    if (vm)
        virDomainObjUnlock(vm);
2100 2101 2102 2103
    return ret;
}


2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
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;
}

2168 2169 2170 2171 2172 2173 2174 2175 2176

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

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

    return 0;
}
2284 2285

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

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2305 2306 2307
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2308 2309
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2310 2311
};

2312 2313 2314
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2315
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2316 2317
    return 0;
}