uml_driver.c 71.6 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2012 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
 * 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 <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>
45
#include <sys/un.h>
46 47 48 49 50 51 52 53 54 55 56

#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"
57
#include "domain_audit.h"
58
#include "datatypes.h"
59
#include "logging.h"
60
#include "domain_nwfilter.h"
E
Eric Blake 已提交
61
#include "virfile.h"
62
#include "fdstream.h"
63
#include "configmake.h"
64
#include "virnetdevtap.h"
65
#include "virnodesuspend.h"
M
Martin Kletzander 已提交
66
#include "viruri.h"
67

68 69
#define VIR_FROM_THIS VIR_FROM_UML

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

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

80 81 82 83 84 85 86 87 88 89
static int umlProcessAutoDestroyInit(struct uml_driver *driver);
static void umlProcessAutoDestroyRun(struct uml_driver *driver,
                                     virConnectPtr conn);
static void umlProcessAutoDestroyShutdown(struct uml_driver *driver);
static int umlProcessAutoDestroyAdd(struct uml_driver *driver,
                                    virDomainObjPtr vm,
                                    virConnectPtr conn);
static int umlProcessAutoDestroyRemove(struct uml_driver *driver,
                                       virDomainObjPtr vm);

90

91 92
static int umlShutdown(void);

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
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);
}


114 115
static void umlDriverLock(struct uml_driver *driver)
{
116
    virMutexLock(&driver->lock);
117 118 119
}
static void umlDriverUnlock(struct uml_driver *driver)
{
120
    virMutexUnlock(&driver->lock);
121 122
}

123

124
static int umlOpenMonitor(struct uml_driver *driver,
125
                          virDomainObjPtr vm);
126
static int umlReadPidFile(struct uml_driver *driver,
127
                          virDomainObjPtr vm);
128 129
static void umlDomainEventQueue(struct uml_driver *driver,
                                virDomainEventPtr event);
130 131 132

static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
133 134
                            virDomainObjPtr vm,
                            bool autoDestroy);
135

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


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

static struct uml_driver *uml_driver = NULL;

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

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

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

static void
umlAutostartConfigs(struct uml_driver *driver) {
184 185 186 187 188
    /* 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
     */
189 190 191
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
192
    /* Ignoring NULL conn which is mostly harmless here */
193

194 195
    struct umlAutostartData data = { driver, conn };

196
    umlDriverLock(driver);
197
    virHashForEach(driver->domains.objs, umlAutostartDomain, &data);
198
    umlDriverUnlock(driver);
199

200 201
    if (conn)
        virConnectClose(conn);
202 203 204 205
}


static int
206
umlIdentifyOneChrPTY(struct uml_driver *driver,
207 208 209 210 211 212 213
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
214
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
215
        virReportOOMError();
216 217 218
        return -1;
    }
requery:
219
    if (umlMonitorCommand(driver, dom, cmd, &res) < 0)
220
        return -1;
221

222
    if (res && STRPREFIX(res, "pts:")) {
223 224
        VIR_FREE(def->source.data.file.path);
        if ((def->source.data.file.path = strdup(res + 4)) == NULL) {
225
            virReportOOMError();
226 227 228 229
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
230
    } else if (!res || STRPREFIX(res, "pts")) {
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        /* 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
247
umlIdentifyChrPTY(struct uml_driver *driver,
248 249 250 251
                  virDomainObjPtr dom)
{
    int i;

252 253
    for (i = 0 ; i < dom->def->nserials; i++)
        if (dom->def->consoles[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
254
        if (umlIdentifyOneChrPTY(driver, dom,
255
                                 dom->def->consoles[i], "con") < 0)
256 257 258
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
259
        if (dom->def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
260
            umlIdentifyOneChrPTY(driver, dom,
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
                                 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;
279
    virDomainEventPtr event = NULL;
280

281
    umlDriverLock(driver);
282
    if (watch != driver->inotifyWatch)
283
        goto cleanup;
284 285 286 287 288 289

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
290
        goto cleanup;
291 292 293 294 295
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
296
            goto cleanup; /* bad */
297 298 299 300 301 302

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

        if (got < e->len)
303
            goto cleanup;
304 305 306 307 308 309 310 311 312 313 314 315 316

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

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

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

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
317
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
318
            if (!virDomainObjIsActive(dom)) {
319
                virDomainObjUnlock(dom);
320 321 322
                continue;
            }

323
            umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
324
            virDomainAuditStop(dom, "shutdown");
325 326 327
            event = virDomainEventNewFromObj(dom,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
328 329 330 331 332
            if (!dom->persistent) {
                virDomainRemoveInactive(&driver->domains,
                                        dom);
                dom = NULL;
            }
333
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
334
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
335
            if (virDomainObjIsActive(dom)) {
336
                virDomainObjUnlock(dom);
337 338 339
                continue;
            }

340
            if (umlReadPidFile(driver, dom) < 0) {
341
                virDomainObjUnlock(dom);
342 343 344 345
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
346 347
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
348

349
            if (umlOpenMonitor(driver, dom) < 0) {
350
                VIR_WARN("Could not open monitor for new domain");
351
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
352
                                    VIR_DOMAIN_SHUTOFF_FAILED);
353
                virDomainAuditStop(dom, "failed");
354 355 356
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
357 358 359 360 361
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
362
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
363
                VIR_WARN("Could not identify character devices for new domain");
364
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
365
                                    VIR_DOMAIN_SHUTOFF_FAILED);
366
                virDomainAuditStop(dom, "failed");
367 368 369
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
370 371 372 373 374
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
375
            }
376
        }
377 378
        if (dom)
            virDomainObjUnlock(dom);
379
    }
