xen_inotify.c 15.4 KB
Newer Older
1 2 3 4 5 6
/*
 * xen_inofify.c: Xen notification of xml file activity in the
 *                following dirs:
 *                /etc/xen
 *                /var/lib/xend/domains
 *
7
 * Copyright (C) 2010 Red Hat, Inc.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 * Copyright (C) 2008 VirtualIron
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Ben Guthro
 */
#include <config.h>
#include <dirent.h>
#include <sys/inotify.h>

#include "virterror_internal.h"
#include "datatypes.h"
#include "driver.h"
#include "memory.h"
#include "event.h"
35
#include "xen_driver.h"
36 37 38 39 40 41
#include "conf.h"
#include "domain_conf.h"
#include "xen_inotify.h"
#include "xend_internal.h"
#include "logging.h"
#include "uuid.h"
42
#include "files.h"
43 44 45

#include "xm_internal.h" /* for xenXMDomainConfigParse */

46 47
#define VIR_FROM_THIS VIR_FROM_XEN_INOTIFY

48
#define virXenInotifyError(code, ...)                                   \
49
        virReportErrorHelper(NULL, VIR_FROM_XEN_INOTIFY, code, __FILE__,      \
50
                             __FUNCTION__, __LINE__, __VA_ARGS__)
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

struct xenUnifiedDriver xenInotifyDriver = {
    xenInotifyOpen, /* open */
    xenInotifyClose, /* close */
    NULL, /* version */
    NULL, /* hostname */
    NULL, /* nodeGetInfo */
    NULL, /* getCapabilities */
    NULL, /* listDomains */
    NULL, /* numOfDomains */
    NULL, /* domainCreateLinux */
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    NULL, /* domainShutdown */
    NULL, /* domainReboot */
    NULL, /* domainDestroy */
    NULL, /* domainGetOSType */
    NULL, /* domainGetMaxMemory */
    NULL, /* domainSetMaxMemory */
    NULL, /* domainSetMemory */
    NULL, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
    NULL, /* domainCoreDump */
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
    NULL, /* listDefinedDomains */
    NULL, /* numOfDefinedDomains */
    NULL, /* domainCreate */
    NULL, /* domainDefineXML */
    NULL, /* domainUndefine */
82 83
    NULL, /* domainAttachDeviceFlags */
    NULL, /* domainDetachDeviceFlags */
84
    NULL, /* domainUpdateDeviceFlags */
85 86 87 88 89 90 91
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
};

92
static int
93 94
xenInotifyXenCacheLookup(virConnectPtr conn,
                         const char *filename,
95
                         char **name, unsigned char *uuid) {
96
    xenUnifiedPrivatePtr priv = conn->privateData;
97 98
    xenXMConfCachePtr entry;

99
    if (!(entry = virHashLookup(priv->configCache, filename))) {
100
        VIR_DEBUG("No config found for %s", filename);
101
        return -1;
102 103
    }

104 105 106 107
    *name = strdup(entry->def->name);
    memcpy(uuid, entry->def->uuid, VIR_UUID_BUFLEN);

    if (!*name) {
108
        VIR_DEBUG0("Error getting dom from def");
109
        virReportOOMError();
110
        return -1;
111
    }
112
    return 0;
113 114
}

115 116 117
static int
xenInotifyXendDomainsDirLookup(virConnectPtr conn, const char *filename,
                               char **name, unsigned char *uuid) {
118 119 120
    int i;
    virDomainPtr dom;
    const char *uuid_str;
121
    unsigned char rawuuid[VIR_UUID_BUFLEN];
122
    xenUnifiedPrivatePtr priv = conn->privateData;
123 124 125 126 127

    /* xend is managing domains. we will get
    * a filename in the manner:
    * /var/lib/xend/domains/<uuid>/
    */
128
    uuid_str = filename + strlen(XEND_DOMAINS_DIR) + 1;
129

130
    if (virUUIDParse(uuid_str, rawuuid) < 0) {
131
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
132
                           _("parsing uuid %s"), uuid_str);
133
        return -1;
134 135 136 137
    }
    /* call directly into xend here, as driver may not yet
       be set during open while we are building our
       initial list of domains */
