uml_driver.c 61.5 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

#include "uml_driver.h"
#include "uml_conf.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"
58
#include "domain_audit.h"
59
#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
                          virDomainObjPtr vm);

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

static void umlShutdownVMDaemon(virConnectPtr conn,
                                struct uml_driver *driver,
J
Jiri Denemark 已提交
123 124
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason);
125 126


127 128 129 130
static int umlMonitorCommand(const struct uml_driver *driver,
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply);
131 132 133

static struct uml_driver *uml_driver = NULL;

134 135 136 137 138 139
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
140
umlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
141 142 143 144 145 146
{
    virDomainObjPtr vm = payload;
    const struct umlAutostartData *data = opaque;

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
147
        !virDomainObjIsActive(vm)) {
148
        int ret;
149
        virResetLastError();
150 151 152
        ret = umlStartVMDaemon(data->conn, data->driver, vm);
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
153 154
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
155
                      vm->def->name, err ? err->message : _("unknown error"));
156 157 158 159
        }
    }
    virDomainObjUnlock(vm);
}
160 161 162

static void
umlAutostartConfigs(struct uml_driver *driver) {
163 164 165 166 167
    /* 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
     */
168 169 170
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
171
    /* Ignoring NULL conn which is mostly harmless here */
172

173 174 175
    struct umlAutostartData data = { driver, conn };

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

177 178
    if (conn)
        virConnectClose(conn);
179 180 181 182
}


static int
183
umlIdentifyOneChrPTY(struct uml_driver *driver,
184 185 186 187 188 189 190
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
191
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
192
        virReportOOMError();
193 194 195
        return -1;
    }
requery:
196
    if (umlMonitorCommand(driver, dom, cmd, &res) < 0)
197
        return -1;
198