380 381

cleanup:
382 383
    if (event)
        umlDomainEventQueue(driver, event);
384
    umlDriverUnlock(driver);
385 386 387 388 389 390 391 392
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
393 394
umlStartup(int privileged)
{
395 396
    uid_t uid = geteuid();
    char *base = NULL;
397
    char *userdir = NULL;
398 399 400 401

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

402 403
    uml_driver->privileged = privileged;

404 405 406 407
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
408 409
    umlDriverLock(uml_driver);

410 411
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
412
    uml_driver->inotifyWatch = -1;
413

414 415 416
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

417
    uml_driver->domainEventState = virDomainEventStateNew();
418 419 420
    if (!uml_driver->domainEventState)
        goto error;

421
    userdir = virGetUserDirectory(uid);
422
    if (!userdir)
423
        goto error;
424

425
    if (privileged) {
426
        if (virAsprintf(&uml_driver->logDir,
427
                        "%s/log/libvirt/uml", LOCALSTATEDIR) == -1)
428 429
            goto out_of_memory;

430
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
431
            goto out_of_memory;
432 433

        if (virAsprintf(&uml_driver->monitorDir,
434
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
435
            goto out_of_memory;
436
    } else {
437

438
        if (virAsprintf(&uml_driver->logDir,
439
                        "%s/.libvirt/uml/log", userdir) == -1)
440 441
            goto out_of_memory;

442
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
443 444
            goto out_of_memory;

445 446 447 448
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
449 450 451 452

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

456
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
457 458 459 460 461 462 463
        goto out_of_memory;

    VIR_FREE(base);

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

464 465
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
466 467

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
468
        VIR_ERROR(_("cannot initialize inotify"));
469
        goto error;
470 471
    }

472
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
473
        char ebuf[1024];
D
Daniel Veillard 已提交
474
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
475
                  uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof(ebuf)));
476
        goto error;
477 478
    }

479
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
480 481 482
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
483
        goto error;
484 485
    }

486 487
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
488 489
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
490

491 492 493
    if (umlProcessAutoDestroyInit(uml_driver) < 0)
        goto error;

494
    if (virDomainLoadAllConfigs(uml_driver->caps,
495 496 497
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
498 499
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
500 501
        goto error;

502 503
    umlDriverUnlock(uml_driver);

504 505
    umlAutostartConfigs(uml_driver);

506 507
    VIR_FREE(userdir);

508 509
    return 0;

510
out_of_memory:
511
    VIR_ERROR(_("umlStartup: out of memory"));
512 513

error:
514
    VIR_FREE(userdir);
515
    VIR_FREE(base);
516 517
    umlDriverUnlock(uml_driver);
    umlShutdown();
518 519 520
    return -1;
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
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);
    }
}


536 537 538 539 540 541 542 543 544 545 546
/**
 * 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;

547
    umlDriverLock(uml_driver);
548
    virDomainLoadAllConfigs(uml_driver->caps,
549 550 551
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
552
                            0, 1 << VIR_DOMAIN_VIRT_UML,
553 554
                            umlNotifyLoadDomain, uml_driver);
    umlDriverUnlock(uml_driver);
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

    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) {
571
    int active = 0;
572 573 574 575

    if (!uml_driver)
        return 0;

576
    umlDriverLock(uml_driver);
577
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
578
    umlDriverUnlock(uml_driver);
579

580
    return active;
581 582
}

583
static void
584
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
585 586 587 588 589
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
590
    if (virDomainObjIsActive(dom)) {
591
        umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
592 593
        virDomainAuditStop(dom, "shutdown");
    }
594 595 596
    virDomainObjUnlock(dom);
}

597 598 599 600 601 602 603 604 605 606
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

607
    umlDriverLock(uml_driver);
608 609
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
610
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
611 612
    virCapabilitiesFree(uml_driver->caps);

613 614 615
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
616

617
    virDomainObjListDeinit(&uml_driver->domains);
618

619 620
    virDomainEventStateFree(uml_driver->domainEventState);

621 622 623 624 625
    VIR_FREE(uml_driver->logDir);
    VIR_FREE(uml_driver->configDir);
    VIR_FREE(uml_driver->autostartDir);
    VIR_FREE(uml_driver->monitorDir);

626 627
    umlProcessAutoDestroyShutdown(uml_driver);

628
    umlDriverUnlock(uml_driver);
629
    virMutexDestroy(&uml_driver->lock);
630 631 632 633 634 635
    VIR_FREE(uml_driver);

    return 0;
}


636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
static int umlProcessAutoDestroyInit(struct uml_driver *driver)
{
    if (!(driver->autodestroy = virHashCreate(5, NULL)))
        return -1;

    return 0;
}

struct umlProcessAutoDestroyData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void umlProcessAutoDestroyDom(void *payload,
                                     const void *name,
                                     void *opaque)
{
    struct umlProcessAutoDestroyData *data = opaque;
    virConnectPtr conn = payload;
    const char *uuidstr = name;
    unsigned char uuid[VIR_UUID_BUFLEN];
    virDomainObjPtr dom;
    virDomainEventPtr event = NULL;

    VIR_DEBUG("conn=%p uuidstr=%s thisconn=%p", conn, uuidstr, data->conn);

    if (data->conn != conn)
        return;

    if (virUUIDParse(uuidstr, uuid) < 0) {
        VIR_WARN("Failed to parse %s", uuidstr);
        return;
    }

    if (!(dom = virDomainFindByUUID(&data->driver->domains,
                                    uuid))) {
        VIR_DEBUG("No domain object to kill");
        return;
    }

    VIR_DEBUG("Killing domain");
    umlShutdownVMDaemon(data->driver, dom, VIR_DOMAIN_SHUTOFF_DESTROYED);
    virDomainAuditStop(dom, "destroyed");
    event = virDomainEventNewFromObj(dom,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    if (dom && !dom->persistent)
        virDomainRemoveInactive(&data->driver->domains, dom);

    if (dom)
        virDomainObjUnlock(dom);
    if (event)
        umlDomainEventQueue(data->driver, event);
    virHashRemoveEntry(data->driver->autodestroy, uuidstr);
}

/*
 * Precondition: driver is locked
 */
