summaryrefslogtreecommitdiff
path: root/src/util/virfilecache.c
blob: c730de066eab39da5b64e36b60aba68831129c96 (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
 * virfilecache.c: file caching for data
 *
 * Copyright (C) 2017 Red Hat, Inc.
 *
 * 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 "internal.h"

#include "virbuffer.h"
#include "vircrypto.h"
#include "virerror.h"
#include "virfile.h"
#include "virfilecache.h"
#include "virhash.h"
#include "virlog.h"
#include "virobject.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define VIR_FROM_THIS VIR_FROM_NONE

VIR_LOG_INIT("util.filecache");


struct _virFileCache {
    virObjectLockable parent;

    GHashTable *table;

    char *dir;
    char *suffix;

    void *priv;

    virFileCacheHandlers handlers;
};


static virClass *virFileCacheClass;


static void
virFileCachePrivFree(virFileCache *cache)
{
    if (cache->priv && cache->handlers.privFree)
        cache->handlers.privFree(cache->priv);
}


static void
virFileCacheDispose(void *obj)
{
    virFileCache *cache = obj;

    g_free(cache->dir);
    g_free(cache->suffix);

    g_clear_pointer(&cache->table, g_hash_table_unref);

    virFileCachePrivFree(cache);
}


static int
virFileCacheOnceInit(void)
{
    if (!VIR_CLASS_NEW(virFileCache, virClassForObjectLockable()))
        return -1;

    return 0;
}


VIR_ONCE_GLOBAL_INIT(virFileCache);


static char *
virFileCacheGetFileName(virFileCache *cache,
                        const char *name)
{
    g_autofree char *namehash = NULL;
    g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;

    if (virCryptoHashString(VIR_CRYPTO_HASH_SHA256, name, &namehash) < 0)
        return NULL;

    if (g_mkdir_with_parents(cache->dir, 0777) < 0) {
        virReportSystemError(errno,
                             _("Unable to create directory '%1$s'"),
                             cache->dir);
        return NULL;
    }

    virBufferAsprintf(&buf, "%s/%s", cache->dir, namehash);

    if (cache->suffix)
        virBufferAsprintf(&buf, ".%s", cache->suffix);

    return virBufferContentAndReset(&buf);
}


static int
virFileCacheLoad(virFileCache *cache,
                 const char *name,
                 void **data)
{
    g_autofree char *file = NULL;
    int ret = -1;
    void *loadData = NULL;
    bool outdated = false;

    *data = NULL;

    if (!(file = virFileCacheGetFileName(cache, name)))
        return ret;

    if (!virFileExists(file)) {
        if (errno == ENOENT) {
            VIR_DEBUG("No cached data '%s' for '%s'", file, name);
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno,
                             _("Unable to access cache '%1$s' for '%2$s'"),
                             file, name);
        goto cleanup;
    }

    if (!(loadData = cache->handlers.loadFile(file, name, cache->priv, &outdated))) {
        if (!outdated) {
            VIR_WARN("Failed to load cached data from '%s' for '%s': %s",
                     file, name, virGetLastErrorMessage());
            virResetLastError();
        }
        ret = 0;
        goto cleanup;
    }

    if (!cache->handlers.isValid(loadData, cache->priv)) {
        VIR_DEBUG("Outdated cached capabilities '%s' for '%s'", file, name);
        unlink(file);
        ret = 0;
        goto cleanup;
    }

    VIR_DEBUG("Loaded cached data '%s' for '%s'", file, name);

    ret = 1;
    *data = g_steal_pointer(&loadData);

 cleanup:
    virObjectUnref(loadData);
    return ret;
}


static int
virFileCacheSave(virFileCache *cache,
                 const char *name,
                 void *data)
{
    g_autofree char *file = NULL;

    if (!(file = virFileCacheGetFileName(cache, name)))
        return -1;

    if (cache->handlers.saveFile(data, file, cache->priv) < 0)
        return -1;

    return 0;
}


static void *
virFileCacheNewData(virFileCache *cache,
                    const char *name)
{
    void *data = NULL;
    int rv;

    if ((rv = virFileCacheLoad(cache, name, &data)) < 0)
        return NULL;

    if (rv == 0) {
        if (!(data = cache->handlers.newData(name, cache->priv)))
            return NULL;

        if (virFileCacheSave(cache, name, data) < 0) {
            g_clear_pointer(&data, virObjectUnref);
        }
    }

    return data;
}


/**
 * virFileCacheNew:
 * @dir: the cache directory where all the cache files will be stored
 * @suffix: the cache file suffix or NULL if no suffix is required
 * @handlers: filled structure with all required handlers
 *
 * Creates a new cache object which handles caching any data to files
 * stored on a filesystem.
 *
 * Returns new cache object or NULL on error.
 */
virFileCache *
virFileCacheNew(const char *dir,
                const char *suffix,
                virFileCacheHandlers *handlers)
{
    virFileCache *cache;

    if (virFileCacheInitialize() < 0)
        return NULL;

    if (!(cache = virObjectNew(virFileCacheClass)))
        return NULL;

    cache->table = virHashNew(virObjectUnref);

    cache->dir = g_strdup(dir);

    cache->suffix = g_strdup(suffix);

    cache->handlers = *handlers;

    return cache;
}


static void
virFileCacheValidate(virFileCache *cache,
                     const char *name,
                     void **data)
{
    if (*data && !cache->handlers.isValid(*data, cache->priv)) {
        VIR_DEBUG("Cached data '%p' no longer valid for '%s'",
                  *data, NULLSTR(name));
        if (name)
            virHashRemoveEntry(cache->table, name);
        *data = NULL;
    }

    if (!*data && name) {
        VIR_DEBUG("Creating data for '%s'", name);
        *data = virFileCacheNewData(cache, name);
        if (*data) {
            VIR_DEBUG("Caching data '%p' for '%s'", *data, name);
            if (virHashAddEntry(cache->table, name, *data) < 0) {
                g_clear_pointer(data, virObjectUnref);
            }
        }
    }
}


/**
 * virFileCacheLookup:
 * @cache: existing cache object
 * @name: name of the data stored in a cache
 *
 * Lookup a data specified by name.  This tries to find a file with
 * cached data, if it doesn't exist or is no longer valid new data
 * is created.
 *
 * Returns data object or NULL on error.  The caller is responsible for
 * unrefing the data.
 */
void *
virFileCacheLookup(virFileCache *cache,
                   const char *name)
{
    void *data = NULL;

    virObjectLock(cache);

    data = virHashLookup(cache->table, name);
    virFileCacheValidate(cache, name, &data);

    virObjectRef(data);
    virObjectUnlock(cache);

    return data;
}


/**
 * virFileCacheLookupByFunc:
 * @cache: existing cache object
 * @iter: an iterator to identify the desired data
 * @iterData: extra opaque information passed to the @iter
 *
 * Similar to virFileCacheLookup() except it search by @iter.
 *
 * Returns data object or NULL on error.  The caller is responsible for
 * unrefing the data.
 */
void *
virFileCacheLookupByFunc(virFileCache *cache,
                         virHashSearcher iter,
                         const void *iterData)
{
    void *data = NULL;
    g_autofree char *name = NULL;

    virObjectLock(cache);

    data = virHashSearch(cache->table, iter, iterData, &name);
    virFileCacheValidate(cache, name, &data);

    virObjectRef(data);
    virObjectUnlock(cache);

    return data;
}


/**
 * virFileCacheGetPriv:
 * @cache: existing cache object
 *
 * Returns private data used by @handlers.
 */
void *
virFileCacheGetPriv(virFileCache *cache)
{
    void *priv;

    virObjectLock(cache);

    priv = cache->priv;

    virObjectUnlock(cache);

    return priv;
}


/**
 * virFileCacheSetPriv:
 * @cache: existing cache object
 * @priv: private data to set
 *
 * Sets private data used by @handlers.  If there is already some @priv
 * set, privFree() will be called on the old @priv before setting a new one.
 */
void
virFileCacheSetPriv(virFileCache *cache,
                    void *priv)
{
    virObjectLock(cache);

    virFileCachePrivFree(cache);

    cache->priv = priv;

    virObjectUnlock(cache);
}


/**
 * virFileCacheInsertData:
 * @cache: existing cache object
 * @name: name of the new data
 * @data: the actual data object to store in cache
 *
 * Adds a new data into a cache but doesn't store the data into
 * a file.  This function should be used only by testing code.
 *
 * Returns 0 on success, -1 on error.
 */
int
virFileCacheInsertData(virFileCache *cache,
                       const char *name,
                       void *data)
{
    int ret;

    virObjectLock(cache);

    ret = virHashUpdateEntry(cache->table, name, data);

    virObjectUnlock(cache);

    return ret;
}


/**
 * virFileCacheClear:
 * @cache: existing cache object
 *
 * Drops all entries from the cache. This is useful in tests to clean out
 * previous usage.
 */
void
virFileCacheClear(virFileCache *cache)
{
    virObjectLock(cache);
    virHashRemoveAll(cache->table);
    virObjectUnlock(cache);
}