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

#include "uml_driver.h"
#include "uml_conf.h"
#include "buf.h"
#include "util.h"
#include "nodeinfo.h"
#include "stats_linux.h"
#include "capabilities.h"
#include "memory.h"
#include "uuid.h"
#include "domain_conf.h"
58
#include "domain_audit.h"
59
#include "datatypes.h"
60
#include "logging.h"
61
#include "domain_nwfilter.h"
E
Eric Blake 已提交
62
#include "virfile.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
                          virDomainObjPtr vm);
116 117 118
static void umlDomainEventFlush(int timer, void *opaque);
static void umlDomainEventQueue(struct uml_driver *driver,
                                virDomainEventPtr event);
119 120 121 122 123 124 125

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

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


130 131 132 133
static int umlMonitorCommand(const struct uml_driver *driver,
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply);
134 135 136

static struct uml_driver *uml_driver = NULL;

137 138 139 140 141 142
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

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

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
150
        !virDomainObjIsActive(vm)) {
151
        int ret;
152
        virResetLastError();
153 154 155
        ret = umlStartVMDaemon(data->conn, data->driver, vm);
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
156 157
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
158
                      vm->def->name, err ? err->message : _("unknown error"));
159 160 161 162 163 164 165
        } else {
            virDomainEventPtr event =
                virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
                umlDomainEventQueue(data->driver, event);
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
    struct umlAutostartData data = { driver, conn };

185
    umlDriverLock(driver);
186
    virHashForEach(driver->domains.objs, umlAutostartDomain, &data);
187
    umlDriverUnlock(driver);
188

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


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

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

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

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

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

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

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

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

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

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

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

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

        if (!dom) {
            continue;
        }

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

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

329
            if (umlReadPidFile(driver, dom) < 0) {
330
                virDomainObjUnlock(dom);
331 332 333 334
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
335 336
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
337

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

cleanup:
371 372
    if (event)
        umlDomainEventQueue(driver, event);
373
    umlDriverUnlock(driver);
374 375 376 377 378 379 380 381
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
382 383
umlStartup(int privileged)
{
384 385
    uid_t uid = geteuid();
    char *base = NULL;
386
    char *userdir = NULL;
387 388 389 390

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

391 392
    uml_driver->privileged = privileged;

393 394 395 396
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
397 398
    umlDriverLock(uml_driver);

399 400
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
401
    uml_driver->inotifyWatch = -1;
402

403 404 405
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

406 407 408 409 410 411 412
    uml_driver->domainEventState = virDomainEventStateNew(umlDomainEventFlush,
                                                          uml_driver,
                                                          NULL,
                                                          true);
    if (!uml_driver->domainEventState)
        goto error;

413
    userdir = virGetUserDirectory(uid);
414
    if (!userdir)
415
        goto error;
416

417
    if (privileged) {
418
        if (virAsprintf(&uml_driver->logDir,
419
                        "%s/log/libvirt/uml", LOCALSTATEDIR) == -1)
420 421
            goto out_of_memory;

422
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
423
            goto out_of_memory;
424 425

        if (virAsprintf(&uml_driver->monitorDir,
426
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
427
            goto out_of_memory;
428
    } else {
429

430
        if (virAsprintf(&uml_driver->logDir,
431
                        "%s/.libvirt/uml/log", userdir) == -1)
432 433
            goto out_of_memory;

434
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
435 436
            goto out_of_memory;

437 438 439 440
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
441 442 443 444

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

448
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
449 450 451 452 453 454 455
        goto out_of_memory;

    VIR_FREE(base);

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

456 457
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
458 459

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
460
        VIR_ERROR(_("cannot initialize inotify"));
461
        goto error;
462 463
    }

464
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
465
        char ebuf[1024];
D
Daniel Veillard 已提交
466
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
467
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
468
        goto error;
469 470
    }

471
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
472 473 474
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
475
        goto error;
476 477
    }

478 479
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
480 481
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
482

483
    if (virDomainLoadAllConfigs(uml_driver->caps,
484 485 486
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
487 488
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
489 490
        goto error;

491 492
    umlDriverUnlock(uml_driver);

493 494
    umlAutostartConfigs(uml_driver);

495 496
    VIR_FREE(userdir);

497 498
    return 0;

499
out_of_memory:
500
    VIR_ERROR(_("umlStartup: out of memory"));
501 502

error:
503
    VIR_FREE(userdir);
504
    VIR_FREE(base);
505 506
    umlDriverUnlock(uml_driver);
    umlShutdown();
507 508 509
    return -1;
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
static void umlNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct uml_driver *driver = opaque;

    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            umlDomainEventQueue(driver, event);
    }
}


525 526 527 528 529 530 531 532 533 534 535
/**
 * 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;

536
    umlDriverLock(uml_driver);
537
    virDomainLoadAllConfigs(uml_driver->caps,
538 539 540
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
541
                            0, 1 << VIR_DOMAIN_VIRT_UML,
542 543
                            umlNotifyLoadDomain, uml_driver);
    umlDriverUnlock(uml_driver);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    umlAutostartConfigs(uml_driver);

    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) {
560
    int active = 0;
561 562 563 564

    if (!uml_driver)
        return 0;

565
    umlDriverLock(uml_driver);
566
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
567
    umlDriverUnlock(uml_driver);
568

569
    return active;
570 571
}

572
static void
573
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
574 575 576 577 578
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
579
    if (virDomainObjIsActive(dom)) {
J
Jiri Denemark 已提交
580
        umlShutdownVMDaemon(NULL, driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
581 582
        virDomainAuditStop(dom, "shutdown");
    }
583 584 585
    virDomainObjUnlock(dom);
}

586 587 588 589 590 591 592 593 594 595
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

596
    umlDriverLock(uml_driver);
597 598
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
599
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
600 601
    virCapabilitiesFree(uml_driver->caps);

602 603 604
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
605

606
    virDomainObjListDeinit(&uml_driver->domains);
607

608 609
    virDomainEventStateFree(uml_driver->domainEventState);

610 611 612 613 614 615 616 617
    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);

618
    umlDriverUnlock(uml_driver);
619
    virMutexDestroy(&uml_driver->lock);
620 621 622 623 624 625
    VIR_FREE(uml_driver);

    return 0;
}


626
static int umlReadPidFile(struct uml_driver *driver,
627 628 629 630 631 632 633 634
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
635 636
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
637
        virReportOOMError();
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
        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;
653
        VIR_FORCE_FCLOSE(file);
654 655 656
        goto cleanup;
    }

657
    if (VIR_FCLOSE(file) < 0)
658 659 660 661 662 663
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
664
        virReportSystemError(errno,
665 666
                             _("failed to read pid: %s"),
                             pidfile);
667 668 669 670
    VIR_FREE(pidfile);
    return rc;
}

671
static int umlMonitorAddress(const struct uml_driver *driver,
672 673 674
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
675
    int retval = 0;
676

677 678
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
679
        virReportOOMError();
680 681 682 683 684
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
685
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
686
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
687 688 689
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
690
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
691
    return retval;
692 693
}

694
static int umlOpenMonitor(struct uml_driver *driver,
695 696 697 698
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
699
    umlDomainObjPrivatePtr priv = vm->privateData;
700

701
    if (umlMonitorAddress(driver, vm, &addr) < 0)
702 703
        return -1;

704
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
705 706 707
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
708
            retries++ < 50) {
709 710 711 712 713 714
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

715
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
716
        virReportSystemError(errno,
717
                             "%s", _("cannot open socket"));
718 719 720 721
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
E
Eric Blake 已提交
722 723
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
724
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
725
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
726
        virReportSystemError(errno,
727
                             "%s", _("cannot bind socket"));
728
        VIR_FORCE_CLOSE(priv->monitor);
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        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];
};


755
static int umlMonitorCommand(const struct uml_driver *driver,
756 757 758 759 760 761 762 763 764 765
                             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;
766
    umlDomainObjPrivatePtr priv = vm->privateData;
767

768 769
    VIR_DEBUG("Run command '%s'", cmd);

770 771
    *reply = NULL;

772
    if (umlMonitorAddress(driver, vm, &addr) < 0)
773 774 775 776 777 778 779
        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)) {
780
        virReportSystemError(EINVAL,
781 782
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
783 784
        return -1;
    }
C
Chris Lalancette 已提交
785
    if (virStrcpyStatic(req.data, cmd) == NULL) {
786
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
787 788 789
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
790

791
    if (sendto(priv->monitor, &req, sizeof req, 0,
792
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
793
        virReportSystemError(errno,
794 795
                             _("cannot send command %s"),
                             cmd);
796 797 798 799
        return -1;
    }

    do {
E
Eric Blake 已提交
800
        ssize_t nbytes;
801
        addrlen = sizeof(addr);
E
Eric Blake 已提交
802
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
803
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
804 805 806
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
807
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
808 809
            goto error;
        }
810 811 812
        /* 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) {
813 814 815
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
816 817

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
818
            virReportOOMError();
819 820 821 822 823 824 825 826 827 828 829
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

830 831
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

832 833 834 835
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
836 837 838 839 840 841 842 843 844

    return ret;

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


845 846 847 848 849 850
static int umlCleanupTapDevices(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virDomainObjPtr vm) {
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
851
    VIR_ERROR(_("Cleanup tap"));
852 853 854 855 856 857 858 859 860 861
    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;

862
        VIR_ERROR(_("Cleanup '%s'"), def->ifname);
863 864
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
865
            VIR_ERROR(_("Cleanup failed %d"), err);
866 867 868
            ret = -1;
        }
    }
869
    VIR_ERROR(_("Cleanup tap done"));
870 871 872 873
    brShutdown(brctl);
    return ret;
}

874 875 876
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
                            virDomainObjPtr vm) {
D
Daniel P. Berrange 已提交
877
    int ret;
878 879
    char *logfile;
    int logfd = -1;
880
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
881
    virCommandPtr cmd = NULL;
882

D
Daniel P. Berrange 已提交
883
    if (virDomainObjIsActive(vm)) {
884
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
885
                       _("VM is already active"));
886 887 888 889
        return -1;
    }

    if (!vm->def->os.kernel) {
890 891
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
892 893 894 895 896 897
        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 已提交
898
    if (!virFileIsExecutable(vm->def->os.kernel)) {
899
        virReportSystemError(errno,
900 901
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
902 903 904
        return -1;
    }

905
    if (virFileMakePath(driver->logDir) < 0) {
906
        virReportSystemError(errno,
907 908
                             _("cannot create log directory %s"),
                             driver->logDir);
909 910 911
        return -1;
    }

912 913
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
914
        virReportOOMError();
915 916 917 918 919
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
920
        virReportSystemError(errno,
921 922
                             _("failed to create logfile %s"),
                             logfile);
923 924 925 926 927
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

E
Eric Blake 已提交
928 929 930
    if (virSetCloseExec(logfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
931
        VIR_FORCE_CLOSE(logfd);
932 933 934
        return -1;
    }

D
Daniel P. Berrange 已提交
935
    if (!(cmd = umlBuildCommandLine(conn, driver, vm))) {
936
        VIR_FORCE_CLOSE(logfd);
937
        virDomainConfVMNWFilterTeardown(vm);
938
        umlCleanupTapDevices(conn, vm);
939 940 941
        return -1;
    }

D
Daniel P. Berrange 已提交
942
    virCommandWriteArgLog(cmd, logfd);
943

944
    priv->monitor = -1;
945

D
Daniel P. Berrange 已提交
946 947 948 949 950 951
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
952
    VIR_FORCE_CLOSE(logfd);
953 954
    if (ret < 0)
        goto cleanup;
955

956
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
957
cleanup:
D
Daniel P. Berrange 已提交
958
    virCommandFree(cmd);
959

960 961
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
962
        umlCleanupTapDevices(conn, vm);
963 964
    }

965 966
    /* NB we don't mark it running here - we do that async
       with inotify */
967 968 969
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
970
    /* XXX this is bad for events too. must fix this better */
971 972 973 974 975 976

    return ret;
}

static void umlShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
                                struct uml_driver *driver ATTRIBUTE_UNUSED,
J
Jiri Denemark 已提交
977 978
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
979 980
{
    int ret;
981 982
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
983
    if (!virDomainObjIsActive(vm))
984 985
        return;

986
    virKillProcess(vm->pid, SIGTERM);
987

988
    VIR_FORCE_CLOSE(priv->monitor);
989 990

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
991
        VIR_WARN("Got unexpected pid %d != %d",
992 993 994 995 996
               ret, vm->pid);
    }

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

999
    virDomainConfVMNWFilterTeardown(vm);
1000 1001
    umlCleanupTapDevices(conn, vm);

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
}


static virDrvOpenStatus umlOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1013 1014 1015 1016
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1017 1018 1019
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
1020

1021
        conn->uri = xmlParseURI(uml_driver->privileged ?
1022 1023 1024
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
1025
            virReportOOMError();
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
            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;
1036 1037


1038
        /* Check path and tell them correct path if they made a mistake */
1039
        if (uml_driver->privileged) {
1040
            if (STRNEQ (conn->uri->path, "/system") &&
1041
                STRNEQ (conn->uri->path, "/session")) {
1042
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1043 1044 1045 1046 1047 1048
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1049
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1050 1051 1052 1053
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1054
        }
1055 1056 1057

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1058
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1059
                           _("uml state driver is not active"));
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1070 1071 1072 1073 1074 1075
    struct uml_driver *driver = conn->privateData;

    umlDriverLock(driver);
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
    umlDriverUnlock(driver);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

    conn->privateData = NULL;

    return 0;
}

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


1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
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;
}