199
    if (res && STRPREFIX(res, "pts:")) {
200 201
        VIR_FREE(def->source.data.file.path);
        if ((def->source.data.file.path = strdup(res + 4)) == NULL) {
202
            virReportOOMError();
203 204 205 206
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
207
    } else if (!res || STRPREFIX(res, "pts")) {
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        /* 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
224
umlIdentifyChrPTY(struct uml_driver *driver,
225 226 227 228 229
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
230
        dom->def->console->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
231
        if (umlIdentifyOneChrPTY(driver, dom,
232 233 234 235
                                 dom->def->console, "con") < 0)
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
236
        if (dom->def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
237
            umlIdentifyOneChrPTY(driver, dom,
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                                 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;

257
    umlDriverLock(driver);
258
    if (watch != driver->inotifyWatch)
259
        goto cleanup;
260 261 262 263 264 265

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
266
        goto cleanup;
267 268 269 270 271
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
272
            goto cleanup; /* bad */
273 274 275 276 277 278

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

        if (got < e->len)
279
            goto cleanup;
280 281 282 283 284 285 286 287 288 289 290 291 292

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

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

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

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
293
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
294
            if (!virDomainObjIsActive(dom)) {
295
                virDomainObjUnlock(dom);
296 297 298
                continue;
            }

J
Jiri Denemark 已提交
299
            umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
300
            virDomainAuditStop(dom, "shutdown");
301 302 303 304 305
            if (!dom->persistent) {
                virDomainRemoveInactive(&driver->domains,
                                        dom);
                dom = NULL;
            }
306
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
307
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
308
            if (virDomainObjIsActive(dom)) {
309
                virDomainObjUnlock(dom);
310 311 312
                continue;
            }

313
            if (umlReadPidFile(driver, dom) < 0) {
314
                virDomainObjUnlock(dom);
315 316 317 318
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
319 320
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
321

322
            if (umlOpenMonitor(driver, dom) < 0) {
323
                VIR_WARN("Could not open monitor for new domain");
J
Jiri Denemark 已提交
324 325
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
326
                virDomainAuditStop(dom, "failed");
327 328 329 330 331
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
332
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
333
                VIR_WARN("Could not identify character devices for new domain");
J
Jiri Denemark 已提交
334 335
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
336
                virDomainAuditStop(dom, "failed");
337 338 339 340 341
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
342
            }
343
        }
344 345
        if (dom)
            virDomainObjUnlock(dom);
346
    }
347 348 349

cleanup:
    umlDriverUnlock(driver);
350 351 352 353 354 355 356 357
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
358 359
umlStartup(int privileged)
{
360 361
    uid_t uid = geteuid();
    char *base = NULL;
362
    char *userdir = NULL;
363 364 365 366

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

367 368
    uml_driver->privileged = privileged;

369 370 371 372
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
373 374
    umlDriverLock(uml_driver);

375 376
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
377
    uml_driver->inotifyWatch = -1;
378

379 380 381
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

382
    userdir = virGetUserDirectory(uid);
383
    if (!userdir)
384
        goto error;
385

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

391
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
392
            goto out_of_memory;
393 394

        if (virAsprintf(&uml_driver->monitorDir,
395
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
396
            goto out_of_memory;
397
    } else {
398

399
        if (virAsprintf(&uml_driver->logDir,
400
                        "%s/.libvirt/uml/log", userdir) == -1)
401 402
            goto out_of_memory;

403
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
404 405
            goto out_of_memory;

406 407 408 409
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
410 411 412 413

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

417
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
418 419 420 421 422 423 424
        goto out_of_memory;

    VIR_FREE(base);

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

425 426
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
427 428

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
429
        VIR_ERROR(_("cannot initialize inotify"));
430
        goto error;
431 432
    }

433
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
434
        char ebuf[1024];
D
Daniel Veillard 已提交
435
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
436
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
437
        goto error;
438 439
    }

440
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
441 442 443
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
444
        goto error;
445 446
    }

447 448
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
449 450
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
451

452
    if (virDomainLoadAllConfigs(uml_driver->caps,
453 454 455
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
456 457
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
458 459
        goto error;

460 461
    umlAutostartConfigs(uml_driver);

462
    umlDriverUnlock(uml_driver);
463 464
    VIR_FREE(userdir);

465 466
    return 0;

467
out_of_memory:
468
    VIR_ERROR(_("umlStartup: out of memory"));
469 470

error:
471
    VIR_FREE(userdir);
472
    VIR_FREE(base);
473 474
    umlDriverUnlock(uml_driver);
    umlShutdown();
475 476 477 478 479 480 481 482 483 484 485 486 487 488
    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;

489
    umlDriverLock(uml_driver);
490
    virDomainLoadAllConfigs(uml_driver->caps,
491 492 493
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
494 495
                            0, 1 << VIR_DOMAIN_VIRT_UML,
                            NULL, NULL);
496 497

    umlAutostartConfigs(uml_driver);
498
    umlDriverUnlock(uml_driver);
499 500 501 502 503 504 505 506 507 508 509 510 511 512

    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) {
513
    int active = 0;
514 515 516 517

    if (!uml_driver)
        return 0;

518
    umlDriverLock(uml_driver);
519
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
520
    umlDriverUnlock(uml_driver);
521

522
    return active;
523 524
}

525
static void
526
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
527 528 529 530 531
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
532
    if (virDomainObjIsActive(dom)) {
J
Jiri Denemark 已提交
533
        umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
534 535
        virDomainAuditStop(dom, "shutdown");
    }
536 537 538
    virDomainObjUnlock(dom);
}

539 540 541 542 543 544 545 546 547 548
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

549
    umlDriverLock(uml_driver);
550 551
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
552
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
553 554
    virCapabilitiesFree(uml_driver->caps);

555 556 557
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
558

559
    virDomainObjListDeinit(&uml_driver->domains);
560 561 562 563 564 565 566 567 568

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

569
    umlDriverUnlock(uml_driver);
570
    virMutexDestroy(&uml_driver->lock);
571 572 573 574 575 576
    VIR_FREE(uml_driver);

    return 0;
}


577
static int umlReadPidFile(struct uml_driver *driver,
578 579 580 581 582 583 584 585
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
586 587
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
588
        virReportOOMError();
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        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;
604
        VIR_FORCE_FCLOSE(file);
605 606 607
        goto cleanup;
    }

608
    if (VIR_FCLOSE(file) < 0)
609 610 611 612 613 614
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
615
        virReportSystemError(errno,
616 617
                             _("failed to read pid: %s"),
                             pidfile);
618 619 620 621
    VIR_FREE(pidfile);
    return rc;
}