static void umlProcessAutoDestroyRun(struct uml_driver *driver, virConnectPtr conn)
{
    struct umlProcessAutoDestroyData data = {
        driver, conn
    };
    VIR_DEBUG("conn=%p", conn);
    virHashForEach(driver->autodestroy, umlProcessAutoDestroyDom, &data);
}

static void umlProcessAutoDestroyShutdown(struct uml_driver *driver)
{
    virHashFree(driver->autodestroy);
}

static int umlProcessAutoDestroyAdd(struct uml_driver *driver,
                                    virDomainObjPtr vm,
                                    virConnectPtr conn)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(vm->def->uuid, uuidstr);
    VIR_DEBUG("vm=%s uuid=%s conn=%p", vm->def->name, uuidstr, conn);
    if (virHashAddEntry(driver->autodestroy, uuidstr, conn) < 0)
        return -1;
    return 0;
}

static int umlProcessAutoDestroyRemove(struct uml_driver *driver,
                                       virDomainObjPtr vm)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(vm->def->uuid, uuidstr);
    VIR_DEBUG("vm=%s uuid=%s", vm->def->name, uuidstr);
    if (virHashRemoveEntry(driver->autodestroy, uuidstr) < 0)
        return -1;
    return 0;
}


734
static int umlReadPidFile(struct uml_driver *driver,
735 736 737 738 739 740 741 742
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
743 744
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
745
        virReportOOMError();
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
        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;
761
        VIR_FORCE_FCLOSE(file);
762 763 764
        goto cleanup;
    }

765
    if (VIR_FCLOSE(file) < 0)
766 767 768 769 770 771
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
772
        virReportSystemError(errno,
773 774
                             _("failed to read pid: %s"),
                             pidfile);
775 776 777 778
    VIR_FREE(pidfile);
    return rc;
}

779
static int umlMonitorAddress(const struct uml_driver *driver,
780 781 782
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
783
    int retval = 0;
784

785 786
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
787
        virReportOOMError();
788 789 790
        return -1;
    }

791
    memset(addr, 0, sizeof(*addr));
792
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
793
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
794
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
795 796 797
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
798
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
799
    return retval;
800 801
}

802
static int umlOpenMonitor(struct uml_driver *driver,
803 804 805 806
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
807
    umlDomainObjPrivatePtr priv = vm->privateData;
808

809
    if (umlMonitorAddress(driver, vm, &addr) < 0)
810 811
        return -1;

812
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
813 814 815
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
816
            retries++ < 50) {
817 818 819 820 821 822
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

823
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
824
        virReportSystemError(errno,
825
                             "%s", _("cannot open socket"));
826 827 828
        return -1;
    }

829
    memset(addr.sun_path, 0, sizeof(addr.sun_path));
E
Eric Blake 已提交
830 831
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
832
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
833
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
834
        virReportSystemError(errno,
835
                             "%s", _("cannot bind socket"));
836
        VIR_FORCE_CLOSE(priv->monitor);
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        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];
};