1101 1102 1103 1104
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1105
    umlDriverLock(driver);
1106
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1107
        virReportOOMError();
1108
    umlDriverUnlock(driver);
1109 1110 1111 1112 1113 1114

    return xml;
}



1115 1116 1117
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1118 1119 1120
    FILE *pidinfo;
    unsigned long long usertime, systime;

1121
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1122 1123 1124 1125 1126 1127
        return -1;
    }

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

1132 1133
    VIR_FREE(proc);

1134 1135
    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");
1136
        VIR_FORCE_FCLOSE(pidinfo);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        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);

1149
    VIR_FORCE_FCLOSE(pidinfo);
1150 1151 1152 1153 1154 1155 1156 1157

    return 0;
}


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

1161
    umlDriverLock(driver);
1162
    vm = virDomainFindByID(&driver->domains, id);
1163 1164
    umlDriverUnlock(driver);

1165
    if (!vm) {
1166
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1167
        goto cleanup;
1168 1169 1170 1171
    }

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

cleanup:
1174 1175
    if (vm)
        virDomainObjUnlock(vm);
1176 1177
    return dom;
}
1178

1179 1180 1181
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1182 1183
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1184

1185
    umlDriverLock(driver);
1186
    vm = virDomainFindByUUID(&driver->domains, uuid);