622
static int umlMonitorAddress(const struct uml_driver *driver,
623 624 625
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
626
    int retval = 0;
627

628 629
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
630
        virReportOOMError();
631 632 633 634 635
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
636
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
637
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
638 639 640
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
641
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
642
    return retval;
643 644
}

645
static int umlOpenMonitor(struct uml_driver *driver,
646 647 648 649
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
650
    umlDomainObjPrivatePtr priv = vm->privateData;
651

652
    if (umlMonitorAddress(driver, vm, &addr) < 0)
653 654
        return -1;

655
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
656 657 658
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
659
            retries++ < 50) {
660 661 662 663 664 665
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

666
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
667
        virReportSystemError(errno,
668
                             "%s", _("cannot open socket"));
669 670 671 672
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
E
Eric Blake 已提交
673 674
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
675
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
676
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
677
        virReportSystemError(errno,
678
                             "%s", _("cannot bind socket"));
679
        VIR_FORCE_CLOSE(priv->monitor);
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        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];
};


706
static int umlMonitorCommand(const struct uml_driver *driver,
707 708 709 710 711 712 713 714 715 716
                             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;
717
    umlDomainObjPrivatePtr priv = vm->privateData;
718

719 720
    VIR_DEBUG("Run command '%s'", cmd);

721 722
    *reply = NULL;

723
    if (umlMonitorAddress(driver, vm, &addr) < 0)
724 725 726 727 728 729 730
        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)) {
731
        virReportSystemError(EINVAL,
732 733
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
734 735
        return -1;
    }
C
Chris Lalancette 已提交
736
    if (virStrcpyStatic(req.data, cmd) == NULL) {
737
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
738 739 740
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
741

742
    if (sendto(priv->monitor, &req, sizeof req, 0,
743
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
744
        virReportSystemError(errno,
745 746
                             _("cannot send command %s"),
                             cmd);
747 748 749 750
        return -1;
    }

    do {
E
Eric Blake 已提交
751
        ssize_t nbytes;
752
        addrlen = sizeof(addr);
E
Eric Blake 已提交
753
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
754
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
755 756 757
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
758
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
759 760
            goto error;
        }
761 762 763
        /* 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) {
764 765 766
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
767 768

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
769
            virReportOOMError();
770 771 772 773 774 775 776 777 778 779 780
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

781 782
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

783 784 785 786
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
787 788 789 790 791 792 793 794 795

    return ret;

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


796 797 798 799 800 801
static int umlCleanupTapDevices(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm) {
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
802
    VIR_ERROR(_("Cleanup tap"));
803 804 805 806 807 808 809 810 811 812
    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;

813
        VIR_ERROR(_("Cleanup '%s'"), def->ifname);
814 815
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
816
            VIR_ERROR(_("Cleanup failed %d"), err);
817 818 819
            ret = -1;
        }
    }
820
    VIR_ERROR(_("Cleanup tap done"));
821 822 823 824
    brShutdown(brctl);
    return ret;
}

825 826 827
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
D
Daniel P. Berrange 已提交
828
    int ret;
829 830
    char *logfile;
    int logfd = -1;
831
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
832
    virCommandPtr cmd = NULL;
833

D
Daniel P. Berrange 已提交
834
    if (virDomainObjIsActive(vm)) {
835
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
836
                       _("VM is already active"));
837 838 839 840
        return -1;
    }

    if (!vm->def->os.kernel) {
841 842
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
843 844 845 846 847 848
        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 已提交
849
    if (!virFileIsExecutable(vm->def->os.kernel)) {
850
        virReportSystemError(errno,
851 852
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
853 854 855
        return -1;
    }

856
    if (virFileMakePath(driver->logDir) < 0) {
857
        virReportSystemError(errno,
858 859
                             _("cannot create log directory %s"),
                             driver->logDir);
860 861 862
        return -1;
    }

863 864
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
865
        virReportOOMError();
866 867 868 869 870
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
871
        virReportSystemError(errno,
872 873
                             _("failed to create logfile %s"),
                             logfile);
874 875 876 877 878
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

E
Eric Blake 已提交
879 880 881
    if (virSetCloseExec(logfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
882
        VIR_FORCE_CLOSE(logfd);
883 884 885
        return -1;
    }

D
Daniel P. Berrange 已提交
886
    if (!(cmd = umlBuildCommandLine(conn, driver, vm))) {
887
        VIR_FORCE_CLOSE(logfd);
888
        virDomainConfVMNWFilterTeardown(vm);
889
        umlCleanupTapDevices(conn, vm);
890 891 892
        return -1;
    }

D
Daniel P. Berrange 已提交
893
    virCommandWriteArgLog(cmd, logfd);
894

895
    priv->monitor = -1;
896

D
Daniel P. Berrange 已提交
897 898 899 900 901 902
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
903
    VIR_FORCE_CLOSE(logfd);
904 905
    if (ret < 0)
        goto cleanup;
906

907
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
908
cleanup:
D
Daniel P. Berrange 已提交
909
    virCommandFree(cmd);
910

911 912
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
913
        umlCleanupTapDevices(conn, vm);
914 915
    }

916 917
    /* NB we don't mark it running here - we do that async
       with inotify */
918 919 920
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
921 922 923 924 925 926

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
J
Jiri Denemark 已提交
927 928
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
929 930
{
    int ret;
931 932
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
933
    if (!virDomainObjIsActive(vm))
934 935
        return;

936
    virKillProcess(vm->pid, SIGTERM);
937

938
    VIR_FORCE_CLOSE(priv->monitor);
939 940

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
941
        VIR_WARN("Got unexpected pid %d != %d",
942 943 944 945 946
               ret, vm->pid);
    }

    vm->pid = -1;
    vm->def->id = -1;
J
Jiri Denemark 已提交
947
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
948

949
    virDomainConfVMNWFilterTeardown(vm);
950 951
    umlCleanupTapDevices(conn, vm);

952 953 954 955 956 957 958 959 960 961 962
    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,
E
Eric Blake 已提交
963 964 965 966
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

967 968 969
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
970

971
        conn->uri = xmlParseURI(uml_driver->privileged ?
972 973 974
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
975
            virReportOOMError();
976 977 978 979 980 981 982 983 984 985
            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;
986 987


988
        /* Check path and tell them correct path if they made a mistake */
989
        if (uml_driver->privileged) {
990
            if (STRNEQ (conn->uri->path, "/system") &&
991
                STRNEQ (conn->uri->path, "/session")) {
992
                umlReportError(VIR_ERR_INTERNAL_ERROR,
993 994 995 996 997 998
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
999
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1000 1001 1002 1003
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1004
        }
1005 1006 1007

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1008
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1009
                           _("uml state driver is not active"));
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1020
    /*struct uml_driver *driver = conn->privateData;*/
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    conn->privateData = NULL;

    return 0;
}

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


1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
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;
}


1046 1047 1048 1049
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1050
    umlDriverLock(driver);
1051
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1052
        virReportOOMError();
1053
    umlDriverUnlock(driver);
1054 1055 1056 1057 1058 1059

    return xml;
}



1060 1061 1062
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1063 1064 1065
    FILE *pidinfo;
    unsigned long long usertime, systime;

1066
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1067 1068 1069 1070 1071 1072
        return -1;
    }

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

1077 1078
    VIR_FREE(proc);

1079 1080
    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");
1081
        VIR_FORCE_FCLOSE(pidinfo);
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        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);

