bhyve_driver.c 47.2 KB
Newer Older
R
Roman Bogorodskiy 已提交
1 2 3 4
/*
 * bhyve_driver.c: core driver methods for managing bhyve guests
 *
 * Copyright (C) 2014 Roman Bogorodskiy
5
 * Copyright (C) 2014-2015 Red Hat, Inc.
R
Roman Bogorodskiy 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Roman Bogorodskiy
 */

#include <config.h>

26
#include <fcntl.h>
R
Roman Bogorodskiy 已提交
27 28 29 30 31 32 33 34 35 36 37
#include <sys/utsname.h>

#include "virerror.h"
#include "datatypes.h"
#include "virbuffer.h"
#include "viruuid.h"
#include "configmake.h"
#include "viralloc.h"
#include "network_conf.h"
#include "interface_conf.h"
#include "domain_audit.h"
R
Roman Bogorodskiy 已提交
38
#include "domain_event.h"
R
Roman Bogorodskiy 已提交
39
#include "snapshot_conf.h"
40
#include "virfdstream.h"
R
Roman Bogorodskiy 已提交
41 42
#include "storage_conf.h"
#include "node_device_conf.h"
43
#include "virdomainobjlist.h"
R
Roman Bogorodskiy 已提交
44 45 46 47 48 49 50 51 52
#include "virxml.h"
#include "virthread.h"
#include "virlog.h"
#include "virfile.h"
#include "virtypedparam.h"
#include "virrandom.h"
#include "virstring.h"
#include "cpu/cpu.h"
#include "viraccessapicheck.h"
53 54
#include "virhostcpu.h"
#include "virhostmem.h"
55
#include "virportallocator.h"
56
#include "conf/domain_capabilities.h"
R
Roman Bogorodskiy 已提交
57

58
#include "bhyve_conf.h"
59
#include "bhyve_device.h"
R
Roman Bogorodskiy 已提交
60
#include "bhyve_driver.h"
61
#include "bhyve_command.h"
62
#include "bhyve_parse_command.h"
63
#include "bhyve_domain.h"
R
Roman Bogorodskiy 已提交
64
#include "bhyve_process.h"
65
#include "bhyve_capabilities.h"
R
Roman Bogorodskiy 已提交
66 67 68

#define VIR_FROM_THIS   VIR_FROM_BHYVE

69 70
VIR_LOG_INIT("bhyve.bhyve_driver");

R
Roman Bogorodskiy 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84
bhyveConnPtr bhyve_driver = NULL;

void
bhyveDriverLock(bhyveConnPtr driver)
{
    virMutexLock(&driver->lock);
}

void
bhyveDriverUnlock(bhyveConnPtr driver)
{
    virMutexUnlock(&driver->lock);
}

85 86 87 88 89 90 91 92 93 94 95
static int
bhyveAutostartDomain(virDomainObjPtr vm, void *opaque)
{
    const struct bhyveAutostartData *data = opaque;
    int ret = 0;
    virObjectLock(vm);
    if (vm->autostart && !virDomainObjIsActive(vm)) {
        virResetLastError();
        ret = virBhyveProcessStart(data->conn, data->driver, vm,
                                   VIR_DOMAIN_RUNNING_BOOTED, 0);
        if (ret < 0) {
96 97 98
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to autostart VM '%s': %s"),
                           vm->def->name, virGetLastErrorMessage());
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        }
    }
    virObjectUnlock(vm);
    return ret;
}

static void
bhyveAutostartDomains(bhyveConnPtr driver)
{
    /* 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
     */
    virConnectPtr conn = virConnectOpen("bhyve:///system");
    /* Ignoring NULL conn which is mostly harmless here */

    struct bhyveAutostartData data = { driver, conn };

    virDomainObjListForEach(driver->domains, bhyveAutostartDomain, &data);

    virObjectUnref(conn);
}

123 124 125 126 127 128 129 130 131 132
/**
 * bhyveDriverGetCapabilities:
 *
 * Get a reference to the virCapsPtr instance for the
 * driver.
 *
 * The caller must release the reference with virObjetUnref
 *
 * Returns: a reference to a virCapsPtr instance or NULL
 */
M
Michal Privoznik 已提交
133
virCapsPtr ATTRIBUTE_NONNULL(1)
134
bhyveDriverGetCapabilities(bhyveConnPtr driver)
R
Roman Bogorodskiy 已提交
135 136
{

137
    return virObjectRef(driver->caps);
R
Roman Bogorodskiy 已提交
138 139 140 141 142 143
}

static char *
bhyveConnectGetCapabilities(virConnectPtr conn)
{
    bhyveConnPtr privconn = conn->privateData;
144
    virCapsPtr caps;
145
    char *xml = NULL;
R
Roman Bogorodskiy 已提交
146 147 148 149

    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

150
    if (!(caps = bhyveDriverGetCapabilities(privconn))) {
151 152
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get Capabilities"));
153 154
        goto cleanup;
    }
155

156
    if (!(xml = virCapabilitiesFormatXML(caps)))
157
        goto cleanup;
R
Roman Bogorodskiy 已提交
158

159 160
 cleanup:
    virObjectUnref(caps);
R
Roman Bogorodskiy 已提交
161 162 163 164 165 166 167 168 169 170
    return xml;
}

static virDomainObjPtr
bhyveDomObjFromDomain(virDomainPtr domain)
{
    virDomainObjPtr vm;
    bhyveConnPtr privconn = domain->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

171
    vm = virDomainObjListFindByUUID(privconn->domains, domain->uuid);
R
Roman Bogorodskiy 已提交
172 173 174 175 176 177 178 179 180 181 182
    if (!vm) {
        virUUIDFormat(domain->uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s' (%s)"),
                       uuidstr, domain->name);
        return NULL;
    }

    return vm;
}

183 184 185 186 187 188 189 190 191 192 193

static int
bhyveConnectURIProbe(char **uri)
{
    if (bhyve_driver == NULL)
        return 0;

    return VIR_STRDUP(*uri, "bhyve:///system");
}


R
Roman Bogorodskiy 已提交
194 195 196
static virDrvOpenStatus
bhyveConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
197
                 virConfPtr conf ATTRIBUTE_UNUSED,
R
Roman Bogorodskiy 已提交
198 199 200 201
                 unsigned int flags)
{
     virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

202
     if (STRNEQ(conn->uri->path, "/system")) {
203 204 205 206 207 208 209 210 211 212
         virReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Unexpected bhyve URI path '%s', try bhyve:///system"),
                        conn->uri->path);
         return VIR_DRV_OPEN_ERROR;
     }

     if (bhyve_driver == NULL) {
         virReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("bhyve state driver is not active"));
         return VIR_DRV_OPEN_ERROR;