1187 1188
    umlDriverUnlock(driver);

1189
    if (!vm) {
1190
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1191
        goto cleanup;
1192 1193 1194 1195
    }

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

cleanup:
1198 1199
    if (vm)
        virDomainObjUnlock(vm);
1200 1201
    return dom;
}
1202

1203 1204 1205
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1206 1207
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1208

1209
    umlDriverLock(driver);
1210
    vm = virDomainFindByName(&driver->domains, name);
1211 1212
    umlDriverUnlock(driver);

1213
    if (!vm) {
1214
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1215
        goto cleanup;
1216 1217 1218 1219
    }

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

cleanup:
1222 1223
    if (vm)
        virDomainObjUnlock(vm);
1224 1225 1226
    return dom;
}

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

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) {
1238
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        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) {
1260
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
        goto cleanup;
    }
    ret = obj->persistent;

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

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
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;
}
1291

1292
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1293
    struct uml_driver *driver = conn->privateData;
1294
    struct utsname ut;
1295
    int ret = -1;
1296

1297
    umlDriverLock(driver);
1298 1299 1300 1301

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

1302
        if (virParseVersionString(ut.release, &driver->umlVersion, true) < 0) {
1303
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1304 1305 1306
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1307 1308
    }

1309 1310 1311 1312 1313 1314
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1315 1316 1317
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1318
    struct uml_driver *driver = conn->privateData;
