xen_inotify.c 13.7 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-2013 Red Hat, Inc.
8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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
21
 * License along with this library.  If not, see
O
Osier Yang 已提交
22
 * <http://www.gnu.org/licenses/>.
23 24 25 26 27 28 29
 *
 * Author: Ben Guthro
 */
#include <config.h>
#include <dirent.h>
#include <sys/inotify.h>

30
#include "virerror.h"
31 32
#include "datatypes.h"
#include "driver.h"
33
#include "viralloc.h"
34
#include "xen_driver.h"
35
#include "virconf.h"
36 37 38
#include "domain_conf.h"
#include "xen_inotify.h"
#include "xend_internal.h"
39
#include "virlog.h"
40
#include "viruuid.h"
E
Eric Blake 已提交
41
#include "virfile.h"
42 43 44

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

45 46
#define VIR_FROM_THIS VIR_FROM_XEN_INOTIFY

47
static int
48 49
xenInotifyXenCacheLookup(virConnectPtr conn,
                         const char *filename,
50 51 52
                         char **name,
                         unsigned char *uuid)
{
53
    xenUnifiedPrivatePtr priv = conn->privateData;
54 55
    xenXMConfCachePtr entry;

56
    if (!(entry = virHashLookup(priv->configCache, filename))) {
57
        VIR_DEBUG("No config found for %s", filename);
58
        return -1;
59 60
    }

61 62 63 64
    *name = strdup(entry->def->name);
    memcpy(uuid, entry->def->uuid, VIR_UUID_BUFLEN);

    if (!*name) {
65
        VIR_DEBUG("Error getting dom from def");
66
        virReportOOMError();
67
        return -1;
68
    }
69
    return 0;
70 71
}

72
static int
73 74 75 76 77
xenInotifyXendDomainsDirLookup(virConnectPtr conn,
                               const char *filename,
                               char **name,
                               unsigned char *uuid)
{
78 79 80
    int i;
    virDomainPtr dom;
    const char *uuid_str;
81
    unsigned char rawuuid[VIR_UUID_BUFLEN];
82
    xenUnifiedPrivatePtr priv = conn->privateData;
83 84 85 86 87

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

90
    if (virUUIDParse(uuid_str, rawuuid) < 0) {
91 92
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("parsing uuid %s"), uuid_str);
93
        return -1;
94 95 96 97
    }
    /* call directly into xend here, as driver may not yet
       be set during open while we are building our
       initial list of domains */
98
    VIR_DEBUG("Looking for dom with uuid: %s", uuid_str);
99
    /* XXX Should not have to go via a virDomainPtr obj instance */
100
    if (!(dom = xenDaemonLookupByUUID(conn, rawuuid))) {
101 102 103
        /* If we are here, the domain has gone away.
           search for, and create a domain from the stored
           list info */
104
        for (i = 0 ; i < priv->configInfoList->count ; i++) {
105
            if (!memcmp(rawuuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN)) {
106
                *name = strdup(priv->configInfoList->doms[i]->name);
107
                if (!*name) {
108
                    virReportOOMError();
109
                    return -1;
110
                }
111
                memcpy(uuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN);
112
                VIR_DEBUG("Found dom on list");
113
                return 0;
114 115
            }
        }
116 117
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("finding dom on config list"));
118
        return -1;
119 120
    }

121
    if (!(*name = strdup(dom->name))) {
122
        virReportOOMError();
123
        virDomainFree(dom);
124
        return -1;
125
    }
126 127
    memcpy(uuid, dom->uuid, VIR_UUID_BUFLEN);
    virDomainFree(dom);
128
    /* succeeded too find domain by uuid */
129
    return 0;
130 131
}

132 133 134
static int
xenInotifyDomainLookup(virConnectPtr conn,
                       const char *filename,
135 136 137
                       char **name,
                       unsigned char *uuid)
{
138 139
    xenUnifiedPrivatePtr priv = conn->privateData;
    if (priv->useXenConfigCache)
140
        return xenInotifyXenCacheLookup(conn, filename, name, uuid);
141 142 143 144 145 146 147
    else
        return xenInotifyXendDomainsDirLookup(conn, filename, name, uuid);
}

static virDomainEventPtr
xenInotifyDomainEventFromFile(virConnectPtr conn,
                              const char *filename,
148 149 150
                              int type,
                              int detail)
{
151 152 153 154 155 156 157 158 159 160
    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;
161 162 163
}

