xen_inotify.c 14.2 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-2011 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
 * 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"
34
#include "xen_driver.h"
35 36 37 38 39 40
#include "conf.h"
#include "domain_conf.h"
#include "xen_inotify.h"
#include "xend_internal.h"
#include "logging.h"
#include "uuid.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
#define virXenInotifyError(code, ...)                                   \
48
        virReportErrorHelper(VIR_FROM_XEN_INOTIFY, code, __FILE__,      \
49
                             __FUNCTION__, __LINE__, __VA_ARGS__)
50 51

struct xenUnifiedDriver xenInotifyDriver = {
E
Eric Blake 已提交
52
    .xenClose = xenInotifyClose,
53 54
};

55
static int
56 57
xenInotifyXenCacheLookup(virConnectPtr conn,
                         const char *filename,
58
                         char **name, unsigned char *uuid) {
59
    xenUnifiedPrivatePtr priv = conn->privateData;
60 61
    xenXMConfCachePtr entry;

62
    if (!(entry = virHashLookup(priv->configCache, filename))) {
63
        VIR_DEBUG("No config found for %s", filename);
64
        return -1;
65 66
    }

67 68 69 70
    *name = strdup(entry->def->name);
    memcpy(uuid, entry->def->uuid, VIR_UUID_BUFLEN);

    if (!*name) {
71
        VIR_DEBUG("Error getting dom from def");
72
        virReportOOMError();
73
        return -1;
74
    }
75
    return 0;
76 77
}

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

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

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

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

135 136 137 138
static int
xenInotifyDomainLookup(virConnectPtr conn,
                       const char *filename,
                       char **name, unsigned char *uuid) {
139 140
    xenUnifiedPrivatePtr priv = conn->privateData;
    if (priv->useXenConfigCache)
141
        return xenInotifyXenCacheLookup(conn, filename, name, uuid);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    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;
160 161 162
}

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

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

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

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

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

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

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

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

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

255
    VIR_DEBUG("got inotify event");
256 257 258 259

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

E
Eric Blake 已提交
357 358
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

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

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}