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

#include <config.h>

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

#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"
#include "datatypes.h"
59
#include "logging.h"
60
#include "domain_nwfilter.h"
61
#include "files.h"
62
#include "fdstream.h"
63
#include "configmake.h"
64

65 66
#define VIR_FROM_THIS VIR_FROM_UML

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

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:
125
    VIR_ERROR(_("Failed to set close-on-exec file descriptor flag"));
126 127 128 129 130 131 132 133 134
    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 已提交
135 136
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason);
137 138


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

static struct uml_driver *uml_driver = NULL;

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

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

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

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

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

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

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


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

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

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

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

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

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

    return 0;
}

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

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

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

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

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

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

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

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

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

        if (!dom) {
            continue;
        }

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

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

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

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
322 323
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
324

325
            if (umlOpenMonitor(driver, dom) < 0) {
326
                VIR_WARN("Could not open monitor for new domain");
J
Jiri Denemark 已提交
327 328
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
329
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
330
                VIR_WARN("Could not identify charater devices for new domain");
J
Jiri Denemark 已提交
331 332
                umlShutdownVMDaemon(NULL, driver, dom,
                                    VIR_DOMAIN_SHUTOFF_FAILED);
333
            }
334
        }
335
        virDomainObjUnlock(dom);
336
    }
337 338 339

cleanup:
    umlDriverUnlock(driver);
340 341 342 343 344 345 346 347
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
348 349
umlStartup(int privileged)
{
350 351
    uid_t uid = geteuid();
    char *base = NULL;
352
    char *userdir = NULL;
353 354 355 356

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

357 358
    uml_driver->privileged = privileged;

359 360 361 362
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
363 364
    umlDriverLock(uml_driver);

365 366
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
367
    uml_driver->inotifyWatch = -1;
368

369 370 371
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

372
    userdir = virGetUserDirectory(uid);
373
    if (!userdir)
374
        goto error;
375

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

381
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
382
            goto out_of_memory;
383 384

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

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

393
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
394 395
            goto out_of_memory;

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

    /* Configuration paths are either ~/.libvirt/uml/... (session) or
     * /etc/libvirt/uml/... (system).
     */
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) {
419
        VIR_ERROR(_("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:
457
    VIR_ERROR(_("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
static void
514
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
515 516 517 518 519
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
D
Daniel P. Berrange 已提交
520
    if (virDomainObjIsActive(dom))
J
Jiri Denemark 已提交
521
        umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
522 523 524
    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
        VIR_FORCE_FCLOSE(file);
591 592 593
        goto cleanup;
    }

594
    if (VIR_FCLOSE(file) < 0)
595 596 597 598 599 600
        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);
E
Eric Blake 已提交
659 660
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
661
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
662
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
663
        virReportSystemError(errno,
664
                             "%s", _("cannot bind socket"));
665
        VIR_FORCE_CLOSE(priv->monitor);
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 691
        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];
};


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

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

707 708
    *reply = NULL;

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

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

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

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

        if (res.error)
            ret = -1;

    } while (res.extra);

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

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

    return ret;

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


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

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

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

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

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

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

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

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

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

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

D
Daniel P. Berrange 已提交
879
    virCommandWriteArgLog(cmd, logfd);
880

881
    priv->monitor = -1;
882

D
Daniel P. Berrange 已提交
883 884 885 886 887 888
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
889
    VIR_FORCE_CLOSE(logfd);
890 891
    if (ret < 0)
        goto cleanup;
892

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

897 898
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
899
        umlCleanupTapDevices(conn, vm);
900 901
    }

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

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
J
Jiri Denemark 已提交
913 914
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
915 916
{
    int ret;
917 918
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
919
    if (!virDomainObjIsActive(vm))
920 921
        return;

922
    virKillProcess(vm->pid, SIGTERM);
923

924
    VIR_FORCE_CLOSE(priv->monitor);
925 926

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

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

935
    virDomainConfVMNWFilterTeardown(vm);
936 937
    umlCleanupTapDevices(conn, vm);

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

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


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1003
    /*struct uml_driver *driver = conn->privateData;*/
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

    conn->privateData = NULL;

    return 0;
}

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


1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
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;
}


1029 1030 1031 1032
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1033
    umlDriverLock(driver);
1034
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1035
        virReportOOMError();
1036
    umlDriverUnlock(driver);
1037 1038 1039 1040 1041 1042

    return xml;
}