static int
164 165
xenInotifyXendDomainsDirRemoveEntry(virConnectPtr conn, const char *fname)
{
166
    xenUnifiedPrivatePtr priv = conn->privateData;
167
    const char *uuidstr = fname + strlen(XEND_DOMAINS_DIR) + 1;
168 169 170 171
    unsigned char uuid[VIR_UUID_BUFLEN];
    int i;

    if (virUUIDParse(uuidstr, uuid) < 0) {
172 173
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("parsing uuid %s"), uuidstr);
174 175 176 177
        return -1;
    }

    /* match and remove on uuid */
178 179 180 181 182 183 184 185 186 187 188 189 190
    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) {
191 192
                ; /* Failure to reduce memory allocation isn't fatal */
            }
193
            priv->configInfoList->count--;
194 195 196 197 198 199 200
            return 0;
        }
    }
    return -1;
}

static int
201 202
xenInotifyXendDomainsDirAddEntry(virConnectPtr conn, const char *fname)
{
203 204
    char *name = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
205 206
    xenUnifiedPrivatePtr priv = conn->privateData;

207
    if (xenInotifyDomainLookup(conn, fname, &name, uuid) < 0) {
208 209
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Error looking up domain"));
210 211 212
        return -1;
    }

213
    if (xenUnifiedAddDomainInfo(priv->configInfoList,
214
                                -1, name, uuid) < 0) {
215 216
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Error adding file to config cache"));
217
        VIR_FREE(name);
218 219
        return -1;
    }
220
    VIR_FREE(name);
221 222 223 224
    return 0;
}

static int
225 226
xenInotifyRemoveDomainConfigInfo(virConnectPtr conn, const char *fname)
{
227 228 229 230
    xenUnifiedPrivatePtr priv = conn->privateData;
    return priv->useXenConfigCache ?
        xenXMConfigCacheRemoveFile(conn, fname) :
        xenInotifyXendDomainsDirRemoveEntry(conn, fname);
231 232 233
}

static int
234 235
xenInotifyAddDomainConfigInfo(virConnectPtr conn, const char *fname)
{
236 237 238 239
    xenUnifiedPrivatePtr priv = conn->privateData;
    return priv->useXenConfigCache ?
        xenXMConfigCacheAddFile(conn, fname) :
        xenInotifyXendDomainsDirAddEntry(conn, fname);
240 241 242 243 244 245 246 247 248 249 250 251 252
}

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;
253
    virConnectPtr conn = data;
254 255
    xenUnifiedPrivatePtr priv = NULL;

256
    VIR_DEBUG("got inotify event");
257

258
    if (conn && conn->privateData) {
259 260
        priv = conn->privateData;
    } else {
261 262
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("conn, or private data is NULL"));
263 264 265
        return;
    }

D
Daniel P. Berrange 已提交
266 267
    xenUnifiedLock(priv);

268 269 270 271 272
reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
D
Daniel P. Berrange 已提交
273
        goto cleanup;
274 275 276 277 278
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
D
Daniel P. Berrange 已提交
279
            goto cleanup; /* bad */
280 281 282 283 284 285

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

        if (got < e->len)
D
Daniel P. Berrange 已提交
286
            goto cleanup;
287 288 289 290 291 292

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

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

293 294
        snprintf(fname, 1024, "%s/%s",
                 priv->configDir, name);
295 296

        if (e->mask & (IN_DELETE | IN_MOVED_FROM)) {
297 298 299 300
            virDomainEventPtr event =
                xenInotifyDomainEventFromFile(conn, fname,
                                              VIR_DOMAIN_EVENT_UNDEFINED,
                                              VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
301
            if (event)
302 303
                xenUnifiedDomainEventDispatch(conn->privateData, event);
            else
304 305
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("looking up dom"));
306

307
            if (xenInotifyRemoveDomainConfigInfo(conn, fname) < 0) {
308 309
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Error adding file to config cache"));
D
Daniel P. Berrange 已提交
310
                goto cleanup;
311
            }
312
        } else if (e->mask & (IN_CREATE | IN_CLOSE_WRITE | IN_MOVED_TO)) {
313
            virDomainEventPtr event;
314
            if (xenInotifyAddDomainConfigInfo(conn, fname) < 0) {
315 316
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Error adding file to config cache"));
D
Daniel P. Berrange 已提交
317
                goto cleanup;
318 319
            }

320 321 322 323 324 325 326
            event = xenInotifyDomainEventFromFile(conn, fname,
                                                  VIR_DOMAIN_EVENT_DEFINED,
                                                  VIR_DOMAIN_EVENT_DEFINED_ADDED);

            if (event)
                xenUnifiedDomainEventDispatch(conn->privateData, event);
            else
327 328
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("looking up dom"));
329 330 331 332

        }

    }