1319
    int n;
1320

1321
    umlDriverLock(driver);
1322
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1323
    umlDriverUnlock(driver);
1324

1325
    return n;
1326 1327
}
static int umlNumDomains(virConnectPtr conn) {
1328
    struct uml_driver *driver = conn->privateData;
1329
    int n;
1330

1331
    umlDriverLock(driver);
1332
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1333
    umlDriverUnlock(driver);
1334 1335 1336 1337

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1338
                                      unsigned int flags) {
1339
    struct uml_driver *driver = conn->privateData;
1340
    virDomainDefPtr def;
1341
    virDomainObjPtr vm = NULL;
1342
    virDomainPtr dom = NULL;
1343
    virDomainEventPtr event = NULL;
1344

1345 1346
    virCheckFlags(0, NULL);

1347
    umlDriverLock(driver);
1348
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1349
                                        1 << VIR_DOMAIN_VIRT_UML,
1350
                                        VIR_DOMAIN_XML_INACTIVE)))
1351
        goto cleanup;
1352

1353
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1354
        goto cleanup;
1355

1356
    if (!(vm = virDomainAssignDef(driver->caps,
1357
                                  &driver->domains,
1358
                                  def, false)))
1359 1360
        goto cleanup;
    def = NULL;
1361 1362

    if (umlStartVMDaemon(conn, driver, vm) < 0) {
1363
        virDomainAuditStart(vm, "booted", false);
1364 1365
        virDomainRemoveInactive(&driver->domains,
                                vm);
1366 1367
        vm = NULL;
        goto cleanup;
1368
    }
