hammer - HAMMER Version 7
[dragonfly.git] / sbin / hammer / cmd_cleanup.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 /*
35  * Clean up specific HAMMER filesystems or all HAMMER filesystems.
36  *
37  * If no filesystems are specified any HAMMER- or null-mounted hammer PFS's
38  * are cleaned.
39  *
40  * Each HAMMER filesystem may contain a configuration file.  If no
41  * configuration file is present one will be created with the following
42  * defaults:
43  *
44  *      snapshots 1d 60d        (0d 0d for /tmp, /var/tmp, /usr/obj)
45  *      prune     1d 5m
46  *      rebalance 1d 5m
47  *      #dedup    1d 5m         (not enabled by default)
48  *      reblock   1d 5m
49  *      recopy    30d 10m
50  *
51  * All hammer commands create and maintain cycle files in the snapshots
52  * directory.
53  *
54  * For HAMMER version 2- the configuration file is a named 'config' in
55  * the snapshots directory, which defaults to <pfs>/snapshots.
56  * For HAMMER version 3+ the configuration file is saved in filesystem
57  * meta-data. The snapshots directory defaults to /var/hammer/<pfs>
58  * (/var/hammer/root for root mount).
59  */
60
61 #include <libutil.h>
62
63 #include "hammer.h"
64
65 struct didpfs {
66         struct didpfs *next;
67         uuid_t          uuid;
68 };
69
70 static void do_cleanup(const char *path);
71 static void config_init(const char *path, struct hammer_ioc_config *config);
72 static void migrate_config(FILE *fp, struct hammer_ioc_config *config);
73 static void migrate_snapshots(int fd, const char *snapshots_path);
74 static void migrate_one_snapshot(int fd, const char *fpath,
75                         struct hammer_ioc_snapshot *snapshot);
76 static int strtosecs(char *ptr);
77 static const char *dividing_slash(const char *path);
78 static int check_period(const char *snapshots_path, const char *cmd, int arg1,
79                         time_t *savep);
80 static void save_period(const char *snapshots_path, const char *cmd,
81                         time_t savet);
82 static int check_softlinks(int fd, int new_config, const char *snapshots_path);
83 static void cleanup_softlinks(int fd, int new_config,
84                         const char *snapshots_path, int arg2, char *arg3);
85 static void delete_snapshots(int fd, struct hammer_ioc_snapshot *dsnapshot);
86 static int check_expired(const char *fpath, int arg2);
87
88 static int create_snapshot(const char *path, const char *snapshots_path);
89 static int cleanup_rebalance(const char *path, const char *snapshots_path,
90                         int arg1, int arg2);
91 static int cleanup_prune(const char *path, const char *snapshots_path,
92                         int arg1, int arg2, int snapshots_disabled);
93 static int cleanup_reblock(const char *path, const char *snapshots_path,
94                         int arg1, int arg2);
95 static int cleanup_recopy(const char *path, const char *snapshots_path,
96                         int arg1, int arg2);
97 static int cleanup_dedup(const char *path, const char *snapshots_path,
98                         int arg1, int arg2);
99
100 static void runcmd(int *resp, const char *ctl, ...) __printflike(2, 3);
101
102 #define WS      " \t\r\n"
103
104 struct didpfs *FirstPFS;
105
106 void
107 hammer_cmd_cleanup(char **av, int ac)
108 {
109         char *fstype, *fs, *path;
110         struct statfs *stfsbuf;
111         int mntsize, i;
112
113         tzset();
114         if (ac == 0) {
115                 mntsize = getmntinfo(&stfsbuf, MNT_NOWAIT);
116                 if (mntsize > 0) {
117                         for (i=0; i < mntsize; i++) {
118                                 /*
119                                  * We will cleanup in the case fstype is hammer.
120                                  * If we have null-mounted PFS, we check the
121                                  * mount source. If it looks like a PFS, we
122                                  * proceed to cleanup also.
123                                  */
124                                 fstype = stfsbuf[i].f_fstypename;
125                                 fs = stfsbuf[i].f_mntfromname;
126                                 if ((strcmp(fstype, "hammer") == 0) ||
127                                     ((strcmp(fstype, "null") == 0) &&
128                                      (strstr(fs, "/@@0x") != NULL ||
129                                       strstr(fs, "/@@-1") != NULL))) {
130                                         path = stfsbuf[i].f_mntonname;
131                                         do_cleanup(path);
132                                 }
133                         }
134                 }
135
136         } else {
137                 while (ac) {
138                         do_cleanup(*av);
139                         --ac;
140                         ++av;
141                 }
142         }
143 }
144
145 static
146 void
147 do_cleanup(const char *path)
148 {
149         struct hammer_ioc_pseudofs_rw pfs;
150         struct hammer_ioc_config config;
151         struct hammer_ioc_version version;
152         union hammer_ioc_mrecord_any mrec_tmp;
153         char *snapshots_path = NULL;
154         char *config_path;
155         struct stat st;
156         char *cmd;
157         char *ptr;
158         int arg1;
159         int arg2;
160         char *arg3;
161         time_t savet;
162         char buf[256];
163         char *cbase;
164         char *cptr;
165         FILE *fp = NULL;
166         struct didpfs *didpfs;
167         int snapshots_disabled = 0;
168         int prune_warning = 0;
169         int new_config = 0;
170         int snapshots_from_pfs = 0;
171         int fd;
172         int r;
173         int found_rebal = 0;
174
175         bzero(&mrec_tmp, sizeof(mrec_tmp));
176         clrpfs(&pfs, &mrec_tmp.pfs.pfsd, -1);
177
178         printf("cleanup %-20s -", path);
179         fd = open(path, O_RDONLY);
180         if (fd < 0) {
181                 printf(" unable to access directory: %s\n", strerror(errno));
182                 return;
183         }
184         if (ioctl(fd, HAMMERIOC_GET_PSEUDOFS, &pfs) < 0) {
185                 printf(" not a HAMMER filesystem: %s\n", strerror(errno));
186                 close(fd);
187                 return;
188         }
189         if (pfs.version != HAMMER_IOC_PSEUDOFS_VERSION) {
190                 printf(" unrecognized HAMMER version\n");
191                 close(fd);
192                 return;
193         }
194         bzero(&version, sizeof(version));
195         if (ioctl(fd, HAMMERIOC_GET_VERSION, &version) < 0) {
196                 printf(" HAMMER filesystem but couldn't retrieve version!\n");
197                 close(fd);
198                 return;
199         }
200         HammerVersion = version.cur_version;
201
202         bzero(&config, sizeof(config));
203         if (version.cur_version >= 3) {
204                 if (ioctl(fd, HAMMERIOC_GET_CONFIG, &config) == 0 &&
205                     config.head.error == 0) {
206                         new_config = 1;
207                 }
208         }
209
210         /*
211          * Make sure we have not already handled this PFS.  Several nullfs
212          * mounts might alias the same PFS.
213          */
214         for (didpfs = FirstPFS; didpfs; didpfs = didpfs->next) {
215                 if (bcmp(&didpfs->uuid, &mrec_tmp.pfs.pfsd.unique_uuid, sizeof(uuid_t)) == 0) {
216                         printf(" PFS#%d already handled\n", pfs.pfs_id);
217                         close(fd);
218                         return;
219                 }
220         }
221         didpfs = malloc(sizeof(*didpfs));
222         didpfs->next = FirstPFS;
223         FirstPFS = didpfs;
224         didpfs->uuid = mrec_tmp.pfs.pfsd.unique_uuid;
225
226         /*
227          * Calculate the old snapshots directory for HAMMER VERSION < 3
228          *
229          * If the directory is explicitly specified in the PFS config
230          * we flag it and will not migrate it later.
231          */
232         if (mrec_tmp.pfs.pfsd.snapshots[0] == '/') {
233                 asprintf(&snapshots_path, "%s", mrec_tmp.pfs.pfsd.snapshots);
234                 snapshots_from_pfs = 1;
235         } else if (mrec_tmp.pfs.pfsd.snapshots[0]) {
236                 printf(" WARNING: pfs-slave's snapshots dir is not absolute\n");
237                 close(fd);
238                 return;
239         } else if (hammer_is_pfs_slave(&mrec_tmp.pfs.pfsd)) {
240                 if (version.cur_version < 3) {
241                         printf(" WARNING: must configure snapshot dir for PFS slave\n");
242                         printf("\tWe suggest <fs>/var/slaves/<name> where "
243                                "<fs> is the base HAMMER fs\n");
244                         printf("\tcontaining the slave\n");
245                         close(fd);
246                         return;
247                 }
248         } else {
249                 asprintf(&snapshots_path,
250                          "%s%ssnapshots", path, dividing_slash(path));
251         }
252
253         /*
254          * Check for old-style config file
255          */
256         if (snapshots_path) {
257                 asprintf(&config_path, "%s/config", snapshots_path);
258                 fp = fopen(config_path, "r");
259         }
260
261         /*
262          * Handle upgrades to hammer version 3, move the config
263          * file into meta-data.
264          *
265          * For the old config read the file into the config structure,
266          * we will parse it out of the config structure regardless.
267          */
268         if (version.cur_version >= 3) {
269                 if (fp) {
270                         printf("(migrating) ");
271                         fflush(stdout);
272                         migrate_config(fp, &config);
273                         migrate_snapshots(fd, snapshots_path);
274                         fclose(fp);
275                         if (ioctl(fd, HAMMERIOC_SET_CONFIG, &config) < 0) {
276                                 printf(" cannot init meta-data config!\n");
277                                 close(fd);
278                                 return;
279                         }
280                         remove(config_path);
281                 } else if (new_config == 0) {
282                         config_init(path, &config);
283                         if (ioctl(fd, HAMMERIOC_SET_CONFIG, &config) < 0) {
284                                 printf(" cannot init meta-data config!\n");
285                                 close(fd);
286                                 return;
287                         }
288                 }
289                 new_config = 1;
290         } else {
291                 /*
292                  * Create missing snapshots directory for HAMMER VERSION < 3
293                  */
294                 if (stat(snapshots_path, &st) < 0) {
295                         if (mkdir(snapshots_path, 0755) != 0) {
296                                 free(snapshots_path);
297                                 printf(" unable to create snapshot dir \"%s\": %s\n",
298                                         snapshots_path, strerror(errno));
299                                 close(fd);
300                                 return;
301                         }
302                 }
303
304                 /*
305                  *  Create missing config file for HAMMER VERSION < 3
306                  */
307                 if (fp == NULL) {
308                         config_init(path, &config);
309                         fp = fopen(config_path, "w");
310                         if (fp) {
311                                 fwrite(config.config.text, 1,
312                                         strlen(config.config.text), fp);
313                                 fclose(fp);
314                         }
315                 } else {
316                         migrate_config(fp, &config);
317                         fclose(fp);
318                 }
319         }
320
321         /*
322          * If snapshots_from_pfs is not set we calculate the new snapshots
323          * directory default (in /var) for HAMMER VERSION >= 3 and migrate
324          * the old snapshots directory over.
325          *
326          * People who have set an explicit snapshots directory will have
327          * to migrate the data manually into /var/hammer, or not bother at
328          * all.  People running slaves may wish to migrate it and then
329          * clear the snapshots specification in the PFS config for the
330          * slave.
331          */
332         if (new_config && snapshots_from_pfs == 0) {
333                 char *npath;
334
335                 if (path[0] != '/') {
336                         printf(" path must start with '/'\n");
337                         return;
338                 }
339                 if (strcmp(path, "/") == 0)
340                         asprintf(&npath, "%s/root", SNAPSHOTS_BASE);
341                 else
342                         asprintf(&npath, "%s/%s", SNAPSHOTS_BASE, path + 1);
343                 if (snapshots_path) {
344                         if (stat(npath, &st) < 0 && errno == ENOENT) {
345                                 if (stat(snapshots_path, &st) < 0 && errno == ENOENT) {
346                                         printf(" HAMMER UPGRADE: Creating snapshots\n"
347                                                "\tCreating snapshots in %s\n",
348                                                npath);
349                                         runcmd(&r, "mkdir -p %s", npath);
350                                 } else {
351                                         printf(" HAMMER UPGRADE: Moving snapshots\n"
352                                                "\tMoving snapshots from %s to %s\n",
353                                                snapshots_path, npath);
354                                         runcmd(&r, "mkdir -p %s", npath);
355                                         runcmd(&r, "cpdup %s %s", snapshots_path, npath);
356                                         if (r != 0) {
357                                     printf("Unable to move snapshots directory!\n");
358                                     printf("Please fix this critical error.\n");
359                                     printf("Aborting cleanup of %s\n", path);
360                                                 close(fd);
361                                                 return;
362                                         }
363                                         runcmd(&r, "rm -rf %s", snapshots_path);
364                                 }
365                         }
366                         free(snapshots_path);
367                 } else if (stat(npath, &st) < 0 && errno == ENOENT) {
368                         runcmd(&r, "mkdir -p %s", npath);
369                 }
370                 snapshots_path = npath;
371         }
372
373         /*
374          * Lock the PFS.  fd is the base directory of the mounted PFS.
375          */
376         if (flock(fd, LOCK_EX|LOCK_NB) == -1) {
377                 if (errno == EWOULDBLOCK)
378                         printf(" PFS#%d locked by other process\n", pfs.pfs_id);
379                 else
380                         printf(" can not lock %s: %s\n", config_path, strerror(errno));
381                 close(fd);
382                 return;
383         }
384
385         printf(" handle PFS#%d using %s\n", pfs.pfs_id, snapshots_path);
386
387         struct pidfh    *pfh = NULL;
388         static char     pidfile[PIDFILE_BUFSIZE];
389
390         snprintf (pidfile, PIDFILE_BUFSIZE, "%s/hammer.cleanup.%d",
391                 pidfile_loc, getpid());
392         pfh = pidfile_open(pidfile, 0644, NULL);
393         if (pfh == NULL) {
394                 warn ("Unable to open or create %s", pidfile);
395         }
396         pidfile_write(pfh);
397
398         /*
399          * Process the config file
400          */
401         cbase = config.config.text;
402
403         while ((cptr = strchr(cbase, '\n')) != NULL) {
404                 bcopy(cbase, buf, cptr - cbase);
405                 buf[cptr - cbase] = 0;
406                 cbase = cptr + 1;
407
408                 cmd = strtok(buf, WS);
409                 if (cmd == NULL || cmd[0] == '#')
410                         continue;
411
412                 arg1 = 0;
413                 arg2 = 0;
414                 arg3 = NULL;
415                 if ((ptr = strtok(NULL, WS)) != NULL) {
416                         arg1 = strtosecs(ptr);
417                         if ((ptr = strtok(NULL, WS)) != NULL) {
418                                 arg2 = strtosecs(ptr);
419                                 arg3 = strtok(NULL, WS);
420                         }
421                 }
422
423                 printf("%20s - ", cmd);
424                 fflush(stdout);
425
426                 r = 1;
427                 if (strcmp(cmd, "snapshots") == 0) {
428                         if (arg1 == 0) {
429                                 if (arg2 &&
430                                     check_softlinks(fd, new_config,
431                                                     snapshots_path)) {
432                                         printf("only removing old snapshots\n");
433                                         prune_warning = 1;
434                                         cleanup_softlinks(fd, new_config,
435                                                           snapshots_path,
436                                                           arg2, arg3);
437                                 } else {
438                                         printf("disabled\n");
439                                         snapshots_disabled = 1;
440                                 }
441                         } else
442                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
443                                 printf("run\n");
444                                 cleanup_softlinks(fd, new_config,
445                                                   snapshots_path,
446                                                   arg2, arg3);
447                                 r = create_snapshot(path, snapshots_path);
448                         } else {
449                                 printf("skip\n");
450                         }
451                 } else if (arg1 == 0) {
452                         /*
453                          * The commands following this check can't handle
454                          * a period of 0, so call the feature disabled and
455                          * ignore the directive.
456                          */
457                         printf("disabled\n");
458                 } else if (strcmp(cmd, "prune") == 0) {
459                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
460                                 if (prune_warning) {
461                                         printf("run - WARNING snapshot "
462                                                "softlinks present "
463                                                "but snapshots disabled\n");
464                                 } else {
465                                         printf("run\n");
466                                 }
467                                 r = cleanup_prune(path, snapshots_path,
468                                               arg1, arg2, snapshots_disabled);
469                         } else {
470                                 printf("skip\n");
471                         }
472                 } else if (strcmp(cmd, "rebalance") == 0) {
473                         found_rebal = 1;
474                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
475                                 printf("run");
476                                 fflush(stdout);
477                                 if (VerboseOpt)
478                                         printf("\n");
479                                 r = cleanup_rebalance(path, snapshots_path,
480                                                 arg1, arg2);
481                         } else {
482                                 printf("skip\n");
483                         }
484                 } else if (strcmp(cmd, "reblock") == 0) {
485                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
486                                 printf("run");
487                                 fflush(stdout);
488                                 if (VerboseOpt)
489                                         printf("\n");
490                                 r = cleanup_reblock(path, snapshots_path,
491                                                 arg1, arg2);
492                         } else {
493                                 printf("skip\n");
494                         }
495                 } else if (strcmp(cmd, "recopy") == 0) {
496                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
497                                 printf("run");
498                                 fflush(stdout);
499                                 if (VerboseOpt)
500                                         printf("\n");
501                                 r = cleanup_recopy(path, snapshots_path,
502                                                arg1, arg2);
503                         } else {
504                                 printf("skip\n");
505                         }
506                 } else if (strcmp(cmd, "dedup") == 0) {
507                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
508                                 printf("run");
509                                 fflush(stdout);
510                                 if (VerboseOpt)
511                                         printf("\n");
512                                 r = cleanup_dedup(path, snapshots_path,
513                                                 arg1, arg2);
514                         } else {
515                                 printf("skip\n");
516                         }
517                 } else {
518                         printf("unknown directive\n");
519                         r = 1;
520                 }
521                 if (r == 0)
522                         save_period(snapshots_path, cmd, savet);
523         }
524
525         /*
526          * Add new rebalance feature if the config doesn't have it.
527          * (old style config only).
528          */
529         if (new_config == 0 && found_rebal == 0) {
530                 if ((fp = fopen(config_path, "r+")) != NULL) {
531                         fseek(fp, 0L, 2);
532                         fprintf(fp, "rebalance 1d 5m\n");
533                         fclose(fp);
534                 }
535         }
536
537         /*
538          * Cleanup, and delay a little
539          */
540         close(fd);
541         usleep(1000);
542         pidfile_close(pfh);
543         pidfile_remove(pfh);
544 }
545
546 /*
547  * Initialize new config data (new or old style)
548  */
549 static void
550 config_init(const char *path, struct hammer_ioc_config *config)
551 {
552         const char *snapshots;
553
554         if (strcmp(path, "/tmp") == 0 ||
555             strcmp(path, "/var/tmp") == 0 ||
556             strcmp(path, "/usr/obj") == 0) {
557                 snapshots = "snapshots 0d 0d\n";
558         } else {
559                 snapshots = "snapshots 1d 60d\n";
560         }
561         bzero(config->config.text, sizeof(config->config.text));
562         snprintf(config->config.text, sizeof(config->config.text) - 1, "%s%s",
563                 snapshots,
564                 "prune     1d 5m\n"
565                 "rebalance 1d 5m\n"
566                 "#dedup    1d 5m\n"
567                 "reblock   1d 5m\n"
568                 "recopy    30d 10m\n");
569 }
570
571 /*
572  * Migrate configuration data from the old snapshots/config
573  * file to the new meta-data format.
574  */
575 static void
576 migrate_config(FILE *fp, struct hammer_ioc_config *config)
577 {
578         int n;
579
580         n = fread(config->config.text, 1, sizeof(config->config.text) - 1, fp);
581         if (n >= 0)
582                 bzero(config->config.text + n, sizeof(config->config.text) - n);
583 }
584
585 /*
586  * Migrate snapshot softlinks in the snapshots directory to the
587  * new meta-data format.  The softlinks are left intact, but
588  * this way the pruning code won't lose track of them if you
589  * happen to blow away the snapshots directory.
590  */
591 static void
592 migrate_snapshots(int fd, const char *snapshots_path)
593 {
594         struct hammer_ioc_snapshot snapshot;
595         struct dirent *den;
596         struct stat st;
597         DIR *dir;
598         char *fpath;
599
600         bzero(&snapshot, sizeof(snapshot));
601
602         if ((dir = opendir(snapshots_path)) != NULL) {
603                 while ((den = readdir(dir)) != NULL) {
604                         if (den->d_name[0] == '.')
605                                 continue;
606                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
607                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode)) {
608                                 migrate_one_snapshot(fd, fpath, &snapshot);
609                         }
610                         free(fpath);
611                 }
612                 closedir(dir);
613         }
614         migrate_one_snapshot(fd, NULL, &snapshot);
615
616 }
617
618 /*
619  * Migrate a single snapshot.  If fpath is NULL the ioctl is flushed,
620  * otherwise it is flushed when it fills up.
621  */
622 static void
623 migrate_one_snapshot(int fd, const char *fpath,
624                      struct hammer_ioc_snapshot *snapshot)
625 {
626         if (fpath) {
627                 hammer_snapshot_data_t snap;
628                 struct tm tm;
629                 time_t t;
630                 int year;
631                 int month;
632                 int day = 0;
633                 int hour = 0;
634                 int minute = 0;
635                 int r;
636                 char linkbuf[1024];
637                 const char *ptr;
638                 hammer_tid_t tid;
639
640                 t = (time_t)-1;
641                 tid = (hammer_tid_t)(int64_t)-1;
642
643                 /* fpath may contain directory components */
644                 if ((ptr = strrchr(fpath, '/')) != NULL)
645                         ++ptr;
646                 else
647                         ptr = fpath;
648                 while (*ptr && *ptr != '-' && *ptr != '.')
649                         ++ptr;
650                 if (*ptr)
651                         ++ptr;
652                 r = sscanf(ptr, "%4d%2d%2d-%2d%2d",
653                            &year, &month, &day, &hour, &minute);
654
655                 if (r >= 3) {
656                         bzero(&tm, sizeof(tm));
657                         tm.tm_isdst = -1;
658                         tm.tm_min = minute;
659                         tm.tm_hour = hour;
660                         tm.tm_mday = day;
661                         tm.tm_mon = month - 1;
662                         tm.tm_year = year - 1900;
663                         t = mktime(&tm);
664                 }
665                 bzero(linkbuf, sizeof(linkbuf));
666                 if (readlink(fpath, linkbuf, sizeof(linkbuf) - 1) > 0 &&
667                     (ptr = strrchr(linkbuf, '@')) != NULL &&
668                     ptr > linkbuf && ptr[-1] == '@') {
669                         tid = strtoull(ptr + 1, NULL, 16);
670                 }
671                 if (t != (time_t)-1 && tid != (hammer_tid_t)(int64_t)-1) {
672                         snap = &snapshot->snaps[snapshot->count];
673                         bzero(snap, sizeof(*snap));
674                         snap->tid = tid;
675                         snap->ts = (uint64_t)t * 1000000ULL;
676                         snprintf(snap->label, sizeof(snap->label),
677                                  "migrated");
678                         ++snapshot->count;
679                 } else {
680                         printf("    non-canonical snapshot softlink: %s->%s\n",
681                                fpath, linkbuf);
682                 }
683         }
684
685         if ((fpath == NULL && snapshot->count) ||
686             snapshot->count == HAMMER_SNAPS_PER_IOCTL) {
687                 printf(" (%d snapshots)", snapshot->count);
688 again:
689                 if (ioctl(fd, HAMMERIOC_ADD_SNAPSHOT, snapshot) < 0) {
690                         printf("    Ioctl to migrate snapshots failed: %s\n",
691                                strerror(errno));
692                 } else if (snapshot->head.error == EALREADY) {
693                         ++snapshot->index;
694                         goto again;
695                 } else if (snapshot->head.error) {
696                         printf("    Ioctl to migrate snapshots failed: %s\n",
697                                strerror(snapshot->head.error));
698                 }
699                 printf("index %d\n", snapshot->index);
700                 snapshot->index = 0;
701                 snapshot->count = 0;
702                 snapshot->head.error = 0;
703         }
704 }
705
706 static
707 int
708 strtosecs(char *ptr)
709 {
710         int val;
711
712         val = strtol(ptr, &ptr, 0);
713         switch(*ptr) {
714         case 'd':
715                 val *= 24;
716                 /* fall through */
717         case 'h':
718                 val *= 60;
719                 /* fall through */
720         case 'm':
721                 val *= 60;
722                 /* fall through */
723         case 's':
724                 break;
725         default:
726                 errx(1, "illegal suffix converting %s", ptr);
727                 break;
728         }
729         return(val);
730 }
731
732 static const char *
733 dividing_slash(const char *path)
734 {
735         int len = strlen(path);
736         if (len && path[len-1] == '/')
737                 return("");
738         else
739                 return("/");
740 }
741
742 /*
743  * Check whether the desired period has elapsed since the last successful
744  * run.  The run may take a while and cross a boundary so we remember the
745  * current time_t so we can save it later on.
746  *
747  * Periods in minutes, hours, or days are assumed to have been crossed
748  * if the local time crosses a minute, hour, or day boundary regardless
749  * of how close the last operation actually was.
750  *
751  * If ForceOpt is set always return true.
752  */
753 static int
754 check_period(const char *snapshots_path, const char *cmd, int arg1,
755         time_t *savep)
756 {
757         char *check_path;
758         struct tm tp1;
759         struct tm tp2;
760         FILE *fp;
761         time_t baset, lastt;
762         char buf[256];
763
764         time(savep);
765         localtime_r(savep, &tp1);
766
767         /*
768          * Force run if -F
769          */
770         if (ForceOpt)
771                 return(1);
772
773         /*
774          * Retrieve the start time of the last successful operation.
775          */
776         asprintf(&check_path, "%s/.%s.period", snapshots_path, cmd);
777         fp = fopen(check_path, "r");
778         free(check_path);
779         if (fp == NULL)
780                 return(1);
781         if (fgets(buf, sizeof(buf), fp) == NULL) {
782                 fclose(fp);
783                 return(1);
784         }
785         fclose(fp);
786
787         lastt = strtol(buf, NULL, 0);
788         localtime_r(&lastt, &tp2);
789
790         /*
791          * Normalize the times.  e.g. if asked to do something on a 1-day
792          * interval the operation will be performed as soon as the day
793          * turns over relative to the previous operation, even if the previous
794          * operation ran a few seconds ago just before midnight.
795          */
796         if (arg1 % 60 == 0) {
797                 tp1.tm_sec = 0;
798                 tp2.tm_sec = 0;
799         }
800         if (arg1 % (60 * 60) == 0) {
801                 tp1.tm_min = 0;
802                 tp2.tm_min = 0;
803         }
804         if (arg1 % (24 * 60 * 60) == 0) {
805                 tp1.tm_hour = 0;
806                 tp2.tm_hour = 0;
807         }
808
809         baset = mktime(&tp1);
810         lastt = mktime(&tp2);
811
812 #if 0
813         printf("%lld vs %lld\n", (long long)(baset - lastt), (long long)arg1);
814 #endif
815
816         if ((int)(baset - lastt) >= arg1)
817                 return(1);
818         return(0);
819 }
820
821 /*
822  * Store the start time of the last successful operation.
823  */
824 static void
825 save_period(const char *snapshots_path, const char *cmd,
826                         time_t savet)
827 {
828         char *ocheck_path;
829         char *ncheck_path;
830         FILE *fp;
831
832         asprintf(&ocheck_path, "%s/.%s.period", snapshots_path, cmd);
833         asprintf(&ncheck_path, "%s/.%s.period.new", snapshots_path, cmd);
834         fp = fopen(ncheck_path, "w");
835         if (fp) {
836                 fprintf(fp, "0x%08llx\n", (long long)savet);
837                 if (fclose(fp) == 0)
838                         rename(ncheck_path, ocheck_path);
839                 remove(ncheck_path);
840         } else {
841                 fprintf(stderr, "hammer: Unable to create period-file %s: %s\n",
842                         ncheck_path, strerror(errno));
843         }
844 }
845
846 /*
847  * Simply count the number of softlinks in the snapshots dir
848  */
849 static int
850 check_softlinks(int fd, int new_config, const char *snapshots_path)
851 {
852         struct dirent *den;
853         struct stat st;
854         DIR *dir;
855         char *fpath;
856         int res = 0;
857
858         /*
859          * Old-style softlink-based snapshots
860          */
861         if ((dir = opendir(snapshots_path)) != NULL) {
862                 while ((den = readdir(dir)) != NULL) {
863                         if (den->d_name[0] == '.')
864                                 continue;
865                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
866                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode))
867                                 ++res;
868                         free(fpath);
869                 }
870                 closedir(dir);
871         }
872
873         /*
874          * New-style snapshots are stored as filesystem meta-data,
875          * count those too.
876          */
877         if (new_config) {
878                 struct hammer_ioc_snapshot snapshot;
879
880                 bzero(&snapshot, sizeof(snapshot));
881                 do {
882                         if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
883                                 err(2, "hammer cleanup: check_softlink "
884                                         "snapshot error");
885                                 /* not reached */
886                         }
887                         res += snapshot.count;
888                 } while (snapshot.head.error == 0 && snapshot.count);
889         }
890         return (res);
891 }
892
893 /*
894  * Clean up expired softlinks in the snapshots dir
895  */
896 static void
897 cleanup_softlinks(int fd, int new_config,
898                   const char *snapshots_path, int arg2, char *arg3)
899 {
900         struct dirent *den;
901         struct stat st;
902         DIR *dir;
903         char *fpath;
904         int anylink = 0;
905
906         if (arg3 != NULL && strstr(arg3, "any") != NULL)
907                 anylink = 1;
908
909         if ((dir = opendir(snapshots_path)) != NULL) {
910                 while ((den = readdir(dir)) != NULL) {
911                         if (den->d_name[0] == '.')
912                                 continue;
913                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
914                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode) &&
915                             (anylink || strncmp(den->d_name, "snap-", 5) == 0)) {
916                                 if (check_expired(den->d_name, arg2)) {
917                                         if (VerboseOpt) {
918                                                 printf("    expire %s\n",
919                                                         fpath);
920                                         }
921                                         remove(fpath);
922                                 }
923                         }
924                         free(fpath);
925                 }
926                 closedir(dir);
927         }
928
929         /*
930          * New-style snapshots are stored as filesystem meta-data,
931          * count those too.
932          */
933         if (new_config) {
934                 struct hammer_ioc_snapshot snapshot;
935                 struct hammer_ioc_snapshot dsnapshot;
936                 hammer_snapshot_data_t snap;
937                 struct tm *tp;
938                 time_t t;
939                 time_t dt;
940                 char snapts[32];
941                 uint32_t i;
942
943                 bzero(&snapshot, sizeof(snapshot));
944                 bzero(&dsnapshot, sizeof(dsnapshot));
945                 do {
946                         if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
947                                 err(2, "hammer cleanup: check_softlink "
948                                         "snapshot error");
949                                 /* not reached */
950                         }
951                         for (i = 0; i < snapshot.count; ++i) {
952                                 snap = &snapshot.snaps[i];
953                                 t = snap->ts / 1000000ULL;
954                                 dt = time(NULL) - t;
955                                 if ((int)dt > arg2 || snap->tid == 0) {
956                                         dsnapshot.snaps[dsnapshot.count++] =
957                                                 *snap;
958                                 }
959                                 if ((int)dt > arg2 && VerboseOpt) {
960                                         tp = localtime(&t);
961                                         strftime(snapts, sizeof(snapts),
962                                                  "%Y-%m-%d %H:%M:%S %Z", tp);
963                                         printf("    expire 0x%016jx %s %s\n",
964                                                (uintmax_t)snap->tid,
965                                                snapts,
966                                                snap->label);
967                                 }
968                                 if (dsnapshot.count == HAMMER_SNAPS_PER_IOCTL)
969                                         delete_snapshots(fd, &dsnapshot);
970                         }
971                 } while (snapshot.head.error == 0 && snapshot.count);
972
973                 if (dsnapshot.count)
974                         delete_snapshots(fd, &dsnapshot);
975         }
976 }
977
978 static void
979 delete_snapshots(int fd, struct hammer_ioc_snapshot *dsnapshot)
980 {
981         for (;;) {
982                 if (ioctl(fd, HAMMERIOC_DEL_SNAPSHOT, dsnapshot) < 0) {
983                         printf("    Ioctl to delete snapshots failed: %s\n",
984                                strerror(errno));
985                         break;
986                 }
987                 if (dsnapshot->head.error) {
988                         printf("    Ioctl to delete snapshots failed at "
989                                "snap=%016jx: %s\n",
990                                dsnapshot->snaps[dsnapshot->index].tid,
991                                strerror(dsnapshot->head.error));
992                         if (++dsnapshot->index < dsnapshot->count)
993                                 continue;
994                 }
995                 break;
996         }
997         dsnapshot->index = 0;
998         dsnapshot->count = 0;
999         dsnapshot->head.error = 0;
1000 }
1001
1002 /*
1003  * Take a softlink path in the form snap-yyyymmdd-hhmm and the
1004  * expiration in seconds (arg2) and return non-zero if the softlink
1005  * has expired.
1006  */
1007 static int
1008 check_expired(const char *fpath, int arg2)
1009 {
1010         struct tm tm;
1011         time_t t;
1012         int year;
1013         int month;
1014         int day = 0;
1015         int hour = 0;
1016         int minute = 0;
1017         int r;
1018
1019         while (*fpath && *fpath != '-' && *fpath != '.')
1020                 ++fpath;
1021         if (*fpath)
1022                 ++fpath;
1023
1024         r = sscanf(fpath, "%4d%2d%2d-%2d%2d",
1025                    &year, &month, &day, &hour, &minute);
1026
1027         if (r >= 3) {
1028                 bzero(&tm, sizeof(tm));
1029                 tm.tm_isdst = -1;
1030                 tm.tm_min = minute;
1031                 tm.tm_hour = hour;
1032                 tm.tm_mday = day;
1033                 tm.tm_mon = month - 1;
1034                 tm.tm_year = year - 1900;
1035                 t = mktime(&tm);
1036                 if (t == (time_t)-1)
1037                         return(0);
1038                 t = time(NULL) - t;
1039                 if ((int)t > arg2)
1040                         return(1);
1041         }
1042         return(0);
1043 }
1044
1045 /*
1046  * Issue a snapshot.
1047  */
1048 static int
1049 create_snapshot(const char *path, const char *snapshots_path)
1050 {
1051         int r;
1052
1053         runcmd(&r, "hammer snapshot %s %s", path, snapshots_path);
1054         return(r);
1055 }
1056
1057 static int
1058 cleanup_prune(const char *path, const char *snapshots_path,
1059                   int arg1 __unused, int arg2, int snapshots_disabled)
1060 {
1061         const char *path_or_snapshots_path;
1062
1063         /*
1064          * If the snapshots_path (e.g. /var/hammer/...) has no snapshots
1065          * in it then prune will get confused and prune the filesystem
1066          * containing the snapshots_path instead of the requested
1067          * filesystem.  De-confuse prune.  We need a better way.
1068          */
1069         if (hammer_softprune_testdir(snapshots_path))
1070                 path_or_snapshots_path = snapshots_path;
1071         else
1072                 path_or_snapshots_path = path;
1073
1074         /*
1075          * If snapshots have been disabled run prune-everything instead
1076          * of prune.
1077          */
1078         if (snapshots_disabled && arg2) {
1079                 runcmd(NULL,
1080                        "hammer -c %s/.prune.cycle -t %d prune-everything %s",
1081                        snapshots_path, arg2, path);
1082         } else if (snapshots_disabled) {
1083                 runcmd(NULL, "hammer prune-everything %s", path);
1084         } else if (arg2) {
1085                 runcmd(NULL, "hammer -c %s/.prune.cycle -t %d prune %s",
1086                         snapshots_path, arg2, path_or_snapshots_path);
1087         } else {
1088                 runcmd(NULL, "hammer prune %s", path_or_snapshots_path);
1089         }
1090         return(0);
1091 }
1092
1093 static int
1094 cleanup_rebalance(const char *path, const char *snapshots_path,
1095                   int arg1 __unused, int arg2)
1096 {
1097         if (VerboseOpt == 0) {
1098                 printf(".");
1099                 fflush(stdout);
1100         }
1101
1102         runcmd(NULL,
1103                "hammer -c %s/.rebalance.cycle -t %d rebalance %s",
1104                snapshots_path, arg2, path);
1105         if (VerboseOpt == 0) {
1106                 printf(".");
1107                 fflush(stdout);
1108         }
1109         if (VerboseOpt == 0)
1110                 printf("\n");
1111         return(0);
1112 }
1113
1114 static int
1115 cleanup_reblock(const char *path, const char *snapshots_path,
1116                   int arg1 __unused, int arg2)
1117 {
1118         if (VerboseOpt == 0) {
1119                 printf(".");
1120                 fflush(stdout);
1121         }
1122
1123         /*
1124          * When reblocking the B-Tree always reblock everything in normal
1125          * mode.
1126          */
1127         runcmd(NULL,
1128                "hammer -c %s/.reblock-1.cycle -t %d reblock-btree %s",
1129                snapshots_path, arg2, path);
1130         if (VerboseOpt == 0) {
1131                 printf(".");
1132                 fflush(stdout);
1133         }
1134
1135         /*
1136          * When reblocking the inodes always reblock everything in normal
1137          * mode.
1138          */
1139         runcmd(NULL,
1140                "hammer -c %s/.reblock-2.cycle -t %d reblock-inodes %s",
1141                snapshots_path, arg2, path);
1142         if (VerboseOpt == 0) {
1143                 printf(".");
1144                 fflush(stdout);
1145         }
1146
1147         /*
1148          * When reblocking the directories always reblock everything in normal
1149          * mode.
1150          */
1151         runcmd(NULL,
1152                "hammer -c %s/.reblock-4.cycle -t %d reblock-dirs %s",
1153                snapshots_path, arg2, path);
1154         if (VerboseOpt == 0) {
1155                 printf(".");
1156                 fflush(stdout);
1157         }
1158
1159         /*
1160          * Do not reblock all the data in normal mode.
1161          */
1162         runcmd(NULL,
1163                "hammer -c %s/.reblock-3.cycle -t %d reblock-data %s 95",
1164                snapshots_path, arg2, path);
1165         if (VerboseOpt == 0)
1166                 printf("\n");
1167         return(0);
1168 }
1169
1170 static int
1171 cleanup_recopy(const char *path, const char *snapshots_path,
1172                   int arg1 __unused, int arg2)
1173 {
1174         if (VerboseOpt == 0) {
1175                 printf(".");
1176                 fflush(stdout);
1177         }
1178         runcmd(NULL,
1179                "hammer -c %s/.recopy-1.cycle -t %d reblock-btree %s",
1180                snapshots_path, arg2, path);
1181         if (VerboseOpt == 0) {
1182                 printf(".");
1183                 fflush(stdout);
1184         }
1185         runcmd(NULL,
1186                "hammer -c %s/.recopy-2.cycle -t %d reblock-inodes %s",
1187                snapshots_path, arg2, path);
1188         if (VerboseOpt == 0) {
1189                 printf(".");
1190                 fflush(stdout);
1191         }
1192         runcmd(NULL,
1193                "hammer -c %s/.recopy-4.cycle -t %d reblock-dirs %s",
1194                snapshots_path, arg2, path);
1195         if (VerboseOpt == 0) {
1196                 printf(".");
1197                 fflush(stdout);
1198         }
1199         runcmd(NULL,
1200                "hammer -c %s/.recopy-3.cycle -t %d reblock-data %s",
1201                snapshots_path, arg2, path);
1202         if (VerboseOpt == 0)
1203                 printf("\n");
1204         return(0);
1205 }
1206
1207 static int
1208 cleanup_dedup(const char *path, const char *snapshots_path __unused,
1209                   int arg1 __unused, int arg2)
1210 {
1211         if (VerboseOpt == 0) {
1212                 printf(".");
1213                 fflush(stdout);
1214         }
1215
1216         runcmd(NULL, "hammer -t %d dedup %s", arg2, path);
1217         if (VerboseOpt == 0) {
1218                 printf(".");
1219                 fflush(stdout);
1220         }
1221         if (VerboseOpt == 0)
1222                 printf("\n");
1223         return(0);
1224 }
1225
1226 static
1227 void
1228 runcmd(int *resp, const char *ctl, ...)
1229 {
1230         va_list va;
1231         char *cmd;
1232         char *arg;
1233         char **av;
1234         int n;
1235         int nmax;
1236         int res;
1237         pid_t pid;
1238
1239         /*
1240          * Generate the command
1241          */
1242         va_start(va, ctl);
1243         vasprintf(&cmd, ctl, va);
1244         va_end(va);
1245         if (VerboseOpt)
1246                 printf("    %s\n", cmd);
1247
1248         /*
1249          * Break us down into arguments.  We do not just use system() here
1250          * because it blocks SIGINT and friends.
1251          */
1252         n = 0;
1253         nmax = 16;
1254         av = malloc(sizeof(char *) * nmax);
1255
1256         for (arg = strtok(cmd, WS); arg; arg = strtok(NULL, WS)) {
1257                 if (n == nmax - 1) {
1258                         nmax += 16;
1259                         av = realloc(av, sizeof(char *) * nmax);
1260                 }
1261                 av[n++] = arg;
1262         }
1263         av[n++] = NULL;
1264
1265         /*
1266          * Run the command.
1267          */
1268         RunningIoctl = 1;
1269         if ((pid = fork()) == 0) {
1270                 if (VerboseOpt < 2) {
1271                         int fd = open("/dev/null", O_RDWR);
1272                         dup2(fd, 1);
1273                         close(fd);
1274                 }
1275                 execvp(av[0], av);
1276                 _exit(127);
1277         } else if (pid < 0) {
1278                 res = 127;
1279         } else {
1280                 int status;
1281
1282                 while (waitpid(pid, &status, 0) != pid)
1283                         ;
1284                 res = WEXITSTATUS(status);
1285         }
1286         RunningIoctl = 0;
1287         if (DidInterrupt)
1288                 _exit(1);
1289
1290         free(cmd);
1291         free(av);
1292         if (resp)
1293                 *resp = res;
1294 }