uml_driver.c 61.8 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-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 123 124 125
                          virDomainObjPtr vm);

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

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

static void umlShutdownVMDaemon(virConnectPtr conn,
                                struct uml_driver *driver,
J
Jiri Denemark 已提交
136 137
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason);
138 139


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

static struct uml_driver *uml_driver = NULL;

147 148 149 150 151 152
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
153
umlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
154 155 156 157 158 159
{
    virDomainObjPtr vm = payload;
    const struct umlAutostartData *data = opaque;

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

static void
umlAutostartConfigs(struct uml_driver *driver) {
176 177 178 179 180
    /* 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
     */
181 182 183
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
184
    /* Ignoring NULL conn which is mostly harmless here */
185

186 187 188
    struct umlAutostartData data = { driver, conn };

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

190 191
    if (conn)
        virConnectClose(conn);
192 193 194 195
}


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

212
    if (res && STRPREFIX(res, "pts:")) {
213 214
        VIR_FREE(def->source.data.file.path);
        if ((def->source.data.file.path = strdup(res + 4)) == NULL) {
215
            virReportOOMError();
216 217 218 219
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
220
    } else if (!res || STRPREFIX(res, "pts")) {
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        /* 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
237
umlIdentifyChrPTY(struct uml_driver *driver,
238 239 240 241 242
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
243
        dom->def->console->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
244
        if (umlIdentifyOneChrPTY(driver, dom,
245 246 247 248
                                 dom->def->console, "con") < 0)
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
249
        if (dom->def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
250
            umlIdentifyOneChrPTY(driver, dom,
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                                 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;

270
    umlDriverLock(driver);
271
    if (watch != driver->inotifyWatch)
272
        goto cleanup;
273 274 275 276 277 278

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
279
        goto cleanup;
280 281 282 283 284
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
285
            goto cleanup; /* bad */
286 287 288 289 290 291

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

        if (got < e->len)
292
            goto cleanup;
293 294 295 296 297 298 299 300 301 302 303 304 305

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

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

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

        if (!dom) {
            continue;
        }

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

J
Jiri Denemark 已提交
312
            umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
313
            virDomainAuditStop(dom, "shutdown");
314 315 316 317 318
            if (!dom->persistent) {
                virDomainRemoveInactive(&driver->domains,
                                        dom);
                dom = NULL;
            }
319
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
320
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
321
            if (virDomainObjIsActive(dom)) {
322
                virDomainObjUnlock(dom);
323 324 325
                continue;
            }

326
            if (umlReadPidFile(driver, dom) < 0) {
327
                virDomainObjUnlock(dom);
328 329 330 331
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
332 333
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
334

335
            if (umlOpenMonitor(driver, dom) < 0) {
336
                VIR_WARN("Could not open monitor for new domain");
J
Jiri Denemark 已提交
337 338
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
339
                virDomainAuditStop(dom, "failed");
340 341 342 343 344
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
345
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
346
                VIR_WARN("Could not identify character devices for new domain");
J
Jiri Denemark 已提交
347 348
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
349
                virDomainAuditStop(dom, "failed");
350 351 352 353 354
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
355
            }
356
        }
357 358
        if (dom)
            virDomainObjUnlock(dom);
359
    }
360 361 362

cleanup:
    umlDriverUnlock(driver);
363 364 365 366 367 368 369 370
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
371 372
umlStartup(int privileged)
{
373 374
    uid_t uid = geteuid();
    char *base = NULL;
375
    char *userdir = NULL;
376 377 378 379

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

380 381
    uml_driver->privileged = privileged;

382 383 384 385
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
386 387
    umlDriverLock(uml_driver);

388 389
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
390
    uml_driver->inotifyWatch = -1;
391

392 393 394
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

395
    userdir = virGetUserDirectory(uid);
396
    if (!userdir)
397
        goto error;
398

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

404
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
405
            goto out_of_memory;
406 407

        if (virAsprintf(&uml_driver->monitorDir,
408
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
409
            goto out_of_memory;
410
    } else {
411

412
        if (virAsprintf(&uml_driver->logDir,
413
                        "%s/.libvirt/uml/log", userdir) == -1)
414 415
            goto out_of_memory;

416
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
417 418
            goto out_of_memory;

419 420 421 422
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
423 424 425 426

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

430
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
431 432 433 434 435 436 437
        goto out_of_memory;

    VIR_FREE(base);

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

438 439
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
440 441

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
442
        VIR_ERROR(_("cannot initialize inotify"));
443
        goto error;
444 445
    }

446
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
447
        char ebuf[1024];
D
Daniel Veillard 已提交
448
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
449
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
450
        goto error;
451 452
    }

453
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
454 455 456
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
457
        goto error;
458 459
    }

460 461
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
462 463
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
464

465
    if (virDomainLoadAllConfigs(uml_driver->caps,
466 467 468
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
469 470
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
471 472
        goto error;

473 474
    umlAutostartConfigs(uml_driver);

475
    umlDriverUnlock(uml_driver);
476 477
    VIR_FREE(userdir);

478 479
    return 0;

480
out_of_memory:
481
    VIR_ERROR(_("umlStartup: out of memory"));
482 483

error:
484
    VIR_FREE(userdir);
485
    VIR_FREE(base);
486 487
    umlDriverUnlock(uml_driver);
    umlShutdown();
488 489 490 491 492 493 494 495 496 497 498 499 500 501
    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;

502
    umlDriverLock(uml_driver);
503
    virDomainLoadAllConfigs(uml_driver->caps,
504 505 506
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
507 508
                            0, 1 << VIR_DOMAIN_VIRT_UML,
                            NULL, NULL);
509 510

    umlAutostartConfigs(uml_driver);
511
    umlDriverUnlock(uml_driver);
512 513 514 515 516 517 518 519 520 521 522 523 524 525

    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) {
526
    int active = 0;
527 528 529 530

    if (!uml_driver)
        return 0;

531
    umlDriverLock(uml_driver);
532
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
533
    umlDriverUnlock(uml_driver);
534

535
    return active;
536 537
}

538
static void
539
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
540 541 542 543 544
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
545
    if (virDomainObjIsActive(dom)) {
J
Jiri Denemark 已提交
546
        umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
547 548
        virDomainAuditStop(dom, "shutdown");
    }
549 550 551
    virDomainObjUnlock(dom);
}

552 553 554 555 556 557 558 559 560 561
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

562
    umlDriverLock(uml_driver);
563 564
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
565
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
566 567
    virCapabilitiesFree(uml_driver->caps);

568 569 570
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
571

572
    virDomainObjListDeinit(&uml_driver->domains);
573 574 575 576 577 578 579 580 581

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

582
    umlDriverUnlock(uml_driver);
583
    virMutexDestroy(&uml_driver->lock);
584 585 586 587 588 589
    VIR_FREE(uml_driver);

    return 0;
}


590
static int umlReadPidFile(struct uml_driver *driver,
591 592 593 594 595 596 597 598
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
599 600
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
601
        virReportOOMError();
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        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;
617
        VIR_FORCE_FCLOSE(file);
618 619 620
        goto cleanup;
    }

621
    if (VIR_FCLOSE(file) < 0)
622 623 624 625 626 627
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
628
        virReportSystemError(errno,
629 630
                             _("failed to read pid: %s"),
                             pidfile);
631 632 633 634
    VIR_FREE(pidfile);
    return rc;
}

