hammer - HAMMER Version 7
[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                 }
185                 if (scan->prune.nelms == 0 &&
186                     (scan->prune.head.flags & HAMMER_IOC_PRUNE_ALL) == 0) {
187                         fprintf(stderr, "No snapshots found\n");
188                         continue;
189                 }
190
191                 printf("Prune %s: objspace %016jx:%04x %016jx:%04x "
192                        "pfs_id %d\n",
193                        scan->filesystem,
194                        (uintmax_t)scan->prune.key_beg.obj_id,
195                        scan->prune.key_beg.localization,
196                        (uintmax_t)scan->prune.key_end.obj_id,
197                        scan->prune.key_end.localization,
198                        pfs.pfs_id);
199                 printf("Prune %s: prune_min is %dd/%02d:%02d:%02d\n",
200                        scan->filesystem,
201                         pfs.ondisk->prune_min / (24 * 60 * 60),
202                         pfs.ondisk->prune_min / 60 / 60 % 24,
203                         pfs.ondisk->prune_min / 60 % 60,
204                         pfs.ondisk->prune_min % 60);
205
206                 RunningIoctl = 1;
207                 if (ioctl(fd, HAMMERIOC_PRUNE, &scan->prune) < 0) {
208                         printf("Prune %s failed: %s\n",
209                                scan->filesystem, strerror(errno));
210                         rcode = 2;
211                 } else if (scan->prune.head.flags & HAMMER_IOC_HEAD_INTR) {
212                         printf("Prune %s interrupted by timer at "
213                                "%016jx %04x\n",
214                                scan->filesystem,
215                                (uintmax_t)scan->prune.key_cur.obj_id,
216                                scan->prune.key_cur.localization);
217                         if (CyclePath)
218                                 hammer_set_cycle(&scan->prune.key_cur, 0);
219                         rcode = 0;
220                 } else {
221                         if (CyclePath)
222                                 hammer_reset_cycle();
223                         printf("Prune %s succeeded\n", scan->filesystem);
224                 }
225                 printf("Pruned %jd/%jd records (%jd directory entries) "
226                        "and %jd bytes\n",
227                         (uintmax_t)scan->prune.stat_rawrecords,
228                         (uintmax_t)scan->prune.stat_scanrecords,
229                         (uintmax_t)scan->prune.stat_dirrecords,
230                         (uintmax_t)scan->prune.stat_bytes
231                 );
232                 RunningIoctl = 0;
233                 close(fd);
234         }
235         if (rcode)
236                 exit(rcode);
237 }
238
239 /*
240  * Scan a directory for softlinks representing snapshots and build
241  * associated softprune structures.
242  *
243  * NOTE: Once a filesystem is completely converted to the meta-data
244  *       snapshot mechanic we don't have to scan softlinks any more
245  *       and can just use the meta-data.  But for now we do both.
246  */
247 static void
248 hammer_softprune_scandir(struct softprune **basep,
249                          struct hammer_ioc_prune *template,
250                          const char *dirname)
251 {
252         struct stat st;
253         struct dirent *den;
254         DIR *dir;
255         char *path;
256         int len;
257         char *linkbuf;
258         char *ptr;
259
260         path = NULL;
261         linkbuf = malloc(MAXPATHLEN);
262
263         if ((dir = opendir(dirname)) == NULL)
264                 err(1, "Cannot open directory %s", dirname);
265         while ((den = readdir(dir)) != NULL) {
266                 if (strcmp(den->d_name, ".") == 0)
267                         continue;
268                 if (strcmp(den->d_name, "..") == 0)
269                         continue;
270                 if (path)
271                         free(path);
272                 asprintf(&path, "%s/%s", dirname, den->d_name);
273                 if (lstat(path, &st) < 0)
274                         continue;
275                 if (!S_ISLNK(st.st_mode))
276                         continue;
277                 if ((len = readlink(path, linkbuf, MAXPATHLEN - 1)) < 0)
278                         continue;
279                 linkbuf[len] = 0;
280                 if ((ptr = strrchr(linkbuf, '@')) &&
281                     ptr > linkbuf && ptr[-1] == '@') {
282                         hammer_softprune_addentry(basep, template,
283                                                   dirname, den->d_name, &st,
284                                                   linkbuf, ptr - 1);
285                 }
286         }
287         free(linkbuf);
288         if (path)
289                 free(path);
290 }
291
292 /*
293  * Scan a directory for softlinks representing snapshots.
294  * Return 1 if the directory contains snapshots, otherwise 0.
295  */
296 int
297 hammer_softprune_testdir(const char *dirname)
298 {
299         struct softprune *base = NULL;
300         struct hammer_ioc_prune dummy_template;
301
302         bzero(&dummy_template, sizeof(dummy_template));
303         hammer_softprune_scandir(&base, &dummy_template, dirname);
304
305         if (base)
306                 return(1);
307         return(0);
308 }
309
310 /*
311  * Scan the metadata snapshots for the filesystem and either delete them
312  * or add them to the pruning list.
313  */
314 static
315 int
316 hammer_softprune_scanmeta(int fd, struct softprune *scan, int delete_all)
317 {
318         struct hammer_ioc_version       version;
319         struct hammer_ioc_snapshot      snapshot;
320         struct hammer_ioc_snapshot      dsnapshot;
321         hammer_snapshot_data_t          snap;
322         time_t ct;
323
324         /*
325          * Stop if we can't get the version.  Meta-data snapshots only
326          * exist for HAMMER version 3 or greater.
327          */
328         bzero(&version, sizeof(version));
329         if (ioctl(fd, HAMMERIOC_GET_VERSION, &version) < 0)
330                 return(-1);
331         HammerVersion = version.cur_version;
332         if (version.cur_version < 3)
333                 return(0);
334
335         bzero(&snapshot, sizeof(snapshot));
336         bzero(&dsnapshot, sizeof(dsnapshot));
337
338         /*
339          * Scan meta-data snapshots, either add them to the prune list or
340          * delete them.  When deleting, just skip any entries which cannot
341          * be deleted.
342          */
343         for (;;) {
344                 if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
345                         printf("hammer prune: Unable to access "
346                                "meta-data snaps: %s\n", strerror(errno));
347                         return(-1);
348                 }
349                 while (snapshot.index < snapshot.count) {
350                         snap = &snapshot.snaps[snapshot.index];
351                         if (delete_all) {
352                                 dsnapshot.snaps[dsnapshot.count++] = *snap;
353                                 if (dsnapshot.count == HAMMER_SNAPS_PER_IOCTL)
354                                         hammer_meta_flushdelete(fd, &dsnapshot);
355                         } else {
356                                 ct = snap->ts / 1000000ULL;
357                                 hammer_softprune_addelm(scan, snap->tid,
358                                                         ct, ct);
359                         }
360                         ++snapshot.index;
361                 }
362                 if (snapshot.head.flags & HAMMER_IOC_SNAPSHOT_EOF)
363                         break;
364                 snapshot.index = 0;
365         }
366         if (delete_all)
367                 hammer_meta_flushdelete(fd, &dsnapshot);
368         return(0);
369 }
370
371 /*
372  * Flush any entries built up in the deletion snapshot ioctl structure.
373  * Used during a prune-everything.
374  */
375 static void
376 hammer_meta_flushdelete(int fd, struct hammer_ioc_snapshot *dsnap)
377 {
378         while (dsnap->index < dsnap->count) {
379                 if (ioctl(fd, HAMMERIOC_DEL_SNAPSHOT, dsnap) < 0)
380                         break;
381                 if (dsnap->head.error == 0)
382                         break;
383                 ++dsnap->index;
384         }
385         dsnap->index = 0;
386         dsnap->count = 0;
387 }
388
389 /*
390  * Add the softlink to the appropriate softprune structure, creating a new
391  * one if necessary.
392  */
393 static
394 struct softprune *
395 hammer_softprune_addentry(struct softprune **basep,
396                          struct hammer_ioc_prune *template,
397                          const char *dirpath, const char *denname __unused,
398                          struct stat *st,
399                          const char *linkbuf, const char *tidptr)
400 {
401         struct softprune *scan;
402         struct statfs fs;
403         char *fspath;
404
405         /*
406          * Calculate filesystem path.
407          */
408         if (linkbuf[0] == '/') {
409                 asprintf(&fspath, "%*.*s",
410                          (int)(tidptr - linkbuf), (int)(tidptr - linkbuf),
411                          linkbuf);
412         } else {
413                 asprintf(&fspath, "%s/%*.*s", dirpath,
414                          (int)(tidptr - linkbuf), (int)(tidptr - linkbuf),
415                          linkbuf);
416         }
417         if (statfs(fspath, &fs) < 0) {
418                 free(fspath);
419                 return(NULL);
420         }
421
422         /*
423          * Locate the filesystem in an existing softprune structure
424          */
425         for (scan = *basep; scan; scan = scan->next) {
426                 if (bcmp(&fs.f_fsid, &scan->fs.f_fsid, sizeof(fs.f_fsid)) != 0)
427                         continue;
428                 if (strcmp(fs.f_mntonname, scan->fs.f_mntonname) != 0)
429                         continue;
430                 break;
431         }
432
433         /*
434          * Create a new softprune structure if necessasry
435          */
436         if (scan == NULL) {
437                 scan = malloc(sizeof(*scan));
438                 bzero(scan, sizeof(*scan));
439
440                 scan->fs = fs;
441                 scan->filesystem = fspath;
442                 scan->prune = *template;
443                 scan->maxelms = 32;
444                 scan->prune.elms = malloc(sizeof(struct hammer_ioc_prune_elm) *
445                                           scan->maxelms);
446                 scan->next = *basep;
447                 *basep = scan;
448         } else {
449                 free(fspath);
450         }
451         hammer_softprune_addelm(scan,
452                                 (hammer_tid_t)strtoull(tidptr + 2, NULL, 0),
453                                 (st ? st->st_ctime : 0),
454                                 (st ? st->st_mtime : 0));
455         return(scan);
456 }
457
458 /*
459  * Add the entry (unsorted).  Just set the beg_tid, we will sort
460  * and set the remaining entries later.
461  *
462  * Always leave one entry free for our terminator.
463  */
464 static void
465 hammer_softprune_addelm(struct softprune *scan, hammer_tid_t tid,
466                         time_t ct, time_t mt)
467 {
468         struct hammer_ioc_prune_elm *elm;
469
470         if (scan->prune.nelms >= scan->maxelms - 1) {
471                 scan->maxelms = (scan->maxelms * 3 / 2);
472                 scan->prune.elms = realloc(scan->prune.elms,
473                                            sizeof(*elm) * scan->maxelms);
474         }
475
476         /*
477          * NOTE: Temporarily store the snapshot timestamp in mod_tid.
478          *       This will be cleaned up in the finalization phase.
479          */
480         elm = &scan->prune.elms[scan->prune.nelms];
481         elm->beg_tid = tid;
482         elm->end_tid = 0;
483         elm->mod_tid = 0;
484         if (ct < mt)
485                 elm->mod_tid = ct;
486         else
487                 elm->mod_tid = mt;
488         ++scan->prune.nelms;
489 }
490
491 /*
492  * Finalize a softprune structure after scanning in its softlinks.
493  * Sort the elements, remove duplicates, and then fill in end_tid and
494  * mod_tid.
495  *
496  * The array must end up in descending order.
497  */
498 static int
499 hammer_softprune_qsort_cmp(const void *arg1, const void *arg2)
500 {
501         const struct hammer_ioc_prune_elm *elm1 = arg1;
502         const struct hammer_ioc_prune_elm *elm2 = arg2;
503
504         if (elm1->beg_tid < elm2->beg_tid)
505                 return(1);
506         if (elm1->beg_tid > elm2->beg_tid)
507                 return(-1);
508         return(0);
509 }
510
511 static void
512 hammer_softprune_finalize(struct softprune *scan)
513 {
514         struct hammer_ioc_prune_elm *elm;
515         time_t t;
516         long delta;
517         int i;
518
519         /*
520          * Don't do anything if there are no elements.
521          */
522         if (scan->prune.nelms == 0)
523                 return;
524
525         /*
526          * Sort the elements in descending order, remove duplicates, and
527          * fill in any missing bits.
528          */
529         qsort(scan->prune.elms, scan->prune.nelms, sizeof(*elm),
530               hammer_softprune_qsort_cmp);
531
532         for (i = 0; i < scan->prune.nelms; ++i) {
533                 elm = &scan->prune.elms[i];
534                 if (i == 0) {
535                         /*
536                          * First (highest TID) (also last if only one element)
537                          */
538                         elm->end_tid = HAMMER_MAX_TID;
539                 } else if (elm[0].beg_tid == elm[-1].beg_tid) {
540                         /*
541                          * Remove duplicate
542                          */
543                         --scan->prune.nelms;
544                         if (i != scan->prune.nelms) {
545                                 bcopy(elm + 1, elm,
546                                       (scan->prune.nelms - i) * sizeof(*elm));
547                         }
548                         --i;
549                         continue;
550                 } else {
551                         /*
552                          * Middle or last.
553                          */
554                         elm->end_tid = elm[-1].beg_tid;
555                 }
556         }
557
558         /*
559          * If a minimum retention time (in seconds) is configured for the
560          * PFS, remove any snapshots from the pruning list that are within
561          * the period.
562          */
563         if (scan->prune_min) {
564                 t = time(NULL);
565                 for (i = scan->prune.nelms - 1; i >= 0; --i) {
566                         elm = &scan->prune.elms[i];
567                         if (elm->mod_tid == 0)
568                                 continue;
569                         delta = (long)(t - (time_t)elm->mod_tid);
570                         if (delta < scan->prune_min)
571                                 break;
572                 }
573                 ++i;
574                 if (i) {
575                         printf("Prune %s: prune_min: Will not clean between "
576                                "the teeth of the first %d snapshots\n",
577                                scan->filesystem, i);
578                         bcopy(&scan->prune.elms[i], &scan->prune.elms[0],
579                               (scan->prune.nelms - i) * sizeof(scan->prune.elms[0]));
580                         scan->prune.elms[0].end_tid = HAMMER_MAX_TID;
581                         scan->prune.nelms -= i;
582                 }
583         }
584
585         /*
586          * Remove the first entry.  This entry represents the prune from
587          * the most recent snapshot to current.  We wish to retain the
588          * fine-grained history for this region.
589          */
590         if (scan->prune.nelms) {
591                 bcopy(&scan->prune.elms[1], &scan->prune.elms[0],
592                       (scan->prune.nelms - 1) * sizeof(scan->prune.elms[0]));
593                 --scan->prune.nelms;
594         }
595
596         /*
597          * Add a final element to prune everything from transaction id
598          * 0 to the lowest transaction id (aka last so far).
599          */
600         if (scan->prune.nelms) {
601                 assert(scan->prune.nelms < scan->maxelms);
602                 elm = &scan->prune.elms[scan->prune.nelms];
603                 elm->beg_tid = 1;
604                 elm->end_tid = elm[-1].beg_tid;
605                 ++scan->prune.nelms;
606         }
607
608         /*
609          * Adjust mod_tid to what the ioctl() expects.
610          */
611         for (i = 0; i < scan->prune.nelms; ++i) {
612                 elm = &scan->prune.elms[i];
613                 elm->mod_tid = elm->end_tid - elm->beg_tid;
614                 printf("TID %016jx - %016jx\n",
615                        (uintmax_t)elm->beg_tid, (uintmax_t)elm->end_tid);
616         }
617 }
618
619 static
620 void
621 softprune_usage(int code)
622 {
623         fprintf(stderr, "Badly formed prune command, use:\n");
624         fprintf(stderr, "hammer prune <softlink-dir>\n");
625         fprintf(stderr, "hammer prune-everything <filesystem>\n");
626         exit(code);
627 }
628
629