qemu_qapi.c 12.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * qemu_qapi.c: helper functions for QEMU QAPI schema handling
 *
 * 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/>.
 */

#include <config.h>

#include "qemu_qapi.h"

#include "viralloc.h"
#include "virstring.h"
#include "virerror.h"
#include "virlog.h"

28 29
#include "c-ctype.h"

30 31 32 33 34 35
#define VIR_FROM_THIS VIR_FROM_QEMU

VIR_LOG_INIT("qemu.qemu_qapi");


/**
36
 * virQEMUQAPISchemaObjectGet:
37 38 39
 * @field: name of the object containing the requested type
 * @name: name of the requested type
 * @namefield: name of the object property holding @name
40
 * @elem: QAPI schema entry JSON object
41 42
 *
 * Helper that selects the type of a QMP schema object member or it's variant
43
 * member. Returns the QMP entry on success or NULL on error.
44
 */
45 46 47 48 49
static virJSONValuePtr
virQEMUQAPISchemaObjectGet(const char *field,
                           const char *name,
                           const char *namefield,
                           virJSONValuePtr elem)
50 51 52 53 54 55 56 57 58 59 60
{
    virJSONValuePtr arr;
    virJSONValuePtr cur;
    const char *curname;
    size_t i;

    if (!(arr = virJSONValueObjectGetArray(elem, field)))
        return NULL;

    for (i = 0; i < virJSONValueArraySize(arr); i++) {
        if (!(cur = virJSONValueArrayGet(arr, i)) ||
61
            !(curname = virJSONValueObjectGetString(cur, namefield)))
62 63 64
            continue;

        if (STREQ(name, curname))
65
            return cur;
66 67 68 69 70 71
    }

    return NULL;
}


72
struct virQEMUQAPISchemaTraverseContext {
73
    const char *prevquery;
74
    virHashTablePtr schema;
75
    char **queries;
76 77 78 79
    virJSONValuePtr returnType;
};


80 81 82 83 84 85 86 87 88 89 90 91 92 93
static void
virQEMUQAPISchemaTraverseContextInit(struct virQEMUQAPISchemaTraverseContext *ctxt,
                                     char **queries,
                                     virHashTablePtr schema)
{
    memset(ctxt, 0, sizeof(*ctxt));
    ctxt->schema = schema;
    ctxt->queries = queries;
}


static const char *
virQEMUQAPISchemaTraverseContextNextQuery(struct virQEMUQAPISchemaTraverseContext *ctxt)
{
94
    ctxt->prevquery = ctxt->queries[0];
95
    ctxt->queries++;
96
    return ctxt->prevquery;
97 98 99 100 101 102 103 104 105 106
}


static bool
virQEMUQAPISchemaTraverseContextHasNextQuery(struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    return !!ctxt->queries[0];
}


107
static int
108
virQEMUQAPISchemaTraverse(const char *baseName,
109
                          struct virQEMUQAPISchemaTraverseContext *ctxt);
110 111 112 113


static int
virQEMUQAPISchemaTraverseObject(virJSONValuePtr cur,
114
                                struct virQEMUQAPISchemaTraverseContext *ctxt)
115
{
116
    virJSONValuePtr obj;
117
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
118
    char modifier = *query;
119 120

    if (!c_isalpha(modifier))
121
        query++;
122

123
    /* exit on modifers for other types */
124
    if (modifier == '^' || modifier == '!')
125 126
        return 0;

127
    if (modifier == '+') {
128
        obj = virQEMUQAPISchemaObjectGet("variants", query, "case", cur);
129
    } else {
130
        obj = virQEMUQAPISchemaObjectGet("members", query, "name", cur);
131 132 133 134 135 136

        if (modifier == '*' &&
            !virJSONValueObjectHasKey(obj, "default"))
            return 0;
    }

137 138 139
    if (!obj)
        return 0;

140
    return virQEMUQAPISchemaTraverse(virJSONValueObjectGetString(obj, "type"), ctxt);
141 142 143 144 145
}


static int
virQEMUQAPISchemaTraverseArray(virJSONValuePtr cur,
146
                               struct virQEMUQAPISchemaTraverseContext *ctxt)
147 148 149 150 151
{
    const char *querytype;

    /* arrays are just flattened by default */
    if (!(querytype = virJSONValueObjectGetString(cur, "element-type")))
152
        return -2;
153

154
    return virQEMUQAPISchemaTraverse(querytype, ctxt);
155
}
156

157 158 159

static int
virQEMUQAPISchemaTraverseCommand(virJSONValuePtr cur,
160
                                 struct virQEMUQAPISchemaTraverseContext *ctxt)