635
static int umlMonitorAddress(const struct uml_driver *driver,
636 637 638
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
639
    int retval = 0;
640

641 642
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
643
        virReportOOMError();
644 645 646 647 648
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
649
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
650
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
651 652 653
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
654
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
655
    return retval;
656 657
}

658
static int umlOpenMonitor(struct uml_driver *driver,
659 660 661 662
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
663
    umlDomainObjPrivatePtr priv = vm->privateData;
664

665
    if (umlMonitorAddress(driver, vm, &addr) < 0)
666 667
        return -1;

668
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
669 670 671
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
672
            retries++ < 50) {
673 674 675 676 677 678
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

679
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
680
        virReportSystemError(errno,
681
                             "%s", _("cannot open socket"));
682 683 684 685
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
E
Eric Blake 已提交
686 687
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
688
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
689
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
690
        virReportSystemError(errno,
691
                             "%s", _("cannot bind socket"));
692
        VIR_FORCE_CLOSE(priv->monitor);
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        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];
};


719
static int umlMonitorCommand(const struct uml_driver *driver,
720 721 722 723 724 725 726 727 728 729
                             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;
730
    umlDomainObjPrivatePtr priv = vm->privateData;
731

732 733
    VIR_DEBUG("Run command '%s'", cmd);

734 735
    *reply = NULL;

736
    if (umlMonitorAddress(driver, vm, &addr) < 0)
737 738 739 740 741 742 743
        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)) {
744
        virReportSystemError(EINVAL,
745 746
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
747 748
        return -1;
    }
C
Chris Lalancette 已提交
749
    if (virStrcpyStatic(req.data, cmd) == NULL) {
750
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
751 752 753
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
754

755
    if (sendto(priv->monitor, &req, sizeof req, 0,
756
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
757
        virReportSystemError(errno,
758 759
                             _("cannot send command %s"),
                             cmd);
760 761 762 763
        return -1;
    }

    do {
E
Eric Blake 已提交
764
        ssize_t nbytes;
765
        addrlen = sizeof(addr);
E
Eric Blake 已提交
766
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
767
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
768 769 770
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
771
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
772 773
            goto error;
        }
774 775 776
        /* 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) {
777 778 779
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
780 781

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
782
            virReportOOMError();
783 784 785 786 787 788 789 790 791 792 793
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

794 795
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

796 797 798 799
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
800 801 802 803 804 805 806 807 808

    return ret;

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


809 810 811 812 813 814
static int umlCleanupTapDevices(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm) {
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
815
    VIR_ERROR(_("Cleanup tap"));
816 817 818 819 820 821 822 823 824 825
    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;

826
        VIR_ERROR(_("Cleanup '%s'"), def->ifname);
827 828
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
829
            VIR_ERROR(_("Cleanup failed %d"), err);
830 831 832
            ret = -1;
        }
    }
833
    VIR_ERROR(_("Cleanup tap done"));
834 835 836 837
    brShutdown(brctl);
    return ret;
}

838 839 840
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
D
Daniel P. Berrange 已提交
841
    int ret;
842 843
    char *logfile;
    int logfd = -1;
844
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
845
    virCommandPtr cmd = NULL;
846

D
Daniel P. Berrange 已提交
847
    if (virDomainObjIsActive(vm)) {
848
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
849
                       _("VM is already active"));
850 851 852 853
        return -1;
    }

    if (!vm->def->os.kernel) {
854 855
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
856 857 858 859 860 861
        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 已提交
862
    if (!virFileIsExecutable(vm->def->os.kernel)) {
863
        virReportSystemError(errno,
864 865
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
866 867 868
        return -1;
    }

869
    if (virFileMakePath(driver->logDir) < 0) {
870
        virReportSystemError(errno,
871 872
                             _("cannot create log directory %s"),
                             driver->logDir);
873 874 875
        return -1;
    }

876 877
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
878
        virReportOOMError();
879 880 881 882 883
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
884
        virReportSystemError(errno,
885 886
                             _("failed to create logfile %s"),
                             logfile);
887 888 889 890 891 892
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

    if (umlSetCloseExec(logfd) < 0) {
893
        virReportSystemError(errno,
894
                             "%s", _("Unable to set VM logfile close-on-exec flag"));
895
        VIR_FORCE_CLOSE(logfd);
896 897 898
        return -1;
    }

D
Daniel P. Berrange 已提交
899
    if (!(cmd = umlBuildCommandLine(conn, driver, vm))) {
900
        VIR_FORCE_CLOSE(logfd);
901
        virDomainConfVMNWFilterTeardown(vm);
902
        umlCleanupTapDevices(conn, vm);
903 904 905
        return -1;
    }

D
Daniel P. Berrange 已提交
906
    virCommandWriteArgLog(cmd, logfd);
907

908
    priv->monitor = -1;
909

D
Daniel P. Berrange 已提交
910 911 912 913 914 915
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
916
    VIR_FORCE_CLOSE(logfd);
917 918
    if (ret < 0)
        goto cleanup;
919

920
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
921
cleanup:
D
Daniel P. Berrange 已提交
922
    virCommandFree(cmd);
923

924 925
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
926
        umlCleanupTapDevices(conn, vm);
927 928
    }

929 930
    /* NB we don't mark it running here - we do that async
       with inotify */
931 932 933
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
934 935 936 937 938 939

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
J
Jiri Denemark 已提交
940 941
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
942 943
{
    int ret;
944 945
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
946
    if (!virDomainObjIsActive(vm))
947 948
        return;

949
    virKillProcess(vm->pid, SIGTERM);
950

951
    VIR_FORCE_CLOSE(priv->monitor);
952 953

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
954
        VIR_WARN("Got unexpected pid %d != %d",
955 956 957 958 959
               ret, vm->pid);
    }

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

962
    virDomainConfVMNWFilterTeardown(vm);
963 964
    umlCleanupTapDevices(conn, vm);

965 966 967 968 969 970 971 972 973 974 975
    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 已提交
976 977 978 979
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

980 981 982
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
983

984
        conn->uri = xmlParseURI(uml_driver->privileged ?
985 986 987
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
988
            virReportOOMError();
989 990 991 992 993 994 995 996 997 998
            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;
999 1000


1001
        /* Check path and tell them correct path if they made a mistake */
1002
        if (uml_driver->privileged) {
1003
            if (STRNEQ (conn->uri->path, "/system") &&
1004
                STRNEQ (conn->uri->path, "/session")) {
1005
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1006 1007 1008 1009 1010 1011
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1012
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1013 1014 1015 1016
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1017
        }
1018 1019 1020

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1021
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1022
                           _("uml state driver is not active"));
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1033
    /*struct uml_driver *driver = conn->privateData;*/
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

    conn->privateData = NULL;

    return 0;
}

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


1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
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;
}


1059 1060 1061 1062
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1063
    umlDriverLock(driver);
1064
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1065
        virReportOOMError();
1066
    umlDriverUnlock(driver);
1067 1068 1069 1070 1071 1072

    return xml;
}



1073 1074 1075
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1076 1077 1078
    FILE *pidinfo;
    unsigned long long usertime, systime;

1079
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1080 1081 1082 1083 1084 1085
        return -1;
    }

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

