uml_driver.c 60.2 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 59

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

66 67
#define VIR_FROM_THIS VIR_FROM_UML

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

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


79 80
static int umlShutdown(void);

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

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

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

    return priv;
}

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

    VIR_FREE(priv);
}


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

111

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

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

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

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


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

static struct uml_driver *uml_driver = NULL;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

        if (!dom) {
            continue;
        }

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

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

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

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

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

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

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

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

358 359
    uml_driver->privileged = privileged;

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

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

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

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

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

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

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

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

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

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

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

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

    VIR_FREE(base);

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

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

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
420
        VIR_ERROR(_("cannot initialize inotify"));
421
        goto error;
422 423
    }

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

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

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

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

450 451
    umlAutostartConfigs(uml_driver);

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

455 456
    return 0;

457
out_of_memory:
458
    VIR_ERROR(_("umlStartup: out of memory"));
459 460

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

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

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

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

    return 0;
}

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

    if (!uml_driver)
        return 0;

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

511
    return active;
512 513
}

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

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

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

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

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

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

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

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

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

    return 0;
}


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

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

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

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

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

    rc = 0;

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

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

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

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

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

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

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

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

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

    return 0;
}


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

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

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


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

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

708 709
    *reply = NULL;

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

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

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

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

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

        if (res.error)
            ret = -1;

    } while (res.extra);

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

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

    return ret;

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


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

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

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

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

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

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

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

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

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

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

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

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

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

882
    priv->monitor = -1;
883

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

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

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

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

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

    return ret;
}

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

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

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

925
    VIR_FORCE_CLOSE(priv->monitor);
926 927

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

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

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

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

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


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

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

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    conn->privateData = NULL;

    return 0;
}

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


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


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

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

    return xml;
}



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

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

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

1061 1062
    VIR_FREE(proc);

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

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

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

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

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

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

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

1226
    umlDriverLock(driver);
1227 1228 1229 1230 1231

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

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

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

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

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

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

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

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

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

1273 1274
    virCheckFlags(0, NULL);

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

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

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

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

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

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


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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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


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

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

1598
    return n;
1599 1600 1601
}

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

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

    return n;
}


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

1618 1619
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1715
cleanup:
1716 1717 1718
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1719
    return ret;
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
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) {
1834
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
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 1941
        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) {
1942
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1943 1944 1945 1946 1947 1948 1949 1950
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

1951 1952 1953

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

2007 2008
        if (autostart) {
            int err;
2009

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

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

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

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


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

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

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

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

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

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

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

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

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


2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
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;
    }

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

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

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

2182 2183

static virDriver umlDriver = {
2184 2185
    .no = VIR_DRV_UML,
    .name = "UML",
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 2220 2221 2222 2223 2224 2225 2226 2227 2228
    .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 */
    .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 */
2229 2230
};

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

    return 0;
}
2239 2240

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

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

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

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

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