863
static int umlMonitorCommand(const struct uml_driver *driver,
864 865 866 867 868 869 870 871 872 873
                             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;
874
    umlDomainObjPrivatePtr priv = vm->privateData;
875

876 877
    VIR_DEBUG("Run command '%s'", cmd);

878 879
    *reply = NULL;

880
    if (umlMonitorAddress(driver, vm, &addr) < 0)
881 882 883 884 885 886 887
        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)) {
888
        virReportSystemError(EINVAL,
889 890
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
891 892
        return -1;
    }
C
Chris Lalancette 已提交
893
    if (virStrcpyStatic(req.data, cmd) == NULL) {
894
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
895 896 897
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
898

899 900
    if (sendto(priv->monitor, &req, sizeof(req), 0,
               (struct sockaddr *)&addr, sizeof(addr)) != sizeof(req)) {
901
        virReportSystemError(errno,
902 903
                             _("cannot send command %s"),
                             cmd);
904 905 906 907
        return -1;
    }

    do {
E
Eric Blake 已提交
908
        ssize_t nbytes;
909
        addrlen = sizeof(addr);
910
        nbytes = recvfrom(priv->monitor, &res, sizeof(res), 0,
911
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
912 913 914
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
915
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
916 917
            goto error;
        }
918 919 920
        /* 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) {
921 922 923
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
924 925

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
926
            virReportOOMError();
927 928 929 930 931 932 933 934 935 936 937
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

938 939
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

940 941 942 943
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
944 945 946 947 948 949 950 951 952

    return ret;

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


953
static void umlCleanupTapDevices(virDomainObjPtr vm) {
954 955 956 957 958 959 960 961 962
    int i;

    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;

963
        ignore_value(virNetDevTapDelete(def->ifname));
964 965 966
    }
}

967 968
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
969 970
                            virDomainObjPtr vm,
                            bool autoDestroy) {
971
    int ret = -1;
972 973
    char *logfile;
    int logfd = -1;
974
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
975
    virCommandPtr cmd = NULL;
976
    size_t i;
977

D
Daniel P. Berrange 已提交
978
    if (virDomainObjIsActive(vm)) {
979
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
980
                       _("VM is already active"));
981 982 983 984
        return -1;
    }

    if (!vm->def->os.kernel) {
985 986
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
987 988 989 990 991 992
        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 已提交
993
    if (!virFileIsExecutable(vm->def->os.kernel)) {
994
        virReportSystemError(errno,
995 996
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
997 998 999
        return -1;
    }

1000
    if (virFileMakePath(driver->logDir) < 0) {
1001
        virReportSystemError(errno,
1002 1003
                             _("cannot create log directory %s"),
                             driver->logDir);
1004 1005 1006
        return -1;
    }

1007 1008
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
1009
        virReportOOMError();
1010 1011 1012 1013 1014
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
1015
        virReportSystemError(errno,
1016 1017
                             _("failed to create logfile %s"),
                             logfile);
1018 1019 1020 1021 1022
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

E
Eric Blake 已提交
1023 1024 1025
    if (virSetCloseExec(logfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
1026
        VIR_FORCE_CLOSE(logfd);
1027 1028 1029
        return -1;
    }

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    /* Do this upfront, so any part of the startup process can add
     * runtime state to vm->def that won't be persisted. This let's us
     * report implicit runtime defaults in the XML, like vnc listen/socket
     */
    VIR_DEBUG("Setting current domain def as transient");
    if (virDomainObjSetDefTransient(driver->caps, vm, true) < 0) {
        VIR_FORCE_CLOSE(logfd);
        return -1;
    }

1040 1041
    if (!(cmd = umlBuildCommandLine(conn, driver, vm)))
        goto cleanup;
1042

1043 1044 1045 1046 1047 1048 1049 1050
    for (i = 0 ; i < vm->def->nconsoles ; i++) {
        VIR_FREE(vm->def->consoles[i]->info.alias);
        if (virAsprintf(&vm->def->consoles[i]->info.alias, "console%zu", i) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

D
Daniel P. Berrange 已提交
1051
    virCommandWriteArgLog(cmd, logfd);
1052

1053
    priv->monitor = -1;
1054

D
Daniel P. Berrange 已提交
1055 1056 1057 1058 1059 1060
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
1061 1062
    if (ret < 0)
        goto cleanup;
1063

1064
    if (autoDestroy &&
1065
        (ret = umlProcessAutoDestroyAdd(driver, vm, conn)) < 0)
1066 1067
        goto cleanup;

1068
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
1069
cleanup:
1070
    VIR_FORCE_CLOSE(logfd);
D
Daniel P. Berrange 已提交
1071
    virCommandFree(cmd);
1072

1073 1074
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
1075
        umlCleanupTapDevices(vm);
1076 1077 1078 1079 1080 1081
        if (vm->newDef) {
            virDomainDefFree(vm->def);
            vm->def = vm->newDef;
            vm->def->id = -1;
            vm->newDef = NULL;
        }
1082 1083
    }

1084 1085
    /* NB we don't mark it running here - we do that async
       with inotify */
1086 1087 1088
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
1089
    /* XXX this is bad for events too. must fix this better */
1090 1091 1092 1093

    return ret;
}

1094
static void umlShutdownVMDaemon(struct uml_driver *driver,
J
Jiri Denemark 已提交
1095 1096
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
1097 1098
{
    int ret;
1099 1100
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
1101
    if (!virDomainObjIsActive(vm))
1102 1103
        return;

1104
    virKillProcess(vm->pid, SIGTERM);
1105

1106
    VIR_FORCE_CLOSE(priv->monitor);
1107 1108

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
1109
        VIR_WARN("Got unexpected pid %d != %d",
1110 1111 1112 1113 1114
               ret, vm->pid);
    }

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

1117
    virDomainConfVMNWFilterTeardown(vm);
1118 1119 1120 1121
    umlCleanupTapDevices(vm);

    /* Stop autodestroy in case guest is restarted */
    umlProcessAutoDestroyRemove(driver, vm);
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    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 已提交
1134 1135 1136 1137
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1138 1139 1140
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
1141

1142 1143 1144
        if (!(conn->uri = virURIParse(uml_driver->privileged ?
                                      "uml:///system" :
                                      "uml:///session")))
1145 1146 1147 1148 1149 1150 1151 1152 1153
            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;
1154 1155


1156
        /* Check path and tell them correct path if they made a mistake */
1157
        if (uml_driver->privileged) {
1158
            if (STRNEQ (conn->uri->path, "/system") &&
1159
                STRNEQ (conn->uri->path, "/session")) {
1160
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1161 1162 1163 1164 1165 1166
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1167
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1168 1169 1170 1171
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1172
        }
1173 1174 1175

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1176
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1177
                           _("uml state driver is not active"));
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1188 1189 1190
    struct uml_driver *driver = conn->privateData;

    umlDriverLock(driver);
1191 1192
    virDomainEventStateDeregisterConn(conn,
                                      driver->domainEventState);
1193
    umlProcessAutoDestroyRun(driver, conn);
1194
    umlDriverUnlock(driver);
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

    conn->privateData = NULL;

    return 0;
}

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


1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
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;
}


1220 1221 1222 1223 1224 1225
static int umlIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}


1226 1227 1228 1229
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1230
    umlDriverLock(driver);
1231
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1232
        virReportOOMError();
1233
    umlDriverUnlock(driver);
1234 1235 1236 1237 1238 1239

    return xml;
}