1094
    VIR_FORCE_FCLOSE(pidinfo);
1095 1096 1097 1098 1099 1100 1101 1102

    return 0;
}


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

1106
    umlDriverLock(driver);
1107
    vm = virDomainFindByID(&driver->domains, id);
1108 1109
    umlDriverUnlock(driver);

1110
    if (!vm) {
1111
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1112
        goto cleanup;
1113 1114 1115 1116
    }

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

cleanup:
1119 1120
    if (vm)
        virDomainObjUnlock(vm);
1121 1122
    return dom;
}
1123

1124 1125 1126
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1127 1128
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1129

1130
    umlDriverLock(driver);
1131
    vm = virDomainFindByUUID(&driver->domains, uuid);
1132 1133
    umlDriverUnlock(driver);

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

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

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

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

1154
    umlDriverLock(driver);
1155
    vm = virDomainFindByName(&driver->domains, name);
1156 1157
    umlDriverUnlock(driver);

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

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

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

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

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) {
1183
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        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) {
1205
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
        goto cleanup;
    }
    ret = obj->persistent;

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

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
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;
}
1236

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

1242
    umlDriverLock(driver);
1243 1244 1245 1246

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

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

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

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

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

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

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

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

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

1289 1290
    virCheckFlags(0, NULL);

1291
    umlDriverLock(driver);