1090 1091
    VIR_FREE(proc);

1092 1093
    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");
1094
        VIR_FORCE_FCLOSE(pidinfo);
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        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);

1107
    VIR_FORCE_FCLOSE(pidinfo);
1108 1109 1110 1111 1112 1113 1114 1115

    return 0;
}


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

1119
    umlDriverLock(driver);
1120
    vm = virDomainFindByID(&driver->domains, id);
1121 1122
    umlDriverUnlock(driver);

1123
    if (!vm) {
1124
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1125
        goto cleanup;
1126 1127 1128 1129
    }

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

cleanup:
1132 1133
    if (vm)
        virDomainObjUnlock(vm);
1134 1135
    return dom;
}
1136

1137 1138 1139
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1140 1141
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1142

1143
    umlDriverLock(driver);
1144
    vm = virDomainFindByUUID(&driver->domains, uuid);
1145 1146
    umlDriverUnlock(driver);

1147
    if (!vm) {
1148
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1149
        goto cleanup;
1150 1151 1152 1153
    }

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

cleanup:
1156 1157
    if (vm)
        virDomainObjUnlock(vm);
1158 1159
    return dom;
}
1160

1161 1162 1163
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1164 1165
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1166

1167
    umlDriverLock(driver);
1168
    vm = virDomainFindByName(&driver->domains, name);