1240
static int umlGetProcessInfo(unsigned long long *cpuTime, pid_t pid)
1241 1242
{
    char *proc;
1243 1244 1245
    FILE *pidinfo;
    unsigned long long usertime, systime;

1246
    if (virAsprintf(&proc, "/proc/%lld/stat", (long long) pid) < 0) {
1247 1248 1249 1250 1251 1252
        return -1;
    }

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

1257 1258
    VIR_FREE(proc);

1259 1260
    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");
1261
        VIR_FORCE_FCLOSE(pidinfo);
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        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);

1274
    VIR_FORCE_FCLOSE(pidinfo);
1275 1276 1277 1278 1279 1280 1281 1282

    return 0;
}


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

1286
    umlDriverLock(driver);
1287
    vm = virDomainFindByID(&driver->domains, id);
1288 1289
    umlDriverUnlock(driver);

1290
    if (!vm) {
1291
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1292
        goto cleanup;
1293 1294 1295 1296
    }

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

cleanup:
1299 1300
    if (vm)
        virDomainObjUnlock(vm);
1301 1302
    return dom;
}
1303

1304 1305 1306
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1307 1308
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1309

1310
    umlDriverLock(driver);
1311
    vm = virDomainFindByUUID(&driver->domains, uuid);
1312 1313
    umlDriverUnlock(driver);

1314
    if (!vm) {
1315
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1316
        goto cleanup;
1317 1318 1319 1320
    }

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

cleanup:
1323 1324
    if (vm)
        virDomainObjUnlock(vm);
1325 1326
    return dom;
}
1327

1328 1329 1330
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1331 1332
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1333

1334
    umlDriverLock(driver);
1335
    vm = virDomainFindByName(&driver->domains, name);
1336 1337
    umlDriverUnlock(driver);

1338
    if (!vm) {
1339
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1340
        goto cleanup;
1341 1342 1343 1344
    }

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

cleanup:
1347 1348
    if (vm)
        virDomainObjUnlock(vm);
1349 1350 1351
    return dom;
}

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

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) {
1363
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
        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) {
1385
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
        goto cleanup;
    }
    ret = obj->persistent;

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

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
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;
}
1416

1417
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1418
    struct uml_driver *driver = conn->privateData;
1419
    struct utsname ut;
1420
    int ret = -1;
1421

1422
    umlDriverLock(driver);
1423 1424 1425 1426

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

1427
        if (virParseVersionString(ut.release, &driver->umlVersion, true) < 0) {
1428
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1429 1430 1431
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1432 1433
    }

1434 1435 1436 1437 1438 1439
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1440 1441 1442
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1443
    struct uml_driver *driver = conn->privateData;
1444
    int n;
1445

1446
    umlDriverLock(driver);
1447
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1448
    umlDriverUnlock(driver);
1449

1450
    return n;
1451 1452
}
static int umlNumDomains(virConnectPtr conn) {
1453
    struct uml_driver *driver = conn->privateData;
1454
    int n;
1455

1456
    umlDriverLock(driver);
1457
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1458
    umlDriverUnlock(driver);
1459 1460 1461 1462

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1463
                                      unsigned int flags) {
1464
    struct uml_driver *driver = conn->privateData;
1465
    virDomainDefPtr def;
1466
    virDomainObjPtr vm = NULL;
1467
    virDomainPtr dom = NULL;
1468
    virDomainEventPtr event = NULL;
1469

1470
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, NULL);
1471

1472
    umlDriverLock(driver);
1473
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1474
                                        1 << VIR_DOMAIN_VIRT_UML,
1475
                                        VIR_DOMAIN_XML_INACTIVE)))
1476
        goto cleanup;
1477

1478
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1479
        goto cleanup;
1480

1481
    if (!(vm = virDomainAssignDef(driver->caps,
1482
                                  &driver->domains,
1483
                                  def, false)))
1484 1485
        goto cleanup;
    def = NULL;
1486

1487 1488
    if (umlStartVMDaemon(conn, driver, vm,
                         (flags & VIR_DOMAIN_START_AUTODESTROY)) < 0) {
1489
        virDomainAuditStart(vm, "booted", false);
1490 1491
        virDomainRemoveInactive(&driver->domains,
                                vm);
1492 1493
        vm = NULL;
        goto cleanup;
1494
    }
1495
    virDomainAuditStart(vm, "booted", true);
1496 1497 1498
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1499 1500 1501

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1502 1503 1504

cleanup:
    virDomainDefFree(def);
1505 1506
    if (vm)
        virDomainObjUnlock(vm);
1507 1508
    if (event)
        umlDomainEventQueue(driver, event);
1509
    umlDriverUnlock(driver);
1510 1511 1512 1513
    return dom;
}


1514 1515
static int umlDomainShutdownFlags(virDomainPtr dom,
                                  unsigned int flags) {
1516 1517
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1518
    char *info = NULL;
1519
    int ret = -1;
1520

1521 1522
    virCheckFlags(0, -1);

1523
    umlDriverLock(driver);
1524
    vm = virDomainFindByID(&driver->domains, dom->id);
1525
    umlDriverUnlock(driver);
1526
    if (!vm) {
1527
        umlReportError(VIR_ERR_NO_DOMAIN,
1528
                       _("no domain with matching id %d"), dom->id);
1529
        goto cleanup;
1530 1531 1532 1533
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1534 1535
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1536
        goto cleanup;
1537
    }
1538
    ret = 0;
1539 1540
#endif

1541 1542
cleanup:
    VIR_FREE(info);
1543 1544
    if (vm)
        virDomainObjUnlock(vm);
1545
    return ret;
1546 1547
}

