summaryrefslogtreecommitdiffstats
path: root/xlators/features/compress/src/cdc-helper.c
blob: 7baccb0cd3d8ae7777953fea3eec2323c314f51c (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*
   Copyright (c) 2013 Red Hat, Inc. <http://www.redhat.com>
   This file is part of GlusterFS.

   This file is licensed to you under your choice of the GNU Lesser
   General Public License, version 3 or any later version (LGPLv3 or
   later), or the GNU General Public License, version 2 (GPLv2), in all
   cases as published by the Free Software Foundation.
*/

#include "glusterfs.h"
#include "logging.h"
#include "syscall.h"

#include "cdc.h"
#include "cdc-mem-types.h"

#ifdef HAVE_LIB_Z
#include "zlib.h"
#endif

#ifdef HAVE_LIB_Z
/* gzip header looks something like this
 * (RFC 1950)
 *
 * +---+---+---+---+---+---+---+---+---+---+
 * |ID1|ID2|CM |FLG|     MTIME     |XFL|OS |
 * +---+---+---+---+---+---+---+---+---+---+
 *
 * Data is usually sent without this header i.e
 * Data sent = <compressed-data> + trailer(8)
 * The trailer contains the checksum.
 *
 * gzip_header is added only during debugging.
 * Refer to the function cdc_dump_iovec_to_disk
 */
static const char gzip_header[10] =
        {
                '\037', '\213', Z_DEFLATED, 0,
                0,      0,      0,          0,
                0,      GF_CDC_OS_ID
        };

static int32_t
cdc_next_iovec (xlator_t *this, cdc_info_t *ci)
{
        int ret = -1;

        ci->ncount++;
        /* check for iovec overflow -- should not happen */
        if (ci->ncount == MAX_IOVEC) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Zlib output buffer overflow"
                        " ->ncount (%d) | ->MAX_IOVEC (%d)",
                        ci->ncount, MAX_IOVEC);
                goto out;
        }

        ret = 0;

 out:
        return ret;
}

static void
cdc_put_long (unsigned char *string, unsigned long x)
{
        string[0] = (unsigned char) (x & 0xff);
        string[1] = (unsigned char) ((x & 0xff00) >> 8);
        string[2] = (unsigned char) ((x & 0xff0000) >> 16);
        string[3] = (unsigned char) ((x & 0xff000000) >> 24);
}

static unsigned long
cdc_get_long (unsigned char *buf)
{
        return ((unsigned long) buf[0])
                | (((unsigned long) buf[1]) << 8)
                | (((unsigned long) buf[2]) << 16)
                | (((unsigned long) buf[3]) << 24);
}

static int32_t
cdc_init_gzip_trailer (xlator_t *this, cdc_priv_t *priv, cdc_info_t *ci)
{
        int   ret = -1;
        char *buf = NULL;

        ret = cdc_next_iovec (this, ci);
        if (ret)
                goto out;

        buf = CURR_VEC(ci).iov_base =
                (char *) GF_CALLOC (1, GF_CDC_VALIDATION_SIZE,
                                    gf_cdc_mt_gzip_trailer_t);

        if (!CURR_VEC(ci).iov_base)
                goto out;

        CURR_VEC(ci).iov_len = GF_CDC_VALIDATION_SIZE;

        cdc_put_long ((unsigned char *)&buf[0], ci->crc);
        cdc_put_long ((unsigned char *)&buf[4], ci->stream.total_in);

        ret = 0;

 out:
        return ret;
}

static int32_t
cdc_alloc_iobuf_and_init_vec (xlator_t *this,
                              cdc_priv_t *priv, cdc_info_t *ci,
                              int size)
{
        int           ret       = -1;
        int           alloc_len = 0;
        struct iobuf *iobuf     = NULL;

        ret = cdc_next_iovec (this, ci);
        if (ret)
                goto out;

        alloc_len = size ? size : ci->buffer_size;

        iobuf = iobuf_get2 (this->ctx->iobuf_pool, alloc_len);
        if (!iobuf)
                goto out;

        ret = iobref_add (ci->iobref, iobuf);
        if (ret)
                goto out;

        /* Initialize this iovec */
        CURR_VEC(ci).iov_base = iobuf->ptr;
        CURR_VEC(ci).iov_len  = alloc_len;

        ret = 0;

 out:
        return ret;
}