1169 1170
    umlDriverUnlock(driver);

1171
    if (!vm) {
1172
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1173
        goto cleanup;
1174 1175 1176 1177
    }

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

cleanup:
1180 1181
    if (vm)
        virDomainObjUnlock(vm);
1182 1183 1184
    return dom;
}

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195

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) {
1196
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        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) {
1218
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
        goto cleanup;
    }
    ret = obj->persistent;

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

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
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;
}
1249

1250
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1251
    struct uml_driver *driver = conn->privateData;
1252
    struct utsname ut;
1253
    int ret = -1;
1254

1255
    umlDriverLock(driver);
1256 1257 1258 1259

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

1260
        if (virParseVersionString(ut.release, &driver->umlVersion, true) < 0) {
1261
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1262 1263 1264
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1265 1266
    }

1267 1268 1269 1270 1271 1272
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1273 1274 1275
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1276
    struct uml_driver *driver = conn->privateData;
1277
    int n;
1278

1279
    umlDriverLock(driver);
1280
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1281
    umlDriverUnlock(driver);
1282

1283
    return n;
1284 1285
}
static int umlNumDomains(virConnectPtr conn) {
1286
    struct uml_driver *driver = conn->privateData;
1287
    int n;
1288

1289
    umlDriverLock(driver);
1290
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1291
    umlDriverUnlock(driver);
1292 1293 1294 1295

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1296
                                      unsigned int flags) {
1297
    struct uml_driver *driver = conn->privateData;
1298
    virDomainDefPtr def;
1299
    virDomainObjPtr vm = NULL;
1300
    virDomainPtr dom = NULL;
1301

1302 1303
    virCheckFlags(0, NULL);

1304
    umlDriverLock(driver);
1305
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1306
                                        1 << VIR_DOMAIN_VIRT_UML,
1307
                                        VIR_DOMAIN_XML_INACTIVE)))