1548 1549 1550 1551 1552
static int
umlDomainShutdown(virDomainPtr dom)
{
    return umlDomainShutdownFlags(dom, 0);
}
1553

1554 1555 1556 1557
static int
umlDomainDestroyFlags(virDomainPtr dom,
                      unsigned int flags)
{
1558 1559
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1560
    virDomainEventPtr event = NULL;
1561
    int ret = -1;
1562

1563 1564
    virCheckFlags(0, -1);

1565
    umlDriverLock(driver);
1566
    vm = virDomainFindByID(&driver->domains, dom->id);
1567
    if (!vm) {
1568
        umlReportError(VIR_ERR_NO_DOMAIN,
1569
                       _("no domain with matching id %d"), dom->id);
1570
        goto cleanup;
1571 1572
    }

1573
    umlShutdownVMDaemon(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1574
    virDomainAuditStop(vm, "destroyed");
1575 1576 1577
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1578
    if (!vm->persistent) {
1579 1580
        virDomainRemoveInactive(&driver->domains,
                                vm);
1581 1582 1583
        vm = NULL;
    }
    ret = 0;
1584

1585
cleanup:
1586 1587
    if (vm)
        virDomainObjUnlock(vm);
1588 1589
    if (event)
        umlDomainEventQueue(driver, event);
1590
    umlDriverUnlock(driver);
1591
    return ret;
1592 1593 1594
}


1595 1596 1597 1598 1599 1600
static int umlDomainDestroy(virDomainPtr dom)
{
    return umlDomainDestroyFlags(dom, 0);
}


1601
static char *umlDomainGetOSType(virDomainPtr dom) {
1602 1603 1604
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1605

1606
    umlDriverLock(driver);
1607
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1608
    umlDriverUnlock(driver);
1609
    if (!vm) {
1610
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1611
                       _("no domain with matching uuid"));
1612
        goto cleanup;
1613 1614
    }

1615
    if (!(type = strdup(vm->def->os.type)))
1616
        virReportOOMError();
1617 1618

cleanup:
1619 1620
    if (vm)
        virDomainObjUnlock(vm);
1621 1622 1623 1624
    return type;
}

/* Returns max memory in kb, 0 if error */
1625 1626 1627
static unsigned long long
umlDomainGetMaxMemory(virDomainPtr dom)
{
1628 1629
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1630
    unsigned long long ret = 0;
1631

1632
    umlDriverLock(driver);
1633
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1634 1635
    umlDriverUnlock(driver);

1636 1637 1638 1639
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1640
        umlReportError(VIR_ERR_NO_DOMAIN,
1641 1642
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1643
    }
1644
    ret = vm->def->mem.max_balloon;
1645

1646
cleanup:
1647 1648
    if (vm)
        virDomainObjUnlock(vm);
1649
    return ret;
1650 1651 1652
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1653 1654 1655
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1656

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

1661 1662 1663 1664
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1665
        umlReportError(VIR_ERR_NO_DOMAIN,
1666
                       _("no domain with matching uuid '%s'"), uuidstr);
1667
        goto cleanup;
1668 1669
    }

1670
    if (newmax < vm->def->mem.cur_balloon) {
1671 1672
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1673
        goto cleanup;
1674 1675
    }

1676
    vm->def->mem.max_balloon = newmax;
1677 1678 1679
    ret = 0;

cleanup:
1680 1681
    if (vm)
        virDomainObjUnlock(vm);
1682
    return ret;
1683 1684 1685
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1686 1687 1688
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1689

1690
    umlDriverLock(driver);
1691
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1692 1693
    umlDriverUnlock(driver);

1694 1695 1696 1697
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1698
        umlReportError(VIR_ERR_NO_DOMAIN,
1699
                       _("no domain with matching uuid '%s'"), uuidstr);
1700
        goto cleanup;
1701 1702
    }

D
Daniel P. Berrange 已提交
1703
    if (virDomainObjIsActive(vm)) {
1704
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1705
                       _("cannot set memory of an active domain"));
1706
        goto cleanup;
1707 1708
    }

1709
    if (newmem > vm->def->mem.max_balloon) {
1710 1711
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1712
        goto cleanup;
1713 1714
    }

1715
    vm->def->mem.cur_balloon = newmem;
1716 1717 1718
    ret = 0;

cleanup:
1719 1720
    if (vm)
        virDomainObjUnlock(vm);
1721
    return ret;
1722 1723 1724 1725
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1726 1727 1728 1729
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1730
    umlDriverLock(driver);
1731
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1732 1733
    umlDriverUnlock(driver);

1734
    if (!vm) {
1735
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1736
                       _("no domain with matching uuid"));
1737
        goto cleanup;
1738 1739
    }

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

D
Daniel P. Berrange 已提交
1742
    if (!virDomainObjIsActive(vm)) {
1743 1744 1745
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1746 1747
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1748
            goto cleanup;
1749 1750 1751
        }
    }

1752 1753
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1754
    info->nrVirtCpu = vm->def->vcpus;
1755 1756 1757
    ret = 0;

cleanup:
1758 1759
    if (vm)
        virDomainObjUnlock(vm);