R
Roman Bogorodskiy 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225
     }

     if (virConnectOpenEnsureACL(conn) < 0)
         return VIR_DRV_OPEN_ERROR;

     conn->privateData = bhyve_driver;

     return VIR_DRV_OPEN_SUCCESS;
}

static int
bhyveConnectClose(virConnectPtr conn)
{
226 227 228
    bhyveConnPtr privconn = conn->privateData;

    virCloseCallbacksRun(privconn->closeCallbacks, conn, privconn->domains, privconn);
R
Roman Bogorodskiy 已提交
229 230 231 232 233 234
    conn->privateData = NULL;

    return 0;
}

static char *
235
bhyveConnectGetHostname(virConnectPtr conn)
R
Roman Bogorodskiy 已提交
236 237 238 239 240 241 242
{
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

    return virGetHostname();
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
static char *
bhyveConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    bhyveConnPtr privconn = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

    if (!privconn->hostsysinfo) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
        return NULL;
    }

    if (virSysinfoFormat(&buf, privconn->hostsysinfo) < 0)
        return NULL;
262
    if (virBufferCheckError(&buf) < 0)
263 264 265 266 267
        return NULL;

    return virBufferContentAndReset(&buf);
}

R
Roman Bogorodskiy 已提交
268
static int
269
bhyveConnectGetVersion(virConnectPtr conn, unsigned long *version)
R
Roman Bogorodskiy 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
{
    struct utsname ver;

    if (virConnectGetVersionEnsureACL(conn) < 0)
        return -1;

    uname(&ver);

    if (virParseVersionString(ver.release, version, true) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown release: %s"), ver.release);
        return -1;
    }

    return 0;
}

static int
bhyveDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainGetInfoEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

299 300 301 302 303 304 305
    if (virDomainObjIsActive(vm)) {
        if (virBhyveGetDomainTotalCpuStats(vm, &(info->cpuTime)) < 0)
            goto cleanup;
    } else {
        info->cpuTime = 0;
    }

R
Roman Bogorodskiy 已提交
306
    info->state = virDomainObjGetState(vm, NULL);
307
    info->maxMem = virDomainDefGetMemoryTotal(vm->def);
308
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
R
Roman Bogorodskiy 已提交
309 310
    ret = 0;

311
 cleanup:
312
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    return ret;
}

static int
bhyveDomainGetState(virDomainPtr domain,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainGetStateEnsureACL(domain->conn, vm->def) < 0)
       goto cleanup;

    *state = virDomainObjGetState(vm, reason);
    ret = 0;

336
 cleanup:
337
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
338 339 340
    return ret;
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
static int
bhyveDomainGetAutostart(virDomainPtr domain, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainGetAutostartEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

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

 cleanup:
357
    virDomainObjEndAPI(&vm);
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    return ret;
}

static int
bhyveDomainSetAutostart(virDomainPtr domain, int autostart)
{
    virDomainObjPtr vm;
    char *configFile = NULL;
    char *autostartLink = NULL;
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainSetAutostartEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

    if (!vm->persistent) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set autostart for transient domain"));
        goto cleanup;
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
        if ((configFile = virDomainConfigFile(BHYVE_CONFIG_DIR, vm->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virDomainConfigFile(BHYVE_AUTOSTART_DIR, vm->def->name)) == NULL)
            goto cleanup;

        if (autostart) {
            if (virFileMakePath(BHYVE_AUTOSTART_DIR) < 0) {
                virReportSystemError(errno,
                                     _("cannot create autostart directory %s"),
                                     BHYVE_AUTOSTART_DIR);
                goto cleanup;
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s' to '%s'"),
                                     autostartLink, configFile);
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
                goto cleanup;
            }
        }

        vm->autostart = autostart;
    }

    ret = 0;

 cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
420
    virDomainObjEndAPI(&vm);
421 422 423
    return ret;
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437
static int
bhyveDomainIsActive(virDomainPtr domain)
{
    virDomainObjPtr obj;
    int ret = -1;

    if (!(obj = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainIsActiveEnsureACL(domain->conn, obj->def) < 0)
        goto cleanup;

    ret = virDomainObjIsActive(obj);

438
 cleanup:
439
    virDomainObjEndAPI(&obj);
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    return ret;
}

static int
bhyveDomainIsPersistent(virDomainPtr domain)
{
    virDomainObjPtr obj;
    int ret = -1;

    if (!(obj = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainIsPersistentEnsureACL(domain->conn, obj->def) < 0)
        goto cleanup;

    ret = obj->persistent;

457
 cleanup:
458
    virDomainObjEndAPI(&obj);
459 460 461
    return ret;
}

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
static char *
bhyveDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *ret = NULL;

    if (!(vm = bhyveDomObjFromDomain(dom)))
        goto cleanup;

    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (VIR_STRDUP(ret, virDomainOSTypeToString(vm->def->os.type)) < 0)
        goto cleanup;

 cleanup:
478
    virDomainObjEndAPI(&vm);
479 480 481
    return ret;
}

R
Roman Bogorodskiy 已提交
482 483 484
static char *
bhyveDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
{
R
Roman Bogorodskiy 已提交
485
    bhyveConnPtr privconn = domain->conn->privateData;
R
Roman Bogorodskiy 已提交
486
    virDomainObjPtr vm;
487
    virCapsPtr caps = NULL;
R
Roman Bogorodskiy 已提交
488 489 490 491 492 493 494 495
    char *ret = NULL;

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainGetXMLDescEnsureACL(domain->conn, vm->def, flags) < 0)
        goto cleanup;

496 497 498 499 500
    caps = bhyveDriverGetCapabilities(privconn);
    if (!caps)
        goto cleanup;

    ret = virDomainDefFormat(vm->def, caps,
501
                             virDomainDefFormatConvertXMLFlags(flags));
R
Roman Bogorodskiy 已提交
502

503
    virObjectUnref(caps);
504
 cleanup:
505
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
506 507 508 509
    return ret;
}