1308
        goto cleanup;
1309

1310
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1311
        goto cleanup;
1312

1313
    if (!(vm = virDomainAssignDef(driver->caps,
1314
                                  &driver->domains,
1315
                                  def, false)))
1316 1317
        goto cleanup;
    def = NULL;
1318 1319

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
1320
        virDomainAuditStart(vm, "booted", false);
1321 1322
        virDomainRemoveInactive(&driver->domains,
                                vm);
1323 1324
        vm = NULL;
        goto cleanup;
1325
    }
1326
    virDomainAuditStart(vm, "booted", true);
1327 1328 1329

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1330 1331 1332

cleanup:
    virDomainDefFree(def);
1333 1334 1335
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1336 1337 1338 1339 1340
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1341 1342
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1343
    char *info = NULL;
1344
    int ret = -1;
1345

1346
    umlDriverLock(driver);
1347
    vm = virDomainFindByID(&driver->domains, dom->id);
1348
    umlDriverUnlock(driver);
1349
    if (!vm) {
1350
        umlReportError(VIR_ERR_NO_DOMAIN,
1351
                       _("no domain with matching id %d"), dom->id);
1352
        goto cleanup;
1353 1354 1355 1356
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1357 1358
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1359
        goto cleanup;
1360
    }
1361
    ret = 0;
1362 1363
#endif

1364 1365
cleanup:
    VIR_FREE(info);
1366 1367
    if (vm)
        virDomainObjUnlock(vm);
1368
    return ret;
1369 1370 1371 1372
}


static int umlDomainDestroy(virDomainPtr dom) {
1373 1374 1375
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1376

1377
    umlDriverLock(driver);
1378
    vm = virDomainFindByID(&driver->domains, dom->id);
1379
    if (!vm) {
1380
        umlReportError(VIR_ERR_NO_DOMAIN,
1381
                       _("no domain with matching id %d"), dom->id);
1382
        goto cleanup;
1383 1384
    }

J
Jiri Denemark 已提交
1385
    umlShutdownVMDaemon(dom->conn, driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1386
    virDomainAuditStop(vm, "destroyed");
1387
    if (!vm->persistent) {
1388 1389
        virDomainRemoveInactive(&driver->domains,
                                vm);
1390 1391 1392
        vm = NULL;
    }
    ret = 0;
1393

1394
cleanup:
1395 1396 1397
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1398
    return ret;
1399 1400 1401 1402
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1403 1404 1405
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1406

1407
    umlDriverLock(driver);
1408
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1409
    umlDriverUnlock(driver);
1410
    if (!vm) {
1411
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1412
                       _("no domain with matching uuid"));
1413
        goto cleanup;
1414 1415
    }

1416
    if (!(type = strdup(vm->def->os.type)))
1417
        virReportOOMError();
1418 1419

cleanup:
1420 1421
    if (vm)
        virDomainObjUnlock(vm);
1422 1423 1424 1425 1426
    return type;
}

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

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

1435 1436 1437 1438
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1439
        umlReportError(VIR_ERR_NO_DOMAIN,
1440 1441
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1442
    }
1443
    ret = vm->def->mem.max_balloon;
1444

1445
cleanup:
1446 1447
    if (vm)
        virDomainObjUnlock(vm);
1448
    return ret;
1449 1450 1451
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1452 1453 1454
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1455

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

1460 1461 1462 1463
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1464
        umlReportError(VIR_ERR_NO_DOMAIN,
1465
                       _("no domain with matching uuid '%s'"), uuidstr);
1466
        goto cleanup;