1760
    return ret;
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
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 已提交
1786
    *state = virDomainObjGetState(vm, reason);
1787 1788 1789 1790 1791 1792 1793 1794 1795
    ret = 0;

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


1796
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1797 1798
                                 unsigned int flags)
{
1799 1800 1801 1802
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1803
    /* Flags checked by virDomainDefFormat */
E
Eric Blake 已提交
1804

1805
    umlDriverLock(driver);
1806
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1807 1808
    umlDriverUnlock(driver);

1809
    if (!vm) {
1810
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1811
                       _("no domain with matching uuid"));
1812
        goto cleanup;
1813 1814
    }

1815
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1816 1817 1818 1819
                             vm->newDef : vm->def,
                             flags);

cleanup:
1820 1821
    if (vm)
        virDomainObjUnlock(vm);
1822
    return ret;
1823 1824 1825 1826 1827
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1828
    struct uml_driver *driver = conn->privateData;
1829
    int n;
1830

1831
    umlDriverLock(driver);
1832
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1833
    umlDriverUnlock(driver);
1834

1835
    return n;
1836 1837 1838
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1839
    struct uml_driver *driver = conn->privateData;
1840
    int n;
1841

1842
    umlDriverLock(driver);
1843
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1844
    umlDriverUnlock(driver);
1845 1846 1847 1848 1849

    return n;
}


1850
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1851 1852
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1853
    virDomainEventPtr event = NULL;
1854
    int ret = -1;
1855

1856
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, -1);
1857

1858
    umlDriverLock(driver);
1859
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1860

1861
    if (!vm) {
1862
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1863
                       _("no domain with matching uuid"));
1864
        goto cleanup;
1865 1866
    }

1867 1868
    ret = umlStartVMDaemon(dom->conn, driver, vm,
                           (flags & VIR_DOMAIN_START_AUTODESTROY));
1869
    virDomainAuditStart(vm, "booted", ret >= 0);
1870 1871 1872 1873
    if (ret == 0)
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
1874 1875

cleanup:
1876 1877
    if (vm)
        virDomainObjUnlock(vm);
1878 1879
    if (event)
        umlDomainEventQueue(driver, event);
1880
    umlDriverUnlock(driver);
1881
    return ret;
1882 1883
}

1884 1885 1886
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1887 1888

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1889
    struct uml_driver *driver = conn->privateData;
1890
    virDomainDefPtr def;
1891
    virDomainObjPtr vm = NULL;
1892
    virDomainPtr dom = NULL;
1893

1894
    umlDriverLock(driver);
1895
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1896
                                        1 << VIR_DOMAIN_VIRT_UML,
1897
                                        VIR_DOMAIN_XML_INACTIVE)))
1898
        goto cleanup;
1899

1900 1901 1902
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1903
    if (!(vm = virDomainAssignDef(driver->caps,
1904
                                  &driver->domains,
1905
                                  def, false)))
1906 1907
        goto cleanup;
    def = NULL;
1908 1909
    vm->persistent = 1;

1910
    if (virDomainSaveConfig(driver->configDir,
1911 1912 1913
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1914
        vm = NULL;
1915
        goto cleanup;
1916 1917 1918 1919
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1920 1921 1922

cleanup:
    virDomainDefFree(def);
1923 1924 1925
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1926 1927 1928
    return dom;
}

1929 1930 1931
static int umlDomainUndefineFlags(virDomainPtr dom,
                                  unsigned int flags)
{
1932 1933 1934
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1935

1936 1937
    virCheckFlags(0, -1);

1938
    umlDriverLock(driver);
1939
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1940
    if (!vm) {
1941
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1942
                       _("no domain with matching uuid"));
1943
        goto cleanup;
1944 1945 1946
    }

    if (!vm->persistent) {
1947
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1948
                       _("cannot undefine transient domain"));
1949
        goto cleanup;
1950 1951
    }

1952
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1953
        goto cleanup;
1954

1955 1956 1957 1958 1959 1960 1961
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

1962
    ret = 0;
1963

1964
cleanup:
1965 1966 1967
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1968
    return ret;
1969 1970 1971
}


1972 1973 1974 1975 1976
static int umlDomainUndefine(virDomainPtr dom)
{
    return umlDomainUndefineFlags(dom, 0);
}

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 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
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;
}


2085 2086 2087 2088 2089 2090 2091
static int
umlDomainAttachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2092
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
        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;
}


2197 2198 2199 2200 2201 2202 2203
static int
umlDomainDetachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2204
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2205 2206 2207 2208 2209 2210 2211 2212
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

2213 2214 2215

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
2216 2217 2218
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2219

2220
    umlDriverLock(driver);
2221
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2222

2223
    if (!vm) {
2224
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2225
                       _("no domain with matching uuid"));
2226
        goto cleanup;
2227 2228 2229
    }

    *autostart = vm->autostart;
2230
    ret = 0;
2231

2232
cleanup:
2233 2234
    if (vm)
        virDomainObjUnlock(vm);
2235
    umlDriverUnlock(driver);
2236
    return ret;
2237 2238 2239 2240
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2241
    struct uml_driver *driver = dom->conn->privateData;
2242
    virDomainObjPtr vm;
2243 2244 2245
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2246 2247 2248
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

2249
    if (!vm) {
2250
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2251
                       _("no domain with matching uuid"));
2252
        goto cleanup;
2253 2254 2255
    }

    if (!vm->persistent) {
2256
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
2257
                       _("cannot set autostart for transient domain"));
2258
        goto cleanup;
2259 2260 2261 2262
    }

    autostart = (autostart != 0);