138
    VIR_DEBUG("Looking for dom with uuid: %s", uuid_str);
139 140
    /* XXX Should not have to go via a virDomainPtr obj instance */
    if(!(dom = xenDaemonLookupByUUID(conn, rawuuid))) {
141 142 143
        /* If we are here, the domain has gone away.
           search for, and create a domain from the stored
           list info */
144
        for (i = 0 ; i < priv->configInfoList->count ; i++) {
145
            if (!memcmp(rawuuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN)) {
146
                *name = strdup(priv->configInfoList->doms[i]->name);
147
                if (!*name) {
148
                    virReportOOMError();
149
                    return -1;
150
                }
151
                memcpy(uuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN);
152
                VIR_DEBUG0("Found dom on list");
153
                return 0;
154 155
            }
        }
156
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
157 158
                           "%s", _("finding dom on config list"));
        return -1;
159 160
    }

161
    if (!(*name = strdup(dom->name))) {
162
        virReportOOMError();
163
        return -1;
164
    }
165 166
    memcpy(uuid, dom->uuid, VIR_UUID_BUFLEN);
    virDomainFree(dom);
167
    /* succeeded too find domain by uuid */
168
    return 0;
169 170
}

171 172 173 174
static int
xenInotifyDomainLookup(virConnectPtr conn,
                       const char *filename,
                       char **name, unsigned char *uuid) {
175 176
    xenUnifiedPrivatePtr priv = conn->privateData;
    if (priv->useXenConfigCache)
177
        return xenInotifyXenCacheLookup(conn, filename, name, uuid);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    else
        return xenInotifyXendDomainsDirLookup(conn, filename, name, uuid);
}

static virDomainEventPtr
xenInotifyDomainEventFromFile(virConnectPtr conn,
                              const char *filename,
                              int type, int detail) {
    virDomainEventPtr event;
    char *name = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];

    if (xenInotifyDomainLookup(conn, filename, &name, uuid) < 0)
        return NULL;

    event = virDomainEventNew(-1, name, uuid, type, detail);
    VIR_FREE(name);
    return event;
196 197 198
}

static int
199
xenInotifyXendDomainsDirRemoveEntry(virConnectPtr conn,
200
                                    const char *fname) {
201
    xenUnifiedPrivatePtr priv = conn->privateData;
202
    const char *uuidstr = fname + strlen(XEND_DOMAINS_DIR) + 1;
203 204 205 206
    unsigned char uuid[VIR_UUID_BUFLEN];
    int i;

    if (virUUIDParse(uuidstr, uuid) < 0) {
207
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
208
                           _("parsing uuid %s"), uuidstr);
209 210 211 212
        return -1;
    }

    /* match and remove on uuid */
213 214 215 216 217 218 219 220 221 222 223 224 225
    for (i = 0 ; i < priv->configInfoList->count ; i++) {
        if (!memcmp(uuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN)) {
            VIR_FREE(priv->configInfoList->doms[i]->name);
            VIR_FREE(priv->configInfoList->doms[i]);

            if (i < (priv->configInfoList->count - 1))
                memmove(priv->configInfoList->doms + i,
                        priv->configInfoList->doms + i + 1,
                        sizeof(*(priv->configInfoList->doms)) *
                                (priv->configInfoList->count - (i + 1)));

            if (VIR_REALLOC_N(priv->configInfoList->doms,
                              priv->configInfoList->count - 1) < 0) {
226 227
                ; /* Failure to reduce memory allocation isn't fatal */
            }
228
            priv->configInfoList->count--;
229 230 231 232 233 234 235 236 237
            return 0;
        }
    }
    return -1;
}

static int
xenInotifyXendDomainsDirAddEntry(virConnectPtr conn,
                                 const char *fname) {
238 239
    char *name = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
240 241
    xenUnifiedPrivatePtr priv = conn->privateData;

242
    if (xenInotifyDomainLookup(conn, fname, &name, uuid) < 0) {
243
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
244
                           "%s", _("Error looking up domain"));
245 246 247
        return -1;
    }