1467 1468
    }

1469
    if (newmax < vm->def->mem.cur_balloon) {
1470 1471
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1472
        goto cleanup;
1473 1474
    }

1475
    vm->def->mem.max_balloon = newmax;
1476 1477 1478
    ret = 0;

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

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1485 1486 1487
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1488

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

1493 1494 1495 1496
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1497
        umlReportError(VIR_ERR_NO_DOMAIN,
1498
                       _("no domain with matching uuid '%s'"), uuidstr);
1499
        goto cleanup;
1500 1501
    }

D
Daniel P. Berrange 已提交
1502
    if (virDomainObjIsActive(vm)) {
1503
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1504
                       _("cannot set memory of an active domain"));
1505
        goto cleanup;
1506 1507
    }

1508
    if (newmem > vm->def->mem.max_balloon) {
1509 1510
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1511
        goto cleanup;
1512 1513
    }

1514
    vm->def->mem.cur_balloon = newmem;
1515 1516 1517
    ret = 0;

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

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1525 1526 1527 1528
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

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

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

D
Daniel P. Berrange 已提交
1541
    if (!virDomainObjIsActive(vm)) {
1542 1543 1544
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1545 1546
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1547
            goto cleanup;
1548 1549 1550
        }
    }

1551 1552
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1553
    info->nrVirtCpu = vm->def->vcpus;
1554 1555 1556
    ret = 0;

cleanup:
1557 1558
    if (vm)
        virDomainObjUnlock(vm);
1559
    return ret;
1560 1561 1562
}


1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
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 已提交
1585
    *state = virDomainObjGetState(vm, reason);
1586 1587 1588 1589 1590 1591 1592 1593 1594
    ret = 0;

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


1595
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1596 1597
                                 unsigned int flags)
{
1598 1599 1600 1601
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

E
Eric Blake 已提交
1602 1603 1604 1605
    virCheckFlags(VIR_DOMAIN_XML_SECURE |
                  VIR_DOMAIN_XML_INACTIVE |
                  VIR_DOMAIN_XML_UPDATE_CPU, NULL);

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

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

1616
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1617 1618 1619 1620
                             vm->newDef : vm->def,
                             flags);

cleanup:
1621 1622
    if (vm)
        virDomainObjUnlock(vm);
1623
    return ret;
1624 1625 1626 1627 1628
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1629
    struct uml_driver *driver = conn->privateData;
1630
    int n;
1631

1632
    umlDriverLock(driver);
1633
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1634
    umlDriverUnlock(driver);
1635

1636
    return n;
1637 1638 1639
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1640
    struct uml_driver *driver = conn->privateData;
1641
    int n;
1642

1643
    umlDriverLock(driver);
1644
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1645
    umlDriverUnlock(driver);
1646 1647 1648 1649 1650

    return n;
}


1651
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1652 1653 1654
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1655

1656 1657
    virCheckFlags(0, -1);

1658
    umlDriverLock(driver);
1659
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1660

1661
    if (!vm) {
1662
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1663
                       _("no domain with matching uuid"));
1664
        goto cleanup;
1665 1666
    }

1667
    ret = umlStartVMDaemon(dom->conn, driver, vm);
1668
    virDomainAuditStart(vm, "booted", ret >= 0);
1669 1670

cleanup:
1671 1672 1673
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1674
    return ret;
1675 1676
}

1677 1678 1679
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1680 1681

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1682
    struct uml_driver *driver = conn->privateData;
1683
    virDomainDefPtr def;
1684
    virDomainObjPtr vm = NULL;
1685
    virDomainPtr dom = NULL;
1686

1687
    umlDriverLock(driver);
1688
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1689
                                        1 << VIR_DOMAIN_VIRT_UML,
1690
                                        VIR_DOMAIN_XML_INACTIVE)))
1691
        goto cleanup;
1692

1693 1694 1695
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1696
    if (!(vm = virDomainAssignDef(driver->caps,
1697
                                  &driver->domains,
1698
                                  def, false)))
1699 1700
        goto cleanup;
    def = NULL;
1701 1702
    vm->persistent = 1;