1369
    virDomainAuditStart(vm, "booted", true);
1370 1371 1372
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1373 1374 1375

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1376 1377 1378

cleanup:
    virDomainDefFree(def);
1379 1380
    if (vm)
        virDomainObjUnlock(vm);
1381 1382
    if (event)
        umlDomainEventQueue(driver, event);
1383
    umlDriverUnlock(driver);
1384 1385 1386 1387 1388
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1389 1390
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1391
    char *info = NULL;
1392
    int ret = -1;
1393

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

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1405 1406
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1407
        goto cleanup;
1408
    }
1409
    ret = 0;
1410 1411
#endif

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


static int umlDomainDestroy(virDomainPtr dom) {
1421 1422
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1423
    virDomainEventPtr event = NULL;
1424
    int ret = -1;
1425

1426
    umlDriverLock(driver);
1427
    vm = virDomainFindByID(&driver->domains, dom->id);
1428
    if (!vm) {
1429
        umlReportError(VIR_ERR_NO_DOMAIN,
1430
                       _("no domain with matching id %d"), dom->id);
1431
        goto cleanup;
1432 1433
    }

J
Jiri Denemark 已提交
1434
    umlShutdownVMDaemon(dom->conn, driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1435
    virDomainAuditStop(vm, "destroyed");
1436 1437 1438
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1439
    if (!vm->persistent) {
1440 1441
        virDomainRemoveInactive(&driver->domains,
                                vm);
1442 1443 1444
        vm = NULL;
    }
    ret = 0;
1445

1446
cleanup:
1447 1448
    if (vm)
        virDomainObjUnlock(vm);
1449 1450
    if (event)
        umlDomainEventQueue(driver, event);
1451
    umlDriverUnlock(driver);
1452
    return ret;
1453 1454 1455 1456
}


static char *umlDomainGetOSType(virDomainPtr dom) {
1457 1458 1459
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1460

1461
    umlDriverLock(driver);
1462
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1463
    umlDriverUnlock(driver);
1464
    if (!vm) {
1465
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1466
                       _("no domain with matching uuid"));
1467
        goto cleanup;
1468 1469
    }

1470
    if (!(type = strdup(vm->def->os.type)))
1471
        virReportOOMError();
1472 1473

cleanup:
1474 1475
    if (vm)
        virDomainObjUnlock(vm);
1476 1477 1478 1479 1480
    return type;
}

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

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

1489 1490 1491 1492
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1493
        umlReportError(VIR_ERR_NO_DOMAIN,
1494 1495
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1496
    }
1497
    ret = vm->def->mem.max_balloon;
1498

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

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1506 1507 1508
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1509

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

1514 1515 1516 1517
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1518
        umlReportError(VIR_ERR_NO_DOMAIN,
1519
                       _("no domain with matching uuid '%s'"), uuidstr);