static void
cdc_init_zlib_output_stream (cdc_priv_t *priv, cdc_info_t *ci, int size)
{
        ci->stream.next_out  = (unsigned char *) CURR_VEC(ci).iov_base;
        ci->stream.avail_out = size ? size : ci->buffer_size;
}

/* This routine is for testing and debugging only.
 * Data written = header(10) + <compressed-data> + trailer(8)
 * So each gzip dump file is at least 18 bytes in size.
 */
void
cdc_dump_iovec_to_disk (xlator_t *this, cdc_info_t *ci, const char *file)
{
        int    i      = 0;
        int    fd     = 0;
        size_t written = 0;
        size_t total_written = 0;

        fd = open (file, O_WRONLY|O_CREAT|O_TRUNC, 0777 );
        if (fd < 0) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Cannot open file: %s", file);
                return;
        }

        written = sys_write (fd, (char *) gzip_header, 10);
        total_written += written;
        for (i = 0; i < ci->ncount; i++) {
                written = sys_write (fd, (char *) ci->vec[i].iov_base, ci->vec[i].iov_len);
                total_written += written;
        }

        gf_log (this->name, GF_LOG_DEBUG,
                        "dump'd %zu bytes to %s", total_written, GF_CDC_DEBUG_DUMP_FILE );

        sys_close (fd);
}

static int32_t
cdc_flush_libz_buffer (cdc_priv_t *priv, xlator_t *this, cdc_info_t *ci,
                       int (*libz_func)(z_streamp, int),
                       int flush)
{
        int32_t ret = Z_OK;
        int done = 0;
        unsigned int deflate_len = 0;

        for (;;) {
                deflate_len = ci->buffer_size - ci->stream.avail_out;

                if (deflate_len != 0) {
                        CURR_VEC(ci).iov_len = deflate_len;

                        ret = cdc_alloc_iobuf_and_init_vec (this, priv, ci, 0);
                        if (ret) {
                                ret = Z_MEM_ERROR;
                                break;
                        }

                        /* Re-position Zlib output buffer */
                        cdc_init_zlib_output_stream (priv, ci, 0);
                }

                if (done) {
                        ci->ncount--;
                        break;
                }

                ret = libz_func (&ci->stream, flush);

                if (ret == Z_BUF_ERROR) {
                        ret = Z_OK;
                        ci->ncount--;
                        break;
                }

                done = (ci->stream.avail_out != 0 || ret == Z_STREAM_END);

                if (ret != Z_OK && ret != Z_STREAM_END)
                        break;
        }

        return ret;
}

static int32_t
do_cdc_compress (struct iovec *vec, xlator_t *this, cdc_priv_t *priv,
                 cdc_info_t *ci)
{
        int ret = -1;

        /* Initialize defalte */
        ret = deflateInit2 (&ci->stream, priv->cdc_level, Z_DEFLATED,
                            priv->window_size, priv->mem_level,
                            Z_DEFAULT_STRATEGY);

        if (ret) {
                gf_log (this->name, GF_LOG_ERROR,
                        "unable to init Zlib (retval: %d)", ret);
                goto out;
        }

        ret = cdc_alloc_iobuf_and_init_vec (this, priv, ci, 0);
        if (ret)
                goto out;

        /* setup output buffer */
        cdc_init_zlib_output_stream (priv, ci, 0);

        /* setup input buffer */
        ci->stream.next_in  = (unsigned char *) vec->iov_base;
        ci->stream.avail_in = vec->iov_len;

        ci->crc = crc32 (ci->crc, (const Bytef *) vec->iov_base, vec->iov_len);

        gf_log (this->name, GF_LOG_DEBUG, "crc=%lu len=%d buffer_size=%d",
                ci->crc, ci->stream.avail_in, ci->buffer_size);

        /* compress !! */
        while (ci->stream.avail_in != 0) {
                if (ci->stream.avail_out == 0) {

                        CURR_VEC(ci).iov_len = ci->buffer_size;

                        ret = cdc_alloc_iobuf_and_init_vec (this, priv, ci, 0);
                        if (ret)
                                break;

                        /* Re-position Zlib output buffer */
                        cdc_init_zlib_output_stream (priv, ci, 0);
                }

                ret = deflate (&ci->stream, Z_NO_FLUSH);
                if (ret != Z_OK)
                        break;
        }

 out:
        return ret;
}