static virDomainPtr
510
bhyveDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
R
Roman Bogorodskiy 已提交
511 512 513 514 515 516
{
    bhyveConnPtr privconn = conn->privateData;
    virDomainPtr dom = NULL;
    virDomainDefPtr def = NULL;
    virDomainDefPtr oldDef = NULL;
    virDomainObjPtr vm = NULL;
R
Roman Bogorodskiy 已提交
517
    virObjectEventPtr event = NULL;
518
    virCapsPtr caps = NULL;
519
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
520

521 522 523
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
524
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
525

526 527 528
    caps = bhyveDriverGetCapabilities(privconn);
    if (!caps)
        return NULL;
R
Roman Bogorodskiy 已提交
529

530
    if ((def = virDomainDefParseString(xml, caps, privconn->xmlopt,
531
                                       NULL, parse_flags)) == NULL)
R
Roman Bogorodskiy 已提交
532 533
        goto cleanup;

534 535 536
    if (virXMLCheckIllegalChars("name", def->name, "\n") < 0)
        goto cleanup;

537
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
R
Roman Bogorodskiy 已提交
538 539
        goto cleanup;

540 541 542
    if (bhyveDomainAssignAddresses(def, NULL) < 0)
        goto cleanup;

R
Roman Bogorodskiy 已提交
543 544 545 546 547
    if (!(vm = virDomainObjListAdd(privconn->domains, def,
                                   privconn->xmlopt,
                                   0, &oldDef)))
        goto cleanup;
    def = NULL;
548
    vm->persistent = 1;
R
Roman Bogorodskiy 已提交
549

550
    if (virDomainSaveConfig(BHYVE_CONFIG_DIR, caps,
551 552 553 554 555
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainObjListRemove(privconn->domains, vm);
        goto cleanup;
    }

R
Roman Bogorodskiy 已提交
556 557 558 559 560 561
    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_DEFINED,
                                              !oldDef ?
                                              VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                              VIR_DOMAIN_EVENT_DEFINED_UPDATED);

562
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
R
Roman Bogorodskiy 已提交
563

564
 cleanup:
565
    virObjectUnref(caps);
R
Roman Bogorodskiy 已提交
566
    virDomainDefFree(def);
567
    virDomainDefFree(oldDef);
568
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
569 570
    if (event)
        virObjectEventStateQueue(privconn->domainEventState, event);
R
Roman Bogorodskiy 已提交
571 572 573 574

    return dom;
}

575 576 577 578 579 580
static virDomainPtr
bhyveDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return bhyveDomainDefineXMLFlags(conn, xml, 0);
}

581 582 583 584
static int
bhyveDomainUndefine(virDomainPtr domain)
{
    bhyveConnPtr privconn = domain->conn->privateData;
R
Roman Bogorodskiy 已提交
585
    virObjectEventPtr event = NULL;
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    virDomainObjPtr vm;
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainUndefineEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

    if (!vm->persistent) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Cannot undefine transient domain"));
        goto cleanup;
    }

    if (virDomainDeleteConfig(BHYVE_CONFIG_DIR,
                              BHYVE_AUTOSTART_DIR,
                              vm) < 0)
        goto cleanup;

R
Roman Bogorodskiy 已提交
606 607 608 609
    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_UNDEFINED,
                                              VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

610
    if (virDomainObjIsActive(vm))
611
        vm->persistent = 0;
612
    else
613 614 615 616
        virDomainObjListRemove(privconn->domains, vm);

    ret = 0;

617
 cleanup:
618
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
619 620
    if (event)
        virObjectEventStateQueue(privconn->domainEventState, event);
621 622 623
    return ret;
}

R
Roman Bogorodskiy 已提交
624 625 626 627 628 629 630 631 632 633 634 635 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
static int
bhyveConnectListDomains(virConnectPtr conn, int *ids, int maxids)
{
    bhyveConnPtr privconn = conn->privateData;
    int n;

    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

    n = virDomainObjListGetActiveIDs(privconn->domains, ids, maxids,
                                     virConnectListDomainsCheckACL, conn);

    return n;
}

static int
bhyveConnectNumOfDomains(virConnectPtr conn)
{
    bhyveConnPtr privconn = conn->privateData;
    int count;

    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

    count = virDomainObjListNumOfDomains(privconn->domains, true,
                                         virConnectNumOfDomainsCheckACL, conn);

    return count;
}

static int
bhyveConnectListDefinedDomains(virConnectPtr conn, char **const names,
                               int maxnames)
{
    bhyveConnPtr privconn = conn->privateData;
    int n;

    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

    memset(names, 0, sizeof(*names) * maxnames);
    n = virDomainObjListGetInactiveNames(privconn->domains, names,
                                         maxnames, virConnectListDefinedDomainsCheckACL, conn);

    return n;
}

static int
bhyveConnectNumOfDefinedDomains(virConnectPtr conn)
{
    bhyveConnPtr privconn = conn->privateData;
    int count;

    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

    count = virDomainObjListNumOfDomains(privconn->domains, false,
                                         virConnectNumOfDefinedDomainsCheckACL, conn);

    return count;
}

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
static char *
bhyveConnectDomainXMLToNative(virConnectPtr conn,
                              const char *format,
                              const char *xmlData,
                              unsigned int flags)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    bhyveConnPtr privconn = conn->privateData;
    virDomainDefPtr def = NULL;
    virCommandPtr cmd = NULL, loadcmd = NULL;
    virCapsPtr caps = NULL;
    char *ret = NULL;

    virCheckFlags(0, NULL);

    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

    if (STRNEQ(format, BHYVE_CONFIG_FORMAT_ARGV)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config type %s"), format);
        goto cleanup;
    }

    if (!(caps = bhyveDriverGetCapabilities(privconn)))
        goto cleanup;

    if (!(def = virDomainDefParseString(xmlData, caps, privconn->xmlopt,
714
                                        NULL, VIR_DOMAIN_DEF_PARSE_INACTIVE)))
715 716
        goto cleanup;

717 718 719
    if (bhyveDomainAssignAddresses(def, NULL) < 0)
        goto cleanup;

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    if (def->os.bootloader == NULL &&
        def->os.loader) {

        if ((def->os.loader->readonly != VIR_TRISTATE_BOOL_YES) ||
            (def->os.loader->type != VIR_DOMAIN_LOADER_TYPE_PFLASH)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Only read-only pflash is supported."));
            goto cleanup;
        }

        if ((bhyveDriverGetCaps(conn) & BHYVE_CAP_LPC_BOOTROM) == 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Installed bhyve binary does not support "
                          "bootrom"));
            goto cleanup;
        }
    } else {
        if (!(loadcmd = virBhyveProcessBuildLoadCmd(conn, def, "<device.map>",
738
                                                NULL)))
739 740 741 742 743
            goto cleanup;

        virBufferAdd(&buf, virCommandToString(loadcmd), -1);
        virBufferAddChar(&buf, '\n');
    }
744

R
Roman Bogorodskiy 已提交
745
    if (!(cmd = virBhyveProcessBuildBhyveCmd(conn, def, true)))
746 747 748 749
        goto cleanup;

    virBufferAdd(&buf, virCommandToString(cmd), -1);

750
    if (virBufferCheckError(&buf) < 0)
751 752 753 754 755 756 757 758 759 760 761 762
        goto cleanup;

    ret = virBufferContentAndReset(&buf);

 cleanup:
    virCommandFree(loadcmd);
    virCommandFree(cmd);
    virDomainDefFree(def);
    virObjectUnref(caps);
    return ret;
}

