pax_global_header00006660000000000000000000000064126737704670014535gustar00rootroot0000000000000052 comment=72d5d497054a991abff89afa716852e57e8a6919 ffindex-0.9.9.7/000077500000000000000000000000001267377046700133445ustar00rootroot00000000000000ffindex-0.9.9.7/.hgignore000066400000000000000000000000371267377046700151470ustar00rootroot00000000000000.*\.o test_big bin lib include ffindex-0.9.9.7/LICENSE000066400000000000000000000527631267377046700143660ustar00rootroot00000000000000AUTHOR FFindex was designed and implemented by Andreas Hauser . Please add your name here if you distribute modified versions. This file must be distributed with any source or binary distribution including parts of this work, excempt ffutil.h and ffutil.c which are also available under MIT license. SHORT SUMMARY OF THE LICENSE FFindex is provided under the Create Commons license "Attribution-ShareAlike 3.0", which basically captures the spirit of the Gnu Public License (GPL). See: http://creativecommons.org/licenses/by-sa/3.0/ Basically you are free: * to Share — to copy, distribute and transmit the work * to Remix — to adapt the work Under the following conditions: * Attribution You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). * Share Alike If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. LICENSE THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions 1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. 2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. 3. "Creative Commons Compatible License" means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. 4. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. 5. "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 6. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. 7. "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. 8. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. 9. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 10. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. 11. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: 1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; 2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; 3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and, 4. to Distribute and Publicly Perform Adaptations. 5. For the avoidance of doubt: 1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; 2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, 3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. 2. You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. 3. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. 4. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination 1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. 2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous 1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. 3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. 5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. 6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. ffindex-0.9.9.7/Makefile000066400000000000000000000003001267377046700147750ustar00rootroot00000000000000all: $(MAKE) -C src $@ %: $(MAKE) -C src $@ release: git archive HEAD --prefix "ffindex-`cat VERSION`/" -o "ffindex-`cat VERSION`.tar.gz" relnotes: git log --pretty=format:" - %s%n%b" ffindex-0.9.9.7/README000066400000000000000000000060051267377046700142250ustar00rootroot00000000000000* Copyright FFindex was written by Andreas Hauser . Please add your name here if you distribute modified versions. FFindex is provided under the Create Commons license "Attribution-ShareAlike 3.0", which basically captures the spirit of the Gnu Public License (GPL). See: http://creativecommons.org/licenses/by-sa/3.0/ * Thanks Thanks to Laszlo Kajan for creating and maintaining Debian packages and many suggestions to improve the build and user experience. * Overview FFindex is a very simple index/database for huge amounts of small files. The files are stored concatenated in one big data file, seperated by '\0'. A second file contains a plain text index, giving name, offset and length of of the small files. The lookup is currently done with a binary search on an array made from the index file. * Installation $ cd src $ make $ make test If you have MPI and want to compile ffindex_apply_mpi: $ make HAVE_MPI=1 On OS X use for the first make line: $ make -f Makefile.osx # Please use a sensible value for INSTALL_DIR, e.g. /usr/local or /opt/ffindex # or $HOME/ffindex instead of "..". $ make install INSTALL_DIR=.. and with MPI: $ make install INSTALL_DIR=.. HAVE_MPI=1 * Usage Please note that before querying or unlinking entries a ffindex must be sorted, although you can add to it without. So either specify -s with ffindex_build or sorted later with ffindex_modify -s. Also the length of the entry names is restricted. See the usage output of the ffindex_build program. Setup environment: $ export PATH="$INSTALL_DIR/bin:$PATH" $ export LD_LIBRARY_PATH="$INSTALL_DIR/lib:$LD_LIBRARY_PATH" On OS X set DYLD_LIBRARY_PATH instead of LD_LIBRARY_PATH. Build index from files in test/data and test/data2. $ ffindex_build -s /tmp/test.data /tmp/test.ffindex test/data test/data2 Retrieve three entries: $ ffindex_get /tmp/test.data /tmp/test.ffindex a b foo Unlink (Remove reference from index) an entry: $ ffindex_modify -u /tmp/test.ffindex b Retrieve three entries, "b" should now be missing: $ ffindex_get /tmp/test.data /tmp/test.ffindex a b foo Convert a Fasta file to ffindex, entry names are incerental IDs starting from 1: $ ffindex_from_fasta -s fasta.ffdata fasta.ffindex NC_007779.ffn Get first entry by name: $ ffindex_get fasta.ffdata fasta.ffindex 1 Get first and third entry by entry index, this a little faster: $ ffindex_get fasta.ffdata fasta.ffindex -n 1 3 Count the characters including header in each entry: $ ffindex_apply fasta.ffdata fasta.ffindex wc -c Count the number of characters in each sequence, without the header: $ ffindex_apply fasta.ffdata fasta.ffindex perl -ne '$x += length unless(/^>/); END{print "$x\n"}' Parallel version for counting the characters including header in each entry: $ mpirun -np 4 ffindex_apply_mpi fasta.ffdata fasta.ffindex -- wc -c Parallel version for counting the characters including header in each entry and saving the output to a new ffindex: $ mpirun -np 4 ffindex_apply_mpi fasta.ffdata fasta.ffindex -i out-wc.ffindex -d out-wc.ffdata -- wc -c ffindex-0.9.9.7/RELEASE_NOTES000066400000000000000000000171741267377046700153310ustar00rootroot000000000000000.9.9.6 - Fix OS X builds and integrate Makefile.osx - Drop OpenMP from compiler flags - Add ffindex_posix_search.o to make clean - Avoid non-standard nested function, even so it's the cleanest solution, since the posix twalk interface is broken. Factor out functions using posix tree. Use TLS variables to stay threadsafe. - Fix ffnchomp check 0.9.9.5 - Make use of our parse_long for higher startup performance. - Add RELEASE_NOTES - Roll our own parse_ulong instead strtol for speed reasons. - Fix usage formatting - Make more clear that tree is already sorted ffindex_modify.c - Remove unused code in ffindex_modify.c 0.9.9.4 and before - ffindex_apply is now ffindex_apply_mpi without MPI - Add src/ffindex_apply_mpi_spawn.c, using spawn istead of fork & exec - Fix example - Add collect_data - Add Markus Meier - perl5/FFindex.pm: Add copyright. Fix entry reading. Add get_entry* methods. - Add perl5/test.pl - Add perl5 - Add each_data - Return Qnil if not found - Add method_ffindex_get_data_by_name - Add first ruby wrapper. - Add ffindex_db - Add nginx server module - Fix memory leak on error - ffindex_get: Add -f FILE argument to let the keys to retrieve be specified by a file. - Add ffindex_from_tsv to Makefile - Add ffindex_from_tsv - Update RPM spec - bump version - Update copyrigths and version. - Set higher limits. Update version. - Handle the case where filenames are actually longer than FFINDEX_MAX_ENTRY_NAME_LENTH. This was also security vulnerability. - fix fprintf - Add log_file option to ffindex_apply_mpi and rework error handling. - fix getopt - merge - Add ffindex_optimize - bumb version - Add -q for quiet - merge - Better usage info. - Make sort work independant from unlink. - Add ffindex_insert_ffindex(). - Make use of ffindex_index_open in ffindex_from_fasta - Add ffindex_index_open() and use it in ffindex_build. - Add -D_GNU_SOURCE=1, probably better here than in source. - Bump version - Export FFINDEX_ENTRY_NAME and unlink() temporary ffindexes in ffindex_apply_mpi. - Print entry and return status of ffindex_apply_mpi to stderr. This allows for further processing based on return status. - Add MPI to README - Don't assume string data, make binary data work too. - Add get_entry_by_name as alias for bsearch - Fix build for some compilers - Ma - Another fix for noncapture and cleanup - Fix no capture mode - First beta of apply_mpi output catching to another ffindex - wip - wip - apply_mpi now works with capturing output to another ffindex, but I/O can block. - Better error message - More clever root Makefile contributed by Laszlo. - Add thanks - Reduce FFINDEX_MAX_ENTRY_NAME_LENTH from 56 to 32 so that by default the malloced space for the index is <2GB. Suggested by Laszlo. - Add message to indicated number of failed bytes. - Bump version to 0.980 - Add ffindex_unpack to install and spec and bump version to 0.9.8 - More improvements to usage info for ffindex_build. - Add better usage info to ffindex_build, proposed by Johannes. - remove modifies -t from usage - merge - merge - wip ffindex_apply_mpi.c - Add ffindex_unpack to unpack all entries/files from an ffindex - Bump version to 0.97 - Check index out of bounds for ffindex_get_entry_by_index - Add some more usage examples to README - Add option -n to ffindex_get to use entry index instead of entry name - Add ifndef wrapper as suggested by Markus. - Add return check for 1 byte fwrite. - Don't access index before NULL check. Reporter: Laszlo Karjan. - Bump version - Diy OSX build - Bump version to 0.9.6 - Fix bug data vs. filedata. - Use optimized interface - Fix comment - Conditionalize MPI - Bump version to 0.9.5. - Refactor to handle entry lookup outside of ffindex_apply. - Handling of left over. - Add first implementation of ffindex_apply_mpi.c. - Handle EPIPE. - Add a first version of ffindex_apply, that executes a program for each entry in the ffindex. - Reflect ffindex_fopen rename. - Rename ffindex_fopen to ffindex_fopen_by_name. Add ffindex_fopen_by_entry and ffindex_get_data_by_entry. - Add hgignore - Clean also .o - Add it also to osx - Add ffindex_from_fasta to clean - Install ffindex_from_fasta - Improve error handling, especially with empty Index file. - Add ffindex_get_data_by_index. And rename other ffindex_get functions to be more uniform. - Use ffindex_get() instead of ffindex_fopen() in ffindex_get program. - Add ffindex_get to get entry as string. - Raise FFINDEX_MAX_INDEX_ENTRIES_DEFAULT from 6 million to 40 million - Make sure ">" is after newline. Better code. - Add -O2. - Complete implementation of ffindex_from_fasta. - Bump version to 0.94 - Sart implementation of ffindex_from_fasta - Add ffindex_insert_memory(). - Improve README - Bump version to 0.9.3 - merge - Better make chdir - Make usage of tree default in ffindex_modify. - Make OSX compile again. - basename() is in libgen.h on BSD. - Clean ffutil.o too. - Add deinstall target - Fix spec libdir - Fix libdir creation - bump version - Fix spec - Respect lib64 - nicer - Add a SPEC file for building an RPM package. - Rework build a little. Build a static library libffindex.a too. - Add top-level Makefile. - Fix remaining printf. - Fix size_t printfs. Use length modifier z. - Bump version. - Move textfiles to top. - Add inclusion clause to LICENSE. - Add advertisement. - Fix fclose with ffindex_add_filestream. - ffindex_build now can incorporate (merge) other ffindexes. - Add -t to ffindex_modify, which tells ffindex to speedup unlinking using a tree. - unlink: walk to lists implmentation - Fix message - Fix unlink. - Fix OS X build - Fix test - Remove more strnlen. Introduce ffnchomp in ffutil that was renamed from fferror. - Use strlen instead of strnlen. Sae case and BSD/OS X do not always have strnlen. - fix includes - little things - better documentation - Add possibility to add single files not only directories. TODO: Decide what should be the name in the index, that is should the whole path be part of the entry name. - Make INSTALL_DIR usable. - Add - Add ffindex_modify that oprates on an existing index. E.g. for unlinking. - Guard against overwriting existing index or data file - Add ffindex_unlink - better tests - Better error handling - comment - Better error handling - nicer error handling - nicer error handling - spell - Better error handling and messages, especially if malloc failes. - ffindex_index_parse now takes a second argument specifying the maximum number of entries. A default is used if 0 is specified. - Add -v for version. Add -f for list_files. - Small code improvement. - Add fmemopen for Mac OS X. - fix warnings - Add install target. - - Add license. - Add append and sort. - Faster parsing. ffindex_mmap interface changed. - Convert index to struct. Implement bsearch. - Rest of data type conversion. Ffindex_build now takes offset return value, which is needed e.g. for multiple directory indexing. - Change *data to from type void* to char* to avoid problems with pointer arithmetics. - Add test for multiple directory indexing - Add second test dir. - Make Makefile more robust. - Add more functions to header. - ffindex_get now support multiple entry retrieves. - Remoove debug extra newlines from ffindex_get output. - Remove debug print. - Add clean. - Add a program to retrieve data from index. - Fix parameter mixup. Add length to index. - Add test - ffindex_fopen - wip - primitive ffindex_get_offset - use read - init ffindex-0.9.9.7/VERSION000066400000000000000000000000101267377046700144030ustar00rootroot000000000000000.9.9.7 ffindex-0.9.9.7/perl5/000077500000000000000000000000001267377046700143735ustar00rootroot00000000000000ffindex-0.9.9.7/perl5/FFindex.pm000066400000000000000000000035651267377046700162650ustar00rootroot00000000000000# # A simple perl native Module interfacing FFindex # written by Andreas Hauser shift, ffindex_filename => shift, mode => shift, ffdata => undef, ffdata_file => undef, ffindex_file => undef, ffindex => [], ffindex_hash => {}, n_entries => [] }; bless $self, $class; #new Sys::Mmap $self->{ffdata}, 0, $self->{ffdata_filename} or die $!; open($self->{ffdata_file}, "<", $self->{ffdata_filename}); mmap($self->{ffdata}, 0, PROT_READ, MAP_SHARED, $self->{ffdata_file}) or die $!; open($self->{ffindex_file}, "<", $self->{ffindex_filename}); my $fh = $self->{ffindex_file}; my $i = 0; while( my $line = <$fh>) { chomp $line; my ($name, $offset, $len) = split(/\t/, $line); $self->{ffindex}[$i] = [$name, $offset, $len]; $self->{ffindex_hash}{$name} = $self->{ffindex}[$i]; $i++; } $self->{n_entries} = $i; return $self; } sub get_num_entries() { my( $self ) = @_; return $self->{n_entries}; } sub get_entry_by_index() { my( $self, $index ) = @_; return $self->{ffindex}[$index]; } sub get_entry_by_name() { my( $self, $qname ) = @_; return $self->{ffindex_hash}{$qname}; } sub get_data_by_index() { my( $self, $index ) = @_; my ($name, $offset, $len) = @{$self->{ffindex}[$index]}; return substr($self->{ffdata}, $offset, $len - 1); } sub get_data_by_name() { my( $self, $qname ) = @_; my ($name, $offset, $len) = @{$self->{ffindex_hash}{$qname}}; return substr($self->{ffdata}, $offset, $len - 1); } sub DESTROY { close($self->{ffdata_file}); close($self->{ffindex_file}); $self->{ffindex} = undef; } 1; ffindex-0.9.9.7/perl5/Makefile000066400000000000000000000000241267377046700160270ustar00rootroot00000000000000test: perl test.pl ffindex-0.9.9.7/perl5/test.pl000077500000000000000000000010641267377046700157130ustar00rootroot00000000000000#!/usr/bin/env perl use strict; use warnings; use FFindex; my $ffindex_db = new FFindex("../src/data.ffdata", "../src/data.ffindex"); print "by index:\n"; my $max = $ffindex_db->get_num_entries(); for(my $i = 0; $i < $max; $i++) { my @entry = @{$ffindex_db->get_entry_by_index($i)}; print join("\t", @entry), "\n"; print $ffindex_db->get_data_by_index($i); } print "by name:\n"; foreach my $name ("a","b","c") { my @entry = @{$ffindex_db->get_entry_by_name($name)}; print join("\t", @entry), "\n"; print $ffindex_db->get_data_by_name($name); } ffindex-0.9.9.7/python/000077500000000000000000000000001267377046700146655ustar00rootroot00000000000000ffindex-0.9.9.7/python/ffindex.py000066400000000000000000000041701267377046700166640ustar00rootroot00000000000000#!/usr/bin/env python ''' Created on Apr 30, 2014 @author: meiermark ''' import sys import mmap from collections import namedtuple FFindexEntry = namedtuple("FFindexEntry", "name, offset, length") def read_index(ffindex_filename): entries = [] fh = open(ffindex_filename) for line in fh: tokens = line.split("\t") entries.append(FFindexEntry(tokens[0], int(tokens[1]), int(tokens[2]))) fh.close() return entries def read_data(ffdata_filename): fh = open(ffdata_filename, "r+b") data = mmap.mmap(fh.fileno(), 0) fh.close() return data def get_entry_by_name(name, index): #TODO: bsearch for entry in index: if(name == entry.name): return entry return None def read_entry_lines(entry, data): lines = data[entry.offset:entry.offset + entry.length - 1].decode("utf-8").split("\n") return lines def read_entry_data(entry, data): return data[entry.offset:entry.offset + entry.length - 1] def write_entry(entries, data_fh, entry_name, offset, data): data_fh.write(data[:-1]) data_fh.write(bytearray(1)) entry = FFindexEntry(entry_name, offset, len(data)) entries.append(entry) return offset + len(data) def write_entry_with_file(entries, data_fh, entry_name, offset, file_name): with open(file_name, "rb") as fh: data = bytearray(fh.read()) return write_entry(entries, data_fh, entry_name, offset, data) def finish_db(entries, ffindex_filename, data_fh): data_fh.close() write_entries_to_db(entries, ffindex_filename) def write_entries_to_db(entries, ffindex_filename): sorted(entries, key=lambda x: x.name) index_fh = open(ffindex_filename, "w") for entry in entries: index_fh.write("{name:.64}\t{offset}\t{length}\n".format(name=entry.name, offset=entry.offset, length=entry.length)) index_fh.close() def write_entry_to_file(entry, data, file): lines = read_lines(entry, data) fh = open(file, "w") for line in lines: fh.write(line+"\n") fh.close() ffindex-0.9.9.7/rpm/000077500000000000000000000000001267377046700141425ustar00rootroot00000000000000ffindex-0.9.9.7/rpm/ffindex.spec000066400000000000000000000020671267377046700164460ustar00rootroot00000000000000Summary: FFindex is a very simple index/database for huge amounts of small files. Name: ffindex Version: 0.9.9.7 Release: 1 License: Create Commons license "Attribution-ShareAlike 3.0" Group: Utilities/System Source: http://www.splashground.de/~andy/programs/FFindex/ffindex-0.9.9.7.tar.gz %description FFindex is a very simple index/database for huge amounts of small files. The files are stored concatenated in one big data file, seperated by '\0'. A second file contains a plain text index, giving name, offset and length of of the small files. The lookup is currently done with a binary search on an array made from the index file. %prep %setup %build make %install make install INSTALL_DIR=%{buildroot}%{_prefix} %files %doc README LICENSE /usr/bin/ffindex_build /usr/bin/ffindex_get /usr/bin/ffindex_modify /usr/bin/ffindex_from_fasta /usr/bin/ffindex_from_tsv /usr/bin/ffindex_apply /usr/bin/ffindex_unpack /usr/include/ffindex.h /usr/include/ffutil.h /usr/include/ffindex_posix_search.h %{_libdir}/libffindex.a %{_libdir}/libffindex.so %{_libdir}/libffindex.so.0.1 ffindex-0.9.9.7/ruby18/000077500000000000000000000000001267377046700144765ustar00rootroot00000000000000ffindex-0.9.9.7/ruby18/FFindex.c000066400000000000000000000075441267377046700161770ustar00rootroot00000000000000#include "../src/ffindex.h" #include "ruby.h" VALUE FFindex = Qnil; void Init_ffindex(); VALUE method_ffindex_initialize(VALUE self, VALUE ffdata_filename, VALUE ffindex_filename); static VALUE ffindex_db_allocate(VALUE klass); static void ffindex_db_deallocate(void * ffindex_db); VALUE method_ffindex_get_data_by_index(VALUE self, VALUE key); VALUE method_ffindex_get_data_by_name(VALUE self, VALUE key); VALUE method_ffindex_each_data(VALUE self, VALUE key); VALUE method_ffindex_collect_data(VALUE self, VALUE key); void Init_ffindex() { FFindex = rb_define_class("FFindex", rb_cObject); rb_define_alloc_func(FFindex, ffindex_db_allocate); rb_define_method(FFindex, "initialize", method_ffindex_initialize, 2); rb_define_method(FFindex, "get_data_by_index", method_ffindex_get_data_by_index, 1); rb_define_method(FFindex, "get_data_by_name", method_ffindex_get_data_by_name, 1); rb_define_method(FFindex, "each_data", method_ffindex_each_data, 0); rb_define_method(FFindex, "collect_data", method_ffindex_collect_data, 0); } static void ffindex_db_deallocate(void * ffindex_db) { free((ffindex_db_t *)ffindex_db); } static VALUE ffindex_db_allocate(VALUE klass) { ffindex_db_t * ffindex_db = (ffindex_db_t *)calloc(1, sizeof(ffindex_db_t)); return Data_Wrap_Struct(klass, NULL, ffindex_db_deallocate, ffindex_db); } VALUE method_ffindex_initialize(VALUE self, VALUE ffdata_filename, VALUE ffindex_filename) { Check_Type(ffdata_filename, T_STRING); Check_Type(ffindex_filename, T_STRING); ffindex_db_t * ffindex_db; Data_Get_Struct(self, ffindex_db_t, ffindex_db); ffindex_db->ffdata_filename = calloc(RSTRING_LEN(ffdata_filename) + 1, sizeof(char)); memcpy(ffindex_db->ffdata_filename, StringValuePtr(ffdata_filename), RSTRING_LEN(ffdata_filename)); ffindex_db->ffindex_filename = calloc(RSTRING_LEN(ffindex_filename) + 1, sizeof(char)); memcpy(ffindex_db->ffindex_filename, StringValuePtr(ffindex_filename), RSTRING_LEN(ffindex_filename)); ffindex_db->mode[0] = 'r'; ffindex_db = ffindex_index_db_open(ffindex_db); return self; } VALUE method_ffindex_get_data_by_index(VALUE self, VALUE key) { ffindex_db_t * ffindex_db; Data_Get_Struct(self, ffindex_db_t, ffindex_db); size_t index = FIX2INT(key); ffindex_entry_t * entry = ffindex_get_entry_by_index(ffindex_db->ffindex, index); if(entry) { char * data = ffindex_get_data_by_entry(ffindex_db->ffdata, entry); return rb_str_new2(data); } else return Qnil; } VALUE method_ffindex_get_data_by_name(VALUE self, VALUE key) { Check_Type(key, T_STRING); char * name = calloc(RSTRING_LEN(key) + 1, sizeof(char)); memcpy(name, StringValuePtr(key), RSTRING_LEN(key)); ffindex_db_t * ffindex_db; Data_Get_Struct(self, ffindex_db_t, ffindex_db); ffindex_entry_t * entry = ffindex_get_entry_by_name(ffindex_db->ffindex, name); if(entry) { char * data = ffindex_get_data_by_entry(ffindex_db->ffdata, entry); return rb_str_new2(data); } else return Qnil; } VALUE method_ffindex_each_data(VALUE self, VALUE key) { if(!rb_block_given_p()) rb_raise(rb_eArgError, "a block is required"); ffindex_db_t * ffindex_db; Data_Get_Struct(self, ffindex_db_t, ffindex_db); size_t num_entries = ffindex_db->ffindex->n_entries; size_t i; for(i = 0; i < num_entries; i++) { rb_yield(rb_funcall(self, rb_intern("get_data_by_index"), 1, INT2FIX(i))); } return INT2FIX(i); } VALUE method_ffindex_collect_data(VALUE self, VALUE key) { if(!rb_block_given_p()) rb_raise(rb_eArgError, "a block is required"); ffindex_db_t * ffindex_db; Data_Get_Struct(self, ffindex_db_t, ffindex_db); size_t num_entries = ffindex_db->ffindex->n_entries; size_t i; VALUE arr = rb_ary_new(); for(i = 0; i < num_entries; i++) { rb_ary_push(arr, rb_yield(rb_funcall(self, rb_intern("get_data_by_index"), 1, INT2FIX(i)))); } return arr; } ffindex-0.9.9.7/ruby18/extconf.rb000066400000000000000000000004701267377046700164720ustar00rootroot00000000000000# Loads mkmf which is used to make makefiles for Ruby extensions require 'mkmf' LIB_DIRS = ["../src"] # Give it a name extension_name = 'ffindex' # The destination dir_config(extension_name, "../src", "../src") find_library('ffindex', 'ffindex_index_db_open') # Do the work create_makefile(extension_name) ffindex-0.9.9.7/src/000077500000000000000000000000001267377046700141335ustar00rootroot00000000000000ffindex-0.9.9.7/src/Makefile000066400000000000000000000130421267377046700155730ustar00rootroot00000000000000INSTALL_DIR?=.. libdir=`([ -d /usr/lib64 ] && echo lib64) || echo lib` LANG=C #CC=musl-gcc #OMPI_CC=musl-gcc #CC=gcc #CC=icc #CC=clang CFLAGS+=-std=c99 -O2 -g -fPIC -Wall -pedantic -D_GNU_SOURCE=1 -I. LDFLAGS=-lffindex -L. OS:= $(shell uname) FFINDEX_LIBS=libffindex.so libffindex.so.0.1 libffindex.a FFINDEX_HEADERS=ffindex.h ffindex_posix_search.h ffutil.h FFINDEX_OBJECTS=$(FFINDEX_HEADERS:.h=.o) FFINDEX_PROGRAMS=ffindex_apply ffindex_from_fasta ffindex_get ffindex_build ffindex_modify ffindex_unpack ffindex_from_tsv ifdef HAVE_MPI FFINDEX_PROGRAMS+=ffindex_apply_mpi endif all: $(FFINDEX_LIBS) $(FFINDEX_PROGRAMS) # for Darwin only ext/fmemopen.o: ext/fmemopen.c make -C ext ffindex.o: ffindex.c $(FFINDEX_HEADERS) libffindex.a: $(FFINDEX_OBJECTS) ar rcs libffindex.a $^ ifeq ($(OS), Darwin) libffindex.so.0.1: $(FFINDEX_OBJECTS) ext/fmemopen.o $(CC) -shared -o libffindex.so.0.1 $^ else ifdef FFINDEX_STATIC STATIC=-static endif libffindex.so.0.1: $(FFINDEX_OBJECTS) $(CC) -Wl,-z,defs -Wl,-soname,libffindex.so.0.1 -shared -o libffindex.so.0.1 $^ endif libffindex.so: libffindex.so.0.1 ln -sf libffindex.so.0.1 libffindex.so ffindex_apply.o: ffindex_apply_mpi.c $(FFINDEX_LIBS) $(CC) $(CFLAGS) -c ffindex_apply_mpi.c -o $@ ffindex_apply: ffindex_apply.o $(FFINDEX_LIBS) $(CC) $(CFLAGS) -o $@ ffindex_apply.o $(LDFLAGS) $(STATIC) ffindex_apply_mpi: ffindex_apply_mpi.o $(FFINDEX_LIBS) mpicc $(CFLAGS) -DHAVE_MPI -o $@ ffindex_apply_mpi.o $(LDFLAGS) ffindex_apply_mpi.o: ffindex_apply_mpi.c $(FFINDEX_HEADERS) mpicc $(CFLAGS) -DHAVE_MPI -c ffindex_apply_mpi.c -o $@ ffindex_apply_mpi_spawn: ffindex_apply_mpi_spawn.o $(FFINDEX_LIBS) mpicc $(CFLAGS) -o $@ ffindex_apply_mpi_spawn.o $(LDFLAGS) ffindex_apply_mpi_spawn.o: ffindex_apply_mpi_spawn.o $(FFINDEX_HEADERS) mpicc $(CFLAGS) -c ffindex_apply_mpi_spawn.c -o $@ ffindex_from_fasta: ffindex_from_fasta.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_from_fasta.o $(LDFLAGS) $(STATIC) ffindex_from_tsv: ffindex_from_tsv.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_from_tsv.o $(LDFLAGS) $(STATIC) ffindex_get: ffindex_get.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_get.o $(LDFLAGS) $(STATIC) ffindex_build: ffindex_build.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_build.o $(LDFLAGS) $(STATIC) ffindex_modify: ffindex_modify.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_modify.o $(LDFLAGS) $(STATIC) ffindex_unpack: ffindex_unpack.o $(FFINDEX_LIBS) $(CC) -o $@ ffindex_unpack.o $(LDFLAGS) $(STATIC) test: rm -f /tmp/test.data /tmp/test.ffindex LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_build -s /tmp/test.data /tmp/test.ffindex ../test/data ../test/data2 LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_get /tmp/test.data /tmp/test.ffindex a b foo | tee /tmp/test.out LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_modify -u /tmp/test.ffindex b LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_get /tmp/test.data /tmp/test.ffindex a b foo | tee /tmp/test-unlink.out LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_build -a -s /tmp/test.data /tmp/test.ffindex ../test/testfile @echo ======== compare results ========= diff /tmp/test.out test.should diff /tmp/test-unlink.out test-unlink.should @echo ======== error handling ========== @echo LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_get /tmp/test.data /tmp/test.ffindex nonexistquery b foo || echo LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_get /nonexist/data /tmp/test.ffindex a foo || echo LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" ./ffindex_get /tmp/test.data /nonexist/index a foo || echo time: LD_LIBRARY_PATH=".:$(LD_LIBRARY_PATH)" zsh -c "time ./ffindex_get ../test_big/nr20_11Jan10_a3m_db ../test_big/nr20_11Jan10_a3m_db.ffindex BABBAMIBA.a3m KARDUZEBA.a3m HARPAQIBA.a3m WOQQATEBA.a3m BEBRAQIBA.a3m GIRSAKEBA.a3m NAQTIFIBA.a3m BIWCIQABA.a3m > /dev/null" clean: rm -f $(FFINDEX_PROGRAMS) $(FFINDEX_OBJECTS) $(FFINDEX_LIBS) \ libffindex.so libffindex.so.0.1 libffindex.a \ ffindex_build.o ffindex_get.o ffindex_modify.o ffindex_from_fasta.o ffindex_apply_mpi.o \ ffindex_apply.o ffindex_from_tsv.o ffindex_unpack.o ffindex_posix_search.o ffindex_apply_mpi_spawn.o install: mkdir -p $(INSTALL_DIR)/bin mkdir -p $(INSTALL_DIR)/$(libdir) mkdir -p $(INSTALL_DIR)/include install ffindex_get $(INSTALL_DIR)/bin/ffindex_get install ffindex_build $(INSTALL_DIR)/bin/ffindex_build install ffindex_modify $(INSTALL_DIR)/bin/ffindex_modify install ffindex_from_fasta $(INSTALL_DIR)/bin/ffindex_from_fasta install ffindex_from_tsv $(INSTALL_DIR)/bin/ffindex_from_tsv install ffindex_apply $(INSTALL_DIR)/bin/ffindex_apply install ffindex_unpack $(INSTALL_DIR)/bin/ffindex_unpack install libffindex.so.0.1 $(INSTALL_DIR)/$(libdir)/libffindex.so.0.1 install libffindex.a $(INSTALL_DIR)/$(libdir)/libffindex.a ln -sf libffindex.so.0.1 $(INSTALL_DIR)/$(libdir)/libffindex.so install ffindex.h $(INSTALL_DIR)/include/ffindex.h install ffutil.h $(INSTALL_DIR)/include/ffutil.h install ffindex_posix_search.h $(INSTALL_DIR)/include/ffindex_posix_search.h ifdef HAVE_MPI install ffindex_apply_mpi $(INSTALL_DIR)/bin/ffindex_apply_mpi endif deinstall: rm -f $(INSTALL_DIR)/bin/ffindex_get $(INSTALL_DIR)/bin/ffindex_build $(INSTALL_DIR)/bin/ffindex_modify \ $(INSTALL_DIR)/$(libdir)/libffindex.so.0.1 $(INSTALL_DIR)/$(libdir)/libffindex.a \ $(INSTALL_DIR)/$(libdir)/libffindex.so $(INSTALL_DIR)/include/ffindex.h $(INSTALL_DIR)/include/ffutil.h\ $(INSTALL_DIR)/include/ffindex_posix_search.h $(INSTALL_DIR)/bin/ffindex_from_fasta $(INSTALL_DIR)/bin/ffindex_from_tsv rmdir $(INSTALL_DIR)/bin || true rmdir $(INSTALL_DIR)/$(libdir) || true rmdir $(INSTALL_DIR)/include || true ffindex-0.9.9.7/src/ext/000077500000000000000000000000001267377046700147335ustar00rootroot00000000000000ffindex-0.9.9.7/src/ext/Makefile.osx000066400000000000000000000002311267377046700171770ustar00rootroot00000000000000INSTALL_DIR=.. LANG=C CFLAGS+=-std=c99 -O3 -g -fPIC -Wall #LDFLAGS+=-Wl,-z,defs #-Wl,--version-script=libffindex.map fmemopen.o: fmemopen.c fmemopen.h ffindex-0.9.9.7/src/ext/fmemopen.c000066400000000000000000000062131267377046700167070ustar00rootroot00000000000000/** * Copyright (c) 2009 Open Information Security Foundation * * \author Pablo Rincon Crespo * Based on FMem.c of Alexandre Flori (2008/10/17 AF) */ #define _GNU_SOURCE #include #include #include #include "fmemopen.h" #ifdef OS_DARWIN #define USE_FMEM_WRAPPER 1 #endif #ifdef OS_FREEBSD #define USE_FMEM_WRAPPER 1 #endif #ifdef USE_FMEM_WRAPPER /** * \brief Seek the mem file from offset and whence * \param handler pointer to the memfile * \param osffset number of bytes to move from whence * \param whence SEEK_SET, SEEK_CUR, SEEK_END * \retval pos the position by the last operation, -1 if sizes are out of bounds */ static fpos_t SeekFn(void *handler, fpos_t offset, int whence) { size_t pos = 0; fmem_t *mem = handler; switch (whence) { case SEEK_SET: if (offset > 0 && (size_t)offset <= mem->size) return mem->pos = offset; break; case SEEK_CUR: if (mem->pos + offset <= mem->size) return mem->pos = offset; break; case SEEK_END: /* must be negative */ if (mem->size + offset <= mem->size) return pos = mem->size + offset; break; } return -1; } /** * \brief Read from the buffer looking for the available memory limits * \param handler pointer to the memfile * \param buf buffer to read from the handler * \param number of bytes to read * \retval count , the number of bytes read */ static int ReadFn(void *handler, char *buf, int size) { size_t count = 0; fmem_t *mem = handler; size_t available = mem->size - mem->pos; if (size < 0) return - 1; if ((size_t)size > available) size = available; while (count < (size_t)size) buf[count++] = mem->buffer[mem->pos++]; return count; } /** * \brief Write into the buffer looking for the available memory limits * \param handler pointer to the memfile * \param buf buffer to write in the handler * \param number of bytes to write * \retval count , the number of bytes writen */ static int WriteFn(void *handler, const char *buf, int size) { size_t count = 0; fmem_t *mem = handler; size_t available = mem->size - mem->pos; if (size < 0) return - 1; if ((size_t)size > available) size = available; while (count < (size_t)size) mem->buffer[mem->pos++] = buf[count++]; return count; } /** * \brief close the mem file handler * \param handler pointer to the memfile * \retval 0 on succesful */ static int CloseFn(void *handler) { free (handler); return 0; } /** * \brief portable version of SCFmemopen for OS X / BSD built on top of funopen() * \param buffer that holds the file content * \param size of the file buffer * \param mode mode of the file to open * \retval pointer to the file; NULL if something is wrong */ FILE *fmemopen(void *buf, size_t size, const char *mode) { fmem_t *mem = (fmem_t *) malloc(sizeof(fmem_t)); memset(mem, 0, sizeof(fmem_t)); mem->size = size, mem->buffer = buf; return funopen(mem, ReadFn, WriteFn, SeekFn, CloseFn); } #endif ffindex-0.9.9.7/src/ext/fmemopen.h000066400000000000000000000007611267377046700167160ustar00rootroot00000000000000#ifndef __FMEMOPEN_H__ #define __FMEMOPEN_H__ #include #include #include /* Include this file only for OSX / BSD compilations */ #ifdef OS_DARWIN #define USE_FMEM_WRAPPER 1 #endif #ifdef OS_FREEBSD #define USE_FMEM_WRAPPER 1 #endif #define USE_FMEM_WRAPPER 1 #ifdef USE_FMEM_WRAPPER struct fmem { size_t pos; size_t size; char *buffer; }; typedef struct fmem fmem_t; FILE *fmemopen(void *, size_t, const char *); #endif #endif /* __FMEMOPEN_H__ */ ffindex-0.9.9.7/src/ext/fmemopen.o000066400000000000000000000145241267377046700167270ustar00rootroot00000000000000 808__text__TEXT0h__debug_frame__DWARF__debug_info__DWARF __debug_abbrev__DWARF' nW__debug_aranges__DWARF 0(__debug_macinfo__DWARF __debug_line__DWARF 0__debug_loc__DWARF `__debug_pubnames__DWARF+[__debug_pubtypes__DWARFJz__debug_inlined__DWARF __debug_str__DWARFM __debug_ranges__DWARF(X__eh_frame__TEXT(XH h P  UHtWt2tHHfH~H;wwH7fHDfDHGHH9rHHHH;GwH7UHLGHx=LH)LcL9r11E1u$HHGA0IHAHM9rDÉLcfDUHLGHx=LH)LcL9r11E1u$HHWA0 HAHIM9rDÉLcfDUHH]LeHIHHHHXL`LH HH5H$Ld$UH1x $q $Z $Z 4@]  $  GNU C 4.2.1 (Apple Inc. build 5664)fmemopen.c/Users/admin.hauser/ffindex/src/extsigned charunsigned charshort intshort unsigned intintunsigned int__int64_t.long long intlong long unsigned intlong intchar__darwin_size_tZ9long unsigned int__darwin_off_tnsize_tP"fpos_tWP__sbufb_basec#_sized#__sFILE_p#_r#_w# _flags#_file#_bf#_lbfsize#(_cookieN#0_close#8_read>#@_seek^#H_write#P_ub#X_extra#h_ur#p_ubuf#t_nbuf#w_lb#x_blksize#_offsett#  N 8 N 8  t^ N t D ~ N ~  d __sFILEX  FILEfmemposf#sizef#buffer8#fmem_tF tq NUoffset tLwhence Qpos!fmem">>NUbuf>8Tsize>Qcount?fmem@Af6U:({UNUbufU~TsizeUtcountVfmemWXf"ON__destNN__valN__lenNfv@bufvNbsizevfmodev~memw>jRjN= ]__CFConstantStringClassReferenceR%  $ > : ; I$ >   : ;  : ; I8  I ' I I &I < I!I/ .: ; ' I@ : ; I : ; I: ; I 4: ; I4: ; I4: ; I.: ; ' I  : ; I.? : ; ' I@ : ; I!4I? 4 < , /usr/include/i386/usr/include/sys/usr/include/usr/include/securefmemopen.c_types.h_types.hstdio.hfmemopen.h_string.h N yqt Xzu<. * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include #include #include #include #include #include "ext/fmemopen.h" /* For OS not yet implementing this new standard function */ #include "ffutil.h" #include "ffindex.h" /* XXX Use page size? */ #define FFINDEX_BUFFER_SIZE 4096 char* ffindex_copyright_text = FFINDEX_COPYRIGHT; char* ffindex_copyright() { return ffindex_copyright_text; } ffindex_db_t * ffindex_index_db_open(ffindex_db_t * ffindex_db) { int ret = ffindex_index_open(ffindex_db->ffdata_filename, ffindex_db->ffindex_filename, ffindex_db->mode, &ffindex_db->ffdata_file, &ffindex_db->ffindex_file, &ffindex_db->offset); if(ret) return NULL; ffindex_db->ffindex = ffindex_index_parse(ffindex_db->ffindex_file, ffindex_db->num_max_entries); if(!ffindex_db->ffindex) { fferror_print(__FILE__, __LINE__, __func__, ffindex_db->ffindex_filename); return NULL; } ffindex_db->ffdata = ffindex_mmap_data(ffindex_db->ffdata_file, &ffindex_db->ffdata_size); if(ffindex_db->ffdata_size == 0) warn("Problem mapping index file. Is it empty or is another process reading it?"); if(ffindex_db->ffdata == MAP_FAILED) { fferror_print(__FILE__, __LINE__, __func__, ffindex_db->ffdata_filename); return NULL; } ffindex_db->ffindex->type = SORTED_ARRAY; /* XXX Assume a sorted file for now */ return ffindex_db; } int ffindex_index_db_close(ffindex_db_t* ffindex_db) { int ret = EXIT_SUCCESS; ffindex_index_close(ffindex_db->ffindex); ret = munmap(ffindex_db->ffdata, ffindex_db->ffdata_size); if(ret) { fferror_print(__FILE__, __LINE__, __func__, "munmap"); return ret; } free(ffindex_db); return EXIT_SUCCESS; } int ffindex_index_close(ffindex_index_t* ffindex) { size_t nbytes = sizeof(ffindex_index_t) + (sizeof(ffindex_entry_t) * ffindex->num_max_entries); int ret = munmap(ffindex, nbytes); if(ret) { fferror_print(__FILE__, __LINE__, __func__, "munmap"); return ret; } return EXIT_SUCCESS; } /* return *out_data_file, *out_index_file, out_offset. Setting to a given offset could be supported with a special mode. */ int ffindex_index_open(char *data_filename, char *index_filename, char* mode, FILE **out_data_file, FILE **out_index_file, size_t *out_offset) { /* open index and data file, seek to end if needed */ if(mode[0] == 'a') { *out_data_file = fopen(data_filename, "a"); if(*out_data_file == NULL) { perror(data_filename); return EXIT_FAILURE; } *out_index_file = fopen(index_filename, "a+"); if(*out_index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } struct stat sb; fstat(fileno(*out_index_file), &sb); fseek(*out_index_file, sb.st_size, SEEK_SET); fstat(fileno(*out_data_file), &sb); fseek(*out_data_file, sb.st_size, SEEK_SET); *out_offset = sb.st_size; } else if(mode[0] == 'r') { *out_data_file = fopen(data_filename, "r"); if(*out_data_file == NULL) { perror(data_filename); return EXIT_FAILURE; } *out_index_file = fopen(index_filename, "r"); if(*out_index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } *out_offset = 0; } else { struct stat st; if(stat(data_filename, &st) == 0) { errno = EEXIST; perror(data_filename); return EXIT_FAILURE; } *out_data_file = fopen(data_filename, "w"); if(*out_data_file == NULL) { perror(data_filename); return EXIT_FAILURE; } if(stat(index_filename, &st) == 0) { errno = EEXIST; perror(index_filename); return EXIT_FAILURE; } *out_index_file = fopen(index_filename, "w+"); if(*out_index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } *out_offset = 0; } return EXIT_SUCCESS; } /* Insert a memory chunk (string even without \0) into ffindex */ int ffindex_insert_memory(FILE *data_file, FILE *index_file, size_t *offset, char *from_start, size_t from_length, char *name) { int myerrno = 0; size_t write_size; size_t offset_before = *offset; /* Write data */ write_size = fwrite(from_start, sizeof(char), from_length, data_file); *offset += write_size; if(from_length != write_size) { myerrno = errno; fferror_print(__FILE__, __LINE__, __func__, name); goto EXCEPTION_ffindex_insert_memory; } /* Seperate by '\0' and thus also make sure at least one byte is written */ char buffer[1] = {'\0'}; if(fwrite(buffer, sizeof(char), 1, data_file) != 1) { myerrno = errno; fferror_print(__FILE__, __LINE__, __func__, name); goto EXCEPTION_ffindex_insert_memory; } *offset += 1; /* Write index entry */ fprintf(index_file, "%s\t%zd\t%zd\n", name, offset_before, *offset - offset_before); EXCEPTION_ffindex_insert_memory: return myerrno; } /* Insert all files from a list into ffindex */ int ffindex_insert_list_file(FILE *data_file, FILE *index_file, size_t *start_offset, FILE *list_file) { size_t offset = *start_offset; char path[PATH_MAX]; while(fgets(path, PATH_MAX, list_file) != NULL) ffindex_insert_file(data_file, index_file, &offset, ffnchomp(path, strnlen(path, PATH_MAX)), basename(path)); /* update return value */ *start_offset = offset; return 0; } /* Insert all files from directory into ffindex */ int ffindex_insert_dir(FILE *data_file, FILE *index_file, size_t *start_offset, char *input_dir_name) { DIR *dir = opendir(input_dir_name); if(dir == NULL) { fferror_print(__FILE__, __LINE__, __func__, input_dir_name); return -1; } size_t input_dir_name_len = strnlen(input_dir_name, FILENAME_MAX); char path[PATH_MAX]; strncpy(path, input_dir_name, NAME_MAX); if(input_dir_name[input_dir_name_len - 1] != '/') { path[input_dir_name_len] = '/'; input_dir_name_len += 1; } size_t offset = *start_offset; struct dirent *entry; while((entry = readdir(dir)) != NULL) { if(entry->d_name[0] == '.') continue; strncpy(path + input_dir_name_len, entry->d_name, NAME_MAX); struct stat sb; if(stat(path, &sb) == -1) fferror_print(__FILE__, __LINE__, __func__, path); if(!S_ISREG(sb.st_mode)) continue; ffindex_insert_file(data_file, index_file, &offset, path, entry->d_name); } closedir(dir); /* update return value */ *start_offset = offset; return 0; } /* Insert one file by path into ffindex */ int ffindex_insert_file(FILE *data_file, FILE *index_file, size_t *offset, const char *path, char *name) { FILE *file = fopen(path, "r"); if(file == NULL) return errno; int ret = ffindex_insert_filestream(data_file, index_file, offset, file, name); fclose(file); return ret; } /* Insert one file by handle into ffindex */ int ffindex_insert_filestream(FILE *data_file, FILE *index_file, size_t *offset, FILE* file, char *name) { int myerrno = 0; /* copy and paste file to data file */ char buffer[FFINDEX_BUFFER_SIZE]; size_t offset_before = *offset; size_t read_size; while((read_size = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) { size_t write_size = fwrite(buffer, sizeof(char), read_size, data_file); *offset += write_size; if(read_size != write_size) fferror_print(__FILE__, __LINE__, __func__, name); } if(ferror(file)) warn("fread"); /* Seperate by '\0' and thus also make sure at least one byte is written */ buffer[0] = '\0'; if(fwrite(buffer, sizeof(char), 1, data_file) != 1) perror("ffindex_insert_filestream"); *offset += 1; if(ferror(data_file) != 0) goto EXCEPTION_ffindex_insert_file; /* write index entry */ fprintf(index_file, "%s\t%zd\t%zd\n", name, offset_before, *offset - offset_before); if(ferror(file) != 0) goto EXCEPTION_ffindex_insert_file; return myerrno; EXCEPTION_ffindex_insert_file: { fferror_print(__FILE__, __LINE__, __func__, ""); return myerrno; } } int ffindex_insert_ffindex(FILE* data_file, FILE* index_file, size_t* offset, char* data_to_add, ffindex_index_t* index_to_add) { int err = EXIT_SUCCESS; for(size_t entry_i = 0; entry_i < index_to_add->n_entries; entry_i++) { ffindex_entry_t *entry = ffindex_get_entry_by_index(index_to_add, entry_i); if(entry == NULL) { fferror_print(__FILE__, __LINE__, __func__, ""); return EXIT_FAILURE; } err = ffindex_insert_memory(data_file, index_file, offset, ffindex_get_data_by_entry(data_to_add, entry), entry->length - 1, entry->name); // skip \0 suffix if(err != EXIT_SUCCESS) { fferror_print(__FILE__, __LINE__, __func__, ""); return EXIT_FAILURE;} } return EXIT_SUCCESS; } /* XXX not implemented yet, the functionality is provided by ffindex_unpack.c though */ int ffindex_restore(FILE *data_file, FILE *index_file, char *output_dir_name) { return -1; } char* ffindex_mmap_data(FILE *file, size_t* size) { struct stat sb; fstat(fileno(file), &sb); *size = sb.st_size; int fd = fileno(file); if(fd < 0) { fferror_print(__FILE__, __LINE__, __func__, "mmap failed"); return MAP_FAILED; } return (char*)mmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0); } int ffindex_compare_entries_by_name(const void *pentry1, const void *pentry2) { ffindex_entry_t* entry1 = (ffindex_entry_t*)pentry1; ffindex_entry_t* entry2 = (ffindex_entry_t*)pentry2; return strncmp(entry1->name, entry2->name, FFINDEX_MAX_ENTRY_NAME_LENTH); } ffindex_entry_t* ffindex_grep_entry_by_str(ffindex_index_t *ffindex, char *name, size_t* offset) { for(size_t i = *offset; i < ffindex->n_entries; i++) if(strstr(ffindex->entries[i].name, name)) { *offset = i; return &ffindex->entries[i]; } return NULL; } ffindex_entry_t* ffindex_get_entry_by_name(ffindex_index_t *index, char *name) { return ffindex_bsearch_get_entry(index, name); } ffindex_entry_t* ffindex_bsearch_get_entry(ffindex_index_t *index, char *name) { ffindex_entry_t search; strncpy(search.name, name, FFINDEX_MAX_ENTRY_NAME_LENTH); return (ffindex_entry_t*)bsearch(&search, index->entries, index->n_entries, sizeof(ffindex_entry_t), ffindex_compare_entries_by_name); } ffindex_index_t* ffindex_index_parse(FILE *index_file, size_t num_max_entries) { if(num_max_entries == 0) num_max_entries = FFINDEX_MAX_INDEX_ENTRIES_DEFAULT; size_t nbytes = sizeof(ffindex_index_t) + (sizeof(ffindex_entry_t) * num_max_entries); ffindex_index_t *index = (ffindex_index_t *)mmap(0, nbytes, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if(index == MAP_FAILED) { fprintf(stderr, "Failed to allocate %ld bytes for index\n", nbytes); fferror_print(__FILE__, __LINE__, __func__, "malloc failed"); return NULL; } index->num_max_entries = num_max_entries; index->file = index_file; index->index_data = ffindex_mmap_data(index_file, &(index->index_data_size)); if(index->index_data_size == 0) warn("Problem mapping index file. Is it empty or is another process reading it?"); if(index->index_data == MAP_FAILED) { ffindex_index_close(index); return NULL; } index->type = SORTED_ARRAY; /* XXX Assume a sorted file for now */ posix_madvise(index->index_data, index->index_data_size, POSIX_MADV_SEQUENTIAL); /* Faster than scanf per line */ size_t names_too_long = 0; const char* d = index->index_data; size_t i; for(i = 0; d < (index->index_data + index->index_data_size); i++) { if(i >= index->num_max_entries) { errno = EINVAL; fferror_print(__FILE__, __LINE__, __func__, "too many entries in index"); munmap(index->index_data, index->index_data_size); ffindex_index_close(index); return NULL; } const char* end; int p; for(p = 0; *d != '\t'; d++) if(p < FFINDEX_MAX_ENTRY_NAME_LENTH) index->entries[i].name[p++] = *d; else names_too_long++; index->entries[i].name[p] = '\0'; index->entries[i].offset = ffparse_ulong(++d, &end); d = end; index->entries[i].length = ffparse_ulong(++d, &end); d = end + 1; /* +1 for newline */ } index->n_entries = i; int ret = 0; ret = munmap(index->index_data, index->index_data_size); if(ret) { fferror_print(__FILE__, __LINE__, __func__, "munmap"); return NULL; } /* Make sure that the actually filled part part of the index stays * in memory even under memory pressure. */ ret = mlock(index, sizeof(ffindex_index_t) + (sizeof(ffindex_entry_t) * index->n_entries)); if(ret) { fferror_print(__FILE__, __LINE__, __func__, "mlock"); return NULL; } if(index->n_entries == 0) warnx("index with 0 entries"); if(names_too_long) { errno = ENAMETOOLONG; warn("Cut-off is %d characters. Are they still unique?" " Warning encountered %zd times", FFINDEX_MAX_ENTRY_NAME_LENTH, names_too_long); errno = 0; } return index; } ffindex_entry_t* ffindex_get_entry_by_index(ffindex_index_t *index, size_t entry_index) { if(entry_index < index->n_entries) return &index->entries[entry_index]; else return NULL; } /* Using a function for this looks like overhead. But a more advanced data format, * say a compressed one, can do it's magic here. */ char* ffindex_get_data_by_offset(char* data, size_t offset) { return data + offset; } char* ffindex_get_data_by_entry(char *data, ffindex_entry_t* entry) { return ffindex_get_data_by_offset(data, entry->offset); } char* ffindex_get_data_by_name(char *data, ffindex_index_t *index, char *name) { ffindex_entry_t* entry = ffindex_bsearch_get_entry(index, name); if(entry == NULL) return NULL; return ffindex_get_data_by_entry(data, entry); } char* ffindex_get_data_by_index(char *data, ffindex_index_t *index, size_t entry_index) { ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index); if(entry == NULL) return NULL; return ffindex_get_data_by_entry(data, entry); } FILE* ffindex_fopen_by_entry(char *data, ffindex_entry_t* entry) { char *filedata = ffindex_get_data_by_offset(data, entry->offset); return fmemopen(filedata, entry->length, "r"); } FILE* ffindex_fopen_by_name(char *data, ffindex_index_t *index, char *filename) { ffindex_entry_t* entry = ffindex_bsearch_get_entry(index, filename); if(entry == NULL) return NULL; return ffindex_fopen_by_entry(data, entry); } void ffindex_sort_index_file(ffindex_index_t *index) { qsort(index->entries, index->n_entries, sizeof(ffindex_entry_t), ffindex_compare_entries_by_name); } /* Faster than fprintf but no error checking. * If more robustness is neeeded, prealocate the output file. */ size_t ffindex_print_entry(FILE* file, ffindex_entry_t* entry) { size_t written; written = fwrite(entry->name, 1, strnlen(entry->name, FFINDEX_MAX_ENTRY_NAME_LENTH), file); fputc('\t', file); written += fffprint_ulong(file, entry->offset); fputc('\t', file); written += fffprint_ulong(file, entry->length); fputc('\n', file); return written + 3; // * fputc } int ffindex_write(ffindex_index_t* index, FILE* index_file) { int ret = EXIT_SUCCESS; #if _POSIX_C_SOURCE >= 200112L ret = posix_fallocate(fileno(index_file), 0, index->n_entries * 30); // guesstimate if(ret) return ret; #endif /* Use tree if available */ if(index->type == TREE) ret = ffindex_tree_write(index, index_file); else for(size_t i = 0; i < index->n_entries; i++) if(ffindex_print_entry(index_file,index->entries + i) < 6) return EXIT_FAILURE; #if _POSIX_C_SOURCE >= 200112L ftruncate(fileno(index_file), ftell(index_file)); #endif return ret; } ffindex_index_t* ffindex_unlink(ffindex_index_t* index, char* name_to_unlink) { /* Use tree if available */ if(index->type == TREE) return ffindex_tree_unlink(index, name_to_unlink); else return NULL; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex.h000066400000000000000000000077641267377046700157450ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * Ffindex is a very simple database for small files. The files are stored * concatenated in one big data file, seperated by '\0'. A second file * contains a plain text index, giving name, offset and length of of the small * files. */ #ifndef _FFINDEX_H #define _FFINDEX_H 1 #include #define FFINDEX_VERSION 0.997 #define FFINDEX_COPYRIGHT "\nDesigned and implemented by Andreas Hauser .\n" #define FFINDEX_MAX_INDEX_ENTRIES_DEFAULT 80000000 #define FFINDEX_MAX_ENTRY_NAME_LENTH 63 enum ffindex_type { PLAIN_FILE, SORTED_FILE, SORTED_ARRAY, TREE }; typedef struct ffindex_entry { size_t offset; size_t length; char name[FFINDEX_MAX_ENTRY_NAME_LENTH + 1]; } ffindex_entry_t; typedef struct ffindex_index { enum ffindex_type type; char* filename; FILE* file; char* index_data; size_t index_data_size; void* tree_root; size_t num_max_entries; size_t n_entries; ffindex_entry_t entries[]; /* This array is as big as the excess memory allocated for this struct. */ } ffindex_index_t; typedef struct ffindex_db { char * ffdata_filename; char * ffindex_filename; FILE * ffdata_file; FILE * ffindex_file; char * ffdata; size_t ffdata_size; ffindex_index_t * ffindex; char mode[3]; size_t offset; size_t num_max_entries; } ffindex_db_t; ffindex_db_t * ffindex_index_db_open(ffindex_db_t * ffindex_db); int ffindex_index_db_close(ffindex_db_t* ffindex_db); int ffindex_index_close(ffindex_index_t* ffindex); /* return *out_data_file, *out_index_file, out_offset. */ int ffindex_index_open(char *data_filename, char *index_filename, char* mode, FILE **out_data_file, FILE **out_index_file, size_t *out_offset); int ffindex_insert_memory(FILE *data_file, FILE *index_file, size_t *offset, char *from_start, size_t from_length, char *name); int ffindex_insert_file(FILE *data_file, FILE *index_file, size_t *offset, const char *path, char *name); int ffindex_insert_filestream(FILE *data_file, FILE *index_file, size_t *offset, FILE* file, char *name); int ffindex_insert_list_file(FILE *data_file, FILE *index_file, size_t *start_offset, FILE *list_file); int ffindex_insert_dir(FILE *data_file, FILE *index_file, size_t *offset, char *input_dir_name); int ffindex_insert_ffindex(FILE* data_file, FILE* index_file, size_t* offset, char* data_to_add, ffindex_index_t* index_to_add); FILE* ffindex_fopen_by_entry(char *data, ffindex_entry_t* entry); FILE* ffindex_fopen_by_name(char *data, ffindex_index_t *index, char *name); char* ffindex_mmap_data(FILE *file, size_t* size); int ffindex_compare_entries_by_name(const void *pentry1, const void *pentry2); char* ffindex_get_data_by_offset(char* data, size_t offset); char* ffindex_get_data_by_entry(char *data, ffindex_entry_t* entry); char* ffindex_get_data_by_name(char *data, ffindex_index_t *index, char *name); char* ffindex_get_data_by_index(char *data, ffindex_index_t *index, size_t entry_index); ffindex_entry_t* ffindex_grep_entry_by_str(ffindex_index_t *ffindex, char *name, size_t* offset); ffindex_entry_t* ffindex_get_entry_by_index(ffindex_index_t *index, size_t entry_index); ffindex_entry_t* ffindex_get_entry_by_name(ffindex_index_t *index, char *name); ffindex_index_t* ffindex_index_parse(FILE *index_file, size_t num_max_entries); ffindex_entry_t* ffindex_bsearch_get_entry(ffindex_index_t *index, char *name); void ffindex_sort_index_file(ffindex_index_t *index); size_t ffindex_print_entry(FILE* file, ffindex_entry_t* entry); int ffindex_write(ffindex_index_t* index, FILE* index_file); ffindex_index_t* ffindex_unlink(ffindex_index_t* index, char *entry_name); char* ffindex_copyright(); #include #endif ffindex-0.9.9.7/src/ffindex_apply_mpi.c000066400000000000000000000256431267377046700200060ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * FFindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * ffindex_apply * apply a program to each FFindex entry */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include #include #ifdef HAVE_MPI # include #endif #include "ffindex.h" #include "ffutil.h" char* read_buffer; int ffindex_apply_by_entry(char *data, ffindex_index_t* index, ffindex_entry_t* entry, char* program_name, char** program_argv, FILE* data_file_out, FILE* index_file_out, size_t *offset, FILE* log_file) { int ret = 0; int capture_stdout = (data_file_out != NULL); int pipefd_stdin[2]; int pipefd_stdout[2]; ret = pipe(pipefd_stdin); if(ret != 0) { fprintf(stderr, "ERROR in pipe stdin!\n"); perror(entry->name); return errno; } if(capture_stdout) { ret = pipe(pipefd_stdout); if(ret != 0) { fprintf(stderr, "ERROR in pipe stdout!\n"); perror(entry->name); return errno; } } // Flush so child doesn't copy and also flushes, leading to duplicate output fflush(data_file_out); fflush(index_file_out); pid_t child_pid = fork(); if(child_pid == 0) { close(pipefd_stdin[1]); if(capture_stdout) { fclose(data_file_out); fclose(index_file_out); close(pipefd_stdout[0]); } // Make pipe from parent our new stdin int newfd_in = dup2(pipefd_stdin[0], fileno(stdin)); if(newfd_in < 0) { fprintf(stderr, "ERROR in dup2 in %d %d\n", pipefd_stdin[0], newfd_in); perror(entry->name); } close(pipefd_stdin[0]); if(capture_stdout) { int newfd_out = dup2(pipefd_stdout[1], fileno(stdout)); if(newfd_out < 0) { fprintf(stderr, "ERROR in dup2 out %d %d\n", pipefd_stdout[1], newfd_out); perror(entry->name); } close(pipefd_stdout[1]); } setenv("FFINDEX_ENTRY_NAME", entry->name, 1); // exec program with the pipe as stdin execvp(program_name, program_argv); // never reached } else if(child_pid > 0) { // parent writes to and possible reads from child int flags = 0; // Read end is for child only close(pipefd_stdin[0]); if(capture_stdout) close(pipefd_stdout[1]); char *filedata = ffindex_get_data_by_entry(data, entry); if(capture_stdout) { flags = fcntl(pipefd_stdout[0], F_GETFL, 0); fcntl(pipefd_stdout[0], F_SETFL, flags | O_NONBLOCK); } // Write file data to child's stdin. ssize_t written = 0; size_t to_write = entry->length - 1; // Don't write ffindex trailing '\0' char* b = read_buffer; while(written < to_write) { size_t rest = to_write - written; int batch_size = PIPE_BUF; if(rest < PIPE_BUF) batch_size = rest; ssize_t w = write(pipefd_stdin[1], filedata + written, batch_size); if(w < 0 && errno != EPIPE) { fprintf(stderr, "ERROR in child!\n"); perror(entry->name); break; } else written += w; if(capture_stdout) { // To avoid blocking try to read some data ssize_t r = read(pipefd_stdout[0], b, PIPE_BUF); if(r > 0) b += r; } } close(pipefd_stdin[1]); // child gets EOF if(capture_stdout) { // Read rest fcntl(pipefd_stdout[0], F_SETFL, flags); // Remove O_NONBLOCK ssize_t r; while((r = read(pipefd_stdout[0], b, PIPE_BUF)) > 0) b += r; close(pipefd_stdout[0]); ffindex_insert_memory(data_file_out, index_file_out, offset, read_buffer, b - read_buffer, entry->name); } int status; waitpid(child_pid, &status, 0); if(log_file != NULL) fprintf(log_file, "%s\t%ld\t%ld\t%d\n", entry->name, entry->offset, entry->length, WEXITSTATUS(status)); } else { fprintf(stderr, "ERROR in fork()\n"); perror(entry->name); return errno; } return EXIT_SUCCESS; } int main(int argn, char **argv) { int mpi_rank, mpi_num_procs; #ifdef HAVE_MPI int mpi_error; mpi_error = MPI_Init(&argn, &argv); if(mpi_error) goto EXCEPTION; mpi_error = MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); if(mpi_error) goto EXCEPTION; mpi_error = MPI_Comm_size(MPI_COMM_WORLD, &mpi_num_procs); if(mpi_error) goto EXCEPTION; #else mpi_rank = 0; mpi_num_procs = 1; #endif int opt, merge = 1; char *data_filename_out = NULL, *index_filename_out = NULL, *log_filename = NULL; while ((opt = getopt(argn, argv, "d:i:mql:")) != -1) { switch (opt) { case 'l': log_filename = optarg; break; case 'm': merge = 0; break; case 'd': data_filename_out = optarg; break; case 'i': index_filename_out = optarg; break; } } if(argn - optind < 3) { fprintf(stderr, "ERROR Not enough arguments.\n\n"); fprintf(stderr, "USAGE: %s [-m] [-q] [-l LOG_FILE] -d DATA_FILENAME_OUT -i INDEX_FILENAME_OUT DATA_FILENAME INDEX_FILENAME -- PROGRAM [PROGRAM_ARGS]*\n" "\t-l\tLOG_FILE like an FFindex file but with the return value of apply added.\n" "\t\tThis file can be processed and used as FFindex file.\n" "\t\tE.g. grep \"\t1$\" foo.log | cut -f 1-3 > foo-special.ffindex.\n" "\t\twhere maybe the %s ran with -- perl -e 'return 1 if(/^SPECIAL/)'\n" "\t-m\tDo not merge the FFindex parts generated by the different MPI processes\n" "\t\tThis is useful for large MPI Jobs where merge time might be accounted.\n" "\t-d\tFFDATA output file, stdout of program will be captured\n" "\t-i\tFFINDEX output file, entries get the same name as input entry\n" FFINDEX_COPYRIGHT, argv[0], argv[0]); errno = EINVAL; goto EXCEPTION; } read_buffer = malloc(400 * 1024 * 1024); char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; char *program_name = argv[optind]; char **program_argv = argv + optind; FILE *data_file = fopen(data_filename, "r"); FILE *index_file = fopen(index_filename, "r"); if( data_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename); exit(EXIT_FAILURE); } if(index_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename); exit(EXIT_FAILURE); } // Setup one output FFindex for each MPI process FILE *data_file_out = NULL, *index_file_out = NULL; if(data_filename_out != NULL && index_filename_out != NULL) { char* data_filename_out_rank = malloc(FILENAME_MAX); char* index_filename_out_rank = malloc(FILENAME_MAX); snprintf( data_filename_out_rank, FILENAME_MAX, "%s.%d", data_filename_out, mpi_rank); snprintf(index_filename_out_rank, FILENAME_MAX, "%s.%d", index_filename_out, mpi_rank); data_file_out = fopen(data_filename_out_rank, "w+"); index_file_out = fopen(index_filename_out_rank, "w+"); if( data_file_out == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename_out); exit(EXIT_FAILURE); } if(index_file_out == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename_out); exit(EXIT_FAILURE); } } FILE *log_file = NULL; // Setup log file if(log_filename) { char* log_filename_rank = malloc(FILENAME_MAX); snprintf(log_filename_rank, FILENAME_MAX, "%s.%d", index_filename_out, mpi_rank); log_file = fopen(log_filename_rank, "w+"); if( log_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], log_filename_rank); exit(EXIT_FAILURE); } } int capture_stdout = (data_file_out != NULL); size_t data_size; char *data = ffindex_mmap_data(data_file, &data_size); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { fferror_print(__FILE__, __LINE__, "ffindex_index_parse", index_filename); #ifdef HAVE_MPI MPI_Finalize(); #endif exit(EXIT_FAILURE); } // Ignore SIGPIPE struct sigaction handler; handler.sa_handler = SIG_IGN; sigemptyset(&handler.sa_mask); handler.sa_flags = 0; sigaction(SIGPIPE, &handler, NULL); size_t batch_size, range_start, range_end; if(index->n_entries >= mpi_num_procs) batch_size = index->n_entries / mpi_num_procs; else batch_size = 0; range_start = mpi_rank * batch_size; range_end = range_start + batch_size; size_t offset = 0; // Foreach entry if(batch_size > 0) for(size_t entry_index = range_start; entry_index < range_end; entry_index++) { ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index); if(entry == NULL) { perror(entry->name); goto EXCEPTION; } int error = ffindex_apply_by_entry(data, index, entry, program_name, program_argv, data_file_out, index_file_out, &offset, log_file); if(error != 0) { perror(entry->name); break; } } ssize_t left_over = index->n_entries - (batch_size * mpi_num_procs); if(mpi_rank < left_over) { size_t left_over_entry_index = (batch_size * mpi_num_procs) + mpi_rank; ffindex_entry_t* entry = ffindex_get_entry_by_index(index, left_over_entry_index); if(entry == NULL) { perror(entry->name); return errno; } //fprintf(stderr, "handling left over: %ld\n", left_over_entry_index); int error = ffindex_apply_by_entry(data, index, entry, program_name, program_argv, data_file_out, index_file_out, &offset, log_file); if(error != 0) perror(entry->name); } if(capture_stdout) fclose(data_file_out); if(index_file_out != NULL) fclose(index_file_out); #ifdef HAVE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif // merge FFindexes in master if(mpi_rank == 0 && merge && data_filename_out != NULL) { char* merge_command = malloc(FILENAME_MAX * 5); for(int i = 0; i < mpi_num_procs; i++) { snprintf( merge_command, FILENAME_MAX, "ffindex_build -as %s %s -d %s.%d -i %s.%d", data_filename_out, index_filename_out, data_filename_out, i, index_filename_out, i); //puts(merge_command); if(system(merge_command) == 0) { snprintf(merge_command, FILENAME_MAX, "%s.%d", data_filename_out, i); unlink(merge_command); snprintf(merge_command, FILENAME_MAX, "%s.%d", index_filename_out, i); unlink(merge_command); } else { fprintf(stderr, "merge command failed: %s\n", merge_command); goto EXCEPTION; } } } #ifdef HAVE_MPI MPI_Finalize(); #endif return EXIT_SUCCESS; EXCEPTION: perror(argv[0]); fprintf(stderr, "\nEXCEPTION ffindex_apply_mpi in rank: %d\n", mpi_rank); #ifdef HAVE_MPI MPI_Finalize(); #endif return EXIT_FAILURE; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_apply_mpi_spawn.c000066400000000000000000000254101267377046700212060ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * FFindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * ffindex_apply * apply a program to each FFindex entry */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" extern char **environ; char* read_buffer; int ffindex_apply_by_entry(char *data, ffindex_index_t* index, ffindex_entry_t* entry, char* program_name, char** program_argv, FILE* data_file_out, FILE* index_file_out, size_t *offset, FILE* log_file) { int ret = 0; int capture_stdout = (data_file_out != NULL); int pipefd_stdin[2]; int pipefd_stdout[2]; ret = pipe(pipefd_stdin); if(ret != 0) { fprintf(stderr, "ERROR in pipe stdin!\n"); perror(entry->name); return errno; } if(capture_stdout) { ret = pipe(pipefd_stdout); if(ret != 0) { fprintf(stderr, "ERROR in pipe stdout!\n"); perror(entry->name); return errno; } } // Flush so child doesn't copy and also flushes, leading to duplicate output fflush(data_file_out); fflush(index_file_out); posix_spawn_file_actions_t factions; posix_spawn_file_actions_init(&factions); posix_spawn_file_actions_addclose(&factions, pipefd_stdin[1]); posix_spawn_file_actions_adddup2(&factions, pipefd_stdin[0], fileno(stdin)); if(capture_stdout) { posix_spawn_file_actions_addclose(&factions, pipefd_stdout[0]); posix_spawn_file_actions_adddup2(&factions, pipefd_stdout[1], fileno(stdout)); } short flags = 0; posix_spawnattr_t attr; posix_spawnattr_init(&attr); flags |= POSIX_SPAWN_USEVFORK; posix_spawnattr_setflags(&attr, flags); pid_t child_pid; int err = posix_spawnp(&child_pid, program_name, &factions, &attr, program_argv, environ); if(err) perror("spawn"); /* setenv("FFINDEX_ENTRY_NAME", entry->name, 1); // exec program with the pipe as stdin execvp(program_name, program_argv); // never reached } else if(child_pid > 0) */ if(!err) { // parent writes to and possible reads from child int flags = 0; // Read end is for child only close(pipefd_stdin[0]); if(capture_stdout) close(pipefd_stdout[1]); char *filedata = ffindex_get_data_by_entry(data, entry); if(capture_stdout) { flags = fcntl(pipefd_stdout[0], F_GETFL, 0); fcntl(pipefd_stdout[0], F_SETFL, flags | O_NONBLOCK); } // Write file data to child's stdin. ssize_t written = 0; size_t to_write = entry->length - 1; // Don't write ffindex trailing '\0' char* b = read_buffer; while(written < to_write) { size_t rest = to_write - written; int batch_size = PIPE_BUF; if(rest < PIPE_BUF) batch_size = rest; ssize_t w = write(pipefd_stdin[1], filedata + written, batch_size); if(w < 0 && errno != EPIPE) { fprintf(stderr, "ERROR in child!\n"); perror(entry->name); break; } else written += w; if(capture_stdout) { // To avoid blocking try to read some data ssize_t r = read(pipefd_stdout[0], b, PIPE_BUF); if(r > 0) b += r; } } close(pipefd_stdin[1]); // child gets EOF if(capture_stdout) { // Read rest fcntl(pipefd_stdout[0], F_SETFL, flags); // Remove O_NONBLOCK ssize_t r; while((r = read(pipefd_stdout[0], b, PIPE_BUF)) > 0) b += r; close(pipefd_stdout[0]); ffindex_insert_memory(data_file_out, index_file_out, offset, read_buffer, b - read_buffer, entry->name); } int status; waitpid(child_pid, &status, 0); if(log_file != NULL) fprintf(log_file, "%s\t%ld\t%ld\t%d\n", entry->name, entry->offset, entry->length, WEXITSTATUS(status)); } else { fprintf(stderr, "ERROR in fork()\n"); perror(entry->name); return errno; } return EXIT_SUCCESS; } int main(int argn, char **argv) { int mpi_error, mpi_rank, mpi_num_procs; mpi_error = MPI_Init(&argn, &argv); if(mpi_error) goto EXCEPTION; mpi_error = MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); if(mpi_error) goto EXCEPTION; mpi_error = MPI_Comm_size(MPI_COMM_WORLD, &mpi_num_procs); if(mpi_error) goto EXCEPTION; int opt, merge = 1; char *data_filename_out = NULL, *index_filename_out = NULL, *log_filename = NULL; while ((opt = getopt(argn, argv, "d:i:mql:")) != -1) { switch (opt) { case 'l': log_filename = optarg; break; case 'm': merge = 0; break; case 'd': data_filename_out = optarg; break; case 'i': index_filename_out = optarg; break; } } if(argn - optind < 3) { fprintf(stderr, "ERROR Not enough arguments.\n\n"); fprintf(stderr, "USAGE: %s [-m] [-q] [-l LOG_FILE] -d DATA_FILENAME_OUT -i INDEX_FILENAME_OUT DATA_FILENAME INDEX_FILENAME -- PROGRAM [PROGRAM_ARGS]*\n" "\t-l\tLOG_FILE like an FFindex file but with the return value of apply added.\n" "\t\tThis file can be processed and used as FFindex file.\n" "\t\tE.g. grep \"\t1$\" foo.log | cut -f 1-3 > foo-special.ffindex.\n" "\t\twhere maybe the ffindex_apply_mpi ran with -- perl -e 'return 1 if(/^SPECIAL/)'\n" "\t-m\tDo not merge the FFindex parts generated by the different MPI processes\n" "\t\tThis is useful for large MPI Jobs where merge time might be accounted.\n" "\t-d\tFFDATA output file, stdout of program will be captured\n" "\t-i\tFFINDEX output file, entries get the same name as input entry\n" FFINDEX_COPYRIGHT, argv[0]); errno = EINVAL; goto EXCEPTION; } read_buffer = malloc(400 * 1024 * 1024); char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; char *program_name = argv[optind]; char **program_argv = argv + optind; FILE *data_file = fopen(data_filename, "r"); FILE *index_file = fopen(index_filename, "r"); if( data_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename); exit(EXIT_FAILURE); } if(index_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename); exit(EXIT_FAILURE); } // Setup one output FFindex for each MPI process FILE *data_file_out = NULL, *index_file_out = NULL; if(data_filename_out != NULL && index_filename_out != NULL) { char* data_filename_out_rank = malloc(FILENAME_MAX); char* index_filename_out_rank = malloc(FILENAME_MAX); snprintf( data_filename_out_rank, FILENAME_MAX, "%s.%d", data_filename_out, mpi_rank); snprintf(index_filename_out_rank, FILENAME_MAX, "%s.%d", index_filename_out, mpi_rank); data_file_out = fopen(data_filename_out_rank, "w+"); index_file_out = fopen(index_filename_out_rank, "w+"); if( data_file_out == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename_out); exit(EXIT_FAILURE); } if(index_file_out == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename_out); exit(EXIT_FAILURE); } } FILE *log_file = NULL; // Setup log file if(log_filename) { char* log_filename_rank = malloc(FILENAME_MAX); snprintf(log_filename_rank, FILENAME_MAX, "%s.%d", index_filename_out, mpi_rank); log_file = fopen(log_filename_rank, "w+"); if( log_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], log_filename_rank); exit(EXIT_FAILURE); } } int capture_stdout = (data_file_out != NULL); size_t data_size; char *data = ffindex_mmap_data(data_file, &data_size); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { fferror_print(__FILE__, __LINE__, "ffindex_index_parse", index_filename); MPI_Finalize(); exit(EXIT_FAILURE); } // Ignore SIGPIPE struct sigaction handler; handler.sa_handler = SIG_IGN; sigemptyset(&handler.sa_mask); handler.sa_flags = 0; sigaction(SIGPIPE, &handler, NULL); size_t batch_size, range_start, range_end; if(index->n_entries >= mpi_num_procs) batch_size = index->n_entries / mpi_num_procs; else batch_size = 0; range_start = mpi_rank * batch_size; range_end = range_start + batch_size; size_t offset = 0; // Foreach entry if(batch_size > 0) for(size_t entry_index = range_start; entry_index < range_end; entry_index++) { ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index); if(entry == NULL) { perror(entry->name); goto EXCEPTION; } int error = ffindex_apply_by_entry(data, index, entry, program_name, program_argv, data_file_out, index_file_out, &offset, log_file); if(error != 0) { perror(entry->name); break; } } ssize_t left_over = index->n_entries - (batch_size * mpi_num_procs); if(mpi_rank < left_over) { size_t left_over_entry_index = (batch_size * mpi_num_procs) + mpi_rank; ffindex_entry_t* entry = ffindex_get_entry_by_index(index, left_over_entry_index); if(entry == NULL) { perror(entry->name); return errno; } //fprintf(stderr, "handling left over: %ld\n", left_over_entry_index); int error = ffindex_apply_by_entry(data, index, entry, program_name, program_argv, data_file_out, index_file_out, &offset, log_file); if(error != 0) perror(entry->name); } if(capture_stdout) fclose(data_file_out); if(index_file_out != NULL) fclose(index_file_out); MPI_Barrier(MPI_COMM_WORLD); // merge FFindexes in master if(mpi_rank == 0 && merge && data_filename_out != NULL) { char* merge_command = malloc(FILENAME_MAX * 5); for(int i = 0; i < mpi_num_procs; i++) { snprintf( merge_command, FILENAME_MAX, "ffindex_build -as %s %s -d %s.%d -i %s.%d", data_filename_out, index_filename_out, data_filename_out, i, index_filename_out, i); //puts(merge_command); if(system(merge_command) == 0) { snprintf(merge_command, FILENAME_MAX, "%s.%d", data_filename_out, i); unlink(merge_command); snprintf(merge_command, FILENAME_MAX, "%s.%d", index_filename_out, i); unlink(merge_command); } else { fprintf(stderr, "merge command failed: %s\n", merge_command); goto EXCEPTION; } } } MPI_Finalize(); return EXIT_SUCCESS; EXCEPTION: perror(argv[0]); fprintf(stderr, "\nEXCEPTION ffindex_apply_mpi in rank: %d\n", mpi_rank); MPI_Finalize(); return EXIT_FAILURE; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_build.c000066400000000000000000000156211267377046700171060ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" #define MAX_FILENAME_LIST_FILES 4096 void usage(char *program_name) { fprintf(stderr, "USAGE: %s [-a|-v] [-s] [-f file]* OUT_DATA_FILE OUT_INDEX_FILE [-d 2ND_DATA_FILE -i 2ND_INDEX_FILE] [DIR_TO_INDEX|FILE]*\n" "\t-a\t\tappend files/indexes, also needed for sorting an already existing ffindex\n" "\t-d FFDATA_FILE\ta second ffindex data file for inserting/appending\n" "\t-i FFINDEX_FILE\ta second ffindex index file for inserting/appending\n" "\t-f FILE\t\tfile containing a list of file names, one per line\n" "\t\t\t-f can be specified up to %d times\n" "\t-s\t\tsort index file, so that the index can queried.\n" "\t\t\tAnother append operations can be done without sorting.\n" "\t-v\t\tprint version and other info then exit\n" "\t-h\t\tdisplay this help message\n" "\nEXAMPLES:\n" "\tCreate a new ffindex containing all files from the \"bar/\" directory containing\n" "\tsay myfile1.txt, myfile2.txt and sort (-s) it so that e.g. ffindex_get can use it.\n" "\t\t$ ffindex_build -s foo.ffdata foo.ffindex bar/\n" "\n\tAdd (-a) more files: myfile3.txt, myfile4.txt.\n" "\t\t$ ffindex_build -a foo.ffdata foo.ffindex myfile3.txt myfile4.txt\n" "\n\tOops, forgot to sort it (-s) so do it afterwards:\n" "\t\t$ ffindex_build -as foo.ffdata foo.ffindex\n" "\nNOTE:\n" "\tCompiled with a maximum key/filename length is %d and\n" "\tdefault maximum entries %d.\n" "\tThis can be changed in the sources.\n" FFINDEX_COPYRIGHT, program_name, MAX_FILENAME_LIST_FILES, FFINDEX_MAX_ENTRY_NAME_LENTH, FFINDEX_MAX_INDEX_ENTRIES_DEFAULT); } int main(int argn, char **argv) { int append = 0, sort = 0, unlink = 0, version = 0; int opt, err = EXIT_SUCCESS; char* list_filenames[MAX_FILENAME_LIST_FILES]; char* list_ffindex_data[MAX_FILENAME_LIST_FILES]; char* list_ffindex_index[MAX_FILENAME_LIST_FILES]; size_t list_ffindex_data_index = 0; size_t list_ffindex_index_index = 0; size_t list_filenames_index = 0; char* program_name = basename(argv[0]); while ((opt = getopt(argn, argv, "asuvd:f:hi:")) != -1) { switch (opt) { case 'a': append = 1; break; case 'd': list_ffindex_data[list_ffindex_data_index++] = optarg; break; case 'i': list_ffindex_index[list_ffindex_index_index++] = optarg; break; case 'f': list_filenames[list_filenames_index++] = optarg; break; case 'h': usage(program_name); return EXIT_SUCCESS; case 's': sort = 1; break; case 'v': version = 1; break; default: usage(argv[0]); return EXIT_FAILURE; } } if(version == 1) { /* Don't you dare running it on a platform where byte != 8 bits */ printf("%s version: %.3f (off_t = %zd bits)\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8); return EXIT_SUCCESS; } if(argn - optind < 2) { usage(argv[0]); return EXIT_FAILURE; } if(append && unlink) { fprintf(stderr, "ERROR: append (-a) and unlink (-u) are mutually exclusive\n"); return EXIT_FAILURE; } if(list_ffindex_data_index != list_ffindex_index_index) { fprintf(stderr, "ERROR: -d and -i must be specified pairwise\n"); return EXIT_FAILURE; } char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; FILE *data_file = NULL, *index_file = NULL; size_t offset = 0; /* open index and data file, seek to end if needed */ char *mode = "w"; if(append) mode = "a"; err = ffindex_index_open(data_filename, index_filename, mode, &data_file, &index_file, &offset); if(err != EXIT_SUCCESS) return EXIT_FAILURE; /* For each list_file insert */ if(list_filenames_index > 0) for(int i = 0; i < list_filenames_index; i++) { FILE *list_file = fopen(list_filenames[i], "r"); if( list_file == NULL) { perror(list_filenames[i]); return EXIT_FAILURE; } if(ffindex_insert_list_file(data_file, index_file, &offset, list_file) < 0) { perror(list_filenames[i]); err = -1; } } /* Append other ffindexes */ if(list_ffindex_data_index > 0) { for(int i = 0; i < list_ffindex_data_index; i++) { FILE* data_file_to_add = fopen(list_ffindex_data[i], "r"); if( data_file_to_add == NULL) { perror(list_ffindex_data[i]); return EXIT_FAILURE; } FILE* index_file_to_add = fopen(list_ffindex_index[i], "r"); if( index_file_to_add == NULL) { perror(list_ffindex_index[i]); return EXIT_FAILURE; } size_t data_size; char *data_to_add = ffindex_mmap_data(data_file_to_add, &data_size); ffindex_index_t* index_to_add = ffindex_index_parse(index_file_to_add, 0); ffindex_insert_ffindex(data_file, index_file, &offset, data_to_add, index_to_add); } } /* Insert files and directories into the index */ for(int i = optind; i < argn; i++) { char *path = argv[i]; struct stat sb; if(stat(path, &sb) == -1) { fferror_print(__FILE__, __LINE__, __func__, path); continue; } if(S_ISDIR(sb.st_mode)) { err = ffindex_insert_dir(data_file, index_file, &offset, path); if(err < 0) fferror_print(__FILE__, __LINE__, __func__, path); } else if(S_ISREG(sb.st_mode)) { ffindex_insert_file(data_file, index_file, &offset, path, path); } } fclose(data_file); /* Sort the index entries and write back */ if(sort) { rewind(index_file); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { fferror_print(__FILE__, __LINE__, __func__, index_filename); exit(EXIT_FAILURE); } fclose(index_file); ffindex_sort_index_file(index); index_file = fopen(index_filename, "w"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } err = ffindex_write(index, index_file); if(err) fferror_print(__FILE__, __LINE__, __func__, index_filename); } return err; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_from_fasta.c000066400000000000000000000062011267377046700201220ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * FFindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" #define MAX_FILENAME_LIST_FILES 4096 void usage(char *program_name) { fprintf(stderr, "USAGE: %s -v | [-s] data_filename index_filename fasta_filename\n" "\t-s\tsort index file\n" FFINDEX_COPYRIGHT, program_name); } int main(int argn, char **argv) { int sort = 0, version = 0; int opt, err = EXIT_SUCCESS; while ((opt = getopt(argn, argv, "sv")) != -1) { switch (opt) { case 's': sort = 1; break; case 'v': version = 1; break; default: usage(argv[0]); return EXIT_FAILURE; } } if(version == 1) { /* Don't you dare running it on a platform where byte != 8 bits */ printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8); return EXIT_SUCCESS; } if(argn - optind < 3) { usage(argv[0]); return EXIT_FAILURE; } char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; char *fasta_filename = argv[optind++]; FILE *data_file, *index_file, *fasta_file; size_t offset = 0; /* open ffindex */ err = ffindex_index_open(data_filename, index_filename, "w", &data_file, &index_file, &offset); if(err != EXIT_SUCCESS) return err; fasta_file = fopen(fasta_filename, "r"); if(fasta_file == NULL) { perror(fasta_filename); return EXIT_FAILURE; } size_t fasta_size; char *fasta_data = ffindex_mmap_data(fasta_file, &fasta_size); size_t from_length = 0; char name[FFINDEX_MAX_ENTRY_NAME_LENTH]; int seq_id = 1; for(size_t fasta_offset = 1; fasta_offset < fasta_size; fasta_offset++) // position after first ">" { from_length = 1; while(fasta_offset < fasta_size && !(*(fasta_data + fasta_offset) == '>' && *(fasta_data + fasta_offset - 1) == '\n')) { fasta_offset++; from_length++; } sprintf(name, "%d", seq_id++); ffindex_insert_memory(data_file, index_file, &offset, fasta_data + (fasta_offset - from_length), from_length, name); } fclose(data_file); /* Sort the index entries and write back */ if(sort) { rewind(index_file); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { perror("ffindex_index_parse failed"); exit(EXIT_FAILURE); } fclose(index_file); ffindex_sort_index_file(index); index_file = fopen(index_filename, "w"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } err += ffindex_write(index, index_file); } return err; } /* vim: ts=2 sw=2 et: */ ffindex-0.9.9.7/src/ffindex_from_tsv.c000066400000000000000000000120521267377046700176410ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * FFindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" #define MAX_FILENAME_LIST_FILES 4096 void usage(char *program_name) { fprintf(stderr, "USAGE: %s -v | [-s] [-k INDEX] data_filename index_filename fasta_filename\n" "\t-k INDEX\tfield index from 1 which is used as key (default = 1)\n" "\t-s\tsort index file (usually you want this)\n" FFINDEX_COPYRIGHT, program_name); } char* tsv_scan_line_for_field(char *tsv_current, int field_selected_index, char **field_start, size_t *field_length) { *field_start = tsv_current; *field_length = 0; int field_index = 1; for(int c = *tsv_current; c != '\n'; c = *(tsv_current++)) { if(c == '\t') { if(field_index == field_selected_index) *field_length = tsv_current - *field_start - 1; field_index++; if(field_index == field_selected_index) *field_start = tsv_current; } } if(*field_length == 0) *field_length = tsv_current - *field_start - 1; return tsv_current; } int main(int argn, char **argv) { int sort = 0, version = 0; int opt, err = EXIT_SUCCESS; int user_selected_field_index = 1; while ((opt = getopt(argn, argv, "svk:")) != -1) { switch (opt) { case 'k': user_selected_field_index = optind; break; case 's': sort = 1; break; case 'v': version = 1; break; default: usage(argv[0]); return EXIT_FAILURE; } } if(version == 1) { /* Don't you dare running it on a platform where byte != 8 bits */ printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8); return EXIT_SUCCESS; } if(argn - optind < 3) { usage(argv[0]); return EXIT_FAILURE; } char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; char *tsv_filename = argv[optind++]; FILE *data_file, *index_file; size_t offset = 0; /* open ffindex */ err = ffindex_index_open(data_filename, index_filename, "w", &data_file, &index_file, &offset); if(err != EXIT_SUCCESS) return err; FILE* tsv_file = fopen(tsv_filename, "r"); if(tsv_file == NULL) { perror(tsv_filename); return EXIT_FAILURE; } size_t tsv_size; char* tsv_data = ffindex_mmap_data(tsv_file, &tsv_size); char* tsv_current = tsv_data; char* tsv_part_begin = tsv_data; char* tsv_last = tsv_data + tsv_size; char field_current[FFINDEX_MAX_ENTRY_NAME_LENTH + 1]; // + seperator size_t field_current_length = 0; // + seperator char* tsv_selected_field_start = NULL; size_t tsv_selected_field_length = 0; tsv_current = tsv_scan_line_for_field(tsv_current, user_selected_field_index, &tsv_selected_field_start, &tsv_selected_field_length); strncpy(field_current, tsv_selected_field_start, tsv_selected_field_length); //XXX field_current_length = tsv_selected_field_length; field_current[field_current_length] = '\0'; while(tsv_current < tsv_last) { char* tsv_next; tsv_next = tsv_scan_line_for_field(tsv_current, user_selected_field_index, &tsv_selected_field_start, &tsv_selected_field_length); if((tsv_selected_field_length != field_current_length || strncmp(field_current, tsv_selected_field_start, tsv_selected_field_length) != 0)) // XXX got a new field value { ffindex_insert_memory(data_file, index_file, &offset, tsv_part_begin, tsv_current - tsv_part_begin, field_current); strncpy(field_current, tsv_selected_field_start, tsv_selected_field_length); //XXX field_current_length = tsv_selected_field_length; field_current[field_current_length] = '\0'; tsv_part_begin = tsv_current; } tsv_current = tsv_next; } ffindex_insert_memory(data_file, index_file, &offset, tsv_part_begin, tsv_current - tsv_part_begin, field_current); strncpy(field_current, tsv_selected_field_start, tsv_selected_field_length); //XXX field_current_length = tsv_selected_field_length; field_current[field_current_length] = '\0'; fclose(data_file); /* Sort the index entries and write back */ if(sort) { rewind(index_file); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { perror("ffindex_index_parse failed"); exit(EXIT_FAILURE); } fclose(index_file); ffindex_sort_index_file(index); index_file = fopen(index_filename, "w"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } err += ffindex_write(index, index_file); } return err; } /* vim: ts=2 sw=2 et: */ ffindex-0.9.9.7/src/ffindex_get.c000066400000000000000000000120201267377046700165540ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include "ffindex.h" #include "ffutil.h" void usage(char* program_name) { fprintf(stderr, "USAGE: %s data_filename index_filename entry name(s)\n" "\t-f FILE\t\tfile containing a list of file names, one per line\n" "\t-h\t\tdisplay this help message\n" "\t-n\t\tuse index of entry instead of entry name\n" FFINDEX_COPYRIGHT, program_name); } int main(int argn, char **argv) { int by_index = 0; int opt; char* list_filenames[4096]; size_t list_filenames_index = 0; char* program_name = basename(argv[0]); while ((opt = getopt(argn, argv, "f:hn")) != -1) { switch (opt) { case 'f': list_filenames[list_filenames_index++] = optarg; break; case 'n': by_index = 1; break; case 'h': usage(program_name); return EXIT_SUCCESS; default: usage(program_name); return EXIT_FAILURE; } } if(argn < 3) { usage(argv[0]); return EXIT_FAILURE; } char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; ffindex_db_t * ffindex_db = calloc(1, sizeof(ffindex_db_t)); ffindex_db->ffdata_filename = data_filename; ffindex_db->ffindex_filename = index_filename; ffindex_db->mode[0] = 'r'; ffindex_db = ffindex_index_db_open(ffindex_db); if(!ffindex_db) { fferror_print(__FILE__, __LINE__, "ffindex_index_db_open failed", argv[0]); return EXIT_FAILURE; } if(by_index) { for(int i = optind; i < argn; i++) { size_t index_n = atol(argv[i]) - 1; // offset from 0 but specify from 1 ffindex_entry_t* entry = ffindex_get_entry_by_index(ffindex_db->ffindex, index_n); if(entry == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get entry index out of range", argv[i]); } else { char *filedata = ffindex_get_data_by_entry(ffindex_db->ffdata, entry); if(filedata == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get entry index out of range", argv[i]); } else fwrite(filedata, entry->length - 1, 1, stdout); } } } else // by name { // get names given by file if(list_filenames_index > 0) { for(int i = 0; i < list_filenames_index; i++) { FILE *list_file = fopen(list_filenames[i], "r"); if( list_file == NULL) { perror(list_filenames[i]); return EXIT_FAILURE; } char name[PATH_MAX]; while(fgets(name, PATH_MAX, list_file) != NULL) { ffindex_entry_t* entry = ffindex_get_entry_by_name(ffindex_db->ffindex, ffnchomp(name, strnlen(name, PATH_MAX))); if(entry == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get key not found in index", name); } else { char *filedata = ffindex_get_data_by_entry(ffindex_db->ffdata, entry); if(filedata == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get key not found in index", name); } else fwrite(filedata, entry->length - 1, 1, stdout); } } } } // get files given on command line for(int i = optind; i < argn; i++) { char *filename = argv[i]; ffindex_entry_t* entry = ffindex_get_entry_by_name(ffindex_db->ffindex, filename); if(entry == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get key not found in index", filename); } else { char *filedata = ffindex_get_data_by_entry(ffindex_db->ffdata, entry); if(filedata == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_get key not found in index", filename); } else fwrite(filedata, entry->length - 1, 1, stdout); } } /* Alternative code using (slower) ffindex_fopen */ /* FILE *file = ffindex_fopen(data, index, filename); if(file == NULL) { errno = ENOENT; fferror_print(__FILE__, __LINE__, "ffindex_fopen file not found in index", filename); } else { char line[LINE_MAX]; while(fgets(line, LINE_MAX, file) != NULL) printf("%s", line); } */ } ffindex_index_db_close(ffindex_db); return 0; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_modify.c000066400000000000000000000102001267377046700172620ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" #define MAX_FILENAME_LIST_FILES 4096 void usage(char *program_name) { fprintf(stderr, "USAGE: %s -s|-u [-v] [-f file]* index_filename [filename]*\n" "\t-f file\tfile each line containing a filename\n" "\t\t-f can be specified up to %d times\n" "\t-s\tsort index file\n" "\t-u\tunlink entry (remove from index only)\n" "\t-v\tprint version and other info then exit\n" "EXAMPLE:\n" "\t%s -us foo.ffindex entry1\n" "\tTo clean up the data file after unlinking insert it to an new one:\n" "\tffindex_build -as cleaned.ffdata cleaned.ffindex -d foo.ffdata -i foo.ffindex\n" FFINDEX_COPYRIGHT, program_name, MAX_FILENAME_LIST_FILES, program_name); } int main(int argn, char **argv) { int sort = 0, unlink = 0, version = 0, use_tree = 1; int opt, err = EXIT_SUCCESS; char* list_filenames[MAX_FILENAME_LIST_FILES]; size_t list_filenames_index = 0; while ((opt = getopt(argn, argv, "stuvf:")) != -1) { switch (opt) { case 'f': list_filenames[list_filenames_index++] = optarg; break; case 's': sort = 1; break; case 't': use_tree = 1; break; case 'u': unlink = 1; break; case 'v': version = 1; break; default: fprintf(stderr, "Option %c not recognized\n", opt); usage(argv[0]); return EXIT_FAILURE; } } if(version == 1) { /* Don't you dare running it on a platform where byte != 8 bits */ printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8); return EXIT_SUCCESS; } if(optind >= argn) { usage(argv[0]); return EXIT_FAILURE; } char *index_filename = argv[optind++]; FILE *index_file; index_file = fopen(index_filename, "r+"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { perror("ffindex_index_parse failed"); return (EXIT_FAILURE); } fclose(index_file); /* Unlink entries */ if(unlink) { if(use_tree) { /* Build tree */ index = ffindex_index_as_tree(index); /* Tree keeps index sorted */ sort = 0; /* For each list_file unlink all entries */ if(list_filenames_index > 0) for(int i = 0; i < list_filenames_index; i++) { printf("Unlinking entries from '%s'\n", list_filenames[i]); FILE *list_file = fopen(list_filenames[i], "r"); if( list_file == NULL) { perror(list_filenames[i]); return EXIT_FAILURE; } /* unlink entries in file, one per line */ char path[PATH_MAX]; while(fgets(path, PATH_MAX, list_file) != NULL) index = ffindex_unlink(index, ffnchomp(path, strnlen(path, PATH_MAX))); } /* unlink entries specified by args */ for(int i = optind; i < argn; i++) index = ffindex_unlink(index, argv[i]); } else fprintf(stderr, "unused case\n"); } if(sort) ffindex_sort_index_file(index); /* Write index back */ index_file = fopen(index_filename, "w"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } err = ffindex_write(index, index_file); if(err) fferror_print(__FILE__, __LINE__, __func__, index_filename); ffindex_index_close(index); return err; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_optimize.c000066400000000000000000000116201267377046700176420ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" #define MAX_FILENAME_LIST_FILES 4096 void usage(char *program_name) { fprintf(stderr, "USAGE: %s OUT_DATA_FILE OUT_INDEX_FILE -d IN_DATA_FILE -i IN_INDEX_FILE\n" "\t-d FFDATA_FILE\tinput ffindex data file to be optimized\n" "\t-i FFINDEX_FILE\tinput ffindex index file to be optimized\n" "\t-v\t\tprint version and other info then exit\n" FFINDEX_COPYRIGHT, program_name, MAX_FILENAME_LIST_FILES, FFINDEX_MAX_ENTRY_NAME_LENTH, FFINDEX_MAX_INDEX_ENTRIES_DEFAULT); } int main(int argn, char **argv) { int version = 0; int opt, err = EXIT_SUCCESS; char* list_ffindex_data[MAX_FILENAME_LIST_FILES]; char* list_ffindex_index[MAX_FILENAME_LIST_FILES]; size_t list_ffindex_data_index = 0; size_t list_ffindex_index_index = 0; size_t list_filenames_index = 0; while ((opt = getopt(argn, argv, "vd:i:")) != -1) { switch (opt) { case 'd': list_ffindex_data[list_ffindex_data_index++] = optarg; break; case 'i': list_ffindex_index[list_ffindex_index_index++] = optarg; break; case 'v': version = 1; break; default: usage(argv[0]); return EXIT_FAILURE; } } if(version == 1) { /* Don't you dare running it on a platform where byte != 8 bits */ printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8); return EXIT_SUCCESS; } if(argn - optind < 2) { usage(argv[0]); return EXIT_FAILURE; } if(list_ffindex_data_index != list_ffindex_index_index) { fprintf(stderr, "ERROR: -d and -i must be specified pairwise\n"); return EXIT_FAILURE; } char *data_filename = argv[optind++]; char *index_filename = argv[optind++]; FILE *data_file = NULL, *index_file = NULL; size_t offset = 0; /* open index and data file, seek to end if needed */ char *mode = "w"; if(append) mode = "a"; err = ffindex_index_open(data_filename, index_filename, mode, &data_file, &index_file, &offset); if(err != EXIT_SUCCESS) return EXIT_FAILURE; /* For each list_file insert */ if(list_filenames_index > 0) for(int i = 0; i < list_filenames_index; i++) { FILE *list_file = fopen(list_filenames[i], "r"); if( list_file == NULL) { perror(list_filenames[i]); return EXIT_FAILURE; } if(ffindex_insert_list_file(data_file, index_file, &offset, list_file) < 0) { perror(list_filenames[i]); err = -1; } } /* Append other ffindexes */ if(list_ffindex_data_index > 0) { for(int i = 0; i < list_ffindex_data_index; i++) { FILE* data_file_to_add = fopen(list_ffindex_data[i], "r"); if( data_file_to_add == NULL) { perror(list_ffindex_data[i]); return EXIT_FAILURE; } FILE* index_file_to_add = fopen(list_ffindex_index[i], "r"); if( index_file_to_add == NULL) { perror(list_ffindex_index[i]); return EXIT_FAILURE; } size_t data_size; char *data_to_add = ffindex_mmap_data(data_file_to_add, &data_size); ffindex_index_t* index_to_add = ffindex_index_parse(index_file_to_add, 0); ffindex_insert_ffindex(data_file, index_file, &offset, data_to_add, index_to_add); } } /* Insert files and directories into the index */ for(int i = optind; i < argn; i++) { char *path = argv[i]; struct stat sb; if(stat(path, &sb) == -1) { fferror_print(__FILE__, __LINE__, __func__, path); continue; } if(S_ISDIR(sb.st_mode)) { err = ffindex_insert_dir(data_file, index_file, &offset, path); if(err < 0)fferror_print(__FILE__, __LINE__, __func__, path); } else if(S_ISREG(sb.st_mode)) { ffindex_insert_file(data_file, index_file, &offset, path, path); } } fclose(data_file); /* Sort the index entries and write back */ if(sort) { rewind(index_file); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { fferror_print(__FILE__, __LINE__, __func__, index_filename); exit(EXIT_FAILURE); } fclose(index_file); ffindex_sort_index_file(index); index_file = fopen(index_filename, "w"); if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; } err += ffindex_write(index, index_file); } return err; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffindex_posix_search.c000066400000000000000000000040611267377046700204720ustar00rootroot00000000000000#include #include #include #include #include /* tree version */ ffindex_entry_t *ffindex_tree_get_entry(ffindex_index_t* index, char* name) { ffindex_entry_t search; strncpy(search.name, name, FFINDEX_MAX_ENTRY_NAME_LENTH); return (ffindex_entry_t *)tfind((const void *)&search, &index->tree_root, ffindex_compare_entries_by_name); } ffindex_index_t* ffindex_tree_unlink(ffindex_index_t* index, char* name_to_unlink) { if(index->tree_root == NULL) { fferror_print(__FILE__, __LINE__, __func__, "tree is NULL"); return NULL; } ffindex_entry_t search; strncpy(search.name, name_to_unlink, FFINDEX_MAX_ENTRY_NAME_LENTH); tdelete((const void *)&search, &index->tree_root, ffindex_compare_entries_by_name); return index; } ffindex_index_t* ffindex_index_as_tree(ffindex_index_t* index) { index->tree_root = NULL; for(size_t i = 0; i < index->n_entries; i++) { ffindex_entry_t *entry = &index->entries[i]; tsearch((const void *)entry, &index->tree_root, ffindex_compare_entries_by_name); //entry = *(ffindex_entry_t **)tsearch((const void *)entry, &index->tree_root, ffindex_compare_entries_by_name); //printf("entry find: %s\n", entry->name); } index->type = TREE; return index; } static __thread FILE * ffindex_tree_write_action_index_file = NULL; static __thread int ffindex_tree_write_action_ret = EXIT_SUCCESS; static void ffindex_tree_write_action(const void *node, const VISIT which, const int depth) { switch (which) { case preorder: break; case endorder: break; case postorder: case leaf: if(ffindex_print_entry(ffindex_tree_write_action_index_file, *(ffindex_entry_t **) node) < 6) ffindex_tree_write_action_ret = EXIT_FAILURE; break; } } int ffindex_tree_write(ffindex_index_t* index, FILE* index_file) { ffindex_tree_write_action_ret = EXIT_SUCCESS; ffindex_tree_write_action_index_file = index_file; twalk(index->tree_root, ffindex_tree_write_action); return ffindex_tree_write_action_ret; } ffindex-0.9.9.7/src/ffindex_posix_search.h000066400000000000000000000003561267377046700205020ustar00rootroot00000000000000#include ffindex_index_t* ffindex_index_as_tree(ffindex_index_t* index); ffindex_index_t* ffindex_tree_unlink(ffindex_index_t* index, char* name_to_unlink); int ffindex_tree_write(ffindex_index_t* index, FILE* index_file); ffindex-0.9.9.7/src/ffindex_unpack.c000066400000000000000000000047521267377046700172730ustar00rootroot00000000000000/* * FFindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * FFindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * ffindex_apply * apply a program to each FFindex entry */ #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include "ffindex.h" #include "ffutil.h" int main(int argn, char **argv) { if(argn < 4) { fprintf(stderr, "USAGE: %s DATA_FILENAME INDEX_FILENAME OUT_DIR\n" "\n\tPlease note that a huge number of files might be created!\n" FFINDEX_COPYRIGHT, argv[0]); return -1; } char *data_filename = argv[1]; char *index_filename = argv[2]; char *out_dir = argv[3]; FILE *data_file = fopen(data_filename, "r"); FILE *index_file = fopen(index_filename, "r"); if( data_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename); exit(EXIT_FAILURE); } if(index_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename); exit(EXIT_FAILURE); } size_t data_size; char *data = ffindex_mmap_data(data_file, &data_size); madvise(data, data_size, MADV_SEQUENTIAL); ffindex_index_t* index = ffindex_index_parse(index_file, 0); if(index == NULL) { fferror_print(__FILE__, __LINE__, "ffindex_index_parse", index_filename); exit(EXIT_FAILURE); } if(chdir(out_dir) < 0){ fferror_print(__FILE__, __LINE__, argv[0], out_dir); exit(EXIT_FAILURE); } size_t range_start = 0; size_t range_end = index->n_entries; // Foreach entry //#pragma omp parallel for for(size_t entry_index = range_start; entry_index < range_end; entry_index++) { //fprintf(stderr, "index %ld\n", entry_index); ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index); if(entry == NULL) { perror(entry->name); continue; } FILE *output_file = fopen(entry->name, "w"); // Write to file char *filedata = ffindex_get_data_by_entry(data, entry); size_t written = fwrite(filedata, entry->length - 1, 1, output_file); if(written < 1) { perror(entry->name); } fclose(output_file); } return 0; } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffutil.c000066400000000000000000000056371267377046700156030ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * Ffindex is a very simple database for small files. The files are stored * concatenated in one big data file, seperated by '\0'. A second file * contains a plain text index, giving name, offset and length of of the small * files. */ /* In addition ffutil.h and ffutil.c is licensed under MIT * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include "ffutil.h" int fferror_print(char *sourcecode_filename, int line, const char *function_name, const char *message) { int myerrno = errno; char* errstr = strerror(myerrno); fprintf(stderr, "%s:%d %s: %s: %s\n", sourcecode_filename , line, function_name, message, errstr); return myerrno; } /* remove \n, assumes UNIX line endings! */ char* ffnchomp(char *s, size_t len) { if(len >= 1 && s[--len] == '\n') s[len] = '\0'; return s; } /* replacement for strtol streamlined for speed */ unsigned long ffparse_ulong(const char *s, const char** end) { const unsigned int base = 10; unsigned long l = 0UL; unsigned char *c = (unsigned char*)s; for(unsigned int digit = *c-'0'; *c && digit < base; digit = *++c-'0') l = (l * base) + digit; *end = (char *)c; return l; } int ffstrncmp(const char* s1, const char* s2, size_t len) { for(size_t i = len; i > 0 && *s1 && *s2 && *s1 == *s2; i--, s1++, s2++) ; return *s1 - *s2; } size_t fffprint_ulong(FILE* file, unsigned long l) { char p[21]; char *c = p + 20; while(l >= 10) { *c-- = '0' + (l % 10); l /= 10; } *c = '0' + l; return fwrite(c, 1, p + 21 - c, file); } /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/ffutil.h000066400000000000000000000041411267377046700155750ustar00rootroot00000000000000/* * Ffindex * written by Andreas Hauser . * Please add your name here if you distribute modified versions. * * Ffindex is provided under the Create Commons license "Attribution-ShareAlike * 3.0", which basically captures the spirit of the Gnu Public License (GPL). * * See: * http://creativecommons.org/licenses/by-sa/3.0/ * * Ffindex is a very simple database for small files. The files are stored * concatenated in one big data file, seperated by '\0'. A second file * contains a plain text index, giving name, offset and length of of the small * files. */ /* In addition ffutil.h and ffutil.c is licensed under MIT * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include int fferror_print(char *sourcecode_filename, int line, const char *function_name, const char *message); char* ffnchomp(char *s, size_t len); int ffstrncmp(const char* s1, const char* s2, size_t len); unsigned long ffparse_ulong(const char *s, const char** end); size_t fffprint_ulong(FILE* file, unsigned long l); /* vim: ts=2 sw=2 et */ ffindex-0.9.9.7/src/nginx/000077500000000000000000000000001267377046700152565ustar00rootroot00000000000000ffindex-0.9.9.7/src/nginx/config000066400000000000000000000003571267377046700164530ustar00rootroot00000000000000ngx_addon_name=ngx_http_ffindex_module HTTP_MODULES="$HTTP_MODULES ngx_http_ffindex_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_ffindex_module.c" CORE_LIBS="$CORE_LIBS -lffindex -L/home/andy/wrk/dev/index/ffindex/src" ffindex-0.9.9.7/src/nginx/ngx_http_ffindex_module.c000066400000000000000000000140521267377046700223270ustar00rootroot00000000000000 /* * Copyright (C) Andreas Hauser */ #include #include #include /* #define _GNU_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include #include */ #include #include typedef struct ffindex_config { ngx_str_t ffdata_filename; ngx_str_t ffindex_filename; FILE * ffdata_file; FILE * ffindex_file; char * ffdata; size_t ffdata_size; ffindex_index_t * ffindex; } ffindex_config_t; //static char * ngx_http_ffindex_setup(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static void * ngx_http_ffindex_create_loc_conf(ngx_conf_t *cf); static char * ngx_http_ffindex_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child); static ngx_int_t ngx_http_ffindex_handler(ngx_http_request_t *req); static ngx_command_t ngx_http_ffindex_commands[] = { { ngx_string("ffdata_filename"), NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_str_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ffindex_config_t, ffdata_filename), NULL }, { ngx_string("ffindex_filename"), NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_str_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ffindex_config_t, ffindex_filename), NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_ffindex_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_ffindex_create_loc_conf, /* create location configuration */ ngx_http_ffindex_merge_loc_conf /* merge location configuration */ }; ngx_module_t ngx_http_ffindex_module = { NGX_MODULE_V1, &ngx_http_ffindex_module_ctx, /* module context */ ngx_http_ffindex_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static void * ngx_http_ffindex_create_loc_conf(ngx_conf_t *cf) { ffindex_config_t *mcf; mcf = ngx_palloc(cf->pool, sizeof(ffindex_config_t)); if (mcf == NULL) { return NULL; } mcf->ffdata_filename.len = 0; mcf->ffindex_filename.len = 0; return mcf; } static char * ngx_http_ffindex_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) { ffindex_config_t * parent_config = parent; ffindex_config_t * child_config = child; if(child_config->ffdata_filename.len && child_config->ffindex_filename.len) { size_t offset; fprintf(stderr, "plen: %ld, clen: %s %ld\n", parent_config->ffdata_filename.len, child_config->ffdata_filename.data, child_config->ffdata_filename.len); //ffindex_index_open(child_config->ffdata_filename.data, child_config->ffindex_filename.data, "r", &data_file, &index_file, &offset); child_config->ffdata_file = fopen(child_config->ffdata_filename.data, "r"); child_config->ffindex_file = fopen(child_config->ffindex_filename.data, "r"); if( child_config->ffdata_file == NULL) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "error ffdata file"); return NGX_CONF_ERROR; } if(child_config->ffindex_file == NULL) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "error ffindex file"); return NGX_CONF_ERROR; } size_t data_size; char *data = ffindex_mmap_data(child_config->ffdata_file, &data_size); child_config->ffdata_size = data_size; child_config->ffdata = data; ffindex_index_t* index = ffindex_index_parse(child_config->ffindex_file, 0); if(index == NULL) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "error parsing ffindex file"); return NGX_CONF_ERROR; } child_config->ffindex = index; ngx_http_core_loc_conf_t *clcf; clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); clcf->handler = ngx_http_ffindex_handler; } return NGX_CONF_OK; } static ngx_str_t ngx_http_ffindex_type = ngx_string("text/plain"); static ngx_int_t ngx_http_ffindex_handler(ngx_http_request_t *req) { ffindex_config_t * ffindex_config = ngx_http_get_module_loc_conf(req, ngx_http_ffindex_module); if (!(req->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) { return NGX_HTTP_NOT_ALLOWED; } if(strncmp("get_data_by_index=", req->args.data, req->args.len)) { size_t index = atol(req->args.data + sizeof("get_data_by_index=")) + 1; // index from 0 request from 1 ffindex_entry_t * entry = ffindex_get_entry_by_index(ffindex_config->ffindex, index); if(entry) { char * data = ffindex_get_data_by_entry(ffindex_config->ffdata, entry); ngx_http_complex_value_t cv; ngx_memzero(&cv, sizeof(ngx_http_complex_value_t)); cv.value.data = data; cv.value.len = entry->length; return ngx_http_send_response(req, NGX_HTTP_OK, &ngx_http_ffindex_type, &cv); } else return NGX_HTTP_NOT_ALLOWED; } else if(strncmp("get_data_by_name=", req->args.data, req->args.len)) { char * name = req->args.data + sizeof("get_data_by_name="); ffindex_entry_t * entry = ffindex_get_entry_by_name(ffindex_config->ffindex, name); if(entry) { char * data = ffindex_get_data_by_entry(ffindex_config->ffdata, entry); ngx_http_complex_value_t cv; ngx_memzero(&cv, sizeof(ngx_http_complex_value_t)); cv.value.data = data; cv.value.len = entry->length; return ngx_http_send_response(req, NGX_HTTP_OK, &ngx_http_ffindex_type, &cv); } else return NGX_HTTP_NOT_ALLOWED; } else return NGX_HTTP_NOT_ALLOWED; } ffindex-0.9.9.7/src/test-unlink.should000066400000000000000000000000141267377046700176230ustar00rootroot00000000000000a fooo fooo ffindex-0.9.9.7/src/test.should000066400000000000000000000000171267377046700163300ustar00rootroot00000000000000a bb fooo fooo ffindex-0.9.9.7/test/000077500000000000000000000000001267377046700143235ustar00rootroot00000000000000ffindex-0.9.9.7/test/data/000077500000000000000000000000001267377046700152345ustar00rootroot00000000000000ffindex-0.9.9.7/test/data/a000066400000000000000000000000021267377046700153670ustar00rootroot00000000000000a ffindex-0.9.9.7/test/data/b000066400000000000000000000000031267377046700153710ustar00rootroot00000000000000bb ffindex-0.9.9.7/test/data/c000066400000000000000000000000031267377046700153720ustar00rootroot00000000000000cc ffindex-0.9.9.7/test/data2/000077500000000000000000000000001267377046700153165ustar00rootroot00000000000000ffindex-0.9.9.7/test/data2/foo000066400000000000000000000000121267377046700160150ustar00rootroot00000000000000fooo fooo ffindex-0.9.9.7/test/testfile000066400000000000000000000000111267377046700160550ustar00rootroot00000000000000testfile