161
{
162
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
163 164
    const char *querytype;

165
    if (!(querytype = virJSONValueObjectGetString(cur, query)))
166 167
        return 0;

168
    return virQEMUQAPISchemaTraverse(querytype, ctxt);
169 170
}

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

static int
virQEMUQAPISchemaTraverseEnum(virJSONValuePtr cur,
                              struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    virJSONValuePtr values;
    virJSONValuePtr enumval;
    const char *value;
    size_t i;

    if (query[0] != '^')
        return 0;

    if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
        return -3;

    query++;

    if (!(values = virJSONValueObjectGetArray(cur, "values")))
        return -2;

    for (i = 0; i < virJSONValueArraySize(values); i++) {
        if (!(enumval = virJSONValueArrayGet(values, i)) ||
            !(value = virJSONValueGetString(enumval)))
            continue;

        if (STREQ(value, query))
            return 1;
    }

    return 0;
}


206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
static int
virQEMUQAPISchemaTraverseBuiltin(virJSONValuePtr cur,
                                 struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    const char *jsontype;

    if (query[0] != '!')
        return 0;

    if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
        return -3;

    query++;

    if (!(jsontype = virJSONValueObjectGetString(cur, "json-type")))
        return -1;

    if (STREQ(jsontype, query))
        return 1;

    return 0;
}


231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
static int
virQEMUQAPISchemaTraverseAlternate(virJSONValuePtr cur,
                                   struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    struct virQEMUQAPISchemaTraverseContext savectxt = *ctxt;
    virJSONValuePtr members;
    virJSONValuePtr member;
    const char *membertype;
    int rc;
    size_t i;

    if (!(members = virJSONValueObjectGetArray(cur, "members")))
        return -2;

    for (i = 0; i < virJSONValueArraySize(members); i++) {
        if (!(member = virJSONValueArrayGet(members, i)) ||
            !(membertype = virJSONValueObjectGetString(member, "type")))
            continue;

        *ctxt = savectxt;

        if ((rc = virQEMUQAPISchemaTraverse(membertype, ctxt)) != 0)
            return rc;
    }

    return 0;
}


260 261 262
/* The function must return 1 on successful query, 0 if the query was not found
 * -1 when a libvirt error is reported, -2 if the schema is invalid and -3 if
 *  the query component is malformed. */
263 264 265 266 267 268 269 270 271 272 273 274 275 276
typedef int (*virQEMUQAPISchemaTraverseFunc)(virJSONValuePtr cur,
                                             struct virQEMUQAPISchemaTraverseContext *ctxt);

struct virQEMUQAPISchemaTraverseMetaType {
    const char *metatype;
    virQEMUQAPISchemaTraverseFunc func;
};


static const struct virQEMUQAPISchemaTraverseMetaType traverseMetaType[] = {
    { "object", virQEMUQAPISchemaTraverseObject },
    { "array", virQEMUQAPISchemaTraverseArray },
    { "command", virQEMUQAPISchemaTraverseCommand },
    { "event", virQEMUQAPISchemaTraverseCommand },
277
    { "enum", virQEMUQAPISchemaTraverseEnum },
278
    { "builtin", virQEMUQAPISchemaTraverseBuiltin },
279
    { "alternate", virQEMUQAPISchemaTraverseAlternate },
280 281 282
};


283 284
static int
virQEMUQAPISchemaTraverse(const char *baseName,
285
                          struct virQEMUQAPISchemaTraverseContext *ctxt)
286 287 288
{
    virJSONValuePtr cur;
    const char *metatype;
289
    size_t i;
290

291
    if (!(cur = virHashLookup(ctxt->schema, baseName)))
292
        return -2;
293

294
    if (!virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt)) {
295
        ctxt->returnType = cur;
296 297
        return 1;
    }
298

299
    if (!(metatype = virJSONValueObjectGetString(cur, "meta-type")))
300
        return -2;
301

302 303 304
    for (i = 0; i < ARRAY_CARDINALITY(traverseMetaType); i++) {
        if (STREQ(metatype, traverseMetaType[i].metatype))
            return traverseMetaType[i].func(cur, ctxt);
305
    }
306

307
    return 0;
308 309 310 311
}