248
    if (xenUnifiedAddDomainInfo(priv->configInfoList,
249
                                -1, name, uuid) < 0) {
250
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
251
                        "%s", _("Error adding file to config cache"));
252
        VIR_FREE(name);
253 254
        return -1;
    }
255
    VIR_FREE(name);
256 257 258 259 260 261
    return 0;
}

static int
xenInotifyRemoveDomainConfigInfo(virConnectPtr conn,
                                 const char *fname) {
262 263 264 265
    xenUnifiedPrivatePtr priv = conn->privateData;
    return priv->useXenConfigCache ?
        xenXMConfigCacheRemoveFile(conn, fname) :
        xenInotifyXendDomainsDirRemoveEntry(conn, fname);
266 267 268 269 270
}

static int
xenInotifyAddDomainConfigInfo(virConnectPtr conn,
                              const char *fname) {
271 272 273 274
    xenUnifiedPrivatePtr priv = conn->privateData;
    return priv->useXenConfigCache ?
        xenXMConfigCacheAddFile(conn, fname) :
        xenInotifyXendDomainsDirAddEntry(conn, fname);
275 276 277 278 279 280 281 282 283 284 285 286 287
}

static void
xenInotifyEvent(int watch ATTRIBUTE_UNUSED,
                int fd,
                int events ATTRIBUTE_UNUSED,
                void *data)
{
    char buf[1024];
    char fname[1024];
    struct inotify_event *e;
    int got;
    char *tmp, *name;
288
    virConnectPtr conn = data;
289 290
    xenUnifiedPrivatePtr priv = NULL;

291
    VIR_DEBUG0("got inotify event");
292 293 294 295

    if( conn && conn->privateData ) {
        priv = conn->privateData;
    } else {
296
        virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
297 298 299 300
                           "%s", _("conn, or private data is NULL"));
        return;
    }

D
Daniel P. Berrange 已提交
301 302
    xenUnifiedLock(priv);

303 304 305 306 307
reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
D
Daniel P. Berrange 已提交
308
        goto cleanup;
309 310 311 312 313
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
D
Daniel P. Berrange 已提交
314
            goto cleanup; /* bad */
315 316 317 318 319 320

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

        if (got < e->len)
D
Daniel P. Berrange 已提交
321
            goto cleanup;
322 323 324 325 326 327

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

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

328 329
        snprintf(fname, 1024, "%s/%s",
                 priv->configDir, name);
330 331

        if (e->mask & (IN_DELETE | IN_MOVED_FROM)) {
332 333 334 335
            virDomainEventPtr event =
                xenInotifyDomainEventFromFile(conn, fname,
                                              VIR_DOMAIN_EVENT_UNDEFINED,
                                              VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
336
            if (event)
337 338
                xenUnifiedDomainEventDispatch(conn->privateData, event);
            else
339
                virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
340
                                   "%s", _("looking up dom"));
341 342

            if (xenInotifyRemoveDomainConfigInfo(conn, fname) < 0 ) {
343
                virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
344
                                   "%s", _("Error adding file to config cache"));
D
Daniel P. Berrange 已提交
345
                goto cleanup;
346 347
            }
        } else if (e->mask & ( IN_CREATE | IN_CLOSE_WRITE | IN_MOVED_TO) ) {
348
            virDomainEventPtr event;
349
            if (xenInotifyAddDomainConfigInfo(conn, fname) < 0 ) {
350
                virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
351
                                   "%s", _("Error adding file to config cache"));
D
Daniel P. Berrange 已提交
352
                goto cleanup;
353 354
            }

355 356 357 358 359 360 361
            event = xenInotifyDomainEventFromFile(conn, fname,
                                                  VIR_DOMAIN_EVENT_DEFINED,
                                                  VIR_DOMAIN_EVENT_DEFINED_ADDED);

            if (event)
                xenUnifiedDomainEventDispatch(conn->privateData, event);
            else
362
                virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
363
                                   "%s", _("looking up dom"));
364 365 366 367

        }

    }
D
Daniel P. Berrange 已提交
368 369 370

cleanup:
    xenUnifiedUnlock(priv);
371 372 373 374 375 376 377 378 379 380 381 382
}