1292
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1293
                                        1 << VIR_DOMAIN_VIRT_UML,
1294
                                        VIR_DOMAIN_XML_INACTIVE)))
1295
        goto cleanup;
1296

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

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

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
1307
        virDomainAuditStart(vm, "booted", false);
1308 1309
        virDomainRemoveInactive(&driver->domains,
                                vm);
1310 1311
        vm = NULL;
        goto cleanup;
1312
    }
1313
    virDomainAuditStart(vm, "booted", true);
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
        umlReportError(VIR_ERR_NO_DOMAIN,
1338
                       _("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
        umlReportError(VIR_ERR_NO_DOMAIN,
1368
                       _("no domain with matching id %d"), dom->id);
1369
        goto cleanup;
1370 1371
    }

J
Jiri Denemark 已提交
1372
    umlShutdownVMDaemon(dom->conn, driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1373
    virDomainAuditStop(vm, "destroyed");
1374
    if (!vm->persistent) {
1375 1376
        virDomainRemoveInactive(&driver->domains,
                                vm);
1377 1378 1379
        vm = NULL;
    }
    ret = 0;
1380

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


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

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

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

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

/* Returns max memory in kb, 0 if error */
static unsigned long umlDomainGetMaxMemory(virDomainPtr dom) {
1414 1415 1416
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
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 1428
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1429
    }
1430
    ret = vm->def->mem.max_balloon;
1431

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

J
Jiri Denemark 已提交
1526
    info->state = virDomainObjGetState(vm, NULL);
1527

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

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

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


1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
static int
umlDomainGetState(virDomainPtr dom,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

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

    if (!vm) {
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
        goto cleanup;
    }

J
Jiri Denemark 已提交
1572
    *state = virDomainObjGetState(vm, reason);
1573 1574 1575 1576 1577 1578 1579 1580 1581
    ret = 0;

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


1582
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1583 1584
                                 unsigned int flags)
{
1585 1586 1587 1588
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

E
Eric Blake 已提交
1589 1590 1591 1592
    virCheckFlags(VIR_DOMAIN_XML_SECURE |
                  VIR_DOMAIN_XML_INACTIVE |
                  VIR_DOMAIN_XML_UPDATE_CPU, NULL);

1593
    umlDriverLock(driver);
1594
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1595 1596
    umlDriverUnlock(driver);

1597
    if (!vm) {
1598
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1599
                       _("no domain with matching uuid"));
1600
        goto cleanup;
1601 1602
    }

1603
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1604 1605 1606 1607
                             vm->newDef : vm->def,
                             flags);

cleanup:
1608 1609
    if (vm)
        virDomainObjUnlock(vm);
1610
    return ret;
1611 1612 1613 1614 1615
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1616
    struct uml_driver *driver = conn->privateData;
1617
    int n;
1618

1619
    umlDriverLock(driver);
1620
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1621
    umlDriverUnlock(driver);
1622

1623
    return n;
1624 1625 1626
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1627
    struct uml_driver *driver = conn->privateData;
1628
    int n;
1629

1630
    umlDriverLock(driver);
1631
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1632
    umlDriverUnlock(driver);
1633 1634 1635 1636 1637

    return n;
}


1638
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1639 1640 1641
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1642

1643 1644
    virCheckFlags(0, -1);

1645
    umlDriverLock(driver);
1646
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1647

1648
    if (!vm) {
1649
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1650
                       _("no domain with matching uuid"));
1651
        goto cleanup;
1652 1653
    }

1654
    ret = umlStartVMDaemon(dom->conn, driver, vm);
1655
    virDomainAuditStart(vm, "booted", ret >= 0);
1656 1657

cleanup:
1658 1659 1660
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1661
    return ret;
1662 1663
}

1664 1665 1666
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1667 1668

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1669
    struct uml_driver *driver = conn->privateData;
1670
    virDomainDefPtr def;
1671
    virDomainObjPtr vm = NULL;
1672
    virDomainPtr dom = NULL;
1673