2263
    if (vm->autostart != autostart) {
2264
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2265
            goto cleanup;
2266
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2267
            goto cleanup;
2268

2269
        if (autostart) {
2270 2271
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2272 2273
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2274 2275
                goto cleanup;
            }
2276

2277
            if (symlink(configFile, autostartLink) < 0) {
2278
                virReportSystemError(errno,
2279 2280
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2281 2282 2283 2284
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2285
                virReportSystemError(errno,
2286 2287
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2288 2289
                goto cleanup;
            }
2290 2291
        }

2292
        vm->autostart = autostart;
2293 2294 2295 2296 2297 2298
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2299 2300
    if (vm)
        virDomainObjUnlock(vm);
2301
    umlDriverUnlock(driver);
2302 2303 2304 2305 2306
    return ret;
}


static int
2307 2308 2309 2310
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2311
                   unsigned int flags)
2312
{
2313 2314
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2315 2316
    int fd = -1, ret = -1;
    const char *actual;
2317

E
Eric Blake 已提交
2318 2319
    virCheckFlags(0, -1);

2320
    umlDriverLock(driver);
2321
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2322 2323
    umlDriverUnlock(driver);

2324
    if (!vm) {
2325
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2326
                       _("no domain with matching uuid"));
2327
        goto cleanup;
2328 2329 2330
    }

    if (!path || path[0] == '\0') {
2331 2332
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2333
        goto cleanup;
2334 2335 2336
    }

    /* Check the path belongs to this domain. */
2337 2338 2339 2340
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
        umlReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path '%s'"), path);
        goto cleanup;
2341
    }
2342
    path = actual;
2343

2344 2345 2346 2347 2348 2349 2350
    /* The path is correct, now try to open it and get its size. */
    fd = open(path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("cannot open %s"), path);
        goto cleanup;
    }
2351

2352 2353 2354 2355 2356 2357 2358 2359 2360
    /* 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) {
        virReportSystemError(errno,
                             _("cannot read %s"), path);
        goto cleanup;
2361 2362
    }

2363 2364
    ret = 0;

2365
cleanup:
2366
    VIR_FORCE_CLOSE(fd);
2367 2368
    if (vm)
        virDomainObjUnlock(vm);
2369 2370 2371 2372
    return ret;
}


2373 2374
static int
umlDomainOpenConsole(virDomainPtr dom,
2375
                     const char *dev_name,
2376 2377 2378 2379 2380 2381 2382 2383
                     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;
2384
    size_t i;
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402

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

2403
    if (dev_name) {
2404 2405 2406 2407 2408 2409 2410
        for (i = 0 ; i < vm->def->nconsoles ; i++) {
            if (vm->def->consoles[i]->info.alias &&
                STREQ(vm->def->consoles[i]->info.alias, dev_name)) {
                chr = vm->def->consoles[i];
                break;
            }
        }
2411
    } else {
2412 2413
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
2414 2415 2416 2417 2418 2419
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
2420 2421
                       _("cannot find console device '%s'"),
                       dev_name ? dev_name : _("default"));
2422 2423 2424
        goto cleanup;
    }

2425
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2426
        umlReportError(VIR_ERR_INTERNAL_ERROR,
2427
                        _("character device %s is not using a PTY"), dev_name);
2428 2429 2430
        goto cleanup;
    }

2431
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
2432
                            0, 0, O_RDWR) < 0)
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
        goto cleanup;

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

2443

2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
static int
umlDomainEventRegister(virConnectPtr conn,
                       virConnectDomainEventCallback callback,
                       void *opaque,
                       virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
2454 2455 2456
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
    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);
2490 2491 2492 2493
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
2494
        ret = -1;
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
    umlDriverUnlock(driver);

    return ret;
}


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

    umlDriverLock(driver);
2509 2510 2511
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    umlDriverUnlock(driver);

    return ret;
}


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



2527
static virDriver umlDriver = {
2528 2529
    .no = VIR_DRV_UML,
    .name = "UML",
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
    .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 */
2544
    .domainShutdownFlags = umlDomainShutdownFlags, /* 0.9.10 */
2545
    .domainDestroy = umlDomainDestroy, /* 0.5.0 */
2546
    .domainDestroyFlags = umlDomainDestroyFlags, /* 0.9.4 */
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
    .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 */
2560
    .domainUndefineFlags = umlDomainUndefineFlags, /* 0.9.4 */
2561 2562 2563 2564 2565 2566 2567
    .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 */
2568
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2569
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2570 2571
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.5.0 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.5.0 */
2572 2573
    .domainEventRegister = umlDomainEventRegister, /* 0.9.4 */
    .domainEventDeregister = umlDomainEventDeregister, /* 0.9.4 */
2574 2575 2576 2577 2578
    .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 */
2579 2580
    .domainEventRegisterAny = umlDomainEventRegisterAny, /* 0.9.4 */
    .domainEventDeregisterAny = umlDomainEventDeregisterAny, /* 0.9.4 */
2581
    .domainOpenConsole = umlDomainOpenConsole, /* 0.8.6 */
2582
    .isAlive = umlIsAlive, /* 0.9.8 */
2583
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
2584 2585
};

2586 2587 2588 2589 2590 2591 2592 2593
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2594 2595

static virStateDriver umlStateDriver = {
2596
    .name = "UML",
2597 2598 2599 2600 2601 2602
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2615 2616 2617
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2618 2619
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2620 2621
};

2622 2623 2624
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2625
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2626 2627
    return 0;
}