/**
 * xenInotifyOpen:
 * @conn: pointer to the connection block
 * @name: URL for the target, NULL for local
 * @flags: combination of virDrvOpenFlag(s)
 *
 * Connects and starts listening for inotify events
 *
 * Returns 0 or -1 in case of error.
 */
383
virDrvOpenStatus
384
xenInotifyOpen(virConnectPtr conn,
385 386 387 388 389
             virConnectAuthPtr auth ATTRIBUTE_UNUSED,
             int flags ATTRIBUTE_UNUSED)
{
    DIR *dh;
    struct dirent *ent;
390
    char *path;
391 392
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;

393
    if (priv->configDir) {
394
        priv->useXenConfigCache = 1;
395 396
    } else {
        /* /var/lib/xend/domains/<uuid>/config.sxp */
397
        priv->configDir = XEND_DOMAINS_DIR;
398
        priv->useXenConfigCache = 0;
399

400
        if (VIR_ALLOC(priv->configInfoList) < 0) {
401
            virReportOOMError();
402 403 404 405
            return -1;
        }

        /* populate initial list */
406
        if (!(dh = opendir(priv->configDir))) {
407
            virReportSystemError(errno,
408
                                 _("cannot open directory: %s"),
409
                                 priv->configDir);
410 411 412 413 414 415 416
            return -1;
        }
        while ((ent = readdir(dh))) {
            if (STRPREFIX(ent->d_name, "."))
                continue;

            /* Build the full file path */
417 418 419 420 421
            if (!(path = virFileBuildPath(priv->configDir, ent->d_name, NULL))) {
                virReportOOMError();
                closedir(dh);
                return -1;
            }
422 423

            if (xenInotifyAddDomainConfigInfo(conn, path) < 0 ) {
424
                virXenInotifyError(VIR_ERR_INTERNAL_ERROR,
425
                                   "%s", _("Error adding file to config list"));
426
                closedir(dh);
427
                VIR_FREE(path);
428 429
                return -1;
            }
430 431

            VIR_FREE(path);
432
        }
433
        closedir(dh);
434 435 436
    }

    if ((priv->inotifyFD = inotify_init()) < 0) {
437
        virReportSystemError(errno,
438
                             "%s", _("initializing inotify"));
439 440 441
        return -1;
    }

442
    VIR_DEBUG("Adding a watch on %s", priv->configDir);
443
    if (inotify_add_watch(priv->inotifyFD,
444
                          priv->configDir,
445 446 447
                          IN_CREATE |
                          IN_CLOSE_WRITE | IN_DELETE |
                          IN_MOVED_TO | IN_MOVED_FROM) < 0) {
448
        virReportSystemError(errno,
449 450
                             _("adding watch on %s"),
                             priv->configDir);
451 452 453
        return -1;
    }

454
    VIR_DEBUG0("Building initial config cache");
455
    if (priv->useXenConfigCache &&
456
        xenXMConfigCacheRefresh (conn) < 0) {
457
        VIR_DEBUG("Failed to enable XM config cache %s", conn->err.message);
458 459 460
        return -1;
    }

461
    VIR_DEBUG0("Registering with event loop");
462 463 464
    /* Add the handle for monitoring */
    if ((priv->inotifyWatch = virEventAddHandle(priv->inotifyFD, VIR_EVENT_HANDLE_READABLE,
                                                xenInotifyEvent, conn, NULL)) < 0) {
465
        VIR_DEBUG0("Failed to add inotify handle, disabling events");
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    }

    return 0;
}

/**
 * xenInotifyClose:
 * @conn: pointer to the connection block
 *
 * Close and stop listening for inotify events
 *
 * Returns 0 in case of success or -1 in case of error.
 */
int
xenInotifyClose(virConnectPtr conn)
{
482
    xenUnifiedPrivatePtr priv = conn->privateData;
483

484 485
    if (priv->configInfoList)
        xenUnifiedDomainInfoListFree(priv->configInfoList);
486 487 488

    if (priv->inotifyWatch != -1)
        virEventRemoveHandle(priv->inotifyWatch);
489
    VIR_FORCE_CLOSE(priv->inotifyFD);
490 491 492

    return 0;
}