1043 1044 1045
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1046 1047 1048
    FILE *pidinfo;
    unsigned long long usertime, systime;

1049
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1050 1051 1052 1053 1054 1055
        return -1;
    }

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

1060 1061
    VIR_FREE(proc);

1062 1063
    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");
1064
        VIR_FORCE_FCLOSE(pidinfo);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        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);

1077
    VIR_FORCE_FCLOSE(pidinfo);
1078 1079 1080 1081 1082 1083 1084 1085

    return 0;
}


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

1089
    umlDriverLock(driver);
1090
    vm = virDomainFindByID(&driver->domains, id);
1091 1092
    umlDriverUnlock(driver);

1093
    if (!vm) {
1094
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1095
        goto cleanup;
1096 1097 1098 1099
    }

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

cleanup:
1102 1103
    if (vm)
        virDomainObjUnlock(vm);
1104 1105
    return dom;
}
1106

1107 1108 1109
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1110 1111
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1112

1113
    umlDriverLock(driver);
1114
    vm = virDomainFindByUUID(&driver->domains, uuid);
1115 1116
    umlDriverUnlock(driver);

1117
    if (!vm) {
1118
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1119
        goto cleanup;
1120 1121 1122 1123
    }

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

cleanup:
1126 1127
    if (vm)
        virDomainObjUnlock(vm);
1128 1129
    return dom;
}
1130

1131 1132 1133
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1134 1135
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1136

1137
    umlDriverLock(driver);
1138
    vm = virDomainFindByName(&driver->domains, name);
1139 1140
    umlDriverUnlock(driver);

1141
    if (!vm) {
1142
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1143
        goto cleanup;
1144 1145 1146 1147
    }

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

cleanup:
1150 1151
    if (vm)
        virDomainObjUnlock(vm);
1152 1153 1154
    return dom;
}

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

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

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

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
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;
}
1219

1220
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1221
    struct uml_driver *driver = conn->privateData;
1222
    struct utsname ut;
1223
    int ret = -1;
1224

1225
    umlDriverLock(driver);
1226 1227 1228 1229 1230

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

        if (virParseVersionString(ut.release, &driver->umlVersion) < 0) {
1231
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1232 1233 1234
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1235 1236
    }

1237 1238 1239 1240 1241 1242
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1243 1244 1245
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1246
    struct uml_driver *driver = conn->privateData;
1247
    int n;
1248

1249
    umlDriverLock(driver);
1250
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1251
    umlDriverUnlock(driver);
1252

1253
    return n;
1254 1255
}
static int umlNumDomains(virConnectPtr conn) {
1256
    struct uml_driver *driver = conn->privateData;
1257
    int n;
1258

1259
    umlDriverLock(driver);
1260
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1261
    umlDriverUnlock(driver);
1262 1263 1264 1265

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

1272 1273
    virCheckFlags(0, NULL);

1274
    umlDriverLock(driver);
1275
    if (!(def = virDomainDefParseString(driver->caps, xml,
1276
                                        VIR_DOMAIN_XML_INACTIVE)))
1277
        goto cleanup;
1278

1279
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1280
        goto cleanup;
1281

1282
    if (!(vm = virDomainAssignDef(driver->caps,
1283
                                  &driver->domains,
1284
                                  def, false)))
1285 1286
        goto cleanup;
    def = NULL;
1287 1288 1289 1290

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1291 1292
        vm = NULL;
        goto cleanup;
1293 1294 1295 1296
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1297 1298 1299

cleanup:
    virDomainDefFree(def);
1300 1301 1302
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1303 1304 1305 1306 1307
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1308 1309
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1310
    char *info = NULL;
1311
    int ret = -1;
1312

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

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

1331 1332
cleanup:
    VIR_FREE(info);
1333 1334
    if (vm)
        virDomainObjUnlock(vm);
1335
    return ret;
1336 1337 1338 1339
}