1674
    umlDriverLock(driver);
1675
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1676
                                        1 << VIR_DOMAIN_VIRT_UML,
1677
                                        VIR_DOMAIN_XML_INACTIVE)))
1678
        goto cleanup;
1679

1680 1681 1682
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1683
    if (!(vm = virDomainAssignDef(driver->caps,
1684
                                  &driver->domains,
1685
                                  def, false)))
1686 1687
        goto cleanup;
    def = NULL;
1688 1689
    vm->persistent = 1;

1690
    if (virDomainSaveConfig(driver->configDir,
1691 1692 1693
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1694
        vm = NULL;
1695
        goto cleanup;
1696 1697 1698 1699
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1700 1701 1702

cleanup:
    virDomainDefFree(def);
1703 1704 1705
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1706 1707 1708 1709
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1710 1711 1712
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1713

1714
    umlDriverLock(driver);
1715
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1716
    if (!vm) {
1717
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1718
                       _("no domain with matching uuid"));
1719
        goto cleanup;
1720 1721
    }

D
Daniel P. Berrange 已提交
1722
    if (virDomainObjIsActive(vm)) {
1723
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1724
                       _("cannot delete active domain"));
1725
        goto cleanup;
1726 1727 1728
    }

    if (!vm->persistent) {
1729
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1730
                       _("cannot undefine transient domain"));
1731
        goto cleanup;
1732 1733
    }

1734
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1735
        goto cleanup;
1736 1737 1738

    virDomainRemoveInactive(&driver->domains,
                            vm);
1739
    vm = NULL;
1740
    ret = 0;
1741

1742
cleanup:
1743 1744 1745
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1746
    return ret;
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
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) {
1861
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
        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) {
1969
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1970 1971 1972 1973 1974 1975 1976 1977
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1978 1979 1980

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1981 1982 1983
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1984

1985
    umlDriverLock(driver);
1986
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1987

1988
    if (!vm) {
1989
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1990
                       _("no domain with matching uuid"));
1991
        goto cleanup;
1992 1993 1994
    }

    *autostart = vm->autostart;
1995
    ret = 0;
1996

1997
cleanup:
1998 1999
    if (vm)
        virDomainObjUnlock(vm);
2000
    umlDriverUnlock(driver);
2001
    return ret;
2002 2003 2004 2005
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2006
    struct uml_driver *driver = dom->conn->privateData;
2007
    virDomainObjPtr vm;
2008 2009 2010
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2011 2012 2013
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

2014
    if (!vm) {
2015
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2016
                       _("no domain with matching uuid"));
2017
        goto cleanup;
2018 2019 2020
    }

    if (!vm->persistent) {
2021
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
2022
                       _("cannot set autostart for transient domain"));
2023
        goto cleanup;
2024 2025 2026 2027
    }

    autostart = (autostart != 0);

2028
    if (vm->autostart != autostart) {
2029
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2030
            goto cleanup;
2031
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2032
            goto cleanup;
2033

2034
        if (autostart) {
2035 2036
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2037 2038
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2039 2040
                goto cleanup;
            }
2041

2042
            if (symlink(configFile, autostartLink) < 0) {
2043
                virReportSystemError(errno,
2044 2045
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2046 2047 2048 2049
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2050
                virReportSystemError(errno,
2051 2052
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2053 2054
                goto cleanup;
            }
2055 2056
        }

2057
        vm->autostart = autostart;
2058 2059 2060 2061 2062 2063
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2064 2065
    if (vm)
        virDomainObjUnlock(vm);
2066
    umlDriverUnlock(driver);
2067 2068 2069 2070 2071
    return ret;
}


static int
2072 2073 2074 2075
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2076
                   unsigned int flags)
2077
{
2078 2079 2080
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2081

E
Eric Blake 已提交
2082 2083
    virCheckFlags(0, -1);

2084
    umlDriverLock(driver);
2085
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2086 2087
    umlDriverUnlock(driver);

2088
    if (!vm) {
2089
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2090
                       _("no domain with matching uuid"));
2091
        goto cleanup;
2092 2093 2094
    }

    if (!path || path[0] == '\0') {
2095 2096
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2097
        goto cleanup;
2098 2099 2100 2101 2102
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2103 2104 2105 2106
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2107 2108
    }