int32_t
cdc_compress (xlator_t *this, cdc_priv_t *priv, cdc_info_t *ci,
              dict_t **xdata)
{
        int ret = -1;
        int i   = 0;

        ci->iobref = iobref_new ();
        if (!ci->iobref)
                goto out;

        if (!*xdata) {
                *xdata = dict_new ();
                if (!*xdata) {
                        gf_log (this->name, GF_LOG_ERROR, "Cannot allocate xdata"
                                " dict");
                        goto out;
                }
        }

        /* data */
        for (i = 0; i < ci->count; i++) {
                ret = do_cdc_compress (&ci->vector[i], this, priv, ci);
                if (ret != Z_OK)
                        goto deflate_cleanup_out;
        }

        /* flush zlib buffer */
        ret = cdc_flush_libz_buffer (priv, this, ci, deflate, Z_FINISH);
        if (!(ret == Z_OK || ret == Z_STREAM_END)) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Compression Error: ret (%d)", ret);
                ret = -1;
                goto deflate_cleanup_out;
        }

        /* trailer */
        ret = cdc_init_gzip_trailer (this, priv, ci);
        if (ret)
                goto deflate_cleanup_out;

        gf_log (this->name, GF_LOG_DEBUG,
                "Compressed %ld to %ld bytes",
                ci->stream.total_in, ci->stream.total_out);

        ci->nbytes = ci->stream.total_out + GF_CDC_VALIDATION_SIZE;

        /* set deflated canary value for identification */
        ret = dict_set_int32 (*xdata, GF_CDC_DEFLATE_CANARY_VAL, 1);
        if (ret) {
                /* Send uncompressed data if we can't _tell_ the client
                 * that deflated data is on it's way. So, we just log
                 * the failure and continue as usual.
                 */
                 gf_log (this->name, GF_LOG_ERROR,
                 "Data deflated, but could not set canary"
                 " value in dict for identification");
        }

        /* This is to be used in testing */
        if ( priv->debug ) {
                cdc_dump_iovec_to_disk (this, ci, GF_CDC_DEBUG_DUMP_FILE );
        }

 deflate_cleanup_out:
        (void) deflateEnd(&ci->stream);

 out:
        return ret;
}


/* deflate content is checked by the presence of a canary
 * value in the dict as the key
 */
static int32_t
cdc_check_content_for_deflate (dict_t *xdata)
{
        return dict_get (xdata, GF_CDC_DEFLATE_CANARY_VAL) ? -1 : 0;
}

static unsigned long
cdc_extract_crc (char *trailer)
{
        return cdc_get_long ((unsigned char *) &trailer[0]);
}

static unsigned long
cdc_extract_size (char *trailer)
{
        return cdc_get_long ((unsigned char *) &trailer[4]);
}

static int32_t
cdc_validate_inflate (cdc_info_t *ci, unsigned long crc,
                      unsigned long len)
{
        return !((crc == ci->crc)
                 /* inflated length is hidden inside
                  * Zlib stream struct */
                 && (len == ci->stream.total_out));
}

