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

#include <config.h>

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

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

65 66
#define VIR_FROM_THIS VIR_FROM_UML

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

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


78 79
static int umlShutdown(void);

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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);
}


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

110

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

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

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

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


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

static struct uml_driver *uml_driver = NULL;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

        if (!dom) {
            continue;
        }

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

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

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

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

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

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

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

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

353 354
    uml_driver->privileged = privileged;

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

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

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

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

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

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

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

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

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

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

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

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

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

    VIR_FREE(base);

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

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

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

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

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

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

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

449 450
    umlAutostartConfigs(uml_driver);

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

454 455
    return 0;

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

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

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

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

    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) {
501
    int active = 0;
502 503 504 505

    if (!uml_driver)
        return 0;

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

510
    return active;
511 512
}

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

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

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

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

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

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

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

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

    return 0;
}


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

    vm->pid = -1;
572 573
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
574
        virReportOOMError();
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        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;
590
        fclose(file);
591 592 593 594 595 596 597 598 599 600
        goto cleanup;
    }

    if (fclose(file) < 0)
        goto cleanup;

    rc = 0;

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

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

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

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

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

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

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

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

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


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

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

706 707
    *reply = NULL;

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

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

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

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

        if (res.error)
            ret = -1;

    } while (res.extra);

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

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

    return ret;

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


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

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

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

    FD_ZERO(&keepfd);

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

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

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

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

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

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

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

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

910
    priv->monitor = -1;
911

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

918 919 920 921 922
    /*
     * At the moment, the only thing that populates keepfd is
     * umlBuildCommandLineChr. We want to close every fd it opens.
     */
    for (i = 0; i < FD_SETSIZE; i++)
923 924 925 926
        if (FD_ISSET(i, &keepfd)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
927

928 929 930 931 932 933 934 935
    for (i = 0 ; argv[i] ; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

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

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

941 942 943

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

    return ret;
}

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

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

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

963
    VIR_FORCE_CLOSE(priv->monitor);
964 965

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

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

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

977 978 979 980 981 982 983 984 985 986 987 988
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
}


static virDrvOpenStatus umlOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                int flags ATTRIBUTE_UNUSED) {
989 990 991
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
992

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


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    conn->privateData = NULL;

    return 0;
}

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


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


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

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

    return xml;
}



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

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

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

    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
        umlDebug("not enough arg");
1099
        fclose(pidinfo);
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
        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);

    fclose(pidinfo);

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

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

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


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

1240
    umlDriverLock(driver);
1241 1242 1243 1244 1245

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

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

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

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

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

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

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

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

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

1287 1288
    virCheckFlags(0, NULL);

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

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

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

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

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

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


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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    info->state = vm->state;

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

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

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


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

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

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

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

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


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

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

1580
    return n;
1581 1582 1583
}

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

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

    return n;
}


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

1600 1601
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1697
cleanup:
1698 1699 1700
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1701
    return ret;
1702 1703 1704
}


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

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
            umlReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
            return -1;
        }
    }

    if (!disk->src) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("disk source path is missing"));
        goto error;
    }

    if (virAsprintf(&cmd, "config %s=%s", disk->dst, disk->src) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto error;

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return 0;

error:

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return -1;
}


static int umlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot attach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);

    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML) {
            ret = umlDomainAttachUmlDisk(driver, vm, dev->data.disk);
            if (ret == 0)
                dev->data.disk = NULL;
        } else {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(dev->data.disk->bus));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
        goto cleanup;
    }

cleanup:

    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


static int umlDomainAttachDeviceFlags(virDomainPtr dom,
                                      const char *xml,
                                      unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainAttachDevice(dom, xml);
}


static int umlDomainDetachUmlDisk(struct uml_driver *driver,
                                  virDomainObjPtr vm,
                                  virDomainDeviceDefPtr dev)
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    char *cmd;
    char *reply;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            break;
        }
    }

    if (i == vm->def->ndisks) {
        umlReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
        return -1;
    }

    detach = vm->def->disks[i];

    if (virAsprintf(&cmd, "remove %s", detach->dst) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto cleanup;

    virDomainDiskRemove(vm->def, i);

    virDomainDiskDefFree(detach);

    ret = 0;

    VIR_FREE(reply);

cleanup:
    VIR_FREE(cmd);

    return ret;
}


static int umlDomainDetachDevice(virDomainPtr dom, const char *xml) {
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot detach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML)
            ret = umlDomainDetachUmlDisk(driver, vm, dev);
        else {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("This type of device cannot be hot unplugged"));
    }

cleanup:
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


static int umlDomainDetachDeviceFlags(virDomainPtr dom,
                                      const char *xml,
                                      unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1933 1934 1935

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

1989 1990
        if (autostart) {
            int err;
1991

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

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

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

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


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

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

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

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

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

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

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

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

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


2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
static int
umlDomainOpenConsole(virDomainPtr dom,
                     const char *devname,
                     virStreamPtr st,
                     unsigned int flags)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    virDomainChrDefPtr chr = NULL;

    virCheckFlags(0, -1);

    umlDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    if (devname) {
        /* XXX support device aliases in future */
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
        goto cleanup;
    } else {
        if (vm->def->console)
            chr = vm->def->console;
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"), devname);
        goto cleanup;
    }

    if (chr->type != VIR_DOMAIN_CHR_TYPE_PTY) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

    if (virFDStreamOpenFile(st, chr->data.file.path, O_RDWR) < 0)
        goto cleanup;

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

2163 2164 2165 2166 2167 2168 2169 2170 2171

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

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

    return 0;
}
2279 2280

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

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

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

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

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