1703
    if (virDomainSaveConfig(driver->configDir,
1704 1705 1706
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1707
        vm = NULL;
1708
        goto cleanup;
1709 1710 1711 1712
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1713 1714 1715

cleanup:
    virDomainDefFree(def);
1716 1717 1718
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1719 1720 1721 1722
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1723 1724 1725
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1726

1727
    umlDriverLock(driver);
1728
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1729
    if (!vm) {
1730
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1731
                       _("no domain with matching uuid"));
1732
        goto cleanup;
1733 1734
    }

D
Daniel P. Berrange 已提交
1735
    if (virDomainObjIsActive(vm)) {
1736
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1737
                       _("cannot delete active domain"));
1738
        goto cleanup;
1739 1740 1741
    }

    if (!vm->persistent) {
1742
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1743
                       _("cannot undefine transient domain"));
1744
        goto cleanup;
1745 1746
    }

1747
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1748
        goto cleanup;
1749 1750 1751

    virDomainRemoveInactive(&driver->domains,
                            vm);
1752
    vm = NULL;
1753
    ret = 0;
1754

1755
cleanup:
1756 1757 1758
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1759
    return ret;
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
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) {
1874
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
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 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
        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) {
1982
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1983 1984 1985 1986 1987 1988 1989 1990
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1991 1992 1993

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1994 1995 1996
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1997

1998
    umlDriverLock(driver);
1999
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2000

2001
    if (!vm) {
2002
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2003
                       _("no domain with matching uuid"));
2004
        goto cleanup;
2005 2006 2007
    }

    *autostart = vm->autostart;
2008
    ret = 0;
2009

2010
cleanup:
2011 2012
    if (vm)
        virDomainObjUnlock(vm);
2013
    umlDriverUnlock(driver);
2014
    return ret;
2015 2016 2017 2018
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2019
    struct uml_driver *driver = dom->conn->privateData;
2020
    virDomainObjPtr vm;
2021 2022 2023
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2024 2025 2026
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

    if (!vm->persistent) {
2034
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
2035
                       _("cannot set autostart for transient domain"));
2036
        goto cleanup;
2037 2038 2039 2040
    }

    autostart = (autostart != 0);

2041
    if (vm->autostart != autostart) {
2042
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2043
            goto cleanup;
2044
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2045
            goto cleanup;
2046

2047
        if (autostart) {
2048 2049
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2050 2051
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2052 2053
                goto cleanup;
            }
2054

2055
            if (symlink(configFile, autostartLink) < 0) {
2056
                virReportSystemError(errno,
2057 2058
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2059 2060 2061 2062
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2063
                virReportSystemError(errno,
2064 2065
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2066 2067
                goto cleanup;
            }
2068 2069
        }

2070
        vm->autostart = autostart;
2071 2072 2073 2074 2075 2076
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2077 2078
    if (vm)
        virDomainObjUnlock(vm);
2079
    umlDriverUnlock(driver);
2080 2081 2082 2083 2084
    return ret;
}


static int
2085 2086 2087 2088
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2089
                   unsigned int flags)
2090
{
2091 2092 2093
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2094

E
Eric Blake 已提交
2095 2096
    virCheckFlags(0, -1);

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

2101
    if (!vm) {
2102
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2103
                       _("no domain with matching uuid"));
2104
        goto cleanup;
2105 2106 2107
    }

    if (!path || path[0] == '\0') {
2108 2109
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2110
        goto cleanup;
2111 2112 2113 2114 2115
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2116 2117 2118 2119
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2120 2121
    }

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

2132 2133 2134 2135 2136 2137
        /* 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) {
2138
            virReportSystemError(errno,
2139
                                 _("cannot read %s"), path);
2140 2141 2142 2143 2144
            goto cleanup;
        }

        ret = 0;
    } else {
2145 2146
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2147 2148
    }

2149
cleanup:
2150
    VIR_FORCE_CLOSE(fd);
2151 2152
    if (vm)
        virDomainObjUnlock(vm);
2153 2154 2155 2156
    return ret;
}


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 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
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;
    }

2204
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2205 2206 2207 2208 2209
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

2210 2211
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
        goto cleanup;

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

2222 2223

static virDriver umlDriver = {
2224 2225
    .no = VIR_DRV_UML,
    .name = "UML",
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
    .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 */
2261
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2262
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2263 2264 2265 2266 2267 2268 2269 2270
    .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 */
2271 2272
};

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

    return 0;
}
2281 2282

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

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

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

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

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