Debian Codegraph @

samtools/tmp_file.c

raw symbols SCIP
1 /*
2 tmp_file.c - write to and read from a temporary binary file
3 for fast storage plus added compression.
4
5 Copyright (C) 2017, 2018 Genome Research Ltd.
6
7 Author: Andrew Whitwham <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE
26 */
27
28 #include <config.h>
29
30 #include <stdio.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <stdarg.h>
35 #include <fcntl.h>
36 #include <errno.h>
37
38 #ifdef _WIN32
39 #include <windows.h>
40 #endif /* _WIN32 */
41
42 #include "tmp_file.h"
43 #include "htslib/sam.h"
44
45
46 static void HTS_FORMAT(HTS_PRINTF_FMT, 2, 3)
47 tmp_print_error(tmp_file_t *tmp, const char *fmt, ...) {
48 va_list argp;
49
50 if (tmp->verbose) {
51 va_start(argp, fmt);
52 vfprintf(stderr, fmt, argp);
53 va_end(argp);
54 }
55 }
56
57
58 static int tmp_file_init(tmp_file_t *tmp, int verbose) {
59 tmp->stream = LZ4_createStream();
60 tmp->data_size = 0;
61 tmp->group_size = TMP_SAM_GROUP_SIZE;
62 tmp->input_size = 0;
63 tmp->read_size = 0;
64 tmp->output_size = 0;
65 tmp->entry_number = 0;
66 tmp->offset = 0;
67 tmp->max_data_size = TMP_SAM_MAX_DATA + sizeof(bam1_t); // arbitrary but growable
68 tmp->ring_buffer_size = TMP_SAM_RING_SIZE; // arbitrary (min 64K) but growable
69 tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size * tmp->group_size);
70 tmp->ring_buffer = malloc(sizeof(uint8_t) * tmp->ring_buffer_size);
71 tmp->ring_index = tmp->ring_buffer;
72 tmp->comp_buffer = malloc(tmp->comp_buffer_size);
73 tmp->verbose = verbose;
74 tmp->dict = NULL;
75 tmp->groups_written = 0;
76
77 if (!tmp->ring_buffer || !tmp->comp_buffer || !tmp->stream) {
78 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression buffers.\n");
79 return TMP_SAM_MEM_ERROR;
80 }
81
82 return TMP_SAM_OK;
83 }
84
85
86 /*
87 * Opens the temp file and initialises memory.
88 * Verbose mode prints out error messages to stderr.
89 * Returns 0 on success, a negative number on failure.
90 */
91 int tmp_file_open_write(tmp_file_t *tmp, char *tmp_name, int verbose) {
92 int ret;
93 unsigned int count = 1;
94 const unsigned int max_count = 100000; // more tries than this then something else is wrong
95 int fd;
96
97 if ((ret = tmp_file_init(tmp, verbose))) {
98 return ret;
99 }
100
101 // make space to write extended file name
102 if ((tmp->name = malloc(strlen(tmp_name) + 7)) == NULL) {
103 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for %s.\n", tmp_name);
104 return TMP_SAM_MEM_ERROR;
105 }
106
107 // make sure temp file has a unique name
108 while (count < max_count) {
109 sprintf(tmp->name, "%s.%d", tmp_name, count);
110
111
112 #ifdef _WIN32
113 if ((fd = _open(tmp->name, O_RDWR|O_CREAT|O_EXCL|O_BINARY|O_TEMPORARY, 0600)) == -1) {
114 #else
115 if ((fd = open(tmp->name, O_RDWR|O_CREAT|O_EXCL, 0600)) == -1) {
116 #endif /* _WIN32 */
117
118 if (errno != EEXIST) {
119 tmp_print_error(tmp, "[tmp_file] Error: unable to create tmp file %s.\n", tmp->name);
120 return TMP_SAM_FILE_ERROR;
121 }
122
123 count++;
124 continue;
125 }
126
127 break;
128 }
129
130 if (count >= max_count) {
131 tmp_print_error(tmp, "[tmp_file] Error: unable to create unique temp file.\n");
132 return TMP_SAM_FILE_ERROR;
133 }
134
135 if ((tmp->fp = fdopen(fd, "w+b")) == NULL) {
136 tmp_print_error(tmp, "[tmp_file] Error: unable to open write file %s.\n", tmp->name);
137 return TMP_SAM_FILE_ERROR;
138 }
139
140 #ifndef _WIN32
141 unlink(tmp->name); // should auto delete when closed on linux
142 #endif
143
144 return TMP_SAM_OK;
145 }
146
147
148 /*
149 * The ring buffer stores precompressionn/post decompression data. LZ4 requires that
150 * previous data (64K worth) be available for efficient compression. This function grows
151 * the ring buffer when needed.
152 * Returns 0 on success, a negative number on failure.
153 */
154 static int tmp_file_grow_ring_buffer(tmp_file_t *tmp, size_t new_size) {
155 // save the dictionary so lz4 can continue to function
156 int dict_size = 64 * 1024; // 64K max size
157
158 if (tmp->groups_written) {
159 // if compression has been done then there is a dictionary to save
160
161 if (tmp->dict == NULL) {
162
163 if ((tmp->dict = malloc(sizeof(char) * dict_size)) == NULL) {
164 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for compression dictionary.\n");
165 return TMP_SAM_MEM_ERROR;
166 }
167 }
168
169 if (LZ4_saveDict(tmp->stream, tmp->dict, dict_size) == 0) {
170 tmp_print_error(tmp, "[tmp_file] Error: unable to save compression dictionary.\n");
171 return TMP_SAM_LZ4_ERROR;
172 }
173 }
174
175 if ((tmp->ring_buffer = realloc(tmp->ring_buffer, sizeof(char) * new_size)) == NULL) {
176 tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate ring buffer.\n");
177 return TMP_SAM_MEM_ERROR;
178 }
179
180 tmp->ring_buffer_size = new_size;
181
182 return TMP_SAM_OK;
183 }
184
185
186 /*
187 * This does the actual compression and writing to a file. The file format consists of a
188 * single size_t for the size of the compressed data followed by the data itself.
189 * Returns 0 on success, a negative number on failure.
190 */
191 static int tmp_file_write_to_file(tmp_file_t *tmp) {
192 size_t comp_size;
193
194 if (tmp->input_size > tmp->max_data_size) {
195 tmp->max_data_size += tmp->input_size + sizeof(bam1_t);
196 tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size);
197
198 if ((tmp->comp_buffer = realloc(tmp->comp_buffer, sizeof(char) * tmp->comp_buffer_size)) == NULL) {
199 tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate compression buffer.\n");
200 return TMP_SAM_MEM_ERROR;
201 }
202
203 // make sure the ring buffer is big enough to accommodate the new max_data_size
204 if (tmp->ring_buffer_size < tmp->max_data_size * 5) {
205 int ret;
206 if ((ret = tmp_file_grow_ring_buffer(tmp, tmp->max_data_size * 5))) {
207 return ret;
208 }
209 }
210 }
211
212 tmp->ring_index = tmp->ring_buffer + tmp->offset;
213
214 comp_size = LZ4_compress_fast_continue(tmp->stream, (const char *)tmp->ring_index,
215 tmp->comp_buffer, tmp->input_size, tmp->comp_buffer_size, 1);
216
217 if (comp_size == 0) {
218 tmp_print_error(tmp, "[tmp_file] Error: compression failed.\n");
219 return TMP_SAM_LZ4_ERROR;
220 }
221
222 if (fwrite(&comp_size, sizeof(size_t), 1, tmp->fp) < 1) {
223 tmp_print_error(tmp, "[tmp_file] Error: tmp file write size failed.\n");
224 return TMP_SAM_FILE_ERROR;
225 }
226
227 if (fwrite(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) < comp_size) {
228 tmp_print_error(tmp, "[tmp_file] Error: tmp file write data failed.\n");
229 return TMP_SAM_FILE_ERROR;
230 }
231
232 tmp->offset += tmp->input_size;
233
234 if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size)
235 tmp->offset = 0;
236
237 tmp->input_size = 0;
238 tmp->entry_number = 0;
239 tmp->groups_written++;
240
241 return TMP_SAM_OK;
242 }
243
244
245 /*
246 * Stores an in memory bam structure for writing and if enough are gathered together writes
247 * it to a file. Multiple alignments compress better that single ones though after a certain number
248 * there is a law of diminishing returns.
249 * Returns 0 on success, a negative number on failure.
250 */
251 int tmp_file_write(tmp_file_t *tmp, bam1_t *inbam) {
252
253 if ((tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) >= tmp->ring_buffer_size) {
254 int ret;
255
256 if ((ret = tmp_file_grow_ring_buffer(tmp, (tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) * 2))) {
257 tmp_print_error(tmp, "[tmp_file] Error: input line too big. (%zu).\n",
258 (tmp->input_size + inbam->l_data));
259
260 return ret;
261 }
262 }
263
264 tmp->ring_index = tmp->ring_buffer + tmp->offset + tmp->input_size;
265
266 // copy data into the ring buffer
267 memcpy(tmp->ring_index, inbam, sizeof(bam1_t));
268 memcpy(tmp->ring_index + sizeof(bam1_t) , inbam->data, inbam->l_data);
269 tmp->input_size += sizeof(bam1_t) + inbam->l_data;
270 tmp->entry_number++;
271
272 if (tmp->entry_number == tmp->group_size) {
273 // actually write out the data
274 int ret;
275
276 if ((ret = tmp_file_write_to_file(tmp))) {
277 return ret;
278 }
279 }
280
281 return TMP_SAM_OK;
282 }
283
284
285 /*
286 * Marks the end of file writing. Adds a size_t 0 to mark the end of
287 * the file. Companion function to tmp_file_begin_read below.
288 * Returns 0 on success, a negative number on failure.
289 */
290 int tmp_file_end_write(tmp_file_t *tmp) {
291 size_t terminator = 0;
292
293 if (tmp->entry_number) {
294 int ret;
295
296 if ((ret = tmp_file_write_to_file(tmp))) {
297 return ret;
298 }
299 }
300
301 if (fwrite(&terminator, sizeof(size_t), 1, tmp->fp) < 1) {
302 tmp_print_error(tmp, "[tmp_file] Error: tmp file write terminator failed.\n");
303 return TMP_SAM_FILE_ERROR;
304 }
305
306 fflush(tmp->fp);
307
308 LZ4_freeStream(tmp->stream);
309
310 return TMP_SAM_OK;
311 }
312
313
314 /*
315 * Prepares the file for reading.
316 * Companion function to tmp_file_end_write above.
317 * Returns 0 on success, a negative number on failure.
318 */
319 int tmp_file_begin_read(tmp_file_t *tmp) {
320
321 rewind(tmp->fp);
322
323 tmp->dstream = LZ4_createStreamDecode();
324 tmp->offset = 0;
325 tmp->entry_number = tmp->group_size;
326
327 if (!tmp->dstream) {
328 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression stream.\n");
329 return TMP_SAM_MEM_ERROR;
330 }
331
332 return TMP_SAM_OK;
333 }
334
335
336 /*
337 * Read the next alignment, either from memory or from a file.
338 * Returns size of entry on success, 0 on end of file or a negative on error.
339 */
340 int tmp_file_read(tmp_file_t *tmp, bam1_t *inbam) {
341 int entry_size;
342 uint8_t *data = inbam->data;
343
344 /* while tmp_file_read assumes that the same bam1_t variable
345 is being used in each call, this may not be the case. So
346 default to the lowest memory size for safety. */
347 if (tmp->data_size > inbam->m_data) {
348 tmp->data_size = inbam->m_data;
349 }
350
351 if (tmp->entry_number == tmp->group_size) {
352 // read more data
353 size_t comp_size;
354
355 if (fread(&comp_size, sizeof(size_t), 1, tmp->fp) == 0 || comp_size == 0) {
356 return TMP_SAM_OK;
357 }
358
359 if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size)
360 tmp->offset = 0;
361
362 tmp->ring_index = tmp->ring_buffer + tmp->offset;
363
364 if (fread(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) > comp_size) {
365 tmp_print_error(tmp, "[tmp_file] Error: error reading compressed data.\n");
366 return TMP_SAM_FILE_ERROR;
367 }
368
369 tmp->output_size = LZ4_decompress_safe_continue(tmp->dstream, tmp->comp_buffer,
370 (char *)tmp->ring_index, comp_size, tmp->max_data_size);
371
372 if (tmp->output_size == 0) {
373 tmp_print_error(tmp, "[tmp_file] Error: decompression failed.\n");
374 return TMP_SAM_LZ4_ERROR;
375 }
376
377 tmp->entry_number = 0;
378 tmp->read_size = 0;
379 }
380
381 tmp->ring_index = tmp->ring_buffer + tmp->offset;
382 memcpy(inbam, tmp->ring_index, sizeof(bam1_t));
383 inbam->data = data; // put the pointer to real bam data back
384
385 if ((unsigned int)inbam->l_data > tmp->data_size) {
386 uint8_t *tmp_data;
387 tmp->data_size = inbam->l_data; kroundup32(tmp->data_size);
388
389 if ((tmp_data = realloc(inbam->data, sizeof(uint8_t) * tmp->data_size)) == NULL) {
390 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate tmp bam data memory.\n");
391 return TMP_SAM_MEM_ERROR;
392 }
393
394 inbam->data = tmp_data;
395 }
396
397 inbam->m_data = tmp->data_size; // set to the actual data size
398
399 entry_size = sizeof(bam1_t);
400
401 memcpy(inbam->data, tmp->ring_index + entry_size, inbam->l_data);
402 entry_size += inbam->l_data;
403
404 tmp->offset += entry_size;
405 tmp->read_size += entry_size;
406 tmp->entry_number++;
407
408 if (tmp->read_size > tmp->output_size) {
409 tmp_print_error(tmp, "[tmp_file] Error: wrong size of data returned RS:%zu OS:%zu EN:%zu GS:%zu.\n",
410 tmp->read_size, tmp->output_size, tmp->entry_number, tmp->group_size);
411 return TMP_SAM_LZ4_ERROR;
412 }
413
414 if (tmp->read_size == tmp->output_size && tmp->entry_number != tmp->group_size) {
415 // hopefully the last entries in the read file
416 tmp->entry_number = tmp->group_size;
417 }
418
419 return entry_size;
420 }
421
422
423 /*
424 * Frees up memory, closes the file and deletes it.
425 * Returns 0 on success or EOF on failure.
426 */
427 int tmp_file_destroy(tmp_file_t *tmp) {
428 int ret = 0;
429
430 ret = fclose(tmp->fp);
431
432 LZ4_freeStreamDecode(tmp->dstream);
433 free(tmp->ring_buffer);
434 free(tmp->comp_buffer);
435 free(tmp->name);
436 free(tmp->dict);
437
438 return ret;
439 }