D
Daniel P. Berrange 已提交
333 334 335

cleanup:
    xenUnifiedUnlock(priv);
336 337 338 339 340 341 342 343 344 345 346 347
}

/**
 * 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.
 */
348
int
349
xenInotifyOpen(virConnectPtr conn,
350
               virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
351
               unsigned int flags)
352 353 354
{
    DIR *dh;
    struct dirent *ent;
355
    char *path;
356
    xenUnifiedPrivatePtr priv = conn->privateData;
357

358
    virCheckFlags(VIR_CONNECT_RO, -1);
E
Eric Blake 已提交
359

360
    if (priv->configDir) {
361
        priv->useXenConfigCache = 1;
362 363
    } else {
        /* /var/lib/xend/domains/<uuid>/config.sxp */
364
        priv->configDir = XEND_DOMAINS_DIR;
365
        priv->useXenConfigCache = 0;
366

367
        if (VIR_ALLOC(priv->configInfoList) < 0) {
368
            virReportOOMError();
369 370 371 372
            return -1;
        }

        /* populate initial list */
373
        if (!(dh = opendir(priv->configDir))) {
374
            virReportSystemError(errno,
375
                                 _("cannot open directory: %s"),
376
                                 priv->configDir);
377 378 379 380 381 382 383
            return -1;
        }
        while ((ent = readdir(dh))) {
            if (STRPREFIX(ent->d_name, "."))
                continue;

            /* Build the full file path */
384 385 386 387
            if (!(path = virFileBuildPath(priv->configDir, ent->d_name, NULL))) {
                closedir(dh);
                return -1;
            }
388

389
            if (xenInotifyAddDomainConfigInfo(conn, path) < 0) {
390 391
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Error adding file to config list"));
392
                closedir(dh);
393
                VIR_FREE(path);
394 395
                return -1;
            }
396 397

            VIR_FREE(path);
398
        }
399
        closedir(dh);
400 401 402
    }

    if ((priv->inotifyFD = inotify_init()) < 0) {
403
        virReportSystemError(errno,
404
                             "%s", _("initializing inotify"));
405 406 407
        return -1;
    }

408
    VIR_DEBUG("Adding a watch on %s", priv->configDir);
409
    if (inotify_add_watch(priv->inotifyFD,
410
                          priv->configDir,
411 412 413
                          IN_CREATE |
                          IN_CLOSE_WRITE | IN_DELETE |
                          IN_MOVED_TO | IN_MOVED_FROM) < 0) {
414
        virReportSystemError(errno,
415 416
                             _("adding watch on %s"),
                             priv->configDir);
417 418 419
        return -1;
    }

420
    VIR_DEBUG("Building initial config cache");
421
    if (priv->useXenConfigCache &&
422
        xenXMConfigCacheRefresh(conn) < 0) {
423
        VIR_DEBUG("Failed to enable XM config cache %s", conn->err.message);
424 425 426
        return -1;
    }

427
    VIR_DEBUG("Registering with event loop");
428 429 430
    /* Add the handle for monitoring */
    if ((priv->inotifyWatch = virEventAddHandle(priv->inotifyFD, VIR_EVENT_HANDLE_READABLE,
                                                xenInotifyEvent, conn, NULL)) < 0) {
431
        VIR_DEBUG("Failed to add inotify handle, disabling events");
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    }

    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)
{
448
    xenUnifiedPrivatePtr priv = conn->privateData;
449

450 451
    if (priv->configInfoList)
        xenUnifiedDomainInfoListFree(priv->configInfoList);
452 453 454

    if (priv->inotifyWatch != -1)
        virEventRemoveHandle(priv->inotifyWatch);
455
    VIR_FORCE_CLOSE(priv->inotifyFD);
456 457 458

    return 0;
}