R
Roman Bogorodskiy 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static int
bhyveConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
{
    bhyveConnPtr privconn = conn->privateData;
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

    ret = virDomainObjListExport(privconn->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);

    return ret;
}

static virDomainPtr
bhyveDomainLookupByUUID(virConnectPtr conn,
                        const unsigned char *uuid)
{
    bhyveConnPtr privconn = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

790
    vm = virDomainObjListFindByUUID(privconn->domains, uuid);
R
Roman Bogorodskiy 已提交
791 792 793 794 795 796 797 798 799 800 801 802

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

803
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
R
Roman Bogorodskiy 已提交
804

805
 cleanup:
806
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    return dom;
}

static virDomainPtr bhyveDomainLookupByName(virConnectPtr conn,
                                            const char *name)
{
    bhyveConnPtr privconn = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

    vm = virDomainObjListFindByName(privconn->domains, name);

    if (!vm) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), name);
        goto cleanup;
    }

    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

828
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
R
Roman Bogorodskiy 已提交
829

830
 cleanup:
831
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
832 833 834
    return dom;
}

W
Wojciech Macek 已提交
835 836 837 838 839 840 841 842
static virDomainPtr
bhyveDomainLookupByID(virConnectPtr conn,
                      int id)
{
    bhyveConnPtr privconn = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

843
    vm = virDomainObjListFindByID(privconn->domains, id);
W
Wojciech Macek 已提交
844 845 846 847 848 849 850 851 852 853

    if (!vm) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching ID '%d'"), id);
        goto cleanup;
    }

    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

854
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
W
Wojciech Macek 已提交
855 856

 cleanup:
857
    virDomainObjEndAPI(&vm);
W
Wojciech Macek 已提交
858 859 860
    return dom;
}

R
Roman Bogorodskiy 已提交
861
static int
862 863
bhyveDomainCreateWithFlags(virDomainPtr dom,
                           unsigned int flags)
R
Roman Bogorodskiy 已提交
864 865 866
{
    bhyveConnPtr privconn = dom->conn->privateData;
    virDomainObjPtr vm;
R
Roman Bogorodskiy 已提交
867
    virObjectEventPtr event = NULL;
868
    unsigned int start_flags = 0;
R
Roman Bogorodskiy 已提交
869 870
    int ret = -1;

871 872 873 874 875
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, -1);

    if (flags & VIR_DOMAIN_START_AUTODESTROY)
        start_flags |= VIR_BHYVE_PROCESS_START_AUTODESTROY;

R
Roman Bogorodskiy 已提交
876 877 878
    if (!(vm = bhyveDomObjFromDomain(dom)))
        goto cleanup;

879
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
R
Roman Bogorodskiy 已提交
880 881 882 883 884 885 886 887 888
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
        goto cleanup;
    }

    ret = virBhyveProcessStart(dom->conn, privconn, vm,
889 890
                               VIR_DOMAIN_RUNNING_BOOTED,
                               start_flags);
R
Roman Bogorodskiy 已提交
891

R
Roman Bogorodskiy 已提交
892 893 894 895 896
    if (ret == 0)
        event = virDomainEventLifecycleNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_STARTED,
                                                  VIR_DOMAIN_EVENT_STARTED_BOOTED);

897
 cleanup:
898
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
899 900
    if (event)
        virObjectEventStateQueue(privconn->domainEventState, event);
R
Roman Bogorodskiy 已提交
901 902 903
    return ret;
}

904 905 906 907 908 909
static int
bhyveDomainCreate(virDomainPtr dom)
{
    return bhyveDomainCreateWithFlags(dom, 0);
}

W
Wojciech Macek 已提交
910 911 912 913 914 915 916 917 918
static virDomainPtr
bhyveDomainCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
{
    bhyveConnPtr privconn = conn->privateData;
    virDomainPtr dom = NULL;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
R
Roman Bogorodskiy 已提交
919
    virObjectEventPtr event = NULL;
W
Wojciech Macek 已提交
920 921
    virCapsPtr caps = NULL;
    unsigned int start_flags = 0;
922
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
W
Wojciech Macek 已提交
923

924 925
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY |
                  VIR_DOMAIN_START_VALIDATE, NULL);
W
Wojciech Macek 已提交
926

927
    if (flags & VIR_DOMAIN_START_VALIDATE)
928
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
W
Wojciech Macek 已提交
929 930 931 932 933 934 935 936
    if (flags & VIR_DOMAIN_START_AUTODESTROY)
        start_flags |= VIR_BHYVE_PROCESS_START_AUTODESTROY;

    caps = bhyveDriverGetCapabilities(privconn);
    if (!caps)
        return NULL;

    if ((def = virDomainDefParseString(xml, caps, privconn->xmlopt,
937
                                       NULL, parse_flags)) == NULL)
W
Wojciech Macek 已提交
938 939 940 941 942
        goto cleanup;

    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

943 944 945
    if (bhyveDomainAssignAddresses(def, NULL) < 0)
        goto cleanup;

W
Wojciech Macek 已提交
946 947
    if (!(vm = virDomainObjListAdd(privconn->domains, def,
                                   privconn->xmlopt,
948
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
W
Wojciech Macek 已提交
949 950 951 952 953 954 955 956
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE, NULL)))
        goto cleanup;
    def = NULL;

    if (virBhyveProcessStart(conn, privconn, vm,
                             VIR_DOMAIN_RUNNING_BOOTED,
                             start_flags) < 0) {
        /* If domain is not persistent, remove its data */
957
        if (!vm->persistent)
W
Wojciech Macek 已提交
958 959 960 961
            virDomainObjListRemove(privconn->domains, vm);
        goto cleanup;
    }

R
Roman Bogorodskiy 已提交
962 963 964 965
    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_STARTED,
                                              VIR_DOMAIN_EVENT_STARTED_BOOTED);

966
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
W
Wojciech Macek 已提交
967 968 969 970

 cleanup:
    virObjectUnref(caps);
    virDomainDefFree(def);
971
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
972 973
    if (event)
        virObjectEventStateQueue(privconn->domainEventState, event);
W
Wojciech Macek 已提交
974 975 976 977

    return dom;
}

R
Roman Bogorodskiy 已提交
978 979 980 981 982
static int
bhyveDomainDestroy(virDomainPtr dom)
{
    bhyveConnPtr privconn = dom->conn->privateData;
    virDomainObjPtr vm;
R
Roman Bogorodskiy 已提交
983
    virObjectEventPtr event = NULL;
R
Roman Bogorodskiy 已提交
984 985 986 987 988 989 990 991
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(dom)))
        goto cleanup;

    if (virDomainDestroyEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

992 993 994 995 996 997
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
        goto cleanup;
    }