static int umlDomainDestroy(virDomainPtr dom) {
1340 1341 1342
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1343

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

J
Jiri Denemark 已提交
1352
    umlShutdownVMDaemon(dom->conn, driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1353
    if (!vm->persistent) {
1354 1355
        virDomainRemoveInactive(&driver->domains,
                                vm);
1356 1357 1358
        vm = NULL;
    }
    ret = 0;
1359

1360
cleanup:
1361 1362 1363
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1364
    return ret;
1365 1366 1367 1368
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1369 1370 1371
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1372

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

1382
    if (!(type = strdup(vm->def->os.type)))
1383
        virReportOOMError();
1384 1385

cleanup:
1386 1387
    if (vm)
        virDomainObjUnlock(vm);
1388 1389 1390 1391 1392
    return type;
}

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

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

1401 1402 1403 1404
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

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

1411
cleanup:
1412 1413
    if (vm)
        virDomainObjUnlock(vm);
1414
    return ret;
1415 1416 1417
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1418 1419 1420
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1421

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

1426 1427 1428 1429
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1430
        umlReportError(VIR_ERR_NO_DOMAIN,
1431
                       _("no domain with matching uuid '%s'"), uuidstr);
1432
        goto cleanup;
1433 1434
    }

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

1441
    vm->def->mem.max_balloon = newmax;
1442 1443 1444
    ret = 0;

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

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

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

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

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

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

1474
    if (newmem > vm->def->mem.max_balloon) {
1475 1476
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1477
        goto cleanup;
1478 1479
    }

1480
    vm->def->mem.cur_balloon = newmem;
1481 1482 1483
    ret = 0;

cleanup:
1484 1485
    if (vm)
        virDomainObjUnlock(vm);
1486
    return ret;
1487 1488 1489 1490
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1491 1492 1493 1494
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

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

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

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

1517 1518
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1519
    info->nrVirtCpu = vm->def->vcpus;
1520 1521 1522
    ret = 0;

cleanup:
1523 1524
    if (vm)
        virDomainObjUnlock(vm);
1525
    return ret;
1526 1527 1528
}


1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
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 已提交
1551
    *state = virDomainObjGetState(vm, reason);
1552 1553 1554 1555 1556 1557 1558 1559 1560
    ret = 0;

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


1561 1562
static char *umlDomainGetXMLDesc(virDomainPtr dom,
                                 int flags ATTRIBUTE_UNUSED) {
1563 1564 1565 1566
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

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

1571
    if (!vm) {
1572
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1573
                       _("no domain with matching uuid"));
1574
        goto cleanup;
1575 1576
    }

1577
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1578 1579 1580 1581
                             vm->newDef : vm->def,
                             flags);

cleanup:
1582 1583
    if (vm)
        virDomainObjUnlock(vm);
1584
    return ret;
1585 1586 1587 1588 1589
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1590
    struct uml_driver *driver = conn->privateData;
1591
    int n;
1592

1593
    umlDriverLock(driver);
1594
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1595
    umlDriverUnlock(driver);
1596

1597
    return n;
1598 1599 1600
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1601
    struct uml_driver *driver = conn->privateData;
1602
    int n;
1603

1604
    umlDriverLock(driver);
1605
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1606
    umlDriverUnlock(driver);
1607 1608 1609 1610 1611

    return n;
}


1612
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1613 1614 1615
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1616

1617 1618
    virCheckFlags(0, -1);

1619
    umlDriverLock(driver);
1620
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1621

1622
    if (!vm) {
1623
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1624
                       _("no domain with matching uuid"));
1625
        goto cleanup;
1626 1627
    }

1628 1629 1630
    ret = umlStartVMDaemon(dom->conn, driver, vm);

cleanup:
1631 1632 1633
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1634
    return ret;
1635 1636
}

1637 1638 1639
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1640 1641

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1642
    struct uml_driver *driver = conn->privateData;
1643
    virDomainDefPtr def;
1644
    virDomainObjPtr vm = NULL;
1645
    virDomainPtr dom = NULL;
1646

1647
    umlDriverLock(driver);
1648
    if (!(def = virDomainDefParseString(driver->caps, xml,
1649
                                        VIR_DOMAIN_XML_INACTIVE)))
1650
        goto cleanup;
1651

1652 1653 1654
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1655
    if (!(vm = virDomainAssignDef(driver->caps,
1656
                                  &driver->domains,
1657
                                  def, false)))
1658 1659
        goto cleanup;
    def = NULL;
1660 1661
    vm->persistent = 1;