static int32_t
do_cdc_decompress (xlator_t *this, cdc_priv_t *priv, cdc_info_t *ci)
{
        int            ret          = -1;
        int            i            = 0;
        int            len          = 0;
        char          *inflte       = NULL;
        char          *trailer      = NULL;
        struct iovec   vec          = {0,};
        unsigned long  computed_crc = 0;
        unsigned long  computed_len = 0;

        ret = inflateInit2 (&ci->stream, priv->window_size);
        if (ret) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Zlib: Unable to initialize inflate");
                goto out;
        }

        vec = THIS_VEC(ci, 0);

        trailer = (char *) (((char *) vec.iov_base) + vec.iov_len
                - GF_CDC_VALIDATION_SIZE);

        /* CRC of uncompressed data */
        computed_crc = cdc_extract_crc (trailer);

        /* size of uncomrpessed data */
        computed_len = cdc_extract_size (trailer);

        gf_log (this->name, GF_LOG_DEBUG, "crc=%lu len=%lu buffer_size=%d",
                computed_crc, computed_len, ci->buffer_size);

        inflte = vec.iov_base ;
        len = vec.iov_len - GF_CDC_VALIDATION_SIZE;

        /* allocate buffer of the original length of the data */
        ret = cdc_alloc_iobuf_and_init_vec (this, priv, ci, 0);
        if (ret)
                goto out;

        /* setup output buffer */
        cdc_init_zlib_output_stream (priv, ci, 0);

        /* setup input buffer */
        ci->stream.next_in = (unsigned char *) inflte;
        ci->stream.avail_in = len;

        while (ci->stream.avail_in != 0) {
                if (ci->stream.avail_out == 0) {
                        CURR_VEC(ci).iov_len = ci->buffer_size;

                        ret = cdc_alloc_iobuf_and_init_vec (this, priv, ci, 0);
                        if (ret)
                                break;

                        /* Re-position Zlib output buffer */
                        cdc_init_zlib_output_stream (priv, ci, 0);
                }

                ret = inflate (&ci->stream, Z_NO_FLUSH);
                if (ret == Z_STREAM_ERROR)
                        break;
        }

        /* flush zlib buffer */
        ret = cdc_flush_libz_buffer (priv, this, ci, inflate, Z_SYNC_FLUSH);
        if (!(ret == Z_OK || ret == Z_STREAM_END)) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Decompression Error: ret (%d)", ret);
                ret = -1;
                goto out;
        }

        /* compute CRC of the uncompresses data to check for
         * correctness */

        for (i = 0; i < ci->ncount; i++) {
                ci->crc = crc32 (ci->crc,
                                 (const Bytef *) ci->vec[i].iov_base,
                                 ci->vec[i].iov_len);
        }

        /* validate inflated data */
        ret = cdc_validate_inflate (ci, computed_crc, computed_len);
        if (ret) {
                gf_log (this->name, GF_LOG_ERROR,
                        "Checksum or length mismatched in inflated data");
        }

 out:
        return ret;
}

int32_t
cdc_decompress (xlator_t *this, cdc_priv_t *priv, cdc_info_t *ci,
                dict_t *xdata)
{
        int32_t ret = -1;

        /* check for deflate content */
        if (!cdc_check_content_for_deflate (xdata)) {
                gf_log (this->name, GF_LOG_DEBUG,
                        "Content not deflated, passing through ...");
                goto passthrough_out;
        }

        ci->iobref = iobref_new ();
        if (!ci->iobref)
                goto passthrough_out;

        /* do we need to do this? can we assume that one iovec
         * will hold per request data every time?
         *
         * server/client protocol seems to deal with a single
         * iovec even if op_ret > 1M. So, it looks ok to
         * assume that a single iovec will contain all the
         * data (This saves us a lot from finding the trailer
         * and the data since it could have been split-up onto
         * two adjacent iovec's.
         *
         * But, in case this translator is loaded above quick-read
         * for some reason, then it's entirely possible that we get
         * multiple iovec's...
         *
         * This case (handled below) is not tested. (by loading the
         * xlator below quick-read)
         */

        /* @@ I_HOPE_THIS_IS_NEVER_HIT */
        if (ci->count > 1) {
                gf_log (this->name, GF_LOG_WARNING, "unable to handle"
                        " multiple iovecs (%d in number)", ci->count);
                goto inflate_cleanup_out;
                /* TODO: coallate all iovecs in one */
        }

        ret = do_cdc_decompress (this, priv, ci);
        if (ret)
                goto inflate_cleanup_out;

        ci->nbytes = ci->stream.total_out;

        gf_log (this->name, GF_LOG_DEBUG,
                "Inflated %ld to %ld bytes",
                ci->stream.total_in, ci->stream.total_out);

 inflate_cleanup_out:
        (void) inflateEnd (&ci->stream);

 passthrough_out:
        return ret;
}

#endif