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 42 43 44
#include "conf.h"
#include "domain_conf.h"
#include "xen_inotify.h"
#include "xend_internal.h"
#include "logging.h"
#include "uuid.h"

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

45 46
#define VIR_FROM_THIS VIR_FROM_XEN_INOTIFY

47
#define virXenInotifyError(conn, code, ...)                                   \
48
        virReportErrorHelper(NULL, VIR_FROM_XEN_INOTIFY, code, __FILE__,      \
49
                             __FUNCTION__, __LINE__, __VA_ARGS__)
50 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 82

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, /* domainSetVcpus */
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
    NULL, /* domainGetMaxVcpus */
    NULL, /* listDefinedDomains */
    NULL, /* numOfDefinedDomains */
    NULL, /* domainCreate */
    NULL, /* domainDefineXML */
    NULL, /* domainUndefine */
83 84
    NULL, /* domainAttachDeviceFlags */
    NULL, /* domainDetachDeviceFlags */
85
    NULL, /* domainUpdateDeviceFlags */
86 87 88 89 90 91 92
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
};

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

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

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

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

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

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

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

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

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

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

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

    /* match and remove on uuid */
214 215 216 217 218 219 220 221 222 223 224 225 226
    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) {
227 228
                ; /* Failure to reduce memory allocation isn't fatal */
            }
229
            priv->configInfoList->count--;
230 231 232 233 234 235 236 237 238
            return 0;
        }
    }
    return -1;
}

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

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

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

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

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

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;
289
    virConnectPtr conn = data;
290 291 292 293 294 295 296 297 298 299 300 301
    xenUnifiedPrivatePtr priv = NULL;

    DEBUG0("got inotify event");

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

/**
 * 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.
 */
384
virDrvOpenStatus
385
xenInotifyOpen(virConnectPtr conn,
386 387 388 389 390 391 392 393
             virConnectAuthPtr auth ATTRIBUTE_UNUSED,
             int flags ATTRIBUTE_UNUSED)
{
    DIR *dh;
    struct dirent *ent;
    char path[PATH_MAX];
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;

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

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

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

            /* Build the full file path */
418 419
            if ((strlen(priv->configDir) + 1 +
                 strlen(ent->d_name) + 1) > PATH_MAX)
420
                continue;
421
            strcpy(path, priv->configDir);
422 423 424 425 426 427
            strcat(path, "/");
            strcat(path, ent->d_name);

            if (xenInotifyAddDomainConfigInfo(conn, path) < 0 ) {
                virXenInotifyError(NULL, VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("Error adding file to config list"));
428
                closedir(dh);
429 430 431
                return -1;
            }
        }
432
        closedir(dh);
433 434 435
    }

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

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

    DEBUG0("Building initial config cache");
454
    if (priv->useXenConfigCache &&
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        xenXMConfigCacheRefresh (conn) < 0) {
        DEBUG("Failed to enable XM config cache %s", conn->err.message);
        return -1;
    }

    DEBUG0("Registering with event loop");
    /* Add the handle for monitoring */
    if ((priv->inotifyWatch = virEventAddHandle(priv->inotifyFD, VIR_EVENT_HANDLE_READABLE,
                                                xenInotifyEvent, conn, NULL)) < 0) {
        DEBUG0("Failed to add inotify handle, disabling events");
    }

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

483 484
    if (priv->configInfoList)
        xenUnifiedDomainInfoListFree(priv->configInfoList);
485 486 487 488 489 490 491

    if (priv->inotifyWatch != -1)
        virEventRemoveHandle(priv->inotifyWatch);
    close(priv->inotifyFD);

    return 0;
}