R
Roman Bogorodskiy 已提交
998
    ret = virBhyveProcessStop(privconn, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
R
Roman Bogorodskiy 已提交
999 1000 1001
    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
R
Roman Bogorodskiy 已提交
1002

1003
    if (!vm->persistent)
W
Wojciech Macek 已提交
1004 1005
        virDomainObjListRemove(privconn->domains, vm);

1006
 cleanup:
1007
    virDomainObjEndAPI(&vm);
R
Roman Bogorodskiy 已提交
1008 1009
    if (event)
        virObjectEventStateQueue(privconn->domainEventState, event);
R
Roman Bogorodskiy 已提交
1010 1011 1012
    return ret;
}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
static int
bhyveDomainShutdown(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

    if (!(vm = bhyveDomObjFromDomain(dom)))
        goto cleanup;

    if (virDomainShutdownEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

    ret = virBhyveProcessShutdown(vm);

 cleanup:
1034
    virDomainObjEndAPI(&vm);
1035 1036 1037
    return ret;
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
static int
bhyveDomainOpenConsole(virDomainPtr dom,
                       const char *dev_name ATTRIBUTE_UNUSED,
                       virStreamPtr st,
                       unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    virDomainChrDefPtr chr = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = bhyveDomObjFromDomain(dom)))
        goto cleanup;

    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

    if (!vm->def->nserials) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no console devices available"));
        goto cleanup;
    }

    chr = vm->def->serials[0];

1070
    if (virFDStreamOpenPTY(st, chr->source->data.nmdm.slave,
1071 1072 1073 1074 1075 1076
                           0, 0, O_RDWR) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
1077
    virDomainObjEndAPI(&vm);
1078 1079 1080
    return ret;
}

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
static int
bhyveDomainSetMetadata(virDomainPtr dom,
                       int type,
                       const char *metadata,
                       const char *key,
                       const char *uri,
                       unsigned int flags)
{
    bhyveConnPtr privconn = dom->conn->privateData;
    virDomainObjPtr vm;
    virCapsPtr caps = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (!(vm = bhyveDomObjFromDomain(dom)))
        return -1;

    if (virDomainSetMetadataEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

    if (!(caps = bhyveDriverGetCapabilities(privconn)))
        goto cleanup;

    ret = virDomainObjSetMetadata(vm, type, metadata, key, uri, caps,
1107 1108
                                  privconn->xmlopt, BHYVE_STATE_DIR,
                                  BHYVE_CONFIG_DIR, flags);
1109

1110 1111 1112 1113 1114 1115 1116
    if (ret == 0) {
        virObjectEventPtr ev = NULL;
        ev = virDomainEventMetadataChangeNewFromObj(vm, type, uri);
        virObjectEventStateQueue(privconn->domainEventState, ev);
    }


1117 1118
 cleanup:
    virObjectUnref(caps);
1119
    virDomainObjEndAPI(&vm);
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    return ret;
}

static char *
bhyveDomainGetMetadata(virDomainPtr dom,
                      int type,
                      const char *uri,
                      unsigned int flags)
{
    virDomainObjPtr vm;
    char *ret = NULL;

    if (!(vm = bhyveDomObjFromDomain(dom)))
        return NULL;

    if (virDomainGetMetadataEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1138
    ret = virDomainObjGetMetadata(vm, type, uri, flags);
1139 1140

 cleanup:
1141
    virDomainObjEndAPI(&vm);
1142 1143 1144
    return ret;
}

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
static int
bhyveNodeGetCPUStats(virConnectPtr conn,
                     int cpuNum,
                     virNodeCPUStatsPtr params,
                     int *nparams,
                     unsigned int flags)
{
    if (virNodeGetCPUStatsEnsureACL(conn) < 0)
        return -1;

1155
    return virHostCPUGetStats(cpuNum, params, nparams, flags);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
}

static int
bhyveNodeGetMemoryStats(virConnectPtr conn,
                        int cellNum,
                        virNodeMemoryStatsPtr params,
                        int *nparams,
                        unsigned int flags)
{
    if (virNodeGetMemoryStatsEnsureACL(conn) < 0)
        return -1;

1168
    return virHostMemGetStats(cellNum, params, nparams, flags);
1169 1170
}

1171 1172
static int
bhyveNodeGetInfo(virConnectPtr conn,
M
Martin Kletzander 已提交
1173
                 virNodeInfoPtr nodeinfo)
1174 1175 1176 1177
{
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

M
Martin Kletzander 已提交
1178
    return virCapabilitiesGetNodeInfo(nodeinfo);
1179 1180
}

R
Roman Bogorodskiy 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
static int
bhyveStateCleanup(void)
{
    VIR_DEBUG("bhyve state cleanup");

    if (bhyve_driver == NULL)
        return -1;

    virObjectUnref(bhyve_driver->domains);
    virObjectUnref(bhyve_driver->caps);
    virObjectUnref(bhyve_driver->xmlopt);
1192
    virSysinfoDefFree(bhyve_driver->hostsysinfo);
1193
    virObjectUnref(bhyve_driver->closeCallbacks);
1194
    virObjectUnref(bhyve_driver->domainEventState);
1195
    virObjectUnref(bhyve_driver->config);
1196
    virPortAllocatorRangeFree(bhyve_driver->remotePorts);
R
Roman Bogorodskiy 已提交
1197 1198 1199 1200 1201 1202 1203 1204

    virMutexDestroy(&bhyve_driver->lock);
    VIR_FREE(bhyve_driver);

    return 0;
}

static int
M
Martin Kletzander 已提交
1205
bhyveStateInitialize(bool privileged,
R
Roman Bogorodskiy 已提交
1206 1207 1208
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
M
Martin Kletzander 已提交
1209 1210
    if (!privileged) {
        VIR_INFO("Not running privileged, disabling driver");
R
Roman Bogorodskiy 已提交
1211 1212 1213
        return 0;
    }

1214
    if (VIR_ALLOC(bhyve_driver) < 0)
R
Roman Bogorodskiy 已提交
1215 1216 1217 1218 1219 1220 1221
        return -1;

    if (virMutexInit(&bhyve_driver->lock) < 0) {
        VIR_FREE(bhyve_driver);
        return -1;
    }

1222 1223 1224
    if (!(bhyve_driver->closeCallbacks = virCloseCallbacksNew()))
        goto cleanup;

1225
    if (!(bhyve_driver->caps = virBhyveCapsBuild()))
R
Roman Bogorodskiy 已提交
1226 1227
        goto cleanup;

R
Roman Bogorodskiy 已提交
1228 1229 1230
    if (virBhyveProbeCaps(&bhyve_driver->bhyvecaps) < 0)
        goto cleanup;

1231 1232 1233
    if (virBhyveProbeGrubCaps(&bhyve_driver->grubcaps) < 0)
        goto cleanup;

1234
    if (!(bhyve_driver->xmlopt = virBhyveDriverCreateXMLConf(bhyve_driver)))
R
Roman Bogorodskiy 已提交
1235 1236 1237 1238 1239
        goto cleanup;

    if (!(bhyve_driver->domains = virDomainObjListNew()))
        goto cleanup;

R
Roman Bogorodskiy 已提交
1240 1241 1242
    if (!(bhyve_driver->domainEventState = virObjectEventStateNew()))
        goto cleanup;

1243
    if (!(bhyve_driver->remotePorts = virPortAllocatorRangeNew(_("display"),
1244
                                                               5900, 65535)))
1245 1246
        goto cleanup;

1247 1248
    bhyve_driver->hostsysinfo = virSysinfoRead();

1249 1250 1251 1252 1253 1254
    if (!(bhyve_driver->config = virBhyveDriverConfigNew()))
        goto cleanup;

    if (virBhyveLoadDriverConfig(bhyve_driver->config, SYSCONFDIR "/libvirt/bhyve.conf") < 0)
        goto cleanup;

R
Roman Bogorodskiy 已提交
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    if (virFileMakePath(BHYVE_LOG_DIR) < 0) {
        virReportSystemError(errno,
                             _("Failed to mkdir %s"),
                             BHYVE_LOG_DIR);
        goto cleanup;
    }

    if (virFileMakePath(BHYVE_STATE_DIR) < 0) {
        virReportSystemError(errno,
                             _("Failed to mkdir %s"),
1265
                             BHYVE_STATE_DIR);
R
Roman Bogorodskiy 已提交
1266 1267 1268
        goto cleanup;
    }

1269 1270
    if (virDomainObjListLoadAllConfigs(bhyve_driver->domains,
                                       BHYVE_STATE_DIR,
1271
                                       NULL, true,
1272 1273 1274 1275 1276
                                       bhyve_driver->caps,
                                       bhyve_driver->xmlopt,
                                       NULL, NULL) < 0)
        goto cleanup;

R
Roman Bogorodskiy 已提交
1277 1278
    if (virDomainObjListLoadAllConfigs(bhyve_driver->domains,
                                       BHYVE_CONFIG_DIR,
1279
                                       BHYVE_AUTOSTART_DIR, false,
R
Roman Bogorodskiy 已提交
1280 1281 1282 1283 1284
                                       bhyve_driver->caps,
                                       bhyve_driver->xmlopt,
                                       NULL, NULL) < 0)
        goto cleanup;

1285 1286
    virBhyveProcessReconnectAll(bhyve_driver);

R
Roman Bogorodskiy 已提交
1287 1288
    return 0;

1289
 cleanup:
R
Roman Bogorodskiy 已提交
1290 1291 1292 1293
    bhyveStateCleanup();
    return -1;
}

R
Roman Bogorodskiy 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
unsigned
bhyveDriverGetCaps(virConnectPtr conn)
{
    bhyveConnPtr driver = conn->privateData;

    if (driver != NULL)
        return driver->bhyvecaps;
    return 0;
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
unsigned
bhyveDriverGetGrubCaps(virConnectPtr conn)
{
    bhyveConnPtr driver = conn->privateData;

    if (driver != NULL)
        return driver->grubcaps;
    return 0;
}

1314 1315 1316 1317 1318 1319 1320 1321 1322
static void
bhyveStateAutoStart(void)
{
    if (!bhyve_driver)
        return;

    bhyveAutostartDomains(bhyve_driver);
}

W
Wojciech Macek 已提交
1323
static int
1324
bhyveConnectGetMaxVcpus(virConnectPtr conn,
1325 1326
                        const char *type)
{
W
Wojciech Macek 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

    /*
     * Bhyve supports up to 16 VCPUs, but offers no method to check this
     * value. Hardcode 16...
     */
    if (!type || STRCASEEQ(type, "bhyve"))
        return 16;

    virReportError(VIR_ERR_INVALID_ARG, _("unknown type '%s'"), type);
    return -1;
}

static unsigned long long
bhyveNodeGetFreeMemory(virConnectPtr conn)
{
1344 1345
    unsigned long long freeMem;

W
Wojciech Macek 已提交
1346 1347 1348
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
        return 0;

1349
    if (virHostMemGetInfo(NULL, &freeMem) < 0)
1350 1351 1352
        return 0;

    return freeMem;
W
Wojciech Macek 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
}

static int
bhyveNodeGetCPUMap(virConnectPtr conn,
                   unsigned char **cpumap,
                   unsigned int *online,
                   unsigned int flags)
{
    if (virNodeGetCPUMapEnsureACL(conn) < 0)
        return -1;

1364
    return virHostCPUGetMap(cpumap, online, flags);
W
Wojciech Macek 已提交
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
}

static int
bhyveNodeGetMemoryParameters(virConnectPtr conn,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
{
    if (virNodeGetMemoryParametersEnsureACL(conn) < 0)
        return -1;

1376
    return virHostMemGetParameters(params, nparams, flags);
W
Wojciech Macek 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
}

static int
bhyveNodeSetMemoryParameters(virConnectPtr conn,
                             virTypedParameterPtr params,
                             int nparams,
                             unsigned int flags)
{
    if (virNodeSetMemoryParametersEnsureACL(conn) < 0)
        return -1;

1388
    return virHostMemSetParameters(params, nparams, flags);
W
Wojciech Macek 已提交
1389
}
R
Roman Bogorodskiy 已提交
1390

1391
static char *
1392
bhyveConnectBaselineCPU(virConnectPtr conn,
1393 1394 1395 1396
                        const char **xmlCPUs,
                        unsigned int ncpus,
                        unsigned int flags)
{
J
Jiri Denemark 已提交
1397 1398 1399
    virCPUDefPtr *cpus = NULL;
    virCPUDefPtr cpu = NULL;
    char *cpustr = NULL;
1400

1401 1402
    virCheckFlags(VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES |
                  VIR_CONNECT_BASELINE_CPU_MIGRATABLE, NULL);
1403 1404 1405 1406

    if (virConnectBaselineCPUEnsureACL(conn) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1407 1408 1409
    if (!(cpus = virCPUDefListParse(xmlCPUs, ncpus, VIR_CPU_TYPE_HOST)))
        goto cleanup;

J
Jiri Denemark 已提交
1410
    if (!(cpu = cpuBaseline(cpus, ncpus, NULL,
J
Jiri Denemark 已提交
1411 1412 1413 1414 1415 1416 1417
                            !!(flags & VIR_CONNECT_BASELINE_CPU_MIGRATABLE))))
        goto cleanup;

    if ((flags & VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES) &&
        virCPUExpandFeatures(cpus[0]->arch, cpu) < 0)
        goto cleanup;

1418
    cpustr = virCPUDefFormat(cpu, NULL);
1419 1420

 cleanup:
J
Jiri Denemark 已提交
1421 1422 1423 1424
    virCPUDefListFree(cpus);
    virCPUDefFree(cpu);

    return cpustr;
1425 1426
}

1427 1428 1429 1430 1431 1432 1433 1434
static int
bhyveConnectCompareCPU(virConnectPtr conn,
                       const char *xmlDesc,
                       unsigned int flags)
{
    bhyveConnPtr driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;
    virCapsPtr caps = NULL;
1435
    bool failIncompatible;
1436

1437 1438
    virCheckFlags(VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE,
                  VIR_CPU_COMPARE_ERROR);
1439 1440 1441 1442

    if (virConnectCompareCPUEnsureACL(conn) < 0)
        goto cleanup;

1443
    failIncompatible = !!(flags & VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE);
1444

1445 1446 1447 1448 1449
    if (!(caps = bhyveDriverGetCapabilities(driver)))
        goto cleanup;

    if (!caps->host.cpu ||
        !caps->host.cpu->model) {
1450
        if (failIncompatible) {
1451 1452 1453 1454 1455 1456
            virReportError(VIR_ERR_CPU_INCOMPATIBLE, "%s",
                           _("cannot get host CPU capabilities"));
        } else {
            VIR_WARN("cannot get host CPU capabilities");
            ret = VIR_CPU_COMPARE_INCOMPATIBLE;
        }
1457
    } else {
1458 1459
        ret = virCPUCompareXML(caps->host.arch, caps->host.cpu,
                               xmlDesc, failIncompatible);
1460 1461 1462 1463 1464 1465 1466
    }

 cleanup:
    virObjectUnref(caps);
    return ret;
}

R
Roman Bogorodskiy 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
static int
bhyveConnectDomainEventRegisterAny(virConnectPtr conn,
                                   virDomainPtr dom,
                                   int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque,
                                   virFreeCallback freecb)
{
    bhyveConnPtr privconn = conn->privateData;
    int ret;

    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

    if (virDomainEventStateRegisterID(conn,
                                      privconn->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
        ret = -1;

    return ret;
}

static int
bhyveConnectDomainEventDeregisterAny(virConnectPtr conn,
                                     int callbackID)
{
    bhyveConnPtr privconn = conn->privateData;

    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

    if (virObjectEventStateDeregisterID(conn,
                                        privconn->domainEventState,
1501
                                        callbackID, true) < 0)
R
Roman Bogorodskiy 已提交
1502 1503 1504 1505 1506
        return -1;

    return 0;
}

1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
static int
bhyveDomainHasManagedSaveImage(virDomainPtr domain, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = bhyveDomObjFromDomain(domain)))
        goto cleanup;

    if (virDomainHasManagedSaveImageEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
1524
    virDomainObjEndAPI(&vm);
1525 1526 1527
    return ret;
}

1528 1529 1530 1531 1532 1533 1534 1535 1536
static const char *
bhyveConnectGetType(virConnectPtr conn)
{
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

    return "BHYVE";
}

1537 1538 1539 1540 1541
static int bhyveConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}

1542 1543 1544 1545 1546 1547 1548
static int
bhyveConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}

1549 1550 1551 1552 1553 1554 1555
static int
bhyveConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
static char *
bhyveConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
                                unsigned int flags)
{
    char *xml = NULL;
    virDomainDefPtr def = NULL;
    bhyveConnPtr privconn = conn->privateData;
    virCapsPtr capabilities = NULL;
    unsigned caps = bhyveDriverGetCaps(conn);

    virCheckFlags(0, NULL);

    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        return NULL;

    capabilities = bhyveDriverGetCapabilities(privconn);
    if (!capabilities)
        return NULL;

    if (STRNEQ(nativeFormat, BHYVE_CONFIG_FORMAT_ARGV)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
        goto cleanup;
    }

    def = bhyveParseCommandLineString(nativeConfig, caps, privconn->xmlopt);
    if (def == NULL)
        goto cleanup;

    xml = virDomainDefFormat(def, capabilities, 0);

 cleanup:
    virObjectUnref(capabilities);
    virDomainDefFree(def);
    return xml;
}

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 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 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
static char *
bhyveConnectGetDomainCapabilities(virConnectPtr conn,
                                  const char *emulatorbin,
                                  const char *arch_str,
                                  const char *machine,
                                  const char *virttype_str,
                                  unsigned int flags)
{
    virDomainCapsPtr caps = NULL;
    char *ret = NULL;
    int virttype = VIR_DOMAIN_VIRT_BHYVE;
    int arch = virArchFromHost(); /* virArch */

    virCheckFlags(0, ret);

    if (virConnectGetDomainCapabilitiesEnsureACL(conn) < 0)
        return ret;

    if (virttype_str &&
        (virttype = virDomainVirtTypeFromString(virttype_str)) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown virttype: %s"),
                       virttype_str);
        goto cleanup;
    }

    if (virttype != VIR_DOMAIN_VIRT_BHYVE) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown virttype: %s"),
                       virttype_str);
        goto cleanup;
    }

    if (arch_str && (arch = virArchFromString(arch_str)) == VIR_ARCH_NONE) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown architecture: %s"),
                       arch_str);
        goto cleanup;
    }

    if (!ARCH_IS_X86(arch)) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("unsupported architecture: %s"),
                       virArchToString(arch));
        goto cleanup;
    }

    if (emulatorbin == NULL) {
        emulatorbin = "/usr/sbin/bhyve";
    } else if (STRNEQ(emulatorbin, "/usr/sbin/bhyve")) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown emulator binary: %s"),
                       emulatorbin);
        goto cleanup;
    }

1651 1652
    if (!(caps = virBhyveDomainCapsBuild(conn->privateData, emulatorbin,
                                         machine, arch, virttype)))
1653 1654 1655 1656 1657 1658 1659 1660 1661
        goto cleanup;

    ret = virDomainCapsFormat(caps);

 cleanup:
    virObjectUnref(caps);
    return ret;
}

1662
static virHypervisorDriver bhyveHypervisorDriver = {
R
Roman Bogorodskiy 已提交
1663
    .name = "bhyve",
1664
    .connectURIProbe = bhyveConnectURIProbe,
R
Roman Bogorodskiy 已提交
1665 1666 1667 1668
    .connectOpen = bhyveConnectOpen, /* 1.2.2 */
    .connectClose = bhyveConnectClose, /* 1.2.2 */
    .connectGetVersion = bhyveConnectGetVersion, /* 1.2.2 */
    .connectGetHostname = bhyveConnectGetHostname, /* 1.2.2 */
1669
    .connectGetSysinfo = bhyveConnectGetSysinfo, /* 1.2.5 */
R
Roman Bogorodskiy 已提交
1670 1671 1672 1673 1674 1675 1676 1677
    .domainGetInfo = bhyveDomainGetInfo, /* 1.2.2 */
    .domainGetState = bhyveDomainGetState, /* 1.2.2 */
    .connectGetCapabilities = bhyveConnectGetCapabilities, /* 1.2.2 */
    .connectListDomains = bhyveConnectListDomains, /* 1.2.2 */
    .connectNumOfDomains = bhyveConnectNumOfDomains, /* 1.2.2 */
    .connectListAllDomains = bhyveConnectListAllDomains, /* 1.2.2 */
    .connectListDefinedDomains = bhyveConnectListDefinedDomains, /* 1.2.2 */
    .connectNumOfDefinedDomains = bhyveConnectNumOfDefinedDomains, /* 1.2.2 */
1678
    .connectDomainXMLToNative = bhyveConnectDomainXMLToNative, /* 1.2.5 */
R
Roman Bogorodskiy 已提交
1679
    .domainCreate = bhyveDomainCreate, /* 1.2.2 */
1680
    .domainCreateWithFlags = bhyveDomainCreateWithFlags, /* 1.2.3 */
W
Wojciech Macek 已提交
1681
    .domainCreateXML = bhyveDomainCreateXML, /* 1.2.4 */
R
Roman Bogorodskiy 已提交
1682
    .domainDestroy = bhyveDomainDestroy, /* 1.2.2 */
1683
    .domainShutdown = bhyveDomainShutdown, /* 1.3.3 */
R
Roman Bogorodskiy 已提交
1684 1685
    .domainLookupByUUID = bhyveDomainLookupByUUID, /* 1.2.2 */
    .domainLookupByName = bhyveDomainLookupByName, /* 1.2.2 */
W
Wojciech Macek 已提交
1686
    .domainLookupByID = bhyveDomainLookupByID, /* 1.2.3 */
R
Roman Bogorodskiy 已提交
1687
    .domainDefineXML = bhyveDomainDefineXML, /* 1.2.2 */
1688
    .domainDefineXMLFlags = bhyveDomainDefineXMLFlags, /* 1.2.12 */
1689
    .domainUndefine = bhyveDomainUndefine, /* 1.2.2 */
1690
    .domainGetOSType = bhyveDomainGetOSType, /* 1.2.21 */
R
Roman Bogorodskiy 已提交
1691
    .domainGetXMLDesc = bhyveDomainGetXMLDesc, /* 1.2.2 */
1692 1693
    .domainIsActive = bhyveDomainIsActive, /* 1.2.2 */
    .domainIsPersistent = bhyveDomainIsPersistent, /* 1.2.2 */
1694 1695
    .domainGetAutostart = bhyveDomainGetAutostart, /* 1.2.4 */
    .domainSetAutostart = bhyveDomainSetAutostart, /* 1.2.4 */
1696
    .domainOpenConsole = bhyveDomainOpenConsole, /* 1.2.4 */
1697 1698
    .domainSetMetadata = bhyveDomainSetMetadata, /* 1.2.4 */
    .domainGetMetadata = bhyveDomainGetMetadata, /* 1.2.4 */
1699 1700
    .nodeGetCPUStats = bhyveNodeGetCPUStats, /* 1.2.2 */
    .nodeGetMemoryStats = bhyveNodeGetMemoryStats, /* 1.2.2 */
1701
    .nodeGetInfo = bhyveNodeGetInfo, /* 1.2.3 */
W
Wojciech Macek 已提交
1702 1703 1704 1705 1706
    .connectGetMaxVcpus = bhyveConnectGetMaxVcpus, /* 1.2.3 */
    .nodeGetFreeMemory = bhyveNodeGetFreeMemory, /* 1.2.3 */
    .nodeGetCPUMap = bhyveNodeGetCPUMap, /* 1.2.3 */
    .nodeGetMemoryParameters = bhyveNodeGetMemoryParameters, /* 1.2.3 */
    .nodeSetMemoryParameters = bhyveNodeSetMemoryParameters, /* 1.2.3 */
1707
    .connectBaselineCPU = bhyveConnectBaselineCPU, /* 1.2.4 */
1708
    .connectCompareCPU = bhyveConnectCompareCPU, /* 1.2.4 */
R
Roman Bogorodskiy 已提交
1709 1710
    .connectDomainEventRegisterAny = bhyveConnectDomainEventRegisterAny, /* 1.2.5 */
    .connectDomainEventDeregisterAny = bhyveConnectDomainEventDeregisterAny, /* 1.2.5 */
1711
    .domainHasManagedSaveImage = bhyveDomainHasManagedSaveImage, /* 1.2.13 */
1712
    .connectGetType = bhyveConnectGetType, /* 1.3.5 */
1713
    .connectIsAlive = bhyveConnectIsAlive, /* 1.3.5 */
1714
    .connectIsSecure = bhyveConnectIsSecure, /* 1.3.5 */
1715
    .connectIsEncrypted = bhyveConnectIsEncrypted, /* 1.3.5 */
1716
    .connectDomainXMLFromNative = bhyveConnectDomainXMLFromNative, /* 2.1.0 */
1717
    .connectGetDomainCapabilities = bhyveConnectGetDomainCapabilities, /* 2.1.0 */
R
Roman Bogorodskiy 已提交
1718 1719 1720
};


1721
static virConnectDriver bhyveConnectDriver = {
1722
    .localOnly = true,
1723
    .uriSchemes = (const char *[]){ "bhyve", NULL },
1724 1725 1726
    .hypervisorDriver = &bhyveHypervisorDriver,
};

R
Roman Bogorodskiy 已提交
1727 1728 1729
static virStateDriver bhyveStateDriver = {
    .name = "bhyve",
    .stateInitialize = bhyveStateInitialize,
1730
    .stateAutoStart = bhyveStateAutoStart,
R
Roman Bogorodskiy 已提交
1731 1732 1733 1734 1735 1736
    .stateCleanup = bhyveStateCleanup,
};

int
bhyveRegister(void)
{
1737 1738
    if (virRegisterConnectDriver(&bhyveConnectDriver,
                                 true) < 0)
1739
        return -1;
1740
    if (virRegisterStateDriver(&bhyveStateDriver) < 0)
1741
        return -1;
1742
    return 0;
R
Roman Bogorodskiy 已提交
1743
}