1520
        goto cleanup;
1521 1522
    }

1523
    if (newmax < vm->def->mem.cur_balloon) {
1524 1525
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1526
        goto cleanup;
1527 1528
    }

1529
    vm->def->mem.max_balloon = newmax;
1530 1531 1532
    ret = 0;

cleanup:
1533 1534
    if (vm)
        virDomainObjUnlock(vm);
1535
    return ret;
1536 1537 1538
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1539 1540 1541
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1542

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

1547 1548 1549 1550
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1551
        umlReportError(VIR_ERR_NO_DOMAIN,
1552
                       _("no domain with matching uuid '%s'"), uuidstr);
1553
        goto cleanup;
1554 1555
    }

D
Daniel P. Berrange 已提交
1556
    if (virDomainObjIsActive(vm)) {
1557
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1558
                       _("cannot set memory of an active domain"));
1559
        goto cleanup;
1560 1561
    }

1562
    if (newmem > vm->def->mem.max_balloon) {
1563 1564
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1565
        goto cleanup;
1566 1567
    }

1568
    vm->def->mem.cur_balloon = newmem;
1569 1570 1571
    ret = 0;

cleanup:
1572 1573
    if (vm)
        virDomainObjUnlock(vm);
1574
    return ret;
1575 1576 1577 1578
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1579 1580 1581 1582
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

1587
    if (!vm) {
1588
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1589
                       _("no domain with matching uuid"));
1590
        goto cleanup;
1591 1592
    }

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

D
Daniel P. Berrange 已提交
1595
    if (!virDomainObjIsActive(vm)) {
1596 1597 1598
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1599 1600
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1601
            goto cleanup;
1602 1603 1604
        }
    }

1605 1606
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1607
    info->nrVirtCpu = vm->def->vcpus;
1608 1609 1610
    ret = 0;

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


1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
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 已提交
1639
    *state = virDomainObjGetState(vm, reason);
1640 1641 1642 1643 1644 1645 1646 1647 1648
    ret = 0;

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


1649
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1650 1651
                                 unsigned int flags)
{
1652 1653 1654 1655
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1656
    /* Flags checked by virDomainDefFormat */
E
Eric Blake 已提交
1657

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

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

1668
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1669 1670 1671 1672
                             vm->newDef : vm->def,
                             flags);

cleanup:
1673 1674
    if (vm)
        virDomainObjUnlock(vm);
1675
    return ret;
1676 1677 1678 1679 1680
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1681
    struct uml_driver *driver = conn->privateData;
1682
    int n;
1683

1684
    umlDriverLock(driver);
1685
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1686
    umlDriverUnlock(driver);
1687

1688
    return n;
1689 1690 1691
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1692
    struct uml_driver *driver = conn->privateData;
1693
    int n;
1694

1695
    umlDriverLock(driver);
1696
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1697
    umlDriverUnlock(driver);
1698 1699 1700 1701 1702

    return n;
}


1703
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1704 1705
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1706
    virDomainEventPtr event = NULL;
1707
    int ret = -1;
1708

1709 1710
    virCheckFlags(0, -1);

1711
    umlDriverLock(driver);
1712
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1713

1714
    if (!vm) {
1715
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1716
                       _("no domain with matching uuid"));
1717
        goto cleanup;
1718 1719
    }

1720
    ret = umlStartVMDaemon(dom->conn, driver, vm);
1721
    virDomainAuditStart(vm, "booted", ret >= 0);
1722 1723 1724 1725
    if (ret == 0)
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
1726 1727

cleanup:
1728 1729
    if (vm)
        virDomainObjUnlock(vm);
1730 1731
    if (event)
        umlDomainEventQueue(driver, event);
1732
    umlDriverUnlock(driver);
1733
    return ret;
1734 1735
}

1736 1737 1738
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1739 1740

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1741
    struct uml_driver *driver = conn->privateData;
1742
    virDomainDefPtr def;
1743
    virDomainObjPtr vm = NULL;
1744
    virDomainPtr dom = NULL;
1745

1746
    umlDriverLock(driver);
1747
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1748
                                        1 << VIR_DOMAIN_VIRT_UML,
1749
                                        VIR_DOMAIN_XML_INACTIVE)))