/**
312
 * virQEMUQAPISchemaPathGet:
313 314
 * @query: string specifying the required data type (see below)
 * @schema: hash table containing the schema data
315
 * @entry: filled with the located schema object requested by @query (optional)
316 317 318 319 320
 *
 * Retrieves the requested schema entry specified by @query to @entry. The
 * @query parameter has the following syntax which is very closely tied to the
 * qemu schema syntax entries separated by slashes with a few special characters:
 *
321
 * "command_or_event/attribute/subattribute/subattribute/..."
322 323 324 325
 *
 * command_or_event: name of the event or attribute to introspect
 * attribute: selects whether arguments or return type should be introspected
 *            ("arg-type" or "ret-type" for commands, "arg-type" for events)
326 327 328 329 330 331 332 333 334 335 336 337
 *
 * 'subattribute' may be one or more of the following depending on the first
 * character.
 *
 * - Type queries - @entry is filled on success with the corresponding schema entry:
 *   'subattribute': selects a plain object member named 'subattribute'
 *   '*subattribute': same as above but the selected member must be optional
 *                    (has a property named 'default' in the schema)
 *   '+variant": In the case of unionized objects, select a specific variant of
 *               the prevously selected member
 *
 * - Boolean queries - @entry remains NULL, return value indicates success:
338
 *   '^enumval': returns true if the previously selected enum contains 'enumval'
339 340 341
 *   '!basictype': returns true if previously selected type is of 'basictype'
 *                 JSON type. Spported are 'null', 'string', 'number', 'value',
 *                 'int' and 'boolean.
342
 *
343 344 345
 * If the name of any (sub)attribute starts with non-alphabetical symbols it
 * needs to be prefixed by a single space.
 *
346 347
 * Array types are automatically flattened to the singular type. Alternates are
 * iterated until first success.
348 349
 *
 * The above types can be chained arbitrarily using slashes to construct any
350 351
 * path into the schema tree, booleans must be always the last component as they
 * don't refer to a type.
352
 *
353 354
 * Returns 1 if @query was found in @schema filling @entry if non-NULL, 0 if
 * @query was not found in @schema and -1 on other errors along with an appropriate
355 356 357
 * error message.
 */
int
358 359 360
virQEMUQAPISchemaPathGet(const char *query,
                         virHashTablePtr schema,
                         virJSONValuePtr *entry)
361
{
362
    VIR_AUTOSTRINGLIST elems = NULL;
363
    struct virQEMUQAPISchemaTraverseContext ctxt;
364
    const char *cmdname;
365
    int rc;
366

367 368
    if (entry)
        *entry = NULL;
369 370 371 372 373 374 375 376 377

    if (!(elems = virStringSplit(query, "/", 0)))
        return -1;

    if (!*elems) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("malformed query string"));
        return -1;
    }

378
    virQEMUQAPISchemaTraverseContextInit(&ctxt, elems, schema);
379
    cmdname = virQEMUQAPISchemaTraverseContextNextQuery(&ctxt);
380

381 382 383 384
    if (!virHashLookup(schema, cmdname))
        return 0;

    rc = virQEMUQAPISchemaTraverse(cmdname, &ctxt);
385 386 387 388

    if (entry)
        *entry = ctxt.returnType;

389 390 391 392 393 394 395 396 397 398 399 400 401 402
    if (rc >= 0)
        return rc;

    if (rc == -2) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed QAPI schema when querying '%s' of '%s'"),
                       NULLSTR(ctxt.prevquery), query);
    } else if (rc == -3) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("terminal QAPI query component '%s' of '%s' must not have followers"),
                       NULLSTR(ctxt.prevquery), query);
    }

    return -1;
403 404 405 406
}


bool
407 408
virQEMUQAPISchemaPathExists(const char *query,
                            virHashTablePtr schema)
409
{
410
    return virQEMUQAPISchemaPathGet(query, schema, NULL) == 1;
411
}
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

static int
virQEMUQAPISchemaEntryProcess(size_t pos ATTRIBUTE_UNUSED,
                              virJSONValuePtr item,
                              void *opaque)
{
    const char *name;
    virHashTablePtr schema = opaque;

    if (!(name = virJSONValueObjectGetString(item, "name"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed QMP schema"));
        return -1;
    }

    if (virHashAddEntry(schema, name, item) < 0)
        return -1;

    return 0;
}


/**
 * virQEMUQAPISchemaConvert:
 * @schemareply: Schema data as returned by the qemu monitor
 *
 * Converts the schema into the hash-table used by the functions working with
 * the schema. @schemareply is consumed and freed.
 */
virHashTablePtr
virQEMUQAPISchemaConvert(virJSONValuePtr schemareply)
{
444 445
    VIR_AUTOPTR(virHashTable) schema = NULL;
    VIR_AUTOPTR(virJSONValue) schemajson = schemareply;
446 447

    if (!(schema = virHashCreate(512, virJSONValueHashFree)))
448
        return NULL;
449

450
    if (virJSONValueArrayForeachSteal(schemajson,
451 452
                                      virQEMUQAPISchemaEntryProcess,
                                      schema) < 0)
453
        return NULL;
454

455
    VIR_RETURN_PTR(schema);
456
}