├── .gitignore ├── ChangeLog.md ├── LICENSE ├── Makefile ├── README.md ├── exclude.c ├── fileProcess.c ├── max.c ├── ppurge.c ├── pwalk.c ├── pwalk.h ├── reassemble.py ├── repairshr.c ├── repairshr.h ├── repexcl.c └── report.py /.gitignore: -------------------------------------------------------------------------------- 1 | pwalk 2 | a.out 3 | test.lst 4 | test 5 | output* 6 | *.o 7 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to pwalk will be documented in this file. 3 | 4 | ## 2023.09.14 5 | - ppurge tested on production BeeGFS file system to maintain delete30 tempary file 6 | system. 7 | 8 | ## 2023.08.14 9 | - Initial work on ppurge for purging files based on mtime age 10 | 11 | ## 2021.07.14 12 | - Add Change Owner feature. File owner is changed conditionally. Two arguments 13 | are required; --chown_from and -chown_to UID:GID. Check everyfile for 14 | "chown_from", if True change the owner to "chown_to". 15 | - A parallel file traversal is a valuable tool for managing very large file 16 | POSIX file systems. The implementation of the change-owner feature is the 17 | first step to make pwalk a general-purpose file operation tool. For each 18 | file found in the filesystem, pwalk executes the fileProcess function. The 19 | call to fileProcess is a function pointer that can set to new types of file 20 | operation functions. Additional file operations are easy to implement via 21 | the function pointer to "fileProcess." 22 | 23 | ## 2020.02.18 24 | ### Fixes 25 | - Parent Inode is not correct for Beegfs, change output format for inode 26 | 27 | ## 2017.05.31 28 | ### Feature 29 | - Add feature to exclude directories. command line option --exclude filename. 30 | filename contains a list of directory names to skip. pwalk can be used with 31 | relative and absolute paths. Be sure to use the correct form of the path 32 | to exclude directories. 33 | 34 | ## 2016.12.12 35 | ### Fixes 36 | - pwalk escapes properly on filename, but not extension: 37 | - escaping commas and backslash within quoted fields (required for PostgreSQL) 38 | 39 | ## 2016.12.09 40 | ### Added 41 | - setuid to root. pwalk needs to run as root to collect all file system information. 42 | - move changelog from source code to ChangeLog.md (what you are reading now) 43 | 44 | ## 2015.03.07 45 | - Fix bug with directory file extensions having more than one dot '.' in the file name. 46 | 47 | ## 2013.08.02 48 | - Add GNU license, --version command line arg added 49 | - becomes a github project 50 | 51 | ## 2013.10.07 52 | ### Added 53 | - Output directory depth. Inital directory argument is given depth of zero regardless of its position 54 | in the file system. Only the inital dirctory (root) has the depth of zero. 55 | - Output parent inode for every file. Each file has its inode and parent inode. 56 | This will allow a topological view of the file system. The top level dir has a 57 | parnet inode of 0. 58 | 59 | ### Changes 60 | - value of "fileCnt" defaults to -1 if file is not a directory. Zero is valid 61 | file count for a directory. This change will effect SQL queries written for earlier 62 | versions. Earlier versions were incorrent to asume fileCNT == 0 as regular file. 63 | - Change "fileCnt" to numeric. Removing the extra quotes from numeric fileds in the 64 | CSV file will save a small amount of file space for the output files. 65 | (a few megabytes for some of our larger directories) 66 | 67 | ### Improvements 68 | - data structures are cleaned up. changes made to improve thread 69 | performance. Expecthing this version to be 10% to 15% faster than previous. 70 | 71 | ## 2013.08.01 72 | - improve command line argument errors 73 | 74 | ## 2012.10.09 75 | ### Added 76 | - --NoSnap command line arrgument added too ignore directories that are named .snapshot 77 | 78 | ## 2010.11.29 79 | - Add mutex for printStat 80 | 81 | ## 2010.03.24 82 | ### Milstone 83 | - Recomended that pwalk be run on physical hardware. Slight network latencies 84 | introduced by virtualization can add up to a significant amount of time 85 | when 10's of billion's of operations are required. 86 | - New physical hardware is available to run pwalk. 87 | - 16 threads are only using about 20% CPU with 10% IO wait. Based on this 88 | the default thread count will be doubled to 32. 89 | 90 | ## [pwalk v2] 2010.02.01 91 | ### Fixed 92 | - pwalk v1 did not detach nor did it join the theads; v2 fixes this short comming; 93 | 94 | ## [pwalk v1] 2010.01.11 95 | ### Major 96 | - Complete re-write of walkv4 transforming it into pwalk. 97 | pwalk is a threaded version of walkv4. 98 | pwalk will call fileDir as a new thread until MAXTHRDS is reached. 99 | 100 | ## 2010.01.08 101 | - Added: file name extension; 102 | Extension is defined as the last part of the name after a Dot "." 103 | if no dot is found extension is empty "" 104 | - Added: accept multible dirctory names as cmd line argument 105 | - Fix issue with directory detection: 106 | This line of code has been replaced 107 | if ( f.st_mode & S_IFDIR && (f.st_mode & S_IFMT != S_IFLNK) ) 108 | With this new line of code: 109 | if ( S_ISDIR(f.st_mode) ) 110 | 111 | ## 2009.12.30 112 | - size for dir should just be dir size; Fix; count returns 0 113 | - for normal files and count of just the local directory; Previously count 114 | - return the recursive file count for the whole tree. 115 | 116 | ## 2009.04.12 [3.1] 117 | - replaced constants with "FILENAME_MAX", 118 | - Size of directory is size of all files in directory plus itself 119 | - Added printStat function 120 | - Add file count field. If the file is a directory 121 | 122 | ## 2009.05.18 123 | - check for control charaters and double qutoes in file names 124 | - escape double quotes and print bad file names to stderr 125 | - Bad file names contain C0 control codes. Remove C0 from files names for CSV output 126 | 127 | ## 2008.04.01 128 | - Add: CSV output for database use 129 | 130 | ## 2004.07.06 131 | - add flags -a and -k, to match features of du 132 | 133 | ## 2002.09.06 134 | - change output to look exactly like du -a 135 | 136 | ## 2002.09.04 137 | - walk.c; walk the directory and gather stats. This is a more flexible version of du to 138 | allow system admins to collect stats on different elements of the inode. Example: Create 139 | histograms of file counts/sizes by uid and or gid etc... 140 | 141 | ## 1997.03.20 142 | - Although this is the first documented date for this file (walk.c) I have versions that date from 1988. 143 | - Starts as an exercise of how to use UNIX calls; opendir and readdir to simulate ls command. 144 | - Over the years this basic tool had many uses and file names: dir.c, walk.c, walkv2,3,4, pwalkfs.c 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | Tools to help system administors manage very large file systems 294 | Copyright (C) 2013 John Dey 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -O2 -Wall 3 | LDFLAGS = -lpthread 4 | 5 | default: all 6 | 7 | all: pwalk ppurge 8 | 9 | pwalk: pwalk.c exclude.c fileProcess.c 10 | $(CC) $(CFALGS) $(LDFLAGS) -o pwalk exclude.c fileProcess.c pwalk.c 11 | 12 | ppurge: ppurge.c 13 | $(CC) $(CFLAGS) $(LDFLAGS) -o ppurge ppurge.c 14 | 15 | install: 16 | chown root ppurge 17 | chmod 4755 ppurge 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | filesystem-reporting-tools 2 | ========================== 3 | 4 | Tools to help system administrators monitor very large file systems 5 | 6 | ### pwalk ### 7 | pwalk (Parallel Walk). Walk a file system using many threads in parallel. 8 | During the walk output inode information for every file. One line of output per file. 9 | 10 | ### Build and install ### 11 | pwalk is a single C program. Once compiled pwalk runs on every flavor of 12 | Linux. Default Linux builds do not have the libraries needed to build pwalk. 13 | Installing the 'lib32gcc1' package to Ubuntu provides all the libraries and 14 | tools necessary to build pwalk. To build pwalk just compile pwalk.c. This one 15 | gcc command is that is needed. 16 | 17 | gcc -pthread pwalk.c exclude.c fileProcess.c -o pwalk 18 | 19 | ### Purpose ### 20 | pwalk was written to solve the problem of reporting disk usage for large file 21 | systems. Single name space file systems with tens of millions of files are 22 | time consuming to traverse and report on. Traditional file systems like NFS 23 | store file meta data within the file system. The only way to discover and 24 | report on all meta data is to walk the whole file system tree. pwalk walks 25 | a file system in parallel using many threads. 26 | 27 | ### Why write pwalk? 28 | Large file systems that support interactive users do not grow in a 29 | deterministic way. As a system administrator I was not able to answer simple 30 | questions like: Who used the last 10TB of disk space last night? There is 31 | no efficient method of discovering this information with very large file 32 | systems. The UNIX du (disk usage) command can take days to complete with 33 | large file systems. This is a long time to wait while your file system is full 34 | and users are calling you. Pwalk was written to solve the problem of walking large 35 | single name space file system in a timely manner. 36 | The typical usage of pwalk is to report on NFS mounted file systems. 37 | 38 | ### Output ### 39 | November 2013 - Two new fields have been added to the output. 40 | Parent Inode and directory level have been added to the 41 | output. parent Inode is output for every file. Parent inode for the top 42 | level directory is set to zero which identifies the top of the tree. Directory 43 | level counter starts at zero relative to the directoy that is being reported on. 44 | The top level directory has a depth of -1. 45 | 46 | The output of pwalk is designed to be loaded into a relational database. 47 | Large file systems are difficult to examine browse or examine by hand. A 48 | practical approach to examine the file system metadata is with SQL. Pwalk 49 | performs a ‘stat’ on each file and every field of the inode is reported in 50 | CSV format. One file is reported per line of output. pwalk complains about 51 | file names that do not load into 'MYSQL' varchar fields. File names are 52 | POSIX compliant but MYSQL has many limits about what can be loaded into a 53 | varchar field. In my environement pwalk complains about a few hundred files per file 54 | system which is a very very small percentage of the 52 million files. There 55 | should be a flag to report all file names and not just DB safe file names. 56 | Output can seem to be random since the program is threaded but every 57 | file does get reported. 58 | ctime, mtime and atime are reported natively in UNIX epoch time 59 | (large integers). The file mode is reported as an octal string. Two additional 60 | fields are populated for directories: count of files in the directory and 61 | the sum of file sizes of all files in the directory. File count is -1 if a 62 | file is not a directory. All file and directory sizes are 63 | reported in bytes. Symbolic links are reported (they are a file) but symbolic 64 | links are never followed. 65 | 66 | April 27, 2017; st_dev has been added to the output. st_dev will allow tracking 67 | of file system volume. This might lead to a new command line option 68 | to prevent crossing of mounted file systems. Similar to find -x. 69 | 70 | ### Usage ### 71 | Pwalk takes a single argument, which is the name of the file system to report 72 | on. In practice pwalk should be run as root or as setuid. Exposing NFS to 73 | the root user is not a good practice. I run pwalk from a system only used by 74 | administrative staff. The NFS file systems to be reported on by pwalk are 75 | exported read only to the admin machine. 76 | 77 | ### Options 78 | 79 | --NoSnap Ignore directories that match the name .snapshot. 80 | 81 | --exclude filename 82 | 83 | Exclude expects a single argument which is the name of a file. 84 | The exclude file contains paths of directories to skip, one path per line. 85 | pwalk will run with absolute or relative paths. The format of the pathnames 86 | in the exclude file should match the output of pwalk. 87 | 88 | Conditionally Change File Owner. Two Flags are required. A list of files that 89 | have been changed is output. 90 | --chown_from UID 91 | --chown_to UID:GID 92 | 93 | ### Reporting ### 94 | SQL allows you to look at file systems differently and more efficiently than 95 | just browsing a file system by hand. As an example: How many files have been 96 | created in the last seven days, sorted by size and grouped by user. 97 | 98 | select uid, count(*), sum(size) from FSdata where ctime > unix_timestamp( date_sub(now(), interval 7 day) ) group by uid order by 3; 99 | 100 | Two additional data fields are reported by pwalk when a file is a directory; 101 | sum in bytes and number of files contained in each directory. If a file is not 102 | a directory the ‘file count’ field is zero. Collecting these additional fields 103 | is almost free while walking the tree but very difficult to create with a SQL 104 | query. These fields allow you to easily report on the largest directives. 105 | Very large directories (greater than one million files) create performance 106 | issues with applications. Knowing the size in bytes for a given directory 107 | can help discover application issues, big data users etc. 108 | 109 | ### Performance ### 110 | pwalk can be 10 to 100 times faster than the UNIX disk usage command ‘du’. The 111 | performance of pwalk is based on many variables: performance of your storage 112 | system, host system and the layout of your files. Reporting on a directory is 113 | the smallest division of work performed by a single tread. Run time for a 114 | directory with ten million files will be no faster than the UNIX command ls. 115 | What makes pwalk faster than du is that many directories are being scanned at 116 | once. On a small file system pwalk can be slower than du because of the 117 | extra time needed to create and manage threads. You should expect pwalk to 118 | perform about 8,000 to 30,000 stat commands per second. 119 | 120 | Example performance metric: 50,000,000 files at a rate of 20,000 stats per 121 | second should take about 41 minutes to complete. 122 | 123 | ### Reporting Tools ### 124 | Robert McDermott has written the [pwalk_reporter](https://github.com/robert-mcdermott/pwalk_reporter) 125 | utility takes the output from the pwalk utility and provides summary statistics about the filesystem. 126 | 127 | It provides the following summary statistics: 128 | 129 | * Total file count and total file size of the filesystem 130 | * A histogram of file ages broken down by file count and size in a fixed set of bins. The histogram can use either 'mtime' (default) or 'atime' I plan to make the histogram bins either automatic or provide the ability to specify them in a future release. 131 | * The top 100 file types by total size 132 | * The top 100 largest directories by size 133 | 134 | ### repair-shared (a variation of pwalk for file system repair) 135 | 136 | repair-shared is an experimental tool that is derived from pwalk and will repair permissions in shared folders. It was generated by Claude.ai and is only lightly tested. 137 | 138 | compile: `gcc -pthread repairshr.c repexcl.c -o /usr/local/bin/repair-shared` 139 | 140 | usage: `./repair-shared --NoSnap --dry-run --exclude otherfolder --change-gids 1234,5678 /my/shared/folder` 141 | 142 | 143 | #### Prompt to Claude.ai 144 | 145 | This initial prompt was sent to the Claude 3.5 Sonnet Model (along with the pwalk source code) and Claude generated 100% of repairshr.c repairshr.h and repexcl.c: 146 | 147 | pwalk is a tool that crawls a posix file system in parallel and reports the metadata to a csv file structure to STDOUT. Use the logic of this tool and write a new tool called repair-shared that uses the same command line arguments --NoSnap, --exclude and folder to scan a file system but creates a new tool that can repair permissions in a shared folder so that the content of that folder is accessible to the members of the security group with which these folders are shared. 148 | 149 | Implement these features while logging all changes to STDOUT and errors to STDERR 150 | 151 | * Set the setgid bit on all folders if not set. 152 | * If a file or folder has a gidNumber that is identical to the uidNumber (private group) or is gidNumber 0 (root) change the group ownership to the group that owns the first found folder up the tree where that gidNumber is not identical to the uidNumber owning that folder and it not 0. Stop searching at the root folder where the crawl began and print an error if no group can be found. Only print one error per tree (e.g. root folder is owned by private group) 153 | * add an option --change-gids which can have a comma separated list of gids that are treated the same way as private groups. 154 | * Ensure that each file has at least group read permissions and each folder has at least group read+execute permissions. (chmod +g) 155 | 156 | also implement a --dry-run argument for testing only where no changes are made to the file system or file system metadata. 157 | 158 | ### Author ### 159 | Pwalk is written by John Dey. I have been a UNIX/Linux administrator since 160 | the days of VAXes and BSD 4.2. I have been privileged to support scientific 161 | researchers and their data since the mid 1990’s. I hope you will find pwalk 162 | to be useful. 163 | -------------------------------------------------------------------------------- /exclude.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | extern char *exclude_list[512]; 9 | 10 | int 11 | check_exclude_list(char *fname) 12 | { 13 | int i =0; 14 | while(exclude_list[i]) 15 | if ( !strcmp(exclude_list[i++], fname)) 16 | return 1; 17 | return 0; 18 | } 19 | 20 | void 21 | verify_paths(char *list[]) 22 | { 23 | int i=0; 24 | struct stat f; 25 | 26 | while(list[i]) { 27 | if ( lstat( list[i], &f ) == -1 ) 28 | fprintf(stderr, "verify not found: %s", list[i]); 29 | i++; 30 | } 31 | } 32 | 33 | void 34 | get_exclude_list(char* fname, char *list[]) 35 | { 36 | FILE *fp; 37 | char *a, buf[1024]; 38 | size_t len; 39 | int i =0; 40 | 41 | fp = fopen(fname, "r"); 42 | if ( fp == NULL ) { 43 | fprintf(stderr, "could not open: %s\n", fname); 44 | exit(1); 45 | } 46 | 47 | while(fgets(buf, 1024, (FILE*) fp)) { 48 | len = strlen(buf); 49 | buf[len-1] = '\0'; 50 | a = (char*)malloc(len); 51 | list[i++] = strncpy(a, buf, len); 52 | } 53 | list[i] = NULL; 54 | fclose(fp); 55 | } 56 | -------------------------------------------------------------------------------- /fileProcess.c: -------------------------------------------------------------------------------- 1 | /* 2 | * fileProcess.c 3 | 4 | Copyright (C) (2013-2016) John F Dey 5 | 6 | This program is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU General Public License 8 | as published by the Free Software Foundation; either version 2 9 | of the License, or (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | 20 | */ 21 | 22 | /* 23 | 24 | For each file found by Pwalk, process the file. 25 | File processing functions go in this file. File process routines must 26 | keep the same arguments as defined by the prototype fileProcess() 27 | 28 | */ 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include "pwalk.h" 38 | 39 | /* conditioanally change file ownership --chown_from --chown_to */ 40 | extern uid_t UID_orig, UID_new; 41 | extern gid_t GID_new; 42 | extern int chown_flag; 43 | 44 | /* Escape CSV delimeters */ 45 | void 46 | csv_escape(char *in, char *out) 47 | { 48 | char *t, *orig; 49 | int cnt = 0; 50 | 51 | t = out; 52 | orig = in; 53 | while ( *in ) { 54 | if ( *in == '"' ) 55 | *out++ = '"'; 56 | if ( (unsigned char)*in < 32 ) { 57 | in++; 58 | cnt++; 59 | } else 60 | *out++ = *in++; 61 | *out = '\0'; 62 | } 63 | if ( cnt ) 64 | fprintf( stderr, "Bad File: %s\n", orig); 65 | } 66 | 67 | 68 | /* 69 | * conditionally change file ownership 70 | * if file owned by UID_orig chown UID_new:GID_new 71 | */ 72 | void 73 | changeOwner( struct threadData *cur, char *exten, struct stat *f, 74 | long fileCnt, /* directory only - count files in directory */ 75 | long dirSz ) /* directory only - sum of files within directory */ 76 | { 77 | int stat; 78 | char fname[FILENAME_MAX]; 79 | 80 | if ( f->st_uid == UID_orig ) { 81 | csv_escape(cur->dname, fname); 82 | if (stat = lchown(cur->dname, UID_new, GID_new)) 83 | fprintf(stderr, "could not chown %s\n", fname); 84 | else { 85 | fputs(fname, stdout); 86 | fputc('\n', stdout); 87 | } 88 | } 89 | } 90 | 91 | /* 92 | * printStat this needs to be in a crital secion (and it is!) 93 | */ 94 | void 95 | printStat( struct threadData *cur, char *exten, struct stat *f, 96 | long fileCnt, /* directory only - count files in directory */ 97 | long dirSz ) /* directory only - sum of files within directory */ 98 | { 99 | char out[FILENAME_MAX+FILENAME_MAX]; 100 | char fname[FILENAME_MAX]; 101 | char exten_csv[FILENAME_MAX]; 102 | ino_t ino, pino; 103 | long depth; 104 | 105 | csv_escape(cur->dname, fname); 106 | if ( exten ) 107 | csv_escape(exten, exten_csv); 108 | else 109 | exten_csv[0] = '\0'; 110 | if ( fileCnt != -1 ) { /* directory */ 111 | ino = f->st_ino; pino = cur->pinode; depth = cur->depth - 1;} 112 | else { /* Not a directory */ 113 | ino = f->st_ino; pino = cur->pstat.st_ino; depth = cur->depth; } 114 | sprintf ( out, "%ju,%ju,%ld,\"%s\",\"%s\",%ld,%ld,%ld,%ld,%ld,%d,\"%07o\",%ld,%ld,%ld,%ld,%ld\n", 115 | (uintmax_t)ino, (uintmax_t)pino, depth, 116 | fname, exten_csv, (long)f->st_uid, 117 | (long)f->st_gid, (long)f->st_size, (long)f->st_dev, 118 | (long)f->st_blocks, (int)f->st_nlink, 119 | (int)f->st_mode, 120 | (long)f->st_atime, (long)f->st_mtime, (long)f->st_ctime, 121 | fileCnt, dirSz ); 122 | fputs( out, stdout ); 123 | } 124 | -------------------------------------------------------------------------------- /max.c: -------------------------------------------------------------------------------- 1 | /* 2 | * check lenght of max file name and path 3 | */ 4 | #include 5 | #include 6 | #include 7 | 8 | int 9 | main( int argc, char* argv[] ) 10 | { 11 | 12 | printf( "FILENAME_MAX : %d\n", FILENAME_MAX ); 13 | printf( "NAME_MAX: %d\n", NAME_MAX ); 14 | printf( "PATH_MAX : %d\n", PATH_MAX ); 15 | } 16 | 17 | -------------------------------------------------------------------------------- /ppurge.c: -------------------------------------------------------------------------------- 1 | /* 2 | ppurge.c Parrallel Walk a file system and remove old files 3 | 4 | Copyright (C) (2023) John F Dey 5 | 6 | This program is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU General Public License 8 | as published by the Free Software Foundation; GPL version 3 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program; If not, see . 17 | 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | /* 34 | ppurge Parallel Purge 35 | 36 | ppurge is a tool for maintaining HPC scratch storage volumes by removing files 37 | past a certain age. 38 | File purging is accomplished with two steps. Step one is to mark a file as 39 | "purgable" by moving the file into a temporary cache directory named .ppurge. 40 | Ppurge subdirectories are local to the directory where the data files reside. 41 | The files in `.ppurge` are kept for an additional n days until removed permanently. 42 | 43 | The example usage case are volumes attached to HPC systems which have names like 44 | "/scratch30". Ppurge should be run once per day. Files are only removed from the 45 | volme after n+n days. The first `n` days the files are moved to `.ppurge`. Then after 46 | an additional `n` days the files are removed (unlink). 47 | 48 | Ppurge should only run on volumes that do not have snapshots. The storage volume 49 | should be a single volume that is not bridged. 50 | 51 | - File age is based on `mtime`. 52 | - `.ppurge` directories only contain files, no directories are moved. 53 | - mtime and atime are not affected by move (rename) 54 | - Remove files from the `.ppurge` cache based on `mtime`. 55 | - during the cache period users can recover files from `.ppurge` 56 | by using the "move" command. Do not let users use "copy" cp. 57 | mv .ppurge/I_need_this_file . 58 | - .ppurge directory has user sticky bit set. Only the file owners can move or delete files 59 | 60 | When the .ppurge directory is empty it will be removed. 61 | 62 | At present Ppurge does not remove directories. There are many structal 63 | directories in scatch systems which could be removed due to in activity. 64 | But not removing directories will leave many empty directory trees in 65 | scratch file systems. A feature for Deleting directories could be implemented 66 | with a directory level test. For scratch volumes with well defined directory 67 | structure. '/scratch30/department/user/project/Purge at this level' 68 | if DEPTH > 4 purge directories 69 | 70 | Output is written to stdout. Output is a list of all files that are purged or removed. 71 | Output is wirtten in CSV format. First character of each line is 'P' or 'R', for Purged or Removed. 72 | 73 | Format of output: 74 | type, depth, fname, UID, GID, st_size, st_mode, atime, mtime, ctime 75 | 76 | ppurge creates a log file with the following name ppurge-YYYY.MM.DD-HH_MM_SS.log 77 | Internal error messages are written to the log file. 78 | 79 | A list of pathname with illegal characters are written to the log file 80 | */ 81 | 82 | static char *whoami = "ppurge"; 83 | static char *Version = "0.1.0 Aug 14 2023 John F Dey john@fuzzdog.com"; 84 | 85 | /* 86 | 0.1.0 Initial version. Code base copied from pwalk. Purging and reporting 87 | seems to difficult to perform in one walk of the tree. Purging 88 | will be a dedicated process. 89 | */ 90 | 91 | #define DEBUG 2 // [0, 1, 2] 92 | 93 | #if defined(DEBUG) && DEBUG == 1 94 | #define DEBUG_1(fmt, args...) fprintf(stderr, "DEBUG: %s(): " fmt, __func__, ##args) 95 | #elif defined(DEBUG) && DEBUG == 2 96 | #define DEBUG_1(fmt, args...) fprintf(stderr, "DEBUG: %s(): " fmt, __func__, ##args) 97 | #define DEBUG_2(fmt, args...) fprintf(stderr, "DEBUG: %s(): " fmt, __func__, ##args) 98 | #else 99 | #define DEBUG_1(fmt, args...) /* Don't do anything in release builds */ 100 | #define DEBUG_2(fmt, args...) /* Don't do anything in release builds */ 101 | #endif 102 | 103 | FILE *Logfd; /* error log */ 104 | time_t Ptime; /* Purge all files older than this time stamp (less than)*/ 105 | time_t Rtime; /* Remove all files older than this time stamp (Ptime * 2) */ 106 | int DEPTH = 0; /* possible furture use for directory purging */ 107 | 108 | struct threadData { 109 | char dname[FILENAME_MAX+1]; /* full path and basename */ 110 | int dirfd; /* file pointer to directory*/ 111 | long depth; /* directory depth */ 112 | long THRDid; /* unique ID increaments with each new THRD */ 113 | int flag; /* 0 if thread; recursion > 0 */ 114 | pthread_t thread_id; /* system assigned */ 115 | pthread_attr_t tattr; 116 | }; 117 | 118 | #define MAXTHRDS 32 119 | int ThreadCNT = 1; /* ThreadCNT < MAXTHRDS */ 120 | int totalTHRDS = 0; 121 | struct threadData tdslot[MAXTHRDS]; 122 | pthread_mutex_t mutexFD; 123 | 124 | void 125 | printVersion( ) { 126 | fprintf(stderr, "%s version %s\n", whoami, Version ); 127 | fprintf(stderr, "%s Copyright (C) 2013 John F Dey\n", whoami ); 128 | fprintf(stderr, "ppurge comes with ABSOLUTELY NO WARRANTY;\n" ); 129 | fprintf(stderr, "This is free software, you can redistribute it and/or\n"); 130 | fprintf(stderr, "modify it under the\nterms of the GNU General Public"); 131 | fprintf(stderr, " License as published by the Free Software Foundation;\n"); 132 | fprintf(stderr, "GPL version 3 License\n"); 133 | } 134 | 135 | 136 | void 137 | printHelp() 138 | { 139 | printf("Useage : %s (fully qualified file name)\n", whoami); 140 | printf("ppurge should be run daly on volumes with the same value for purgeDays\n"); 141 | printf("Flags: --help\n --version\n" ); 142 | printf(" --purgeDays (positive integer) Purge files older than n days.\n"); 143 | } 144 | 145 | /* Escape CSV delimeters */ 146 | void 147 | csv_escape(char *in, char *out) 148 | { 149 | char *orig; 150 | int cnt = 0; 151 | 152 | orig = in; 153 | while ( *in ) { 154 | if ( *in == '"' ) 155 | *out++ = '"'; 156 | if ( (unsigned char)*in < 32 ) { 157 | in++; 158 | cnt++; 159 | } else 160 | *out++ = *in++; 161 | *out = '\0'; 162 | } 163 | if ( cnt ) 164 | fprintf( Logfd, "Bad File Name: %s\n", orig); 165 | } 166 | 167 | /* 168 | * purgeLog 169 | * log files that are moved to purge, and files that are removed. 170 | * Initial release of ppurge only purges file. Asume no directories are purged. 171 | * 172 | */ 173 | void 174 | purgeLog( struct threadData *cur, char type, struct stat *f) 175 | { 176 | char out[FILENAME_MAX+FILENAME_MAX]; 177 | char fname[FILENAME_MAX]; 178 | long depth; 179 | 180 | csv_escape(cur->dname, fname); 181 | depth = cur->depth; 182 | sprintf ( out, "%c,%ld,\"%s\",%ld,%ld,%ld,\"%07o\",%ld,%ld,%ld\n", 183 | type, depth, fname, (long)f->st_uid, (long)f->st_gid, (long)f->st_size, (int)f->st_mode, 184 | (long)f->st_atime, (long)f->st_mtime, (long)f->st_ctime); 185 | fputs( out, stdout ); 186 | } 187 | 188 | /******************************** 189 | opendir .ppurge directory 190 | if mtime < PPURGE_tm remove the file 191 | return the number of files which are not deleted 192 | 193 | when all the files are deleted, then .ppurge dir can be removed 194 | *********************************/ 195 | int 196 | rm_purged(struct threadData *cur, char* DirName, time_t purgedir_atime, int purgedir_fd) 197 | { 198 | DIR *purgeDIR; 199 | int ret; 200 | struct dirent *d; 201 | struct stat f; 202 | long int fcount =0; 203 | char *s, *t, *end_dname; 204 | 205 | DEBUG_1("check purgedir: %s\n", DirName); 206 | if ( (purgeDIR = fdopendir( purgedir_fd )) == NULL ) { 207 | fprintf( Logfd, "rm_purged - opendir error: %s\n", DirName ); 208 | return -1; 209 | } 210 | 211 | s = cur->dname + strlen(cur->dname); 212 | *s++ = '/'; 213 | end_dname = s; 214 | while ( (d = readdir( purgeDIR )) != NULL ) { 215 | if ( strcmp(".", d->d_name) == 0 ) continue; 216 | if ( strcmp("..", d->d_name) == 0 ) continue; 217 | if ( fstatat (purgedir_fd, d->d_name, &f, 0 ) == -1 ) { 218 | fprintf( Logfd, "fstatat: '%s' %s\n", d->d_name, strerror(errno)); 219 | continue; 220 | } 221 | if (purgedir_atime < Ptime && f.st_mtime < Rtime) { 222 | s = d->d_name; t = end_dname; 223 | while ( *s ) /* copy file name to end of current path */ 224 | *t++ = *s++; 225 | *t = '\0'; 226 | if ((ret =unlinkat(purgedir_fd, d->d_name, 0)) != 0) { 227 | fprintf( Logfd, "rm_purged - unlink failed: '%s' %s\n", d->d_name, strerror(errno)); 228 | } else { 229 | purgeLog( cur, 'R', &f); 230 | } 231 | } else 232 | fcount +=1; 233 | } 234 | DEBUG_1("%s number of files: %ld\n", DirName, fcount); 235 | closedir(purgeDIR); 236 | return fcount; 237 | } 238 | 239 | /* Open/Create .ppurge directory */ 240 | int 241 | create_ppurge(int dirfd, time_t *purgedir_atime) 242 | { 243 | int purgedir_fd = -1; 244 | struct stat f; 245 | int ret; 246 | 247 | /* test if directory exists before creating */ 248 | DEBUG_1("\n"); 249 | if ((purgedir_fd = openat( dirfd, ".ppurge", O_DIRECTORY |O_RDONLY)) != -1) 250 | if ((ret = fstatat( dirfd, ".ppurge", &f, 0)) != -1 ) 251 | *purgedir_atime = f.st_atime; 252 | else 253 | fprintf(Logfd, "create_ppurge - fstatat_1: %s\n", strerror(errno)); 254 | else { 255 | if ((ret = mkdirat(dirfd, ".ppurge", 01777 )) == 0 ) { 256 | if ((purgedir_fd = openat( dirfd, ".ppurge", O_DIRECTORY |O_RDONLY)) == -1 ) 257 | fprintf(Logfd, "create_ppurge - openat .ppurge: %s\n", strerror(errno)); 258 | *purgedir_atime = time(NULL); 259 | } else 260 | fprintf(Logfd, "create_ppurge - mkdirat .ppurge: %s\n", strerror(errno)); 261 | } 262 | return purgedir_fd; 263 | } 264 | 265 | /******************************** 266 | Open a directory and read the conents. 267 | call opendir with path passed in as an argument 268 | stat every file from opendir 269 | 270 | If maxthread is not reached creat a new thread and call self 271 | If no threads available Recursively call self for each directory 272 | from opendir. 273 | 274 | *********************************/ 275 | void 276 | *fileDir( void *arg ) 277 | { 278 | char *s, *t, *end_dname; 279 | int slot =0, ret; 280 | int fcount; 281 | DIR *dirp; 282 | int subfd, purgedir_fd = -1; 283 | time_t purgedir_atime; 284 | long localCnt =0; /* number of files in a specific directory */ 285 | struct dirent *d; 286 | struct stat f; 287 | struct threadData *cur, thrd_inst = {.THRDid = -1}, *thrd_ptr = &thrd_inst; 288 | 289 | cur = (struct threadData *) arg; 290 | DEBUG_2("threadID=%ld,rdepth=%ld,file=%s\n", cur->THRDid, cur->depth, cur->dname); 291 | if ((dirp = fdopendir( cur->dirfd )) == NULL ) { 292 | fprintf( Logfd, "Locked Dir: %s\n", cur->dname ); 293 | goto return_thread; 294 | } 295 | s = cur->dname + strlen(cur->dname); 296 | *s++ = '/'; 297 | end_dname = s; 298 | while ( (d = readdir( dirp )) != NULL ) { 299 | if ( d->d_name[0] == '.' && 300 | (!d->d_name[1] || (d->d_name[1]=='.' && !d->d_name[2]))) continue; 301 | s = d->d_name; t = end_dname; 302 | while ( *s ) /* copy file name to end of cur->dname */ 303 | *t++ = *s++; 304 | *t = '\0'; 305 | if ( fstatat( cur->dirfd, d->d_name, &f, AT_SYMLINK_NOFOLLOW) == -1 ) { 306 | fprintf( Logfd, "threadID=%ld,rdepth=%d fstatat: '%s' %s\n", 307 | cur->THRDid, cur->flag, strerror(errno), cur->dname); 308 | continue; 309 | } 310 | fprintf(stderr, "%8ld %s\n",f.st_size, cur->dname); 311 | /* Follow Sub dirs recursivly but don't follow links */ 312 | if ( S_ISDIR(f.st_mode) ) { 313 | if ( !strcmp(".ppurge", d->d_name)) { 314 | if (purgedir_fd == -1) { 315 | purgedir_fd = openat(cur->dirfd, ".ppurge", O_RDONLY); 316 | purgedir_atime = f.st_atime; 317 | } 318 | continue; 319 | } 320 | s = d->d_name; t = end_dname; 321 | while ( *s ) /* copy file name to end of current path */ 322 | *t++ = *s++; 323 | if ((subfd = openat(cur->dirfd, d->d_name, O_RDONLY)) == -1 ) { 324 | fprintf(Logfd, "openat fail: %s\n", cur->dname); 325 | continue; 326 | } 327 | DEBUG_1("follow directory: %s\n", cur->dname); 328 | pthread_mutex_lock (&mutexFD); 329 | if ( ThreadCNT < MAXTHRDS ) { 330 | slot = 0; 331 | while ( slot < MAXTHRDS ) { 332 | if ( tdslot[slot].THRDid == -1 ) { 333 | thrd_ptr = &tdslot[slot]; 334 | thrd_ptr->THRDid = totalTHRDS++; 335 | thrd_ptr->flag = 0; /* recurse flag reset for thread instance */ 336 | thrd_ptr->dirfd = subfd; 337 | break; 338 | } 339 | slot++; 340 | } 341 | ThreadCNT++; /* allocate the thread */ 342 | } else { 343 | thrd_ptr = &thrd_inst; 344 | thrd_ptr->THRDid = cur->THRDid; 345 | thrd_ptr->flag = cur->flag + 1; 346 | thrd_ptr->dirfd = subfd; 347 | } 348 | pthread_mutex_unlock (&mutexFD); 349 | /* create ponter to tdslot that will be used for next 350 | call to fileDir - local or from array - shorten next block of 351 | code 352 | */ 353 | strcpy( thrd_ptr->dname, (const char*)cur->dname ); 354 | thrd_ptr->depth = cur->depth + 1; 355 | if ( thrd_ptr->THRDid != cur->THRDid ) { /* new thread available */ 356 | DEBUG_1("creating new thread: %s\n", thrd_ptr->dname); 357 | pthread_create( &tdslot[slot].thread_id, &tdslot[slot].tattr, 358 | fileDir, (void*)thrd_ptr ); 359 | } else 360 | fileDir( (void*) thrd_ptr ); 361 | } else { /* regular file */ 362 | if (f.st_mtime <= (time_t)0 || f.st_atime <= (time_t)0) { // BeeGFS issue with empty mtime 363 | fprintf(Logfd, "bad mtime: %s\n", cur->dname); 364 | if ((ret = utimensat(cur->dirfd, d->d_name, NULL, 0)) != 0) 365 | fprintf(Logfd, "utimes fail: %s\n", cur->dname); 366 | continue; 367 | } 368 | if ( (f.st_mode & S_IFMT) == S_IFLNK) { 369 | DEBUG_1("link:%s\n", cur->dname); 370 | continue; 371 | } 372 | if ( f.st_mtime < Ptime) { 373 | DEBUG_1("purge: %s\n", cur->dname); 374 | if ( purgedir_fd == -1 ) 375 | purgedir_fd = create_ppurge(cur->dirfd, &purgedir_atime); 376 | if (renameat(cur->dirfd, d->d_name, purgedir_fd, d->d_name) == -1) { 377 | fprintf(Logfd, "BADNESS %s could not be moved to .ppurge: %s\n", cur->dname, strerror(errno)); 378 | } else { 379 | // need full path name for csv output 380 | purgeLog( cur, 'P', &f); 381 | } 382 | } else 383 | localCnt++; 384 | } 385 | } 386 | if ( purgedir_fd != -1 ) { 387 | fcount = rm_purged(cur, cur->dname, purgedir_atime, purgedir_fd); 388 | if ( fcount == 0 ) /* directory is empty */ 389 | if ((ret = unlinkat(cur->dirfd, ".ppurge", AT_REMOVEDIR)) != 0) { 390 | fprintf( Logfd, "unlink .ppurge failed: '%s'\n", strerror(errno)); 391 | } 392 | 393 | } 394 | closedir( dirp ); 395 | *--end_dname = '\0'; 396 | 397 | return_thread: 398 | if ( cur->flag == 0 ) { /* this instance of fileDir is a thread */ 399 | pthread_mutex_lock ( &mutexFD ); 400 | DEBUG_2("msg=endTHRD,threadID=%ld,rdepth=%d,file=<%s>\n", cur->THRDid, cur->flag, cur->dname); 401 | --ThreadCNT; 402 | cur->THRDid = -1; 403 | pthread_mutex_unlock ( &mutexFD ); 404 | pthread_exit( EXIT_SUCCESS ); 405 | } else 406 | return 0; 407 | } 408 | 409 | /* open a log file */ 410 | void 411 | openLog(time_t now) 412 | { 413 | char logName[64]; 414 | 415 | (void)strftime(logName, 63, "ppurge-%Y.%m.%d-%H_%M_%S.log", localtime(&now)); 416 | if ((Logfd = fopen(logName, "w")) < 0) { 417 | fprintf(stderr, "could not open: %s\n", logName); 418 | exit(errno); 419 | } 420 | } 421 | 422 | int 423 | main( int argc, char* argv[] ) 424 | { 425 | int error, i, pdays = 0; 426 | int rootfd; 427 | time_t now; 428 | 429 | if ( argc < 2 ) { 430 | printHelp( ); 431 | exit( EXIT_FAILURE ); 432 | } 433 | argc--; argv++; 434 | now = time(NULL); 435 | while ( argc > 0 && *argv[0] == '-' ) { 436 | if ( !strcmp(*argv, "--depth" ) ) { 437 | argc--; argv++; 438 | DEPTH = atoi(*argv); 439 | } 440 | if ( !strcmp(*argv, "--help" ) ) { 441 | printHelp( ); 442 | exit(0); } 443 | if ( !strcmp(*argv, "--version" ) || !strcmp(*argv, "-v") ) { 444 | printVersion( ); 445 | exit(0); } 446 | if ( !strcmp(*argv, "--purgeDays")) { 447 | argc--; argv++; 448 | pdays = atoi(*argv); 449 | if ( pdays < 1 || pdays > 32000) { 450 | fprintf(stderr, "purgeDays should be possitive integer between 1 and 32000\n"); 451 | exit(1); 452 | } 453 | Ptime = now - (pdays * 86400); 454 | Rtime = Ptime * 2; 455 | } 456 | argc--; argv++; 457 | } 458 | openLog(now); 459 | if (pdays == 0) { 460 | fprintf(stderr, "--purgeDays must be specified\n"); 461 | exit(1); 462 | } 463 | if ( setuid((uid_t) 0)) { 464 | fprintf(stderr, "unable to setuid root; not all files will be processed\n"); 465 | exit(1); 466 | } 467 | (void) umask((mode_t)00); /* create .ppurge directories with 1777 like /tmp */ 468 | 469 | 470 | for ( i=0; i 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "pwalk.h" 33 | 34 | /* #define THRD_DEBUG */ 35 | 36 | static char *whoami = "pwalk"; 37 | static char *Version = "3.0.0 Jul 14 2020 John F Dey john@fuzzdog.com"; 38 | 39 | // 3.0.0 Major feature Change - use a function pointer to call generic file 40 | // processing functions. Separate the traversal code from the file 41 | // operations code into a new file: fileProcess.c 42 | 43 | // 2.6.10 pino used wrong type, improve error message for lstat 44 | // improve output format for inodes 45 | 46 | // 2.6.9 Oct 27 2018 Add header to to CSV as option 47 | // 2.6.8 Oct 27 2017 depth feature 48 | // 2.6.7 May 31 2017 exclude feature 49 | // static char *Version = "2.6.4 Dec 12 2015 John F Dey john@fuzzdog.com"; 50 | // static char *Version = "2.6.3 Dec 9 2015 John F Dey john@fuzzdog.com"; 51 | // static char *Version = "2.6.2 Aug 7 2015 John F Dey john@fuzzdog.com"; 52 | 53 | #define MAXEXFILES 512 54 | char *exclude_list[MAXEXFILES]; 55 | 56 | int SNAPSHOT =0; /* if set ignore directories called .snapshot */ 57 | int DEPTH = 0; /* if set do not traverse beyond directory depth */ 58 | int ONE_FS =0; /* skip directories on different file systems -x */ 59 | dev_t ST_DEV; /* save st_dev of root file */ 60 | 61 | #define MAXTHRDS 32 62 | int ThreadCNT = 1; /* ThreadCNT < MAXTHRDS */ 63 | int totalTHRDS =0; 64 | struct threadData tdslot[MAXTHRDS]; 65 | pthread_mutex_t mutexFD; 66 | pthread_mutex_t mutexPrintStat; 67 | 68 | int check_exclude_list(char *fname); 69 | void verify_paths(char *list[]); 70 | void get_exclude_list(char *fname, char *list[]); 71 | 72 | /* conditioanally change file ownership --chown_from --chown_to */ 73 | uid_t UID_orig, UID_new; 74 | gid_t GID_new; 75 | int chown_flag =0; 76 | 77 | /* Process files */ 78 | void 79 | (*fileProcess)( struct threadData *cur, char *exten, struct stat *f, long, long); 80 | 81 | /* 82 | * conditionally change file ownership 83 | * if file owned by UID_orig chown UID_new:GID_new 84 | */ 85 | void 86 | changeOwner( struct threadData *cur, char *exten, struct stat *f, 87 | long fileCnt, /* directory only - count files in directory */ 88 | long dirSz ); /* directory only - sum of files within directory */ 89 | /* 90 | * printStat this needs to be in a crital secion (and it is!) 91 | */ 92 | void 93 | printStat( struct threadData *cur, char *exten, struct stat *f, 94 | long fileCnt, /* directory only - count files in directory */ 95 | long dirSz ); /* directory only - sum of files within directory */ 96 | 97 | 98 | void 99 | printVersion( ) { 100 | fprintf(stderr, "%s version %s\n", whoami, Version ); 101 | fprintf(stderr, "%s Copyright (C) 2013 John F Dey\n", whoami ); 102 | fprintf(stderr, "pwalk comes with ABSOLUTELY NO WARRANTY;\n" ); 103 | fprintf(stderr, "This is free software, you can redistribute it and/or\n"); 104 | fprintf(stderr, "modify it under the\nterms of the GNU General Public"); 105 | fprintf(stderr, " License as published by the Free Software Foundation;\n"); 106 | fprintf(stderr, "either version 2 of the License, or (at your option) any"); 107 | fprintf(stderr, " later version.\n\n" ); 108 | } 109 | 110 | void 111 | printHeader() 112 | { 113 | printf("inode,parent-inode,directory-depth,\"filename\""); 114 | printf(",\"fileExtension\",UID,GID,st_size,st_dev,st_blocks" ); 115 | printf(",st_nlink,\"st_mode\",st_atime,st_mtime,st_ctime,pw_fcount"); 116 | printf(",pw_dirsum\n"); 117 | } 118 | 119 | void 120 | printHelp() 121 | { 122 | printf("Useage : %s (fully qualified file name)\n", whoami); 123 | printf("Flags: --help --version \n" ); 124 | printf(" --depth n Stop walking when (n) depth is reached\n"); 125 | printf(" --NoSnap Ignore directories with name .snapshot\n"); 126 | printf(" --exclude filename contains a list of"); 127 | printf(" directories \n"); 128 | printf(" to exclude from reporting\n"); 129 | printf(" --one-file-system skip directories on different file"); 130 | printf(" systems\n"); 131 | printf(" --header write CSV header with output\n"); 132 | printf("Conditionally Change File Owner. Two Flags are required.\n"); 133 | printf(" --chown_from UID\n"); 134 | printf(" --chown_to UID:GID\n\n"); 135 | printf("Each line of output represents one file. st_* fields are direct "); 136 | printf("from the inode\ndata structure. pwalk provides additional "); 137 | printf("data for directories.\n\n"); 138 | printf(" - directory-depth: Values are incremented by directory depth. "); 139 | printf("Initial root\n directory has value of -1. "); 140 | printf("Files in the root directory have value 0.\n"); 141 | printf(" - pw_fcount: Number of files in a directory. Value is -1 "); 142 | printf("if file is not a directory\n" ); 143 | printf(" - pw_dirsum: Sum of file sizes in single directory. Value "); 144 | printf("of -1 if\n file is not a directory\n\n"); 145 | printf("File Header:\n"); 146 | printHeader(); 147 | } 148 | 149 | /******************************** 150 | Open a directory and read the conents. 151 | call opendir with path passed in as an argument 152 | stat every file from opendir 153 | 154 | If maxthread is not reached creat a new thread and call self 155 | If no threads available Recursively call self for each directory 156 | from opendir. 157 | 158 | print inode meta data for each file, one line per file in CSV format 159 | print directory information after every file is processed from 160 | open dir. Direcory information has - count of files, sum of file sizes 161 | 162 | *********************************/ 163 | void 164 | *fileDir( void *arg ) 165 | { 166 | char *s, *t, *u, *dot, *end_dname; 167 | int i, slot, status; 168 | DIR *dirp; 169 | long localCnt =0; /* number of files in a specific directory */ 170 | long localSz =0; /* byte cnt of files in the local directory 2010.07 */ 171 | struct dirent *d; 172 | struct stat f; 173 | struct threadData *cur, *new, local; 174 | 175 | cur = (struct threadData *) arg; 176 | #ifdef THRD_DEBUG 177 | fprintf( stderr, "msg=fileDir,threadID=%ld,rdepth=%d,file=%s\n", 178 | cur->THRDid, cur->flag, cur->dname ); 179 | #endif /* THRD_DEBUG */ 180 | if ( (dirp = opendir( cur->dname )) == NULL ) { 181 | fprintf( stderr, "Locked Dir: %s\n", cur->dname ); 182 | return arg; 183 | } 184 | /* find the end of fs->name and put '/' at the end 185 | points to char after '/' */ 186 | s = cur->dname + strlen(cur->dname); 187 | *s++ = '/'; 188 | end_dname = s; 189 | while ( (d = readdir( dirp )) != NULL ) { 190 | if ( strcmp(".",d->d_name) == 0 ) continue; 191 | if ( strcmp("..",d->d_name) == 0 ) continue; 192 | localCnt++; 193 | s = d->d_name; t = end_dname; 194 | while ( *s ) /* copy file name to end of current path */ 195 | *t++ = *s++; 196 | *t = '\0'; 197 | if ( lstat ( cur->dname, &f ) == -1 ) { 198 | fprintf( stderr, "threadID=%ld,rdepth=%d lstat: '%s' %s\n", 199 | cur->THRDid, cur->flag, strerror(errno), cur->dname); 200 | continue; 201 | } 202 | /* don't report data from foreign file systems */ 203 | if ( ONE_FS && f.st_dev != ST_DEV ) 204 | continue; 205 | /* Follow Sub dirs recursivly but don't follow links */ 206 | localSz += f.st_size; 207 | if ( S_ISDIR(f.st_mode) ) { 208 | if ( SNAPSHOT && !strcmp( ".snapshot", d->d_name ) ) 209 | continue; /* next file from readdir */ 210 | if ( DEPTH && DEPTH == cur->depth ) 211 | continue; /* don't do any deeper than this */ 212 | if ( exclude_list[0] && check_exclude_list(cur->dname) ) 213 | continue; 214 | pthread_mutex_lock (&mutexFD); 215 | if ( ThreadCNT < MAXTHRDS ) { 216 | slot = 0; 217 | while ( slot < MAXTHRDS ) { 218 | if ( tdslot[slot].THRDid == -1 ) { 219 | new = &tdslot[slot]; 220 | new->THRDid = totalTHRDS++; 221 | new->flag = 0; /* recurse flag reset for new thread */ 222 | break; 223 | } 224 | slot++; 225 | } 226 | if ( slot == MAXTHRDS ) { /* this would be bad */ 227 | fprintf( stderr, "error=%s,threadID=%ld,rdepth=%d,ThreadCNT=%d\n", 228 | "\"no available threads\"", cur->THRDid, cur->flag, ThreadCNT ); 229 | exit( 1 ); 230 | } 231 | ThreadCNT++; /* allocate the thread */ 232 | } else { 233 | new = &local; 234 | new->THRDid = cur->THRDid; 235 | new->flag = cur->flag + 1; 236 | } 237 | pthread_mutex_unlock (&mutexFD); 238 | /* create ponter to tdslot that will be used for next 239 | call to fileDir - local or from array - shorten next block of 240 | code 241 | */ 242 | memcpy( &(new->pstat), &f, sizeof( struct stat ) ); 243 | strcpy( new->dname, (const char*)cur->dname ); 244 | new->depth = cur->depth + 1; 245 | new->pinode = cur->pstat.st_ino; /* Parent Inode */ 246 | if ( new->THRDid != cur->THRDid ) { /* new thread available */ 247 | pthread_create( &tdslot[slot].thread_id, &tdslot[slot].tattr, 248 | fileDir, (void*)new ); 249 | } else { 250 | fileDir( (void*) new ); 251 | } 252 | } else { 253 | s = end_dname + 1; dot = NULL; /* file extension */ 254 | while ( *s ) { 255 | if (*s == '.') dot = s+1; 256 | s++; 257 | } 258 | pthread_mutex_lock (&mutexPrintStat); 259 | (*fileProcess)( cur, dot, &f, (long)-1, (long)0 ); 260 | pthread_mutex_unlock (&mutexPrintStat); 261 | } 262 | } 263 | closedir( dirp ); 264 | *--end_dname = '\0'; 265 | s = end_dname - 1; dot = NULL; 266 | while ( *s != '/' ) { 267 | if (*s == '.') { dot = s+1; break; } 268 | s--; } 269 | if ( s+1 == dot ) /* Dot file is not an extension Exp: /.bashrc */ 270 | dot = NULL; 271 | pthread_mutex_lock (&mutexPrintStat); 272 | (*fileProcess)( cur, dot, &cur->pstat, localCnt, localSz); 273 | pthread_mutex_unlock (&mutexPrintStat); 274 | if ( cur->flag == 0 ) { /* this instance of fileDir is a thread */ 275 | pthread_mutex_lock ( &mutexFD ); 276 | #ifdef THRD_DEBUG 277 | fprintf( stderr, "msg=endTHRD,threadID=%ld,rdepth=%d,file=<%s>\n", 278 | cur->THRDid, cur->flag, cur->dname ); 279 | #endif 280 | --ThreadCNT; 281 | cur->THRDid = -1; 282 | pthread_mutex_unlock ( &mutexFD ); 283 | pthread_exit( EXIT_SUCCESS ); 284 | } 285 | /* else return ; */ 286 | #ifdef THRD_DEBUG 287 | fprintf( stderr, "msg=endRecurse,threadID=%ld,rdepth=%d,file=<%s>\n", 288 | cur->THRDid, cur->flag, cur->dname ); 289 | #endif /* THRD_DEBUG */ 290 | } 291 | 292 | int 293 | main( int argc, char* argv[] ) 294 | { 295 | int error, i, colon =':'; 296 | char *s, *c, *gid_ptr; 297 | struct stat root; 298 | 299 | if ( argc < 2 ) { 300 | printHelp( ); 301 | exit( EXIT_FAILURE ); 302 | } 303 | exclude_list[0] = NULL; 304 | argc--; argv++; 305 | while ( argc > 0 && *argv[0] == '-' ) { 306 | if ( !strcmp(*argv, "--NoSnap" ) ) 307 | SNAPSHOT = 1; 308 | if ( !strcmp(*argv, "--depth" ) ) { 309 | argc--; argv++; 310 | DEPTH = atoi(*argv); 311 | } 312 | if ( !strcmp(*argv, "--help" ) ) { 313 | printHelp( ); 314 | exit(0); } 315 | if ( !strcmp(*argv, "--version" ) || !strcmp(*argv, "-v") ) 316 | printVersion( ); 317 | if ( !strcmp(*argv, "--header" ) || !strcmp(*argv, "-v") ) 318 | printHeader(); 319 | if ( !strcmp(*argv, "--exclude" )) { 320 | argc--; argv++; 321 | get_exclude_list(*argv, exclude_list); 322 | verify_paths(exclude_list); } 323 | if ( !strcmp(*argv, "--one-file-system" ) || !strcmp(*argv, "-x") ) 324 | ONE_FS = 1; 325 | if ( !strcmp(*argv, "--chown_from")) { 326 | argc--; argv++; 327 | UID_orig = atoi(*argv); 328 | chown_flag++; 329 | } 330 | if ( !strcmp(*argv, "--chown_to")) { 331 | argc--; argv++; 332 | UID_new = atoi(*argv); 333 | if ( gid_ptr = strchr(*argv, colon)) 334 | GID_new = atoi(++gid_ptr); 335 | else { 336 | fprintf( stderr, "--chown_to requires UID:GID as argument\n"); 337 | exit(1); 338 | } 339 | chown_flag++; 340 | } 341 | argc--; argv++; 342 | } 343 | if (setuid((uid_t) 0)) { 344 | fprintf(stderr, "unable to setuid root; not all files will be processed\n"); 345 | } 346 | fileProcess = &printStat; 347 | if ( chown_flag == 2 ) { 348 | fprintf(stderr, "chown UID_orig: %d UID_new: %d GID_new: %d\n", (int)UID_orig, (int)UID_new, (int)GID_new); 349 | fileProcess = &changeOwner; 350 | } 351 | for ( i=0; i 0 */ 7 | struct stat pstat; /* Parent inode stat struct */ 8 | pthread_t thread_id; /* system assigned */ 9 | pthread_attr_t tattr; 10 | }; 11 | -------------------------------------------------------------------------------- /reassemble.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | import sys 4 | import csv 5 | from pprint import pprint 6 | 7 | """2018.10.28 John Dey 8 | consume CSV output from pwalk and reassemble directory data. 9 | File system data from pwalk is flattened and out of order. 10 | Rewalk the tree data and create two new fields for each directory. 11 | Create a tree sum of file count and bytes at each directory (node) 12 | that represents the child nodes. Sums for the root will 13 | become the total file count and sum size for every file. 14 | 15 | Notes: I wrote this in Python as a proof of concept. 16 | """ 17 | 18 | def usage(): 19 | """how to use and exit""" 20 | print("usage: % inputfile.csv" % sys.argv[0]) 21 | sys.exit(1) 22 | 23 | if len(sys.argv ) != 2: 24 | usage() 25 | 26 | dd = {} 27 | with open(sys.argv[1], newline='') as csvfile: 28 | pwalk = csv.reader(csvfile, delimiter=',', quotechar='"') 29 | for row in pwalk: 30 | if int(row[15]) >= 0: # only store directories 31 | dd[int(row[0])] = {'parent': int(row[1]), 32 | 'depth': int(row[2]), 33 | 'dircnt': int(row[15]), 34 | 'sumcnt': int(row[15]), # or Zero? 35 | 'dirsiz': int(row[16]), 36 | 'sumsiz': int(row[16])} 37 | if int(row[1]) == 0: 38 | root = int(row[0]) 39 | dd[int(row[0])]['sumcnt'] += 1 40 | dd[int(row[0])]['sumsiz'] += int(row[7]) 41 | 42 | print("Total directories: %d" % len(dd.keys())) 43 | 44 | """reassemble the tree""" 45 | for inode in dd.keys(): 46 | parent = dd[inode]['parent'] 47 | while parent != 0: 48 | dd[parent]['sumcnt'] += dd[inode]['dircnt'] 49 | dd[parent]['sumsiz'] += dd[inode]['dirsiz'] 50 | parent = dd[parent]['parent'] 51 | pprint(dd[root]) 52 | 53 | -------------------------------------------------------------------------------- /repairshr.c: -------------------------------------------------------------------------------- 1 | /* 2 | * repair-shared. Parallel permission repair for shared folders 3 | Copyright (C) (2024) John F Dey 4 | This program is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU General Public License 6 | as published by the Free Software Foundation; either version 2 7 | of the License, or (at your option) any later version. 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | You should have received a copy of the GNU General Public License 13 | along with this program; if not, write to the Free Software 14 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "repairshr.h" 29 | 30 | #define MAX_PATH 4096 31 | #define MAXEXFILES 512 32 | #define MAX_GROUPS 100 33 | 34 | int SNAPSHOT = 0; 35 | int ONE_FS = 0; 36 | int DRY_RUN = 0; 37 | dev_t ST_DEV; 38 | 39 | char *exclude_list[MAXEXFILES]; 40 | gid_t change_groups[MAX_GROUPS]; 41 | int change_groups_count = 0; 42 | 43 | pthread_mutex_t mutexFD; 44 | pthread_mutex_t mutexLog; 45 | 46 | // Function declarations 47 | int check_exclude_list(char *fname); 48 | void get_exclude_list(char* fname, char *list[]); 49 | void verify_paths(char *list[]); 50 | 51 | void log_change(const char *format, ...) { 52 | va_list args; 53 | va_start(args, format); 54 | pthread_mutex_lock(&mutexLog); 55 | vprintf(format, args); 56 | pthread_mutex_unlock(&mutexLog); 57 | va_end(args); 58 | } 59 | 60 | void log_error(const char *format, ...) { 61 | va_list args; 62 | va_start(args, format); 63 | pthread_mutex_lock(&mutexLog); 64 | vfprintf(stderr, format, args); 65 | pthread_mutex_unlock(&mutexLog); 66 | va_end(args); 67 | } 68 | 69 | int should_change_group(gid_t gid) { 70 | int i; 71 | for (i = 0; i < change_groups_count; i++) { 72 | if (gid == change_groups[i]) { 73 | return 1; 74 | } 75 | } 76 | return 0; 77 | } 78 | 79 | gid_t find_non_private_group(const char *path, gid_t start_gid) { 80 | char current_path[MAX_PATH]; 81 | struct stat st; 82 | strncpy(current_path, path, sizeof(current_path)); 83 | 84 | while (strlen(current_path) > 1) { 85 | if (lstat(current_path, &st) == 0) { 86 | if (st.st_gid != st.st_uid && st.st_gid != 0 && !should_change_group(st.st_gid)) { 87 | return st.st_gid; 88 | } 89 | } 90 | char *last_slash = strrchr(current_path, '/'); 91 | if (last_slash != NULL) { 92 | *last_slash = '\0'; 93 | } else { 94 | break; 95 | } 96 | } 97 | 98 | // If we reach here, we didn't find a suitable non-private, non-root group 99 | return 0; // Indicate that no suitable group was found 100 | } 101 | 102 | void repair_permissions(const char *path, struct stat *st) { 103 | mode_t new_mode = st->st_mode; 104 | gid_t new_gid = st->st_gid; 105 | int changes = 0; 106 | 107 | // Set setgid bit on directories 108 | if (S_ISDIR(st->st_mode) && !(st->st_mode & S_ISGID)) { 109 | new_mode |= S_ISGID; 110 | changes = 1; 111 | } 112 | 113 | // Check for private group, root group, or groups to change 114 | if (st->st_gid == st->st_uid || st->st_gid == 0 || should_change_group(st->st_gid)) { 115 | gid_t non_private_gid = find_non_private_group(path, st->st_gid); 116 | if (non_private_gid != 0) { 117 | new_gid = non_private_gid; 118 | changes = 1; 119 | } else { 120 | log_error("Error: No suitable non-private, non-root group found for %s (current gid: %d)\n", path, st->st_gid); 121 | } 122 | } 123 | 124 | // Ensure minimum group permissions 125 | if (S_ISDIR(st->st_mode)) { 126 | if ((st->st_mode & S_IRGRP) == 0 || (st->st_mode & S_IXGRP) == 0) { 127 | new_mode |= S_IRGRP | S_IXGRP; 128 | changes = 1; 129 | } 130 | } else { 131 | if ((st->st_mode & S_IRGRP) == 0) { 132 | new_mode |= S_IRGRP; 133 | changes = 1; 134 | } 135 | } 136 | 137 | // Apply changes if needed 138 | if (changes) { 139 | if (new_mode != st->st_mode) { 140 | if (DRY_RUN) { 141 | log_change("Would change mode of %s from %o to %o\n", path, st->st_mode, new_mode); 142 | } else { 143 | if (chmod(path, new_mode) != 0) { 144 | log_error("Error: Failed to change mode for %s: %s\n", path, strerror(errno)); 145 | } else { 146 | log_change("Changed mode of %s from %o to %o\n", path, st->st_mode, new_mode); 147 | } 148 | } 149 | } 150 | 151 | if (new_gid != st->st_gid) { 152 | if (DRY_RUN) { 153 | log_change("Would change group of %s from %d to %d\n", path, st->st_gid, new_gid); 154 | } else { 155 | if (chown(path, -1, new_gid) != 0) { 156 | log_error("Error: Failed to change group for %s: %s\n", path, strerror(errno)); 157 | } else { 158 | log_change("Changed group of %s from %d to %d\n", path, st->st_gid, new_gid); 159 | } 160 | } 161 | } 162 | } 163 | } 164 | 165 | void *repair_directory(void *arg) { 166 | struct threadData *cur = (struct threadData *)arg; 167 | DIR *dirp; 168 | struct dirent *d; 169 | char path[MAX_PATH]; 170 | struct stat st; 171 | 172 | if ((dirp = opendir(cur->dname)) == NULL) { 173 | log_error("Error: Unable to open directory %s: %s\n", cur->dname, strerror(errno)); 174 | return NULL; 175 | } 176 | 177 | while ((d = readdir(dirp)) != NULL) { 178 | if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) { 179 | continue; 180 | } 181 | 182 | snprintf(path, sizeof(path), "%s/%s", cur->dname, d->d_name); 183 | 184 | if (lstat(path, &st) == -1) { 185 | log_error("Error: Unable to stat %s: %s\n", path, strerror(errno)); 186 | continue; 187 | } 188 | 189 | if (ONE_FS && st.st_dev != ST_DEV) { 190 | continue; 191 | } 192 | 193 | repair_permissions(path, &st); 194 | 195 | if (S_ISDIR(st.st_mode)) { 196 | if (SNAPSHOT && strcmp(d->d_name, ".snapshot") == 0) { 197 | continue; 198 | } 199 | 200 | if (check_exclude_list(path)) { 201 | continue; 202 | } 203 | 204 | struct threadData new_td; 205 | strncpy(new_td.dname, path, sizeof(new_td.dname)); 206 | new_td.pinode = st.st_ino; 207 | new_td.depth = cur->depth + 1; 208 | 209 | repair_directory(&new_td); 210 | } 211 | } 212 | 213 | closedir(dirp); 214 | return NULL; 215 | } 216 | 217 | void remove_trailing_slash(char *path) { 218 | size_t len = strlen(path); 219 | if (len > 1 && path[len - 1] == '/') { 220 | path[len - 1] = '\0'; 221 | } 222 | } 223 | 224 | int main(int argc, char *argv[]) { 225 | if (argc < 2) { 226 | fprintf(stderr, "Usage: %s [options] \n", argv[0]); 227 | fprintf(stderr, "Options:\n"); 228 | fprintf(stderr, " --NoSnap Ignore .snapshot directories\n"); 229 | fprintf(stderr, " --exclude Specify a file containing paths to exclude\n"); 230 | fprintf(stderr, " -x, --one-file-system Stay on one file system\n"); 231 | fprintf(stderr, " --dry-run Show changes without making them\n"); 232 | fprintf(stderr, " --change-gids Comma-separated list of group IDs to change\n"); 233 | exit(1); 234 | } 235 | 236 | // Parse command-line arguments 237 | int i; 238 | char *directory = NULL; 239 | for (i = 1; i < argc; i++) { 240 | if (argv[i][0] == '-') { 241 | if (strcmp(argv[i], "--NoSnap") == 0) { 242 | SNAPSHOT = 1; 243 | } else if (strcmp(argv[i], "--exclude") == 0) { 244 | if (++i < argc) { 245 | get_exclude_list(argv[i], exclude_list); 246 | verify_paths(exclude_list); 247 | } else { 248 | fprintf(stderr, "Error: --exclude requires a filename\n"); 249 | exit(1); 250 | } 251 | } else if (strcmp(argv[i], "-x") == 0 || strcmp(argv[i], "--one-file-system") == 0) { 252 | ONE_FS = 1; 253 | } else if (strcmp(argv[i], "--dry-run") == 0) { 254 | DRY_RUN = 1; 255 | } else if (strcmp(argv[i], "--change-gids") == 0) { 256 | if (++i < argc) { 257 | char *token = strtok(argv[i], ","); 258 | while (token != NULL && change_groups_count < MAX_GROUPS) { 259 | change_groups[change_groups_count++] = (gid_t)atoi(token); 260 | token = strtok(NULL, ","); 261 | } 262 | } else { 263 | fprintf(stderr, "Error: --change-gids requires a comma-separated list of group IDs\n"); 264 | exit(1); 265 | } 266 | } else if (argv[i][1] == '-') { 267 | fprintf(stderr, "Error: Unknown option '%s'\n", argv[i]); 268 | exit(1); 269 | } else if (strlen(argv[i]) == 2) { 270 | fprintf(stderr, "Error: Unknown option '%s'\n", argv[i]); 271 | exit(1); 272 | } else { 273 | fprintf(stderr, "Error: Invalid option '%s'\n", argv[i]); 274 | exit(1); 275 | } 276 | } else if (directory == NULL) { 277 | directory = argv[i]; 278 | } else { 279 | fprintf(stderr, "Error: Unexpected argument '%s'\n", argv[i]); 280 | exit(1); 281 | } 282 | } 283 | 284 | if (directory == NULL) { 285 | fprintf(stderr, "Error: No directory specified\n"); 286 | exit(1); 287 | } 288 | 289 | // Remove trailing slash from directory path 290 | remove_trailing_slash(directory); 291 | 292 | if (DRY_RUN) { 293 | printf("Dry run mode: No changes will be made to the file system\n"); 294 | } 295 | 296 | struct stat root_st; 297 | if (lstat(directory, &root_st) == -1) { 298 | fprintf(stderr, "Error: Unable to stat root directory %s: %s\n", directory, strerror(errno)); 299 | exit(1); 300 | } 301 | 302 | ST_DEV = root_st.st_dev; 303 | 304 | pthread_mutex_init(&mutexFD, NULL); 305 | pthread_mutex_init(&mutexLog, NULL); 306 | 307 | struct threadData root_td; 308 | strncpy(root_td.dname, directory, sizeof(root_td.dname)); 309 | root_td.pinode = 0; 310 | root_td.depth = 0; 311 | 312 | repair_directory(&root_td); 313 | 314 | pthread_mutex_destroy(&mutexFD); 315 | pthread_mutex_destroy(&mutexLog); 316 | 317 | return 0; 318 | } -------------------------------------------------------------------------------- /repairshr.h: -------------------------------------------------------------------------------- 1 | #ifndef REPAIRSHR_H 2 | #define REPAIRSHR_H 3 | 4 | #include 5 | 6 | struct threadData { 7 | char dname[4096]; // Assuming MAX_PATH is 4096 8 | ino_t pinode; 9 | long depth; 10 | }; 11 | 12 | #endif // REPAIRSHR_H 13 | 14 | -------------------------------------------------------------------------------- /repexcl.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "repairshr.h" 5 | 6 | extern char *exclude_list[512]; 7 | 8 | int check_exclude_list(char *fname) { 9 | int i = 0; 10 | while(exclude_list[i]) { 11 | if (strcmp(exclude_list[i], fname) == 0) { 12 | return 1; 13 | } 14 | i++; 15 | } 16 | return 0; 17 | } 18 | 19 | void verify_paths(char *list[]) { 20 | // This function can be implemented to verify the paths in the exclude list 21 | // For now, we'll leave it empty 22 | } 23 | 24 | void get_exclude_list(char* fname, char *list[]) { 25 | FILE *fp = fopen(fname, "r"); 26 | if (fp == NULL) { 27 | fprintf(stderr, "Error opening exclude list file: %s\n", fname); 28 | return; 29 | } 30 | 31 | char line[256]; 32 | int i = 0; 33 | while (fgets(line, sizeof(line), fp)) { 34 | line[strcspn(line, "\n")] = 0; // Remove newline 35 | list[i] = strdup(line); 36 | i++; 37 | if (i >= 512) break; // Prevent buffer overflow 38 | } 39 | list[i] = NULL; // Null-terminate the list 40 | 41 | fclose(fp); 42 | } 43 | -------------------------------------------------------------------------------- /report.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import csv 5 | import operator 6 | import os 7 | import pwd 8 | 9 | """ 10 | Very simple Python filter to collect stats from pwalk output. 11 | use as a template to create other filters 12 | 13 | Read csv file generated by pwalk and output the biggest users 14 | """ 15 | 16 | _version_ = '1.0.0' 17 | _author_ = 'jfdey@fredhutch.org' 18 | 19 | # pwalk fields 20 | fields = ['inode', 'parent-inode', 'directory-depth', 'filename', 'extension', 21 | 'UID', 'GID', 'st_size', 'st_dev', 'st_blocks"', 'st_nlink', '"st_mode"', 22 | 'atime', 'mtime', 'ctime', 'fcount', 'sum'] 23 | 24 | users = {} 25 | with open(sys.argv[1]) as csv_file: 26 | csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"') 27 | for row in csv_reader: 28 | uid = row[fields.index('UID')] 29 | if uid in users: 30 | users[uid]['sum'] += int(row[fields.index('st_size')]) 31 | users[uid]['fcount'] += 1 32 | else: 33 | users[uid] = {} 34 | users[uid]['sum'] = int(row[fields.index('st_size')]) 35 | users[uid]['fcount'] = 1 36 | 37 | # create new hash to be sorted by size 38 | summary = {} 39 | for user in users: 40 | summary[user] = users[user]['sum'] 41 | 42 | # sorted_size is list of tuples (uid, size) 43 | sorted_size = sorted(summary.items(), key=operator.itemgetter(1)) 44 | print(type(sorted_size)) 45 | 46 | for user in sorted_size: 47 | try: 48 | uname = pwd.getpwuid(int(user[0])).pw_name 49 | except KeyError: 50 | uname = user[0] 51 | print('{} UID: {} FileCount: {}'.format(user[1], uname, users[user[0]]['fcount'])) 52 | 53 | --------------------------------------------------------------------------------