1750
        goto cleanup;
1751

1752 1753 1754
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1755
    if (!(vm = virDomainAssignDef(driver->caps,
1756
                                  &driver->domains,
1757
                                  def, false)))
1758 1759
        goto cleanup;
    def = NULL;
1760 1761
    vm->persistent = 1;

1762
    if (virDomainSaveConfig(driver->configDir,
1763 1764 1765
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1766
        vm = NULL;
1767
        goto cleanup;
1768 1769 1770 1771
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1772 1773 1774

cleanup:
    virDomainDefFree(def);
1775 1776 1777
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1778 1779 1780
    return dom;
}

1781 1782 1783
static int umlDomainUndefineFlags(virDomainPtr dom,
                                  unsigned int flags)
{
1784 1785 1786
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1787

1788 1789
    virCheckFlags(0, -1);

1790
    umlDriverLock(driver);
1791
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1792
    if (!vm) {
1793
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1794
                       _("no domain with matching uuid"));
1795
        goto cleanup;
1796 1797
    }

D
Daniel P. Berrange 已提交
1798
    if (virDomainObjIsActive(vm)) {
1799
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1800
                       _("cannot delete active domain"));
1801
        goto cleanup;
1802 1803 1804
    }

    if (!vm->persistent) {
1805
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1806
                       _("cannot undefine transient domain"));
1807
        goto cleanup;
1808 1809
    }

1810
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1811
        goto cleanup;
1812 1813 1814

    virDomainRemoveInactive(&driver->domains,
                            vm);
1815
    vm = NULL;
1816
    ret = 0;
1817

1818
cleanup:
1819 1820 1821
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1822
    return ret;
1823 1824 1825
}


1826 1827 1828 1829 1830
static int umlDomainUndefine(virDomainPtr dom)
{
    return umlDomainUndefineFlags(dom, 0);
}

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
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;
}


1939 1940 1941 1942 1943 1944 1945
static int
umlDomainAttachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

1946
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
        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;
}


2051 2052 2053 2054 2055 2056 2057
static int
umlDomainDetachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2058
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2059 2060 2061 2062 2063 2064 2065 2066
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

2067 2068 2069

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
2070 2071 2072
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2073

2074
    umlDriverLock(driver);
2075
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2076

2077
    if (!vm) {
2078
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2079
                       _("no domain with matching uuid"));
2080
        goto cleanup;
2081 2082 2083
    }

    *autostart = vm->autostart;
2084
    ret = 0;
2085

2086
cleanup:
2087 2088
    if (vm)
        virDomainObjUnlock(vm);
2089
    umlDriverUnlock(driver);
2090
    return ret;
2091 2092 2093 2094
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2095
    struct uml_driver *driver = dom->conn->privateData;
2096
    virDomainObjPtr vm;
2097 2098 2099
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2100 2101 2102
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

    if (!vm->persistent) {
2110
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
2111
                       _("cannot set autostart for transient domain"));
2112
        goto cleanup;
2113 2114 2115 2116
    }

    autostart = (autostart != 0);

2117
    if (vm->autostart != autostart) {
2118
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2119
            goto cleanup;
2120
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2121
            goto cleanup;
2122

2123
        if (autostart) {
2124 2125
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2126 2127
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2128 2129
                goto cleanup;
            }
2130

2131
            if (symlink(configFile, autostartLink) < 0) {
2132
                virReportSystemError(errno,
2133 2134
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2135 2136 2137 2138
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2139
                virReportSystemError(errno,
2140 2141
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2142 2143
                goto cleanup;
            }
2144 2145
        }

2146
        vm->autostart = autostart;
2147 2148 2149 2150 2151 2152
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2153 2154
    if (vm)
        virDomainObjUnlock(vm);
2155
    umlDriverUnlock(driver);
2156 2157 2158 2159 2160
    return ret;
}


static int
2161 2162 2163 2164
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2165
                   unsigned int flags)
2166
{
2167 2168 2169
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
2170

E
Eric Blake 已提交
2171 2172
    virCheckFlags(0, -1);

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

2177
    if (!vm) {
2178
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2179
                       _("no domain with matching uuid"));
2180
        goto cleanup;
2181 2182 2183
    }

    if (!path || path[0] == '\0') {
2184 2185
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2186
        goto cleanup;
2187 2188 2189 2190 2191
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
2192 2193 2194 2195
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
2196 2197
    }