2109 2110 2111 2112 2113
    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) {
2114
            virReportSystemError(errno,
2115
                                 _("cannot open %s"), path);
2116 2117
            goto cleanup;
        }
2118

2119 2120 2121 2122 2123 2124
        /* 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) {
2125
            virReportSystemError(errno,
2126
                                 _("cannot read %s"), path);
2127 2128 2129 2130 2131
            goto cleanup;
        }

        ret = 0;
    } else {
2132 2133
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2134 2135
    }

2136
cleanup:
2137
    VIR_FORCE_CLOSE(fd);
2138 2139
    if (vm)
        virDomainObjUnlock(vm);
2140 2141 2142 2143
    return ret;
}


2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
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;
    }

2191
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2192 2193 2194 2195 2196
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

2197 2198
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
        goto cleanup;

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

2209 2210

static virDriver umlDriver = {
2211 2212
    .no = VIR_DRV_UML,
    .name = "UML",
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
    .open = umlOpen, /* 0.5.0 */
    .close = umlClose, /* 0.5.0 */
    .type = umlGetType, /* 0.5.0 */
    .version = umlGetVersion, /* 0.5.0 */
    .getHostname = virGetHostname, /* 0.5.0 */
    .nodeGetInfo = nodeGetInfo, /* 0.5.0 */
    .getCapabilities = umlGetCapabilities, /* 0.5.0 */
    .listDomains = umlListDomains, /* 0.5.0 */
    .numOfDomains = umlNumDomains, /* 0.5.0 */
    .domainCreateXML = umlDomainCreate, /* 0.5.0 */
    .domainLookupByID = umlDomainLookupByID, /* 0.5.0 */
    .domainLookupByUUID = umlDomainLookupByUUID, /* 0.5.0 */
    .domainLookupByName = umlDomainLookupByName, /* 0.5.0 */
    .domainShutdown = umlDomainShutdown, /* 0.5.0 */
    .domainDestroy = umlDomainDestroy, /* 0.5.0 */
    .domainGetOSType = umlDomainGetOSType, /* 0.5.0 */
    .domainGetMaxMemory = umlDomainGetMaxMemory, /* 0.5.0 */
    .domainSetMaxMemory = umlDomainSetMaxMemory, /* 0.5.0 */
    .domainSetMemory = umlDomainSetMemory, /* 0.5.0 */
    .domainGetInfo = umlDomainGetInfo, /* 0.5.0 */
    .domainGetState = umlDomainGetState, /* 0.9.2 */
    .domainGetXMLDesc = umlDomainGetXMLDesc, /* 0.5.0 */
    .listDefinedDomains = umlListDefinedDomains, /* 0.5.0 */
    .numOfDefinedDomains = umlNumDefinedDomains, /* 0.5.0 */
    .domainCreate = umlDomainStart, /* 0.5.0 */
    .domainCreateWithFlags = umlDomainStartWithFlags, /* 0.8.2 */
    .domainDefineXML = umlDomainDefine, /* 0.5.0 */
    .domainUndefine = umlDomainUndefine, /* 0.5.0 */
    .domainAttachDevice = umlDomainAttachDevice, /* 0.8.4 */
    .domainAttachDeviceFlags = umlDomainAttachDeviceFlags, /* 0.8.4 */
    .domainDetachDevice = umlDomainDetachDevice, /* 0.8.4 */
    .domainDetachDeviceFlags = umlDomainDetachDeviceFlags, /* 0.8.4 */
    .domainGetAutostart = umlDomainGetAutostart, /* 0.5.0 */
    .domainSetAutostart = umlDomainSetAutostart, /* 0.5.0 */
    .domainBlockPeek = umlDomainBlockPeek, /* 0.5.0 */
2248
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2249
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2250 2251 2252 2253 2254 2255 2256 2257
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.5.0 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.5.0 */
    .isEncrypted = umlIsEncrypted, /* 0.7.3 */
    .isSecure = umlIsSecure, /* 0.7.3 */
    .domainIsActive = umlDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = umlDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = umlDomainIsUpdated, /* 0.8.6 */
    .domainOpenConsole = umlDomainOpenConsole, /* 0.8.6 */
2258 2259
};

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

    return 0;
}
2268 2269

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

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

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

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

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