1662
    if (virDomainSaveConfig(driver->configDir,
1663 1664 1665
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1666
        vm = NULL;
1667
        goto cleanup;
1668 1669 1670 1671
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1672 1673 1674

cleanup:
    virDomainDefFree(def);
1675 1676 1677
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1678 1679 1680 1681
    return dom;
}

static int umlDomainUndefine(virDomainPtr dom) {
1682 1683 1684
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1685

1686
    umlDriverLock(driver);
1687
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1688
    if (!vm) {
1689
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1690
                       _("no domain with matching uuid"));
1691
        goto cleanup;
1692 1693
    }

D
Daniel P. Berrange 已提交
1694
    if (virDomainObjIsActive(vm)) {
1695
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1696
                       _("cannot delete active domain"));
1697
        goto cleanup;
1698 1699 1700
    }

    if (!vm->persistent) {
1701
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1702
                       _("cannot undefine transient domain"));
1703
        goto cleanup;
1704 1705
    }

1706
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1707
        goto cleanup;
1708 1709 1710

    virDomainRemoveInactive(&driver->domains,
                            vm);
1711
    vm = NULL;
1712
    ret = 0;
1713

1714
cleanup:
1715 1716 1717
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1718
    return ret;
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
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) {
1833
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
        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) {
1941
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1942 1943 1944 1945 1946 1947 1948 1949
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1950 1951 1952

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
1953 1954 1955
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1956

1957
    umlDriverLock(driver);
1958
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1959

1960
    if (!vm) {
1961
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1962
                       _("no domain with matching uuid"));
1963
        goto cleanup;
1964 1965 1966
    }

    *autostart = vm->autostart;
1967
    ret = 0;
1968

1969
cleanup:
1970 1971
    if (vm)
        virDomainObjUnlock(vm);
1972
    umlDriverUnlock(driver);
1973
    return ret;
1974 1975 1976 1977
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
1978
    struct uml_driver *driver = dom->conn->privateData;
1979
    virDomainObjPtr vm;
1980 1981 1982
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

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

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

    if (!vm->persistent) {
1993
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1994
                       _("cannot set autostart for transient domain"));
1995
        goto cleanup;
1996 1997 1998 1999
    }

    autostart = (autostart != 0);

2000
    if (vm->autostart != autostart) {
2001
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2002
            goto cleanup;
2003
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2004
            goto cleanup;
2005

2006 2007
        if (autostart) {
            int err;
2008

2009
            if ((err = virFileMakePath(driver->autostartDir))) {
2010
                virReportSystemError(err,
2011 2012
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2013 2014
                goto cleanup;
            }
2015

2016
            if (symlink(configFile, autostartLink) < 0) {
2017
                virReportSystemError(errno,
2018 2019
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2020 2021 2022 2023
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2024
                virReportSystemError(errno,
2025 2026
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2027 2028
                goto cleanup;
            }
2029 2030
        }

2031
        vm->autostart = autostart;
2032 2033 2034 2035 2036 2037
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2038 2039
    if (vm)
        virDomainObjUnlock(vm);
2040
    umlDriverUnlock(driver);
2041 2042 2043 2044 2045
    return ret;
}


static int
2046 2047 2048 2049 2050
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
                   unsigned int flags ATTRIBUTE_UNUSED)
2051
{
2052 2053 2054
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2055

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

2060
    if (!vm) {
2061
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2062
                       _("no domain with matching uuid"));
2063
        goto cleanup;
2064 2065 2066
    }

    if (!path || path[0] == '\0') {
2067 2068
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2069
        goto cleanup;
2070 2071 2072 2073 2074
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2075 2076 2077 2078
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2079 2080
    }

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

2091 2092 2093 2094 2095 2096
        /* 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) {
2097
            virReportSystemError(errno,
2098
                                 _("cannot read %s"), path);
2099 2100 2101 2102 2103
            goto cleanup;
        }

        ret = 0;
    } else {
2104 2105
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2106 2107
    }

2108
cleanup:
2109
    VIR_FORCE_CLOSE(fd);
2110 2111
    if (vm)
        virDomainObjUnlock(vm);
2112 2113 2114 2115
    return ret;
}


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

2163
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2164 2165 2166 2167 2168
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

2169 2170
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
        goto cleanup;

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

2181 2182

static virDriver umlDriver = {
2183 2184
    .no = VIR_DRV_UML,
    .name = "UML",
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
    .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 */
2220
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2221
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2222 2223 2224 2225 2226 2227 2228 2229
    .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 */
2230 2231
};

2232 2233 2234 2235 2236 2237 2238 2239
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2240 2241

static virStateDriver umlStateDriver = {
2242
    .name = "UML",
2243 2244 2245 2246 2247 2248
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2261 2262 2263
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2264 2265
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2266 2267
};

2268 2269 2270
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2271
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2272 2273
    return 0;
}