2198 2199 2200 2201 2202
    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) {
2203
            virReportSystemError(errno,
2204
                                 _("cannot open %s"), path);
2205 2206
            goto cleanup;
        }
2207

2208 2209 2210 2211 2212 2213
        /* 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) {
2214
            virReportSystemError(errno,
2215
                                 _("cannot read %s"), path);
2216 2217 2218 2219 2220
            goto cleanup;
        }

        ret = 0;
    } else {
2221 2222
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path"));
2223 2224
    }

2225
cleanup:
2226
    VIR_FORCE_CLOSE(fd);
2227 2228
    if (vm)
        virDomainObjUnlock(vm);
2229 2230 2231 2232
    return ret;
}


2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
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;
    }

2280
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2281 2282 2283 2284 2285
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"), devname);
        goto cleanup;
    }

2286 2287
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
        goto cleanup;

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

2298

2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
static int
umlDomainEventRegister(virConnectPtr conn,
                       virConnectDomainEventCallback callback,
                       void *opaque,
                       virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
                                        callback, opaque, freecb);
    umlDriverUnlock(driver);

    return ret;
}

static int
umlDomainEventDeregister(virConnectPtr conn,
                         virConnectDomainEventCallback callback)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
    umlDriverUnlock(driver);

    return ret;
}

static int
umlDomainEventRegisterAny(virConnectPtr conn,
                          virDomainPtr dom,
                          int eventID,
                          virConnectDomainEventGenericCallback callback,
                          void *opaque,
                          virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventCallbackListAddID(conn,
                                          driver->domainEventState->callbacks,
                                          dom, eventID,
                                          callback, opaque, freecb);
    umlDriverUnlock(driver);

    return ret;
}


static int
umlDomainEventDeregisterAny(virConnectPtr conn,
                            int callbackID)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
    umlDriverUnlock(driver);

    return ret;
}


static void umlDomainEventDispatchFunc(virConnectPtr conn,
                                       virDomainEventPtr event,
                                       virConnectDomainEventGenericCallback cb,
                                       void *cbopaque,
                                       void *opaque)
{
    struct uml_driver *driver = opaque;

    /* Drop the lock whle dispatching, for sake of re-entrancy */
    umlDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    umlDriverLock(driver);
}


static void umlDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    struct uml_driver *driver = opaque;

    umlDriverLock(driver);
    virDomainEventStateFlush(driver->domainEventState,
                             umlDomainEventDispatchFunc,
                             driver);
    umlDriverUnlock(driver);
}


/* driver must be locked before calling */
static void umlDomainEventQueue(struct uml_driver *driver,
                                virDomainEventPtr event)
{
    virDomainEventStateQueue(driver->domainEventState, event);
}



2408
static virDriver umlDriver = {
2409 2410
    .no = VIR_DRV_UML,
    .name = "UML",
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
    .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 */
2439
    .domainUndefineFlags = umlDomainUndefineFlags, /* 0.9.4 */
2440 2441 2442 2443 2444 2445 2446
    .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 */
2447
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2448
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2449 2450
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.5.0 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.5.0 */
2451 2452
    .domainEventRegister = umlDomainEventRegister, /* 0.9.4 */
    .domainEventDeregister = umlDomainEventDeregister, /* 0.9.4 */
2453 2454 2455 2456 2457
    .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 */
2458 2459
    .domainEventRegisterAny = umlDomainEventRegisterAny, /* 0.9.4 */
    .domainEventDeregisterAny = umlDomainEventDeregisterAny, /* 0.9.4 */
2460
    .domainOpenConsole = umlDomainOpenConsole, /* 0.8.6 */
2461 2462
};

2463 2464 2465 2466 2467 2468 2469 2470
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2471 2472

static virStateDriver umlStateDriver = {
2473
    .name = "UML",
2474 2475 2476 2477 2478 2479
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2492 2493 2494
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2495 2496
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2497 2498
};

2499 2500 2501
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2502
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2503 2504
    return 0;
}