sbin/hammer: Cleanup blocks with a single statement
[dragonfly.git] / sbin / hammer / cmd_softprune.c
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $DragonFly: src/sbin/hammer/cmd_softprune.c,v 1.7 2008/08/21 23:28:43 thomas Exp $
35  */
36
37 #include "hammer.h"
38
39 struct softprune {
40         struct softprune *next;
41         struct statfs fs;
42         char *filesystem;
43         struct hammer_ioc_prune prune;
44         int maxelms;
45         int prune_min;
46 };
47
48 static void hammer_softprune_scandir(struct softprune **basep,
49                         struct hammer_ioc_prune *template,
50                         const char *dirname);
51 static int hammer_softprune_scanmeta(int fd, struct softprune *scan,
52                         int delete_all);
53 static void hammer_meta_flushdelete(int fd, struct hammer_ioc_snapshot *dsnap);
54 static struct softprune *hammer_softprune_addentry(struct softprune **basep,
55                         struct hammer_ioc_prune *template,
56                         const char *dirpath, const char *denname,
57                         struct stat *st,
58                         const char *linkbuf, const char *tidptr);
59 static void hammer_softprune_addelm(struct softprune *scan, hammer_tid_t tid,
60                         time_t ct, time_t mt);
61 static void hammer_softprune_finalize(struct softprune *scan);
62 static void softprune_usage(int code);
63
64 /*
65  * prune <softlink-dir>
66  * prune-everything <filesystem>
67  */
68 void
69 hammer_cmd_softprune(char **av, int ac, int everything_opt)
70 {
71         struct hammer_ioc_prune template;
72         struct hammer_ioc_pseudofs_rw pfs;
73         struct softprune *base, *scan;
74         int fd;
75         int rcode;
76
77         base = NULL;
78         rcode = 0;
79         if (TimeoutOpt > 0)
80                 alarm(TimeoutOpt);
81
82         clrpfs(&pfs, NULL, -1);
83
84         /*
85          * NOTE: To restrict to a single file XXX we have to set
86          * the localization the same (not yet implemented).  Typically
87          * two passes would be needed, one using HAMMER_LOCALIZE_MISC
88          * and one using HAMMER_LOCALIZE_INODE.
89          */
90
91         bzero(&template, sizeof(template));
92         template.key_beg.localization = HAMMER_MIN_LOCALIZATION;
93         template.key_beg.obj_id = HAMMER_MIN_OBJID;
94         template.key_end.localization = HAMMER_MAX_LOCALIZATION;
95         template.key_end.obj_id = HAMMER_MAX_OBJID;
96         hammer_get_cycle(&template.key_end, NULL);
97         template.stat_oldest_tid = HAMMER_MAX_TID;
98
99         /*
100          * For now just allow one directory
101          */
102         if (ac == 0 || ac > 1)
103                 softprune_usage(1);
104
105         /*
106          * Scan the softlink directory.
107          */
108         if (everything_opt) {
109                 const char *dummylink = "";
110                 scan = hammer_softprune_addentry(&base, &template,
111                                                  *av, NULL, NULL,
112                                                  dummylink, dummylink);
113                 if (scan == NULL)
114                         softprune_usage(1);
115                 scan->prune.nelms = 0;
116                 scan->prune.head.flags |= HAMMER_IOC_PRUNE_ALL;
117         } else {
118                 hammer_softprune_scandir(&base, &template, *av);
119                 if (base == NULL) {
120                         const char *dummylink = "";
121                         scan = hammer_softprune_addentry(&base, &template,
122                                                          *av, NULL, NULL,
123                                                          dummylink, dummylink);
124                         if (scan == NULL)
125                                 softprune_usage(1);
126                         scan->prune.nelms = 0;
127                 }
128                 ++av;
129                 --ac;
130         }
131
132         /*
133          * XXX future (need to store separate cycles for each filesystem)
134          */
135         if (base->next)
136                 errx(1, "Currently only one HAMMER filesystem may "
137                         "be specified in the softlink scan");
138
139         /*
140          * Issue the prunes
141          */
142         for (scan = base; scan; scan = scan->next) {
143                 /*
144                  * Open the filesystem for ioctl calls and extract the
145                  * PFS.
146                  */
147                 fd = open(scan->filesystem, O_RDONLY);
148                 if (fd < 0) {
149                         warn("Unable to open %s", scan->filesystem);
150                         rcode = 1;
151                         continue;
152                 }
153
154                 if (ioctl(fd, HAMMERIOC_GET_PSEUDOFS, &pfs) < 0) {
155                         warn("Filesystem %s is not HAMMER", scan->filesystem);
156                         rcode = 1;
157                         close(fd);
158                         continue;
159                 }
160                 scan->prune_min = pfs.ondisk->prune_min;
161
162                 /*
163                  * Incorporate meta-data snapshots into the pruning regimen.
164                  * If pruning everything we delete the meta-data snapshots.
165                  */
166                 if (hammer_softprune_scanmeta(fd, scan, everything_opt) < 0) {
167                         warn("Filesystem %s could not scan meta-data snaps",
168                              scan->filesystem);
169                         rcode = 1;
170                         close(fd);
171                         continue;
172                 }
173
174                 /*
175                  * Finalize operations
176                  */
177                 hammer_softprune_finalize(scan);
178                 if (everything_opt)
179                         printf("Prune %s: EVERYTHING\n",
180                                scan->filesystem);
181                 else
182                         printf("Prune %s: %d snapshots\n",
183                                scan->filesystem, scan->prune.nelms);
184                 if (scan->prune.nelms == 0 &&
185                     (scan->prune.head.flags & HAMMER_IOC_PRUNE_ALL) == 0) {
186                         fprintf(stderr, "No snapshots found\n");
187                         continue;
188                 }
189
190                 printf("Prune %s: objspace %016jx:%04x %016jx:%04x "
191                        "pfs_id %d\n",
192                        scan->filesystem,
193                        (uintmax_t)scan->prune.key_beg.obj_id,
194                        scan->prune.key_beg.localization,
195                        (uintmax_t)scan->prune.key_end.obj_id,
196                        scan->prune.key_end.localization,
197                        pfs.pfs_id);
198                 printf("Prune %s: prune_min is %dd/%02d:%02d:%02d\n",
199                        scan->filesystem,
200                         pfs.ondisk->prune_min / (24 * 60 * 60),
201                         pfs.ondisk->prune_min / 60 / 60 % 24,
202                         pfs.ondisk->prune_min / 60 % 60,
203                         pfs.ondisk->prune_min % 60);
204
205                 RunningIoctl = 1;
206                 if (ioctl(fd, HAMMERIOC_PRUNE, &scan->prune) < 0) {
207                         printf("Prune %s failed: %s\n",
208                                scan->filesystem, strerror(errno));
209                         rcode = 2;
210                 } else if (scan->prune.head.flags & HAMMER_IOC_HEAD_INTR) {
211                         printf("Prune %s interrupted by timer at "
212                                "%016jx %04x\n",
213                                scan->filesystem,
214                                (uintmax_t)scan->prune.key_cur.obj_id,
215                                scan->prune.key_cur.localization);
216                         if (CyclePath)
217                                 hammer_set_cycle(&scan->prune.key_cur, 0);
218                         rcode = 0;
219                 } else {
220                         if (CyclePath)
221                                 hammer_reset_cycle();
222                         printf("Prune %s succeeded\n", scan->filesystem);
223                 }
224                 printf("Pruned %jd/%jd records (%jd directory entries) "
225                        "and %jd bytes\n",
226                         (uintmax_t)scan->prune.stat_rawrecords,
227                         (uintmax_t)scan->prune.stat_scanrecords,
228                         (uintmax_t)scan->prune.stat_dirrecords,
229                         (uintmax_t)scan->prune.stat_bytes
230                 );
231                 RunningIoctl = 0;
232                 close(fd);
233         }
234         if (rcode)
235                 exit(rcode);
236 }
237
238 /*
239  * Scan a directory for softlinks representing snapshots and build
240  * associated softprune structures.
241  *
242  * NOTE: Once a filesystem is completely converted to the meta-data
243  *       snapshot mechanic we don't have to scan softlinks any more
244  *       and can just use the meta-data.  But for now we do both.
245  */
246 static void
247 hammer_softprune_scandir(struct softprune **basep,
248                          struct hammer_ioc_prune *template,
249                          const char *dirname)
250 {
251         struct stat st;
252         struct dirent *den;
253         DIR *dir;
254         char *path;
255         int len;
256         char *linkbuf;
257         char *ptr;
258
259         path = NULL;
260         linkbuf = malloc(MAXPATHLEN);
261
262         if ((dir = opendir(dirname)) == NULL)
263                 err(1, "Cannot open directory %s", dirname);
264         while ((den = readdir(dir)) != NULL) {
265                 if (strcmp(den->d_name, ".") == 0)
266                         continue;
267                 if (strcmp(den->d_name, "..") == 0)
268                         continue;
269                 if (path)
270                         free(path);
271                 asprintf(&path, "%s/%s", dirname, den->d_name);
272                 if (lstat(path, &st) < 0)
273                         continue;
274                 if (!S_ISLNK(st.st_mode))
275                         continue;
276                 if ((len = readlink(path, linkbuf, MAXPATHLEN - 1)) < 0)
277                         continue;
278                 linkbuf[len] = 0;
279                 if ((ptr = strrchr(linkbuf, '@')) &&
280                     ptr > linkbuf && ptr[-1] == '@')
281                         hammer_softprune_addentry(basep, template,
282                                                   dirname, den->d_name, &st,
283                                                   linkbuf, ptr - 1);
284         }
285         free(linkbuf);
286         if (path)
287                 free(path);
288 }
289
290 /*
291  * Scan a directory for softlinks representing snapshots.
292  * Return 1 if the directory contains snapshots, otherwise 0.
293  */
294 int
295 hammer_softprune_testdir(const char *dirname)
296 {
297         struct softprune *base = NULL;
298         struct hammer_ioc_prune dummy_template;
299
300         bzero(&dummy_template, sizeof(dummy_template));
301         hammer_softprune_scandir(&base, &dummy_template, dirname);
302
303         if (base)
304                 return(1);
305         return(0);
306 }
307
308 /*
309  * Scan the metadata snapshots for the filesystem and either delete them
310  * or add them to the pruning list.
311  */
312 static
313 int
314 hammer_softprune_scanmeta(int fd, struct softprune *scan, int delete_all)
315 {
316         struct hammer_ioc_version       version;
317         struct hammer_ioc_snapshot      snapshot;
318         struct hammer_ioc_snapshot      dsnapshot;
319         hammer_snapshot_data_t          snap;
320         time_t ct;
321
322         /*
323          * Stop if we can't get the version.  Meta-data snapshots only
324          * exist for HAMMER version 3 or greater.
325          */
326         bzero(&version, sizeof(version));
327         if (ioctl(fd, HAMMERIOC_GET_VERSION, &version) < 0)
328                 return(-1);
329         HammerVersion = version.cur_version;
330         if (version.cur_version < 3)
331                 return(0);
332
333         bzero(&snapshot, sizeof(snapshot));
334         bzero(&dsnapshot, sizeof(dsnapshot));
335
336         /*
337          * Scan meta-data snapshots, either add them to the prune list or
338          * delete them.  When deleting, just skip any entries which cannot
339          * be deleted.
340          */
341         for (;;) {
342                 if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
343                         printf("hammer prune: Unable to access "
344                                "meta-data snaps: %s\n", strerror(errno));
345                         return(-1);
346                 }
347                 while (snapshot.index < snapshot.count) {
348                         snap = &snapshot.snaps[snapshot.index];
349                         if (delete_all) {
350                                 dsnapshot.snaps[dsnapshot.count++] = *snap;
351                                 if (dsnapshot.count == HAMMER_SNAPS_PER_IOCTL)
352                                         hammer_meta_flushdelete(fd, &dsnapshot);
353                         } else {
354                                 ct = snap->ts / 1000000ULL;
355                                 hammer_softprune_addelm(scan, snap->tid,
356                                                         ct, ct);
357                         }
358                         ++snapshot.index;
359                 }
360                 if (snapshot.head.flags & HAMMER_IOC_SNAPSHOT_EOF)
361                         break;
362                 snapshot.index = 0;
363         }
364         if (delete_all)
365                 hammer_meta_flushdelete(fd, &dsnapshot);
366         return(0);
367 }
368
369 /*
370  * Flush any entries built up in the deletion snapshot ioctl structure.
371  * Used during a prune-everything.
372  */
373 static void
374 hammer_meta_flushdelete(int fd, struct hammer_ioc_snapshot *dsnap)
375 {
376         while (dsnap->index < dsnap->count) {
377                 if (ioctl(fd, HAMMERIOC_DEL_SNAPSHOT, dsnap) < 0)
378                         break;
379                 if (dsnap->head.error == 0)
380                         break;
381                 ++dsnap->index;
382         }
383         dsnap->index = 0;
384         dsnap->count = 0;
385 }
386
387 /*
388  * Add the softlink to the appropriate softprune structure, creating a new
389  * one if necessary.
390  */
391 static
392 struct softprune *
393 hammer_softprune_addentry(struct softprune **basep,
394                          struct hammer_ioc_prune *template,
395                          const char *dirpath, const char *denname __unused,
396                          struct stat *st,
397                          const char *linkbuf, const char *tidptr)
398 {
399         struct softprune *scan;
400         struct statfs fs;
401         char *fspath;
402
403         /*
404          * Calculate filesystem path.
405          */
406         if (linkbuf[0] == '/')
407                 asprintf(&fspath, "%*.*s",
408                          (int)(tidptr - linkbuf), (int)(tidptr - linkbuf),
409                          linkbuf);
410         else
411                 asprintf(&fspath, "%s/%*.*s", dirpath,
412                          (int)(tidptr - linkbuf), (int)(tidptr - linkbuf),
413                          linkbuf);
414         if (statfs(fspath, &fs) < 0) {
415                 free(fspath);
416                 return(NULL);
417         }
418
419         /*
420          * Locate the filesystem in an existing softprune structure
421          */
422         for (scan = *basep; scan; scan = scan->next) {
423                 if (bcmp(&fs.f_fsid, &scan->fs.f_fsid, sizeof(fs.f_fsid)) != 0)
424                         continue;
425                 if (strcmp(fs.f_mntonname, scan->fs.f_mntonname) != 0)
426                         continue;
427                 break;
428         }
429
430         /*
431          * Create a new softprune structure if necessasry
432          */
433         if (scan == NULL) {
434                 scan = malloc(sizeof(*scan));
435                 bzero(scan, sizeof(*scan));
436
437                 scan->fs = fs;
438                 scan->filesystem = fspath;
439                 scan->prune = *template;
440                 scan->maxelms = 32;
441                 scan->prune.elms = malloc(sizeof(struct hammer_ioc_prune_elm) *
442                                           scan->maxelms);
443                 scan->next = *basep;
444                 *basep = scan;
445         } else {
446                 free(fspath);
447         }
448         hammer_softprune_addelm(scan,
449                                 (hammer_tid_t)strtoull(tidptr + 2, NULL, 0),
450                                 (st ? st->st_ctime : 0),
451                                 (st ? st->st_mtime : 0));
452         return(scan);
453 }
454
455 /*
456  * Add the entry (unsorted).  Just set the beg_tid, we will sort
457  * and set the remaining entries later.
458  *
459  * Always leave one entry free for our terminator.
460  */
461 static void
462 hammer_softprune_addelm(struct softprune *scan, hammer_tid_t tid,
463                         time_t ct, time_t mt)
464 {
465         struct hammer_ioc_prune_elm *elm;
466
467         if (scan->prune.nelms >= scan->maxelms - 1) {
468                 scan->maxelms = (scan->maxelms * 3 / 2);
469                 scan->prune.elms = realloc(scan->prune.elms,
470                                            sizeof(*elm) * scan->maxelms);
471         }
472
473         /*
474          * NOTE: Temporarily store the snapshot timestamp in mod_tid.
475          *       This will be cleaned up in the finalization phase.
476          */
477         elm = &scan->prune.elms[scan->prune.nelms];
478         elm->beg_tid = tid;
479         elm->end_tid = 0;
480         elm->mod_tid = 0;
481         if (ct < mt)
482                 elm->mod_tid = ct;
483         else
484                 elm->mod_tid = mt;
485         ++scan->prune.nelms;
486 }
487
488 /*
489  * Finalize a softprune structure after scanning in its softlinks.
490  * Sort the elements, remove duplicates, and then fill in end_tid and
491  * mod_tid.
492  *
493  * The array must end up in descending order.
494  */
495 static int
496 hammer_softprune_qsort_cmp(const void *arg1, const void *arg2)
497 {
498         const struct hammer_ioc_prune_elm *elm1 = arg1;
499         const struct hammer_ioc_prune_elm *elm2 = arg2;
500
501         if (elm1->beg_tid < elm2->beg_tid)
502                 return(1);
503         if (elm1->beg_tid > elm2->beg_tid)
504                 return(-1);
505         return(0);
506 }
507
508 static void
509 hammer_softprune_finalize(struct softprune *scan)
510 {
511         struct hammer_ioc_prune_elm *elm;
512         time_t t;
513         long delta;
514         int i;
515
516         /*
517          * Don't do anything if there are no elements.
518          */
519         if (scan->prune.nelms == 0)
520                 return;
521
522         /*
523          * Sort the elements in descending order, remove duplicates, and
524          * fill in any missing bits.
525          */
526         qsort(scan->prune.elms, scan->prune.nelms, sizeof(*elm),
527               hammer_softprune_qsort_cmp);
528
529         for (i = 0; i < scan->prune.nelms; ++i) {
530                 elm = &scan->prune.elms[i];
531                 if (i == 0) {
532                         /*
533                          * First (highest TID) (also last if only one element)
534                          */
535                         elm->end_tid = HAMMER_MAX_TID;
536                 } else if (elm[0].beg_tid == elm[-1].beg_tid) {
537                         /*
538                          * Remove duplicate
539                          */
540                         --scan->prune.nelms;
541                         if (i != scan->prune.nelms)
542                                 bcopy(elm + 1, elm,
543                                       (scan->prune.nelms - i) * sizeof(*elm));
544                         --i;
545                         continue;
546                 } else {
547                         /*
548                          * Middle or last.
549                          */
550                         elm->end_tid = elm[-1].beg_tid;
551                 }
552         }
553
554         /*
555          * If a minimum retention time (in seconds) is configured for the
556          * PFS, remove any snapshots from the pruning list that are within
557          * the period.
558          */
559         if (scan->prune_min) {
560                 t = time(NULL);
561                 for (i = scan->prune.nelms - 1; i >= 0; --i) {
562                         elm = &scan->prune.elms[i];
563                         if (elm->mod_tid == 0)
564                                 continue;
565                         delta = (long)(t - (time_t)elm->mod_tid);
566                         if (delta < scan->prune_min)
567                                 break;
568                 }
569                 ++i;
570                 if (i) {
571                         printf("Prune %s: prune_min: Will not clean between "
572                                "the teeth of the first %d snapshots\n",
573                                scan->filesystem, i);
574                         bcopy(&scan->prune.elms[i], &scan->prune.elms[0],
575                               (scan->prune.nelms - i) * sizeof(scan->prune.elms[0]));
576                         scan->prune.elms[0].end_tid = HAMMER_MAX_TID;
577                         scan->prune.nelms -= i;
578                 }
579         }
580
581         /*
582          * Remove the first entry.  This entry represents the prune from
583          * the most recent snapshot to current.  We wish to retain the
584          * fine-grained history for this region.
585          */
586         if (scan->prune.nelms) {
587                 bcopy(&scan->prune.elms[1], &scan->prune.elms[0],
588                       (scan->prune.nelms - 1) * sizeof(scan->prune.elms[0]));
589                 --scan->prune.nelms;
590         }
591
592         /*
593          * Add a final element to prune everything from transaction id
594          * 0 to the lowest transaction id (aka last so far).
595          */
596         if (scan->prune.nelms) {
597                 assert(scan->prune.nelms < scan->maxelms);
598                 elm = &scan->prune.elms[scan->prune.nelms];
599                 elm->beg_tid = 1;
600                 elm->end_tid = elm[-1].beg_tid;
601                 ++scan->prune.nelms;
602         }
603
604         /*
605          * Adjust mod_tid to what the ioctl() expects.
606          */
607         for (i = 0; i < scan->prune.nelms; ++i) {
608                 elm = &scan->prune.elms[i];
609                 elm->mod_tid = elm->end_tid - elm->beg_tid;
610                 printf("TID %016jx - %016jx\n",
611                        (uintmax_t)elm->beg_tid, (uintmax_t)elm->end_tid);
612         }
613 }
614
615 static
616 void
617 softprune_usage(int code)
618 {
619         fprintf(stderr, "Badly formed prune command, use:\n");
620         fprintf(stderr, "hammer prune <softlink-dir>\n");
621         fprintf(stderr, "hammer prune-everything <filesystem>\n");
622         exit(code);
623 }
624