Esempio n. 1
0
int virSystemdTerminateMachine(const char *name)
{
    int ret;
    DBusConnection *conn;
    virError error;

    if (!name)
        return 0;

    memset(&error, 0, sizeof(error));

    if ((ret = virSystemdHasMachined()) < 0)
        goto cleanup;

    ret = -1;

    if (!(conn = virDBusGetSystemBus()))
        goto cleanup;

    /*
     * The systemd DBus API we're invoking has the
     * following signature
     *
     * TerminateMachine(in  s name);
     *
     * @name a host unique name for the machine. shows up
     * in 'ps' listing & similar
     */

    VIR_DEBUG("Attempting to terminate machine via systemd");
    if (virDBusCallMethod(conn,
                          NULL,
                          &error,
                          "org.freedesktop.machine1",
                          "/org/freedesktop/machine1",
                          "org.freedesktop.machine1.Manager",
                          "TerminateMachine",
                          "s",
                          name) < 0)
        goto cleanup;

    if (error.level == VIR_ERR_ERROR &&
        STRNEQ_NULLABLE("org.freedesktop.machine1.NoSuchMachine",
                        error.str1)) {
        virReportErrorObject(&error);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    virResetError(&error);

    return ret;
}
Esempio n. 2
0
static char *
getSocketPath(virURIPtr uri)
{
    char *rundir = virGetUserRuntimeDirectory();
    char *sock_path = NULL;
    size_t i = 0;

    if (!uri)
        goto cleanup;


    for (i = 0; i < uri->paramsCount; i++) {
        virURIParamPtr param = &uri->params[i];

        if (STREQ(param->name, "socket")) {
            VIR_FREE(sock_path);
            if (VIR_STRDUP(sock_path, param->value) < 0)
                goto error;
        } else {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unknown URI parameter '%s'"), param->name);
            goto error;
        }
    }

    if (!sock_path) {
        if (STRNEQ_NULLABLE(uri->scheme, "libvirtd")) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported URI scheme '%s'"),
                           NULLSTR(uri->scheme));
            goto error;
        }
        if (STREQ_NULLABLE(uri->path, "/system")) {
            if (VIR_STRDUP(sock_path, LIBVIRTD_ADMIN_UNIX_SOCKET) < 0)
                goto error;
        } else if (STREQ_NULLABLE(uri->path, "/session")) {
            if (!rundir || virAsprintf(&sock_path, "%s%s", rundir,
                                       LIBVIRTD_ADMIN_SOCK_NAME) < 0)
                goto error;
        } else {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Invalid URI path '%s', try '/system'"),
                           uri->path ? uri->path : "");
            goto error;
        }
    }

 cleanup:
    VIR_FREE(rundir);
    return sock_path;

 error:
    VIR_FREE(sock_path);
    goto cleanup;
}
Esempio n. 3
0
static bool
virCapsDomainDataCompare(virCapsGuestPtr guest,
                         virCapsGuestDomainPtr domain,
                         virCapsGuestMachinePtr machine,
                         int ostype,
                         virArch arch,
                         int domaintype,
                         const char *emulator,
                         const char *machinetype)
{
    const char *check_emulator = NULL;

    if (ostype != -1 && guest->ostype != ostype)
        return false;
    if ((arch != VIR_ARCH_NONE) && (guest->arch.id != arch))
        return false;

    if (domaintype != -1 && (!domain || domain->type != domaintype))
        return false;

    if (emulator) {
        if (domain)
            check_emulator = domain->info.emulator;
        if (!check_emulator)
            check_emulator = guest->arch.defaultInfo.emulator;
        if (STRNEQ_NULLABLE(check_emulator, emulator))
            return false;
    }

    if (machinetype) {
        if (!machine)
            return false;
        if (STRNEQ(machine->name, machinetype) &&
            (STRNEQ_NULLABLE(machine->canonical, machinetype)))
            return false;
    }

    return true;
}
Esempio n. 4
0
/**
 * virIdentityIsEqual:
 * @identA: the first identity
 * @identB: the second identity
 *
 * Compares every attribute in @identA and @identB
 * to determine if they refer to the same identity
 *
 * Returns true if they are equal, false if not equal
 */
bool virIdentityIsEqual(virIdentityPtr identA,
                        virIdentityPtr identB)
{
    bool ret = false;
    size_t i;
    VIR_DEBUG("identA=%p identB=%p", identA, identB);

    for (i = 0; i < VIR_IDENTITY_ATTR_LAST; i++) {
        if (STRNEQ_NULLABLE(identA->attrs[i],
                            identB->attrs[i]))
            goto cleanup;
    }

    ret = true;
 cleanup:
    return ret;
}
Esempio n. 5
0
static int
testVirNetDevBandwidthSet(const void *data)
{
    int ret = -1;
    const struct testSetStruct *info = data;
    const char *iface = info->iface;
    virNetDevBandwidthPtr band = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *actual_cmd = NULL;

    PARSE(info->band, band);

    if (!iface)
        iface = "eth0";

    virCommandSetDryRun(&buf, NULL, NULL);

    if (virNetDevBandwidthSet(iface, band, info->hierarchical_class) < 0)
        goto cleanup;

    if (!(actual_cmd = virBufferContentAndReset(&buf))) {
        int err = virBufferError(&buf);
        if (err) {
            fprintf(stderr, "buffer's in error state: %d", err);
            goto cleanup;
        }
        /* This is interesting, no command has been executed.
         * Maybe that's expected, actually. */
    }

    if (STRNEQ_NULLABLE(info->exp_cmd, actual_cmd)) {
        virTestDifference(stderr,
                          NULLSTR(info->exp_cmd),
                          NULLSTR(actual_cmd));
        goto cleanup;
    }

    ret = 0;
cleanup:
    virCommandSetDryRun(NULL, NULL, NULL);
    virNetDevBandwidthFree(band);
    virBufferFreeAndReset(&buf);
    VIR_FREE(actual_cmd);
    return ret;
}
Esempio n. 6
0
static virDrvOpenStatus
bhyveConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
{
     virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

     if (conn->uri == NULL) {
         if (bhyve_driver == NULL)
             return VIR_DRV_OPEN_DECLINED;

         if (!(conn->uri = virURIParse("bhyve:///system")))
             return VIR_DRV_OPEN_ERROR;
     } else {
         if (!conn->uri->scheme || STRNEQ(conn->uri->scheme, "bhyve"))
             return VIR_DRV_OPEN_DECLINED;

         if (conn->uri->server)
             return VIR_DRV_OPEN_DECLINED;

         if (STRNEQ_NULLABLE(conn->uri->path, "/system")) {
            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;
         }
     }

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

     conn->privateData = bhyve_driver;

     return VIR_DRV_OPEN_SUCCESS;
}
Esempio n. 7
0
static int
testCryptoHash(const void *opaque)
{
    const struct testCryptoHashData *data = opaque;
    char *actual = NULL;
    int ret = -1;

    if (virCryptoHashString(data->hash, data->input, &actual) < 0) {
        fprintf(stderr, "Failed to generate crypto hash\n");
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(data->output, actual)) {
        fprintf(stderr, "Expected hash '%s' but got '%s'\n",
                data->output, NULLSTR(actual));
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(actual);
    return ret;
}
Esempio n. 8
0
static int
testQemuCommandBuildObjectFromJSON(const void *opaque)
{
    const testQemuCommandBuildObjectFromJSONData *data = opaque;
    virJSONValuePtr val = NULL;
    char *expect = NULL;
    char *result = NULL;
    int ret = -1;

    if (!(val = virJSONValueFromString(data->props))) {
        fprintf(stderr, "Failed to parse JSON string '%s'", data->props);
        return -1;
    }

    if (virAsprintf(&expect, "testobject,id=testalias%s%s",
                    data->expectprops ? "," : "",
                    data->expectprops ? data->expectprops : "") < 0)
        return -1;

    result = qemuBuildObjectCommandlineFromJSON("testobject",
                                                "testalias",
                                                val);

    if (STRNEQ_NULLABLE(expect, result)) {
        fprintf(stderr, "\nFailed to create object string. "
                "\nExpected:\n'%s'\nGot:\n'%s'",
                NULLSTR(expect), NULLSTR(result));
        goto cleanup;
    }

    ret = 0;
 cleanup:
    virJSONValueFree(val);
    VIR_FREE(result);
    VIR_FREE(expect);
    return ret;
}
Esempio n. 9
0
static int
testVirPCIDeviceCheckDriver(virPCIDevicePtr dev, const char *expected)
{
    char *path = NULL;
    char *driver = NULL;
    int ret = -1;

    if (virPCIDeviceGetDriverPathAndName(dev, &path, &driver) < 0)
        goto cleanup;

    if (STRNEQ_NULLABLE(driver, expected)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "PCI device %s driver mismatch: %s, expecting %s",
                       virPCIDeviceGetName(dev), NULLSTR(driver),
                       NULLSTR(expected));
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(path);
    VIR_FREE(driver);
    return ret;
}
Esempio n. 10
0
static int
testJSONAddRemove(const void *data)
{
    const struct testInfo *info = data;
    virJSONValuePtr json;
    virJSONValuePtr name = NULL;
    char *result = NULL;
    int ret = -1;

    json = virJSONValueFromString(info->doc);
    if (!json) {
        VIR_TEST_VERBOSE("Fail to parse %s\n", info->name);
        ret = -1;
        goto cleanup;
    }

    switch (virJSONValueObjectRemoveKey(json, "name", &name)) {
    case 1:
        if (!info->pass) {
            VIR_TEST_VERBOSE("should not remove from non-object %s\n",
                             info->name);
            goto cleanup;
        }
        break;
    case -1:
        if (!info->pass)
            ret = 0;
        else
            VIR_TEST_VERBOSE("Fail to recognize non-object %s\n", info->name);
        goto cleanup;
    default:
        VIR_TEST_VERBOSE("unexpected result when removing from %s\n",
                         info->name);
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(virJSONValueGetString(name), "sample")) {
        VIR_TEST_VERBOSE("unexpected value after removing name: %s\n",
                         NULLSTR(virJSONValueGetString(name)));
        goto cleanup;
    }
    if (virJSONValueObjectRemoveKey(json, "name", NULL)) {
        VIR_TEST_VERBOSE("%s",
                         "unexpected success when removing missing key\n");
        goto cleanup;
    }
    if (virJSONValueObjectAppendString(json, "newname", "foo") < 0) {
        VIR_TEST_VERBOSE("%s", "unexpected failure adding new key\n");
        goto cleanup;
    }
    if (!(result = virJSONValueToString(json, false))) {
        VIR_TEST_VERBOSE("%s", "failed to stringize result\n");
        goto cleanup;
    }
    if (STRNEQ(info->expect, result)) {
        virTestDifference(stderr, info->expect, result);
        goto cleanup;
    }
    ret = 0;

 cleanup:
    virJSONValueFree(json);
    virJSONValueFree(name);
    VIR_FREE(result);
    return ret;
}
Esempio n. 11
0
static int
testJSONLookup(const void *data)
{
    const struct testInfo *info = data;
    virJSONValuePtr json;
    virJSONValuePtr value = NULL;
    char *result = NULL;
    int rc;
    int number;
    const char *str;
    int ret = -1;

    json = virJSONValueFromString(info->doc);
    if (!json) {
        VIR_TEST_VERBOSE("Fail to parse %s\n", info->doc);
        ret = -1;
        goto cleanup;
    }

    value = virJSONValueObjectGetObject(json, "a");
    if (value) {
        if (!info->pass) {
            VIR_TEST_VERBOSE("lookup for 'a' in '%s' should have failed\n",
                             info->doc);
            goto cleanup;
        } else {
            result = virJSONValueToString(value, false);
            if (STRNEQ_NULLABLE(result, "{}")) {
                VIR_TEST_VERBOSE("lookup for 'a' in '%s' found '%s' but "
                                 "should have found '{}'\n",
                                 info->doc, NULLSTR(result));
                goto cleanup;
            }
            VIR_FREE(result);
        }
    } else if (info->pass) {
        VIR_TEST_VERBOSE("lookup for 'a' in '%s' should have succeeded\n",
                         info->doc);
        goto cleanup;
    }

    number = 2;
    rc = virJSONValueObjectGetNumberInt(json, "b", &number);
    if (rc == 0) {
        if (!info->pass) {
            VIR_TEST_VERBOSE("lookup for 'b' in '%s' should have failed\n",
                             info->doc);
            goto cleanup;
        } else if (number != 1) {
            VIR_TEST_VERBOSE("lookup for 'b' in '%s' found %d but "
                             "should have found 1\n",
                             info->doc, number);
            goto cleanup;
        }
    } else if (info->pass) {
        VIR_TEST_VERBOSE("lookup for 'b' in '%s' should have succeeded\n",
                         info->doc);
        goto cleanup;
    }

    str = virJSONValueObjectGetString(json, "c");
    if (str) {
        if (!info->pass) {
            VIR_TEST_VERBOSE("lookup for 'c' in '%s' should have failed\n",
                             info->doc);
            goto cleanup;
        } else if (STRNEQ(str, "str")) {
            VIR_TEST_VERBOSE("lookup for 'c' in '%s' found '%s' but "
                             "should have found 'str'\n", info->doc, str);
                goto cleanup;
        }
    } else if (info->pass) {
        VIR_TEST_VERBOSE("lookup for 'c' in '%s' should have succeeded\n",
                         info->doc);
        goto cleanup;
    }

    value = virJSONValueObjectGetArray(json, "d");
    if (value) {
        if (!info->pass) {
            VIR_TEST_VERBOSE("lookup for 'd' in '%s' should have failed\n",
                             info->doc);
            goto cleanup;
        } else {
            result = virJSONValueToString(value, false);
            if (STRNEQ_NULLABLE(result, "[]")) {
                VIR_TEST_VERBOSE("lookup for 'd' in '%s' found '%s' but "
                                 "should have found '[]'\n",
                                 info->doc, NULLSTR(result));
                goto cleanup;
            }
            VIR_FREE(result);
        }
    } else if (info->pass) {
        VIR_TEST_VERBOSE("lookup for 'd' in '%s' should have succeeded\n",
                         info->doc);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    virJSONValueFree(json);
    VIR_FREE(result);
    return ret;
}
Esempio n. 12
0
bool
virCPUDefIsEqual(virCPUDefPtr src,
                 virCPUDefPtr dst)
{
    bool identical = false;
    int i;

    if (!src && !dst)
        return true;

    if ((src && !dst) || (!src && dst)) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("Target CPU does not match source"));
        goto cleanup;
    }

    if (src->type != dst->type) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU type %s does not match source %s"),
                          virCPUTypeToString(dst->type),
                          virCPUTypeToString(src->type));
        goto cleanup;
    }

    if (src->mode != dst->mode) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU mode %s does not match source %s"),
                          virCPUModeTypeToString(dst->mode),
                          virCPUModeTypeToString(src->mode));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->arch, dst->arch)) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU arch %s does not match source %s"),
                          NULLSTR(dst->arch), NULLSTR(src->arch));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->model, dst->model)) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU model %s does not match source %s"),
                          NULLSTR(dst->model), NULLSTR(src->model));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->vendor, dst->vendor)) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU vendor %s does not match source %s"),
                          NULLSTR(dst->vendor), NULLSTR(src->vendor));
        goto cleanup;
    }

    if (src->sockets != dst->sockets) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU sockets %d does not match source %d"),
                          dst->sockets, src->sockets);
        goto cleanup;
    }

    if (src->cores != dst->cores) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU cores %d does not match source %d"),
                          dst->cores, src->cores);
        goto cleanup;
    }

    if (src->threads != dst->threads) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU threads %d does not match source %d"),
                          dst->threads, src->threads);
        goto cleanup;
    }

    if (src->nfeatures != dst->nfeatures) {
        virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                          _("Target CPU feature count %zu does not match source %zu"),
                          dst->nfeatures, src->nfeatures);
        goto cleanup;
    }

    for (i = 0 ; i < src->nfeatures ; i++) {
        if (STRNEQ(src->features[i].name, dst->features[i].name)) {
            virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                              _("Target CPU feature %s does not match source %s"),
                              dst->features[i].name, src->features[i].name);
            goto cleanup;
        }

        if (src->features[i].policy != dst->features[i].policy) {
            virCPUReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                              _("Target CPU feature policy %s does not match source %s"),
                              virCPUFeaturePolicyTypeToString(dst->features[i].policy),
                              virCPUFeaturePolicyTypeToString(src->features[i].policy));
            goto cleanup;
        }
    }

    identical = true;

cleanup:
    return identical;
}
Esempio n. 13
0
static int testURIParse(const void *args)
{
    int ret = -1;
    virURIPtr uri = NULL;
    const struct URIParseData *data = args;
    char *uristr = NULL;
    size_t i;

    if (!(uri = virURIParse(data->uri)))
        goto cleanup;

    if (STRNEQ(uri->scheme, data->scheme)) {
        VIR_DEBUG("Expected scheme '%s', actual '%s'",
                  data->scheme, uri->scheme);
        goto cleanup;
    }

    if (STRNEQ(uri->server, data->server)) {
        VIR_DEBUG("Expected server '%s', actual '%s'",
                  data->server, uri->server);
        goto cleanup;
    }

    if (uri->port != data->port) {
        VIR_DEBUG("Expected port '%d', actual '%d'",
                  data->port, uri->port);
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(uri->path, data->path)) {
        VIR_DEBUG("Expected path '%s', actual '%s'",
                  data->path, uri->path);
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(uri->query, data->query)) {
        VIR_DEBUG("Expected query '%s', actual '%s'",
                  data->query, uri->query);
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(uri->fragment, data->fragment)) {
        VIR_DEBUG("Expected fragment '%s', actual '%s'",
                  data->fragment, uri->fragment);
        goto cleanup;
    }

    for (i = 0; data->params && data->params[i].name && i < uri->paramsCount; i++) {
        if (STRNEQ_NULLABLE(data->params[i].name, uri->params[i].name)) {
            VIR_DEBUG("Expected param name %zu '%s', actual '%s'",
                      i, data->params[i].name, uri->params[i].name);
            goto cleanup;
        }
        if (STRNEQ_NULLABLE(data->params[i].value, uri->params[i].value)) {
            VIR_DEBUG("Expected param value %zu '%s', actual '%s'",
                      i, data->params[i].value, uri->params[i].value);
            goto cleanup;
        }
    }
    if (data->params && data->params[i].name) {
        VIR_DEBUG("Missing parameter %zu %s=%s",
                  i, data->params[i].name, data->params[i].value);
        goto cleanup;
    }
    if (i != uri->paramsCount) {
        VIR_DEBUG("Unexpected parameter %zu %s=%s",
                  i, uri->params[i].name, uri->params[i].value);
        goto cleanup;
    }

    VIR_FREE(uri->query);
    uri->query = virURIFormatParams(uri);

    if (!(uristr = virURIFormat(uri)))
        goto cleanup;

    if (STRNEQ(uristr, data->uri_out)) {
        VIR_DEBUG("URI did not roundtrip, expect '%s', actual '%s'",
                  data->uri_out, uristr);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(uristr);
    virURIFree(uri);
    return ret;
}
Esempio n. 14
0
static int
testCompareXMLToArgvFiles(bool shouldFail,
                          const char *poolxml,
                          const char *volxml,
                          const char *inputpoolxml,
                          const char *inputvolxml,
                          const char *cmdline,
                          unsigned int flags,
                          int imgformat)
{
    char *volXmlData = NULL;
    char *poolXmlData = NULL;
    char *inputpoolXmlData = NULL;
    char *inputvolXmlData = NULL;
    char *expectedCmdline = NULL;
    char *actualCmdline = NULL;
    int ret = -1;

    int len;

    virCommandPtr cmd = NULL;
    virConnectPtr conn;

    virStorageVolDefPtr vol = NULL, inputvol = NULL;
    virStoragePoolDefPtr pool = NULL;
    virStoragePoolDefPtr inputpool = NULL;
    virStoragePoolObj poolobj = {.def = NULL };


    if (!(conn = virGetConnect()))
        goto cleanup;

    if (virtTestLoadFile(poolxml, &poolXmlData) < 0)
        goto cleanup;
    if (virtTestLoadFile(volxml, &volXmlData) < 0)
        goto cleanup;
    if (inputvolxml &&
        virtTestLoadFile(inputvolxml, &inputvolXmlData) < 0)
        goto cleanup;

    if (!(pool = virStoragePoolDefParseString(poolXmlData)))
        goto cleanup;

    poolobj.def = pool;

    if (inputpoolxml) {
        if (virtTestLoadFile(inputpoolxml, &inputpoolXmlData) < 0)
            goto cleanup;
        if (!(inputpool = virStoragePoolDefParseString(inputpoolXmlData)))
            goto cleanup;
    }

    if (!(vol = virStorageVolDefParseString(pool, volXmlData)))
        goto cleanup;

    if (inputvolxml &&
        !(inputvol = virStorageVolDefParseString(inputpool, inputvolXmlData)))
        goto cleanup;

    testSetVolumeType(vol, pool);
    testSetVolumeType(inputvol, inputpool);

    cmd = virStorageBackendCreateQemuImgCmd(conn, &poolobj, vol, inputvol,
                                            flags, create_tool, imgformat);
    if (!cmd) {
        if (shouldFail) {
            virResetLastError();
            ret = 0;
        }
        goto cleanup;
    }

    if (!(actualCmdline = virCommandToString(cmd)))
        goto cleanup;

    len = virtTestLoadFile(cmdline, &expectedCmdline);
    if (len < 0)
        goto cleanup;
    if (len && expectedCmdline[len-1] == '\n')
        expectedCmdline[len-1] = '\0';

    if (STRNEQ_NULLABLE(expectedCmdline, actualCmdline)) {
        virtTestDifference(stderr, expectedCmdline, actualCmdline);
        goto cleanup;
    }

    ret = 0;

cleanup:
    virStoragePoolDefFree(pool);
    virStoragePoolDefFree(inputpool);
    virStorageVolDefFree(vol);
    virStorageVolDefFree(inputvol);
    virCommandFree(cmd);
    VIR_FREE(actualCmdline);
    VIR_FREE(expectedCmdline);
    VIR_FREE(inputpoolXmlData);
    VIR_FREE(poolXmlData);
    VIR_FREE(volXmlData);
    VIR_FREE(inputvolXmlData);
    virObjectUnref(conn);
    return ret;
}
Esempio n. 15
0
int virSystemdTerminateMachine(const char *name,
                               const char *drivername,
                               bool privileged)
{
    int ret;
    DBusConnection *conn;
    char *machinename = NULL;
    virError error;

    memset(&error, 0, sizeof(error));

    ret = virDBusIsServiceEnabled("org.freedesktop.machine1");
    if (ret < 0)
        goto cleanup;

    if ((ret = virDBusIsServiceRegistered("org.freedesktop.systemd1")) < 0)
        goto cleanup;

    ret = -1;

    if (!(conn = virDBusGetSystemBus()))
        goto cleanup;

    if (!(machinename = virSystemdMakeMachineName(name, drivername, privileged)))
        goto cleanup;

    /*
     * The systemd DBus API we're invoking has the
     * following signature
     *
     * TerminateMachine(in  s name);
     *
     * @name a host unique name for the machine. shows up
     * in 'ps' listing & similar
     */

    VIR_DEBUG("Attempting to terminate machine via systemd");
    if (virDBusCallMethod(conn,
                          NULL,
                          &error,
                          "org.freedesktop.machine1",
                          "/org/freedesktop/machine1",
                          "org.freedesktop.machine1.Manager",
                          "TerminateMachine",
                          "s",
                          machinename) < 0)
        goto cleanup;

    if (error.code == VIR_ERR_ERROR &&
        STRNEQ_NULLABLE("org.freedesktop.machine1.NoSuchMachine",
                        error.str1)) {
        virReportErrorObject(&error);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    virResetError(&error);

    VIR_FREE(machinename);
    return ret;
}
Esempio n. 16
0
void qemuDomainReAttachHostdevDevices(struct qemud_driver *driver,
                                      const char *name,
                                      virDomainHostdevDefPtr *hostdevs,
                                      int nhostdevs)
{
    pciDeviceList *pcidevs;
    int i;

    if (!(pcidevs = qemuGetActivePciHostDeviceList(driver,
                                                   hostdevs,
                                                   nhostdevs))) {
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to allocate pciDeviceList: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
        return;
    }

    /* Again 4 loops; mark all devices as inactive before reset
     * them and reset all the devices before re-attach.
     * Attach mac and port profile parameters to devices
     */
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
        pciDevice *activeDev = NULL;

        /* Never delete the dev from list driver->activePciHostdevs
         * if it's used by other domain.
         */
        activeDev = pciDeviceListFind(driver->activePciHostdevs, dev);
        if (activeDev &&
            STRNEQ_NULLABLE(name, pciDeviceGetUsedBy(activeDev))) {
            pciDeviceListSteal(pcidevs, dev);
            continue;
        }

        /* pciDeviceListFree() will take care of freeing the dev. */
        pciDeviceListSteal(driver->activePciHostdevs, dev);
    }

    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
    for (i = 0; i < nhostdevs; i++) {
         virDomainHostdevDefPtr hostdev = hostdevs[i];
         if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
             continue;
         if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
             continue;
         if (hostdev->parent.type == VIR_DOMAIN_DEVICE_NET &&
             hostdev->parent.data.net) {
             qemuDomainHostdevNetConfigRestore(hostdev, driver->stateDir);
         }
    }

    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
        if (pciResetDevice(dev, driver->activePciHostdevs,
                           driver->inactivePciHostdevs) < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to reset PCI device: %s"),
                      err ? err->message : _("unknown error"));
            virResetError(err);
        }
    }

    while (pciDeviceListCount(pcidevs) > 0) {
        pciDevice *dev = pciDeviceListStealIndex(pcidevs, 0);
        qemuReattachPciDevice(dev, driver);
    }

    pciDeviceListFree(pcidevs);
}
Esempio n. 17
0
bool
virCPUDefIsEqual(virCPUDefPtr src,
                 virCPUDefPtr dst,
                 bool reportError)
{
    bool identical = false;
    size_t i;

    if (!src && !dst)
        return true;

#define MISMATCH(fmt, ...) \
    if (reportError) \
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, fmt, __VA_ARGS__)

    if ((src && !dst) || (!src && dst)) {
        MISMATCH("%s", _("Target CPU does not match source"));
        goto cleanup;
    }

    if (src->type != dst->type) {
        MISMATCH(_("Target CPU type %s does not match source %s"),
                 virCPUTypeToString(dst->type),
                 virCPUTypeToString(src->type));
        goto cleanup;
    }

    if (src->mode != dst->mode) {
        MISMATCH(_("Target CPU mode %s does not match source %s"),
                 virCPUModeTypeToString(dst->mode),
                 virCPUModeTypeToString(src->mode));
        goto cleanup;
    }

    if (src->check != dst->check) {
        MISMATCH(_("Target CPU check %s does not match source %s"),
                 virCPUCheckTypeToString(dst->check),
                 virCPUCheckTypeToString(src->check));
        goto cleanup;
    }

    if (src->arch != dst->arch) {
        MISMATCH(_("Target CPU arch %s does not match source %s"),
                 virArchToString(dst->arch),
                 virArchToString(src->arch));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->model, dst->model)) {
        MISMATCH(_("Target CPU model %s does not match source %s"),
                 NULLSTR(dst->model), NULLSTR(src->model));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->vendor, dst->vendor)) {
        MISMATCH(_("Target CPU vendor %s does not match source %s"),
                 NULLSTR(dst->vendor), NULLSTR(src->vendor));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(src->vendor_id, dst->vendor_id)) {
        MISMATCH(_("Target CPU vendor id %s does not match source %s"),
                 NULLSTR(dst->vendor_id), NULLSTR(src->vendor_id));
        goto cleanup;
    }

    if (src->sockets != dst->sockets) {
        MISMATCH(_("Target CPU sockets %d does not match source %d"),
                 dst->sockets, src->sockets);
        goto cleanup;
    }

    if (src->cores != dst->cores) {
        MISMATCH(_("Target CPU cores %d does not match source %d"),
                 dst->cores, src->cores);
        goto cleanup;
    }

    if (src->threads != dst->threads) {
        MISMATCH(_("Target CPU threads %d does not match source %d"),
                 dst->threads, src->threads);
        goto cleanup;
    }

    if (src->nfeatures != dst->nfeatures) {
        MISMATCH(_("Target CPU feature count %zu does not match source %zu"),
                 dst->nfeatures, src->nfeatures);
        goto cleanup;
    }

    for (i = 0; i < src->nfeatures; i++) {
        if (STRNEQ(src->features[i].name, dst->features[i].name)) {
            MISMATCH(_("Target CPU feature %s does not match source %s"),
                     dst->features[i].name, src->features[i].name);
            goto cleanup;
        }

        if (src->features[i].policy != dst->features[i].policy) {
            MISMATCH(_("Target CPU feature policy %s does not match source %s"),
                     virCPUFeaturePolicyTypeToString(dst->features[i].policy),
                     virCPUFeaturePolicyTypeToString(src->features[i].policy));
            goto cleanup;
        }
    }

    if ((src->cache && !dst->cache) ||
        (!src->cache && dst->cache) ||
        (src->cache && dst->cache &&
         (src->cache->level != dst->cache->level ||
          src->cache->mode != dst->cache->mode))) {
        MISMATCH("%s", _("Target CPU cache does not match source"));
        goto cleanup;
    }

#undef MISMATCH

    identical = true;

 cleanup:
    return identical;
}
Esempio n. 18
0
void
qemuDomainReAttachHostdevDevices(virQEMUDriverPtr driver,
                                 const char *name,
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs)
{
    virPCIDeviceListPtr pcidevs;
    size_t i;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);

    if (!(pcidevs = qemuGetActivePciHostDeviceList(driver,
                                                   hostdevs,
                                                   nhostdevs))) {
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
        goto cleanup;
    }

    /* Again 4 loops; mark all devices as inactive before reset
     * them and reset all the devices before re-attach.
     * Attach mac and port profile parameters to devices
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr activeDev = NULL;

        /* delete the copy of the dev from pcidevs if it's used by
         * other domain. Or delete it from activePciHostDevs if it had
         * been used by this domain.
         */
        activeDev = virPCIDeviceListFind(driver->activePciHostdevs, dev);
        if (activeDev &&
            STRNEQ_NULLABLE(name, virPCIDeviceGetUsedBy(activeDev))) {
            virPCIDeviceListDel(pcidevs, dev);
            continue;
        }

        virPCIDeviceListDel(driver->activePciHostdevs, dev);
    }

    /* At this point, any device that had been used by the guest is in
     * pcidevs, but has been removed from activePciHostdevs.
     */

    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
    for (i = 0; i < nhostdevs; i++) {
         virDomainHostdevDefPtr hostdev = hostdevs[i];
         if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
             continue;
         if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
             continue;
         if (hostdev->parent.type == VIR_DOMAIN_DEVICE_NET &&
             hostdev->parent.data.net) {
             qemuDomainHostdevNetConfigRestore(hostdev, cfg->stateDir);
         }
    }

    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

        if (virPCIDeviceReset(dev, driver->activePciHostdevs,
                              driver->inactivePciHostdevs) < 0) {
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to reset PCI device: %s"),
                      err ? err->message : _("unknown error"));
            virResetError(err);
        }
    }

    while (virPCIDeviceListCount(pcidevs) > 0) {
        virPCIDevicePtr dev = virPCIDeviceListStealIndex(pcidevs, 0);
        qemuReattachPciDevice(dev, driver);
    }

    virObjectUnref(pcidevs);
cleanup:
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);
    virObjectUnref(cfg);
}
Esempio n. 19
0
static int
testStorageLookup(const void *args)
{
    const struct testLookupData *data = args;
    int ret = 0;
    virStorageSourcePtr result;
    const char *actualParent;
    unsigned int idx;

    if (virStorageFileParseChainIndex(data->target, data->name, &idx) < 0 &&
        data->expIndex) {
        fprintf(stderr, "call should not have failed\n");
        ret = -1;
    }
    if (idx != data->expIndex) {
        fprintf(stderr, "index: expected %u, got %u\n", data->expIndex, idx);
        ret = -1;
    }

     /* Test twice to ensure optional parameter doesn't cause NULL deref. */
    result = virStorageFileChainLookup(data->chain, NULL,
                                       idx ? NULL : data->name,
                                       idx, NULL);

    if (!data->expResult) {
        if (!virGetLastError()) {
            fprintf(stderr, "call should have failed\n");
            ret = -1;
        }
        virResetLastError();
    } else {
        if (virGetLastError()) {
            fprintf(stderr, "call should not have warned\n");
            ret = -1;
        }
    }

    if (!result) {
        if (data->expResult) {
            fprintf(stderr, "result 1: expected %s, got NULL\n",
                    data->expResult);
            ret = -1;
        }
    } else if (STRNEQ_NULLABLE(data->expResult, result->path)) {
        fprintf(stderr, "result 1: expected %s, got %s\n",
                NULLSTR(data->expResult), NULLSTR(result->path));
        ret = -1;
    }

    result = virStorageFileChainLookup(data->chain, data->chain,
                                       data->name, idx, &actualParent);
    if (!data->expResult)
        virResetLastError();

    if (!result) {
        if (data->expResult) {
            fprintf(stderr, "result 2: expected %s, got NULL\n",
                    data->expResult);
            ret = -1;
        }
    } else if (STRNEQ_NULLABLE(data->expResult, result->path)) {
        fprintf(stderr, "result 2: expected %s, got %s\n",
                NULLSTR(data->expResult), NULLSTR(result->path));
        ret = -1;
    }
    if (data->expMeta != result) {
        fprintf(stderr, "meta: expected %p, got %p\n",
                data->expMeta, result);
        ret = -1;
    }
    if (STRNEQ_NULLABLE(data->expParent, actualParent)) {
        fprintf(stderr, "parent: expected %s, got %s\n",
                NULLSTR(data->expParent), NULLSTR(actualParent));
        ret = -1;
    }

    return ret;
}
Esempio n. 20
0
static int
testFirewallRemoveRule(const void *opaque)
{
    virBuffer cmdbuf = VIR_BUFFER_INITIALIZER;
    virFirewallPtr fw = NULL;
    int ret = -1;
    const char *actual = NULL;
    const char *expected =
        IPTABLES_PATH " -A INPUT --source-host 192.168.122.1 --jump ACCEPT\n"
        IPTABLES_PATH " -A INPUT --source-host '!192.168.122.1' --jump REJECT\n";
    const struct testFirewallData *data = opaque;
    virFirewallRulePtr fwrule;

    fwDisabled = data->fwDisabled;
    if (virFirewallSetBackend(data->tryBackend) < 0)
        goto cleanup;

    if (data->expectBackend == VIR_FIREWALL_BACKEND_DIRECT)
        virCommandSetDryRun(&cmdbuf, NULL, NULL);
    else
        fwBuf = &cmdbuf;

    fw = virFirewallNew();

    virFirewallStartTransaction(fw, 0);

    virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                       "-A", "INPUT",
                       "--source-host", "192.168.122.1",
                       "--jump", "ACCEPT", NULL);

    fwrule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                "-A", "INPUT", NULL);
    virFirewallRuleAddArg(fw, fwrule, "--source-host");
    virFirewallRemoveRule(fw, fwrule);

    fwrule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                "-A", "INPUT", NULL);
    virFirewallRuleAddArg(fw, fwrule, "--source-host");
    virFirewallRuleAddArgFormat(fw, fwrule, "%s", "!192.168.122.1");
    virFirewallRuleAddArgList(fw, fwrule, "--jump", "REJECT", NULL);

    if (virFirewallApply(fw) < 0)
        goto cleanup;

    if (virBufferError(&cmdbuf))
        goto cleanup;

    actual = virBufferCurrentContent(&cmdbuf);

    if (STRNEQ_NULLABLE(expected, actual)) {
        fprintf(stderr, "Unexected command execution\n");
        virTestDifference(stderr, expected, actual);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    virBufferFreeAndReset(&cmdbuf);
    fwBuf = NULL;
    virCommandSetDryRun(NULL, NULL, NULL);
    virFirewallFree